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

+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])
]