[Bug]: embedding reindex incomplete: N chunks failed — one CJK chunk over the provider's per-item token limit silently drops its whole batch (recurrence of #5950)
QwenPaw Version
2.2.1
Description
ReMe embedding reindex fails with embedding reindex incomplete: 20 chunks failed, while the batch loop logs claim full success (processed=126/126). Root cause chain (fully verified with an empirical replay against the real provider):
Per-item token limit vs character-based truncation.
LocalEmbeddingStore._truncate()(reme) truncates by a CJK-weighted character budget (max_input_length=8192chars; the #6098 fix weights CJK chars at 1.5 units, i.e. up to ~5024 pure-CJK chars pass). This budget is calibrated for a model whose native window is 8192 tokens (bge-m3), but the serving stack's effective per-item window can be much smaller — ours (bge-m3 behind an OpenAI-compat gateway, likely Ollama with defaultnum_ctx=2048) enforces ~2048 tokens per item. A chunk truncated by reme to 6279 chars (~2400+ real tokens, measured 1716 tokens for its first 4000 chars ≈ 0.43 tok/char on this mixed-CJK content) is then rejected with HTTP 400the input length exceeds the context length, while reme believed it safely inside budget. Verified empirically: that chunk[:4600]= 2027 tokens → OK;[:4800]→ 400 rejected (3/3 deterministic). Note: over-limit ASCII items were silently clamped to ~2048 tokens by the serving stack (5 items all reported prompt_tokens 2042–2048 — a truncation artifact), while over-limit CJK-dense items were hard-rejected. Upstream policy is opaque; the client must be robust to both. (Silent clamping is itself a data-quality problem: the stored vector represents only the truncated text, with no warning.)One poison chunk kills its whole batch. agentscope's
OpenAIEmbeddingModelsends the whole reme batch (10 texts) in ONE API request. A single over-limit text makes the provider reject the entire request → all 10 chunks in the batch lose their vectors. In our case 2 chunks (one in batch 7, one in batch 12) → 2 × 10 = exactly the 20 "chunks failed".Silent failure propagation. reme swallows the batch failure at three levels:
LocalEmbeddingStore._call_with_retry()catches the exception, logs once, returnsNone;get_node_embeddings()silently skipsNoneresults (no per-chunk error);- the backfill loop counts
processed += len(batch)regardless of success →processed=126/126is misleading.
The only surfacing is the final
RuntimeError("embedding reindex incomplete: 20 chunks failed")from_reindex_embedding(), which does not say which chunks or why.Cache makes it 100% reproducible. The 106 successful chunks hit the on-disk npz cache (no API call), so every reindex run re-sends only the 2 poison batches and fails identically.
Note: max_input_length is a character budget with no knowledge of (a) the provider's per-item token window, (b) the tokenizer. Related closed issues #5950 / #6098 fixed the ASCII-blind case but the fix is still character-based and still fails for CJK-heavy chunks against an 8192-token-window model behind a 2048-token-per-item gateway cap (or any provider whose real per-item limit is below the character budget).
Root cause: the truncation budget (max_input_length, characters) is calibrated to the model's native window (8192 tokens) but not to the serving stack's effective per-item token limit (~2048 here); CJK-heavy chunks exceed it after truncation, batch-level API semantics turn one bad item into 10 lost vectors, and silent failure handling makes the job report success (processed=126/126) before failing at finalization.
Security considerations: None. No credentials exposed (API key read from agent.json, redacted in all logs above).
Component(s) Affected
- Core / Backend (app, agents, config, providers, utils, local_models)
- Console (frontend web UI)
- Channels (DingTalk, Feishu, QQ, Discord, iMessage, etc.)
- Skills
- CLI
- Documentation (website)
- Tests
- CI/CD
- Scripts / Deploy
Environment
- QwenPaw version: 2.2.1 (reme 0.4.1.11, agentscope 2.0.7.post1, openai 2.33.0)
- OS: Linux 7.0.0-1019-nvidia (aarch64)
- Install method: pip (venv)
- Python version: 3.11
- Embedding provider:
backend=openai(OpenAI-compatible gateway),model_name=bge-m3:latest,dimensions=1024,max_input_length=8192,max_batch_size=10,enable_cache=true
Steps to Reproduce
- Configure ReMe light memory with an OpenAI-compatible embedding gateway serving
bge-m3whose per-item token limit is ~2048 (or any provider whose per-item limit <max_input_lengthin real tokens for CJK text). - Have memory chunks with CJK-heavy daily notes; e.g. one chunk of ~7375 raw chars (3059 CJK chars) that
_truncate()reduces to 6279 chars. - Trigger embedding reindex (
/reme_reindexor model switch →reindex scope=embeddingjob). - Observe:
embedding batches complete: processed=126/126followed byFailed to execute job: embedding reindex incomplete: 20 chunks failed.
Actual vs Expected
- Actual: Reindex job fails wholesale; exactly the 2 batches containing the over-limit chunks lose all 10 vectors each (20 chunks); 106 good vectors are also left unpublished (
_finalize_embedding_reindex()never runs,_embedding_rebuild_pending=True); logs claimprocessed=126/126with no per-chunk error; every retry fails identically (cache hits for the 106). - Expected: (a) over-limit chunks are truncated to fit the provider's real token limit (token-aware, not char-aware), or split; (b) one bad item must not drop the whole batch (per-item fallback or per-item error); (c) the batch loop must report failed items (
filledvsattempted), and the final error should list the failing chunk ids.
Logs / Screenshots
[INFO ] embedding backfill scan complete: chunks=126, missing=126, elapsed=0.000s
[INFO ] embedding backfill started: total=126, batch_size=10
[ERROR] Embedding request failed # batch 7 (first poison chunk)
Traceback (most recent call last):
File ".../reme/components/embedding_store/local_embedding_store.py", line 190, in _call_with_retry
result = await self.as_embedding(texts, **kwargs)
...
File ".../agentscope/embedding/_openai/_model.py", line 152, in _call_api
response = await self.client.embeddings.create(**api_kwargs)
...
openai.BadRequestError: Error code: 400 - {'error': {'message': 'the input length exceeds the context length', ...}}
[ERROR] Embedding request failed # batch 12 (second poison chunk)
openai.BadRequestError: Error code: 400 - {'error': {'message': 'the input length exceeds the context length', ...}}
[INFO ] embedding batches complete: processed=126/126, batches=13, elapsed=6.440s
[INFO ] embedding backfill complete: filled=106/126, elapsed=6.53s
[ERROR] Failed to execute job: embedding reindex incomplete: 20 chunks failedEmpirical replay against the same gateway (deterministic; key rows):
batch 7 whole (10 items, 13830 chars) FAIL 400
batch 12 whole (10 items, 30473 chars) FAIL 400
batch 1 whole (10 items, 23484 chars) OK prompt_tokens=11104
batch 5 whole (10 items, 28504 chars) OK prompt_tokens=13178 # bigger request totals pass!
batch 5 x2 (20 items, ~26k chars) OK prompt_tokens=26356 # request-level total is NOT the limit
single idx=62 (6279 chars, 2513 CJK) FAIL 400 # poison chunk 1
single idx=117 (3395 chars, 1247 CJK) FAIL 400 # poison chunk 2, 3/3 runs
single idx=11 (6753 chars, ASCII-heavy) OK prompt_tokens=2048 # longer but ASCII — silently clamped
idx62 [0:4000] OK prompt_tokens=1716
idx62 [0:4600] OK prompt_tokens=2027
idx62 [0:4800] FAIL 400 # boundary ~2048 tokens per item
ASCII 24000 chars OK prompt_tokens=2048 # clamped, not rejectedAdditional Notes
Suggested fixes (any one restores correctness; the first two combined are ideal):
- Token-aware truncation in
_truncate()/max_input_lengthsemantics: count tokens (tokenizer if available, else CJK-aware estimate; measured ~0.43 tok/char on mixed CJK here, but bge-m3's tokenizer is more compact than the 1.5-unit char weighting assumes for dense-CJK text), and/or exposemax_input_lengthas provider-relative (e.g. allow setting it below the model window, documented as tokens). Also document that the effective per-item limit depends on the serving stack (e.g. Ollamanum_ctx), not just the model. - Per-item fallback on batch failure: when a batch request fails, re-embed items one by one so one poison chunk costs one vector, not ten. Alternatively, pre-validate each item against the provider limit before batching.
- Honest accounting + diagnostics: log
filledvsattemptedin the batch loop; make the finalRuntimeErrorinclude the failing chunk ids (and ideally reasons).processed=126/126after a 20-chunk loss is actively misleading. - Fail-soft semantics: allow reindex to complete with a warning + scheduled background backfill (the
_start_embedding_backfillmachinery already exists) instead of discarding the 106 good vectors and failing the whole job.
Workaround for affected users: reduce max_input_length in agent.json (e.g. 2000–2500 for CJK-heavy memories behind a 2048-token-per-item gateway) and re-run reindex; or switch to a provider whose per-item window exceeds 8192 tokens.
Related: #5950 (same error signature, closed), #6098 (character-based CJK-weighted truncation fix — insufficient for this case), #310 (bge-m3 dimension/matryoshka quirks).
Source: agentscope-ai/QwenPaw