fix: chunk-budget blowups, FastEmbed built-ins, and re-embed gaps

Follow-up review pass over the embeddings branch.

- Fold an oversized header back into the body, and drop header duplication
  when it would leave under a quarter of the chunk budget. A header at or
  over max_tokens collapsed the body budget to one token, so a document
  became one chunk per body token, each still over the cap: a 95 KB file
  produced 20k chunks of 2563 tokens against a 1250 cap. Also clamp
  max_tokens to at least 1, as the strategy chunkers already do.
- Emit a header-only document as its own chunk. With no body piece to
  attach it to, splitting returned nothing and the document was dropped
  from the index with no error and no log line.
- Skip add_custom_model for a repository FastEmbed already ships. It
  rejects a name it knows, so configuring any of its ~30 built-ins
  (MiniLM, bge, e5, gte, ...) failed every embed call and every query.
- Decide "the user chose this model" by comparing against the field
  default rather than model_fields_set, which is true for anything read
  from .env. Every setup script has always written EMBEDDINGS_NAME, so an
  upgraded remote-embeddings install inherited mpnet's 384-token window
  and silently clipped ~80% off every chunk.
- Cut tiktoken splits at character offsets instead of decoding each token
  window. A multi-byte character straddling a boundary decoded to U+FFFD
  on both sides, destroying one character at roughly one boundary in five
  on CJK text -- including at the default max_tokens of 2000.
- Let the re-embed script open a FAISS index whose width does not match
  the configured model. That mismatch is the main reason to run it, and
  the error recommending the script was raised by the script itself, so
  the advice failed on every source.
- Re-embed graph_nodes.name_embedding when GraphRAG is enabled. Those
  vectors seed every traversal and share the chunk vectors' width, so a
  same-width model swap left the graph retrieving from the old space with
  nothing to report it.
- Prefetch the models before copying the application source, so editing
  any file no longer re-downloads ~780 MB of artifacts on every build.
- Mirror the setup.sh embedding menu into setup.ps1: granite default,
  legacy mpnet as an explicit option, and both engine flows updated.
  Windows users were otherwise stranded on mpnet with no granite path.
- Drop the unused EmbeddingsWrapper.tokenizer property.
This commit is contained in:
Alex committed 2026-08-27 15:55:21 +01:00
1 parent 25e07f5cee
commit de22be5a21
16 files changed
+707 -54

No files matched your search

+65
View File
@@ -127,6 +127,71 @@ class TestSplitDocument:
assert len(result) > 1
assert all("h1" in chunk.text for chunk in result)
def test_oversized_header_does_not_multiply_chunks(self):
"""A header past the budget used to leave a one-token body budget.
``max(1, max_tokens - header_tokens)`` bottomed out at 1, so the body
was cut into one chunk per token -- each still over ``max_tokens``,
since the whole header was prepended to it.
"""
chunker = Chunker(max_tokens=50, min_tokens=5, duplicate_headers=True)
header = ("verylongheaderword " * 40) + "h2\nh3\n"
body = "word " * 100
doc = Document(text=f"{header}\n{body}", doc_id="doc1")
result = chunker.split_document(doc)
body_tokens = chunker.counter.count(body)
assert len(result) <= body_tokens // 10, "chunk count must track the budget"
for chunk in result:
assert chunk.extra_info["token_count"] <= chunker.max_tokens
assert "".join(chunk.text for chunk in result) == doc.text
def test_header_taking_most_of_the_budget_is_not_duplicated(self):
"""Duplication is dropped when it would leave almost no room for body.
Below a quarter of the budget every chunk is mostly repeated header,
which multiplies the chunk count without adding retrievable text.
"""
chunker = Chunker(max_tokens=50, min_tokens=5, duplicate_headers=True)
header = ("headerword " * 20) + "h2\nh3\n"
doc = Document(text=f"{header}\n" + "word " * 200, doc_id="doc1")
result = chunker.split_document(doc)
assert len(result) > 1
assert "headerword" in result[0].text
assert all("headerword" not in chunk.text for chunk in result[1:])
def test_header_only_document_is_not_dropped(self):
"""The loop only ever emitted the header attached to a body piece.
With no body there was no piece, so an entire document disappeared
from the index with no error and no log line.
"""
chunker = Chunker(max_tokens=50, min_tokens=1, duplicate_headers=False)
text = "h1\nh2\nh3\n"
doc = Document(text=text, doc_id="doc1")
result = chunker.split_document(doc)
assert len(result) == 1
assert result[0].text == text
def test_header_only_document_keeps_its_text_through_chunk(self):
"""The reachable shape: three lines that alone exceed the budget."""
chunker = Chunker(max_tokens=5, min_tokens=1, duplicate_headers=False)
text = "h1\nh2\nh3\n"
result = chunker.chunk([Document(text=text, doc_id="doc1")])
assert result, "the document must not vanish"
assert "".join(chunk.text for chunk in result) == text
def test_zero_max_tokens_does_not_split_per_token(self):
chunker = Chunker(max_tokens=0, min_tokens=1)
assert chunker.max_tokens == 1
def test_split_preserves_embedding(self):
chunker = Chunker(max_tokens=50, min_tokens=5)
doc = Document(
+49
View File
@@ -29,6 +29,10 @@ class _StubEncoding:
def decode(self, ids):
return "".join(chr(i) for i in ids)
def decode_with_offsets(self, ids):
# One token per character, so each token starts where the last ended.
return self.decode(ids), list(range(len(ids)))
@pytest.fixture(autouse=True)
def _clear_cache():
@@ -107,6 +111,51 @@ class TestSelection:
assert get_token_counter("granite-311m") is first
class TestTiktokenSplitAgainstRealCl100k:
"""The stub above is one token per character, so it can never place a cut
inside a character. Real cl100k can, and that is the case that corrupted
text: decoding each window on its own turns a straddled multi-byte
character into U+FFFD on both sides of the cut."""
@pytest.fixture
def real_counter(self):
try:
counter = TiktokenCounter()
counter.count("probe")
except Exception as exc: # offline CI, same policy as the HF fixture
pytest.skip(f"cl100k encoding unavailable: {exc}")
return counter
# 2000 is the shipped default max_tokens, 384 mpnet's window; the small
# values place many more cuts per unit of text.
@pytest.mark.parametrize("window", [1, 2, 3, 7, 128, 384, 2000])
@pytest.mark.parametrize(
"text",
[
"日本語のテキストです。絵文字も🎉あります。",
"検索は自然言語でできます。" * 200,
"Здравствуйте, как настроить аутентификацию?",
"🎉🎊✨🚀🔥💡📚🧠" * 50,
"Ünïcödé — em-dashes, curly “quotes”, and 日本語 text.",
],
ids=["ja-short", "ja-long", "ru", "emoji", "mixed"],
)
def test_split_reassembles_exactly(self, real_counter, text, window):
pieces = real_counter.split(text, window)
assert "".join(pieces) == text
@pytest.mark.parametrize("window", [1, 3, 128, 2000])
def test_split_never_emits_a_replacement_character(self, real_counter, window):
text = "検索は自然言語でできます。絵文字も🎉あります。" * 100
assert "�" not in "".join(real_counter.split(text, window))
def test_first_window_budget_is_honoured_and_lossless(self, real_counter):
text = "日本語のテキストです。" * 50
pieces = real_counter.split(text, 20, first_max_tokens=5)
assert "".join(pieces) == text
assert real_counter.count(pieces[0]) <= 5
class TestTiktokenCounterEdges:
"""The cl100k path is the fallback, so its edges matter as much."""
+120 -1
View File
@@ -117,6 +117,20 @@ class TestFaissRebuild:
reembed.reembed_faiss("s1", batch_size=8, dry_run=False)
assert factory.call_args_list[1].kwargs["ids"] == ["1", "2"]
def test_existing_index_is_opened_past_the_dimension_check(self, stores):
"""A width change is the main reason to run this script.
``assert_embedding_dimensions`` refuses to open an index whose width
differs from the configured model -- and its error message recommends
this script, so without the opt-out the advice failed on every source.
The chunk text lives in the sidecar, so reading it needs no match.
"""
_, _, factory = stores
reembed.reembed_faiss("s1", batch_size=8, dry_run=False)
assert factory.call_args_list[0].kwargs["skip_dimension_check"] is True
# The rebuild writes the new width, so it must still be checked.
assert "skip_dimension_check" not in factory.call_args_list[1].kwargs
def test_batch_size_is_forwarded_to_the_rebuild(self, stores):
"""On a remote embeddings server the whole index is otherwise one POST."""
_, _, factory = stores
@@ -171,7 +185,7 @@ class TestPgvectorWithoutTheExtension:
]
with patch.object(
reembed.VectorCreator, "create_vectorstore", return_value=store
):
), patch.object(reembed.settings, "GRAPHRAG_ENABLED", False):
yield store, conn, cursor
def test_reads_and_rewrites_every_chunk(self, store):
@@ -255,3 +269,108 @@ class TestFaissSourceDiscovery:
def test_unsupported_store_error_names_the_alternatives(self):
with patch.object(reembed.settings, "VECTOR_STORE", "milvus", create=True):
assert reembed.main([]) == 2
class TestGraphNodeReembedding:
"""``graph_nodes.name_embedding`` seeds every graph traversal.
It is written once at extraction time and never revisited, so rewriting
only the chunk table leaves the graph seeding from the previous model --
and since mpnet and granite-311m are both 768-dimensional, the column
accepts the mismatch and nothing reports it.
"""
@pytest.fixture
def graph(self):
store = MagicMock()
store._embedding.embed_documents.side_effect = lambda texts: [
[0.5] * 4 for _ in texts
]
cursor = MagicMock()
cursor.fetchone.return_value = ("graph_nodes",)
cursor.fetchall.return_value = [
("n1", "Alpha"),
("n2", "Beta"),
("n3", "Gamma"),
]
conn = MagicMock()
conn.cursor.return_value = cursor
return store, conn, cursor
def test_rewrites_every_node_name(self, graph):
store, conn, cursor = graph
written = reembed.reembed_graph_nodes(
store, conn, "s1", batch_size=64, dry_run=False
)
assert written == 3
store._embedding.embed_documents.assert_called_once_with(
["Alpha", "Beta", "Gamma"]
)
statement = cursor.executemany.call_args.args[0]
assert "graph_nodes" in statement and "name_embedding" in statement
conn.commit.assert_called()
def test_dry_run_counts_without_embedding(self, graph):
store, conn, cursor = graph
assert reembed.reembed_graph_nodes(store, conn, "s1", 64, dry_run=True) == 3
store._embedding.embed_documents.assert_not_called()
cursor.executemany.assert_not_called()
def test_missing_table_is_a_no_op(self, graph):
store, conn, cursor = graph
cursor.fetchone.return_value = (None,)
assert reembed.reembed_graph_nodes(store, conn, "s1", 64, dry_run=False) == 0
store._embedding.embed_documents.assert_not_called()
def test_batches_commit_separately(self, graph):
store, conn, cursor = graph
reembed.reembed_graph_nodes(store, conn, "s1", batch_size=2, dry_run=False)
assert cursor.executemany.call_count == 2
assert conn.commit.call_count == 2
def test_failed_batch_rolls_back_and_raises(self, graph):
store, conn, cursor = graph
cursor.executemany.side_effect = RuntimeError("write failed")
with pytest.raises(RuntimeError, match="write failed"):
reembed.reembed_graph_nodes(store, conn, "s1", 64, dry_run=False)
conn.rollback.assert_called_once()
def test_pgvector_run_skips_the_graph_when_disabled(self):
store, conn, cursor = self._pgvector_mocks()
with patch.object(
reembed.VectorCreator, "create_vectorstore", return_value=store
), patch.object(reembed.settings, "GRAPHRAG_ENABLED", False):
reembed.reembed_pgvector("s1", batch_size=64, dry_run=False)
assert not self._graph_statements(cursor)
def test_pgvector_run_reembeds_the_graph_when_enabled(self):
store, conn, cursor = self._pgvector_mocks()
with patch.object(
reembed.VectorCreator, "create_vectorstore", return_value=store
), patch.object(reembed.settings, "GRAPHRAG_ENABLED", True):
reembed.reembed_pgvector("s1", batch_size=64, dry_run=False)
assert self._graph_statements(cursor)
@staticmethod
def _pgvector_mocks():
store = MagicMock()
store._table_name = "documents"
store._vector_column = "embedding"
cursor = MagicMock()
cursor.fetchone.return_value = ("graph_nodes",)
cursor.fetchall.return_value = [(1, "alpha"), (2, "beta")]
conn = MagicMock()
conn.cursor.return_value = cursor
store._get_connection.return_value = conn
store._embedding.embed_documents.side_effect = lambda texts: [
[0.5] * 4 for _ in texts
]
return store, conn, cursor
@staticmethod
def _graph_statements(cursor):
return [
call
for call in cursor.executemany.call_args_list
if "graph_nodes" in str(call.args[0])
]
+106
View File
@@ -189,3 +189,109 @@ class TestReembedPgvectorLive:
_seed(live_dsn, "src-f", TEXTS, _Embeddings(1.0))
_seed(live_dsn, "src-g", TEXTS, _Embeddings(1.0))
assert reembed.list_source_ids("pgvector") == ["src-f", "src-g"]
GRAPH_SOURCE = "11111111-2222-3333-4444-555555555555"
def _seed_graph_node(dsn, source_id, name, seed):
"""Insert one graph node carrying a name embedding at ``seed``."""
from application.graphrag.store import GraphStore
store = PGVectorStore(source_id=source_id, connection_string=dsn)
conn = store._get_connection()
GraphStore.create_schema(conn, dimension=DIM)
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO graph_nodes (id, source_id, name, normalized_name, type, "
"description, degree, doc_freq, name_embedding) "
"VALUES (gen_random_uuid(), %s, %s, %s, 'ENTITY', '', 0, 0, %s::vector)",
(source_id, name, name.lower(), str([seed] + [0.0] * (DIM - 1))),
)
conn.commit()
finally:
cursor.close()
store.close()
def _node_vectors(dsn, source_id):
store = PGVectorStore(source_id=source_id, connection_string=dsn)
conn = store._get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"SELECT name, name_embedding FROM graph_nodes "
"WHERE source_id = %s ORDER BY name",
(source_id,),
)
return [(name, _as_list(vector)) for name, vector in cursor.fetchall()]
finally:
cursor.close()
store.close()
class TestGraphNodeReembedLive:
"""``graph_nodes.name_embedding`` seeds every graph traversal.
Rewriting only the chunk table leaves it in the previous model's space,
and because mpnet and granite-311m share a width the column accepts the
mismatch silently -- exactly the failure the script exists to prevent.
"""
def test_node_names_are_re_embedded(self, live_dsn, monkeypatch):
from application.core import settings as settings_module
monkeypatch.setattr(
settings_module.settings, "GRAPHRAG_ENABLED", True, raising=False
)
_seed(live_dsn, GRAPH_SOURCE, TEXTS, _Embeddings(1.0))
_seed_graph_node(live_dsn, GRAPH_SOURCE, "Alpha", 1.0)
assert all(v[0] == pytest.approx(1.0) for _, v in _node_vectors(live_dsn, GRAPH_SOURCE))
with patch(
"application.vectorstore.base.BaseVectorStore._get_embeddings",
return_value=_Embeddings(9.0),
):
reembed.reembed_pgvector(GRAPH_SOURCE, batch_size=64, dry_run=False)
after = _node_vectors(live_dsn, GRAPH_SOURCE)
assert [name for name, _ in after] == ["Alpha"]
assert all(v[0] == pytest.approx(9.0) for _, v in after), (
"graph node names must move with the chunk vectors"
)
def test_graph_is_left_alone_when_graphrag_is_off(self, live_dsn, monkeypatch):
from application.core import settings as settings_module
monkeypatch.setattr(
settings_module.settings, "GRAPHRAG_ENABLED", False, raising=False
)
_seed(live_dsn, GRAPH_SOURCE, TEXTS, _Embeddings(1.0))
_seed_graph_node(live_dsn, GRAPH_SOURCE, "Alpha", 1.0)
with patch(
"application.vectorstore.base.BaseVectorStore._get_embeddings",
return_value=_Embeddings(9.0),
):
reembed.reembed_pgvector(GRAPH_SOURCE, batch_size=64, dry_run=False)
assert all(v[0] == pytest.approx(1.0) for _, v in _node_vectors(live_dsn, GRAPH_SOURCE))
def test_dry_run_leaves_node_vectors_untouched(self, live_dsn, monkeypatch):
from application.core import settings as settings_module
monkeypatch.setattr(
settings_module.settings, "GRAPHRAG_ENABLED", True, raising=False
)
_seed(live_dsn, GRAPH_SOURCE, TEXTS, _Embeddings(1.0))
_seed_graph_node(live_dsn, GRAPH_SOURCE, "Alpha", 1.0)
with patch(
"application.vectorstore.base.BaseVectorStore._get_embeddings",
return_value=_Embeddings(9.0),
):
reembed.reembed_pgvector(GRAPH_SOURCE, batch_size=64, dry_run=True)
assert all(v[0] == pytest.approx(1.0) for _, v in _node_vectors(live_dsn, GRAPH_SOURCE))
@@ -25,10 +25,57 @@ def fake_fastembed():
instance = MagicMock()
instance.embed.return_value = iter([np.array([0.1, 0.2, 0.3])])
text_embedding.return_value = instance
# Registration checks this before calling ``add_custom_model``; an empty
# list means "no built-in collides", which is the case for every name in
# our registry.
text_embedding.list_supported_models.return_value = []
with patch("fastembed.TextEmbedding", text_embedding):
yield text_embedding, instance
class TestBuiltinModelRegistration:
"""FastEmbed ships ~30 models of its own and refuses to re-register any of
them, so registering unconditionally broke every natively-supported name."""
def test_builtin_name_is_not_re_registered(self, fake_fastembed):
text_embedding, _ = fake_fastembed
text_embedding.list_supported_models.return_value = [
{"model": "BAAI/bge-small-en-v1.5"}
]
EmbeddingsWrapper("BAAI/bge-small-en-v1.5")
text_embedding.add_custom_model.assert_not_called()
assert text_embedding.call_args.kwargs["model_name"] == "BAAI/bge-small-en-v1.5"
def test_builtin_match_ignores_case(self, fake_fastembed):
text_embedding, _ = fake_fastembed
text_embedding.list_supported_models.return_value = [
{"model": "baai/BGE-Small-EN-v1.5"}
]
EmbeddingsWrapper("BAAI/bge-small-en-v1.5")
text_embedding.add_custom_model.assert_not_called()
def test_unknown_name_is_still_registered(self, fake_fastembed):
text_embedding, _ = fake_fastembed
text_embedding.list_supported_models.return_value = [
{"model": "BAAI/bge-small-en-v1.5"}
]
EmbeddingsWrapper("some-org/custom-embedder")
text_embedding.add_custom_model.assert_called_once()
def test_real_fastembed_accepts_its_own_builtin(self):
"""Runs against the installed FastEmbed, not the MagicMock.
The mocked tests above cannot catch this: the failure was
``add_custom_model`` raising, and a MagicMock never raises.
"""
fastembed = pytest.importorskip("fastembed")
builtins = [m["model"] for m in fastembed.TextEmbedding.list_supported_models()]
assert builtins, "expected FastEmbed to ship built-in models"
spec = embeddings_local._spec_for(builtins[0])
# Must not raise ValueError("... is already registered ...").
embeddings_local._register(spec)
class TestRegistryDrivenLoading:
def test_registered_model_loads_by_repo_not_by_configured_name(self, fake_fastembed):
text_embedding, _ = fake_fastembed
@@ -150,3 +150,48 @@ class TestInputLimitResolution:
def test_unknown_model_dimension_is_probed_not_assumed(self):
"""The old hardcoded 768 made the probe below unreachable."""
assert self._remote("some-org/mystery").dimension is None
class TestEmbeddingsNameIsExplicit:
"""Which names count as chosen decides whether a remote server inherits a
context window it may not have.
The tests above monkeypatch the predicate, so they cannot see it being
wrong. These drive the real one.
"""
def _default(self):
from application.core.settings import Settings
return Settings.model_fields["EMBEDDINGS_NAME"].default
def test_the_default_name_is_not_a_choice(self, monkeypatch):
"""Every setup script has always written this value unconditionally.
Reading it as deliberate lends the server mpnet's 384-token window and
clips ~80% off every chunk, silently, on upgrade. ``model_fields_set``
could not tell the difference: pydantic marks a field set for anything
that reached it, ``.env`` included.
"""
monkeypatch.setattr(base.settings, "EMBEDDINGS_NAME", self._default())
assert base._embeddings_name_is_explicit() is False
def test_a_different_name_is_a_choice(self, monkeypatch):
monkeypatch.setattr(
base.settings,
"EMBEDDINGS_NAME",
"ibm-granite/granite-embedding-311m-multilingual-r2",
)
assert base._embeddings_name_is_explicit() is True
def test_dotenv_written_default_does_not_clip(self, monkeypatch):
"""End to end: the common upgrade path must send the full chunk."""
monkeypatch.setattr(base.settings, "EMBEDDINGS_MAX_INPUT_TOKENS", None)
monkeypatch.setattr(base.settings, "EMBEDDINGS_NAME", self._default())
captured = _capture_post(monkeypatch)
long_text = " ".join(["word"] * 1000)
emb = RemoteEmbeddings(api_url="http://embeddings", model_name=self._default())
emb.embed_documents([long_text])
assert captured["payload"]["input"][0] == long_text