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

+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."""