Skip to content

fix(rag): reject incomplete embedding batches - #3860

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:codex/fix-3530-embedding-alignment
Sep 17, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:codex/fix-3530-embedding-alignment

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

An incomplete embedding batch could pair vectors with the wrong passages or files. RAG now validates whole batches and response indices before publishing index changes, using the existing bounded retry policy for a warming model and preserving existing documents when indexing fails.

Fixes #3530.

Test plan:

  • Latest alignment and real-FAISS transaction suites: 27 passed, including recovery, invalid indices, multi-batch ordering, and existing-document preservation.
  • Live Lemonade indexing of a temporary document succeeded with matching chunk/vector counts.
  • Earlier complete RAG unit run: 53 passed; two existing optional DOCX/PPTX modules skipped because their dependencies are absent. All changed-path tests ran.
  • Black, isort, whitespace checks, code and architecture review passed.

@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes tests Test changes performance Performance-critical changes labels Sep 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This replaces the RAG indexer's one-by-one fallback with a hard failure whenever the embedding backend returns fewer, empty, or differently-sized vectors than requested — the right call, since the old path silently paired vectors with the wrong passages. The alignment fix itself is solid and well tested; what's missing is the retry the old fallback was accidentally providing.

Headline issue — a warming-up embedder will now abort a whole document. Lemonade answers HTTP 200 with too few (or zero) vectors while the model is still loading. The old one-by-one path re-asked and usually succeeded a moment later; the new code fails on the first short answer and tells the user to retry indexing by hand — a full re-run of a large PDF for a race that clears itself in seconds. GAIA's code-index module already hit exactly this and solved it by re-sending the same batch up to twice before giving up; reuse that here and the fix keeps its strictness without the new fragility.

Secondary — one failure mode gets advice that will never work. A chunk that's still too long for the embedder comes back as an empty vector, and indexing now stops with a message telling the user to check that the model is loaded and retry. That retry is deterministic: the same document fails forever, with nothing in the error pointing at the real cause. Worth naming the over-long-chunk possibility in the message.

Real-world evidence

No evidence bundle was produced for this PR, and pytest isn't installed in the review environment, so I could not run the new tests or exercise indexing here — the verdict rests on static review plus the PR's reported unit-suite result (53 passed).

The gap worth closing before merge: the PR shows unit tests for the failure paths, but nothing showing a normal document still indexes end-to-end now that the fallback is gone — one gaia chat (or SDK) run indexing a real PDF, with its output pasted in, would cover it.

🔍 Technical details

🟡 Short/empty HTTP-200 responses are no longer retried (src/gaia/rag/sdk.py:614)

The existing retry loop at sdk.py:585-603 only catches exceptions. A short 200 never enters it, so the new count check raises on the first occurrence. The removed fallback re-issued a request per text, which is why the warm-up race was previously survivable (slowly).

src/gaia/code_index/sdk.py:812-851 documents and implements the fix for the identical symptom:

Lemonade occasionally answers HTTP 200 with fewer (or zero) vectors than requested while the model is still warming up — no exception is raised... Retrying the same batch a couple of times resolves the transient case without callers paying the ~25x cost of a one-by-one fallback.

Both modules call _load_embedder() before encoding, so the load-model call up-front doesn't remove the race. Suggest lifting the same shape into RAGSDK._encode_texts: fold the short/empty check into the existing attempt loop so a short batch triggers time.sleep(2) + re-send, and raise the current RuntimeError only after retries are exhausted (mirroring the "after retries" wording at code_index/sdk.py:875-882). The per-item empty-vector check should sit behind the same retries — a partially-warm model can return an empty vector rather than a short list.

🟡 Empty-vector error names only one of two causes (src/gaia/rag/sdk.py:626-630)

sdk.py:548-552 records that GGUF embedders "silently return empty data for inputs that exceed their token limit (~512 tokens)", and that MAX_EMBED_CHARS = 1200 is a ~3 chars/token approximation. For token-dense text (CJK, minified code, base64) 1200 chars can exceed the limit, so the empty vector is deterministic and "retry indexing" is dead-end advice. Per CLAUDE.md's actionable-error rule, name the second cause:

                    raise RuntimeError(
                        f"Embedding backend returned an empty or inconsistent vector "
                        f"in batch {batch_num} using {self.config.embedding_model!r}. "
                        "This is usually a chunk that exceeds the embedding model's "
                        "token limit, or a model that is not fully loaded. Lower "
                        "chunk_size or verify the model is loaded, then retry indexing."
                    )

🟢 Vector↔text order relies on response ordering (src/gaia/rag/sdk.py:610-612)

data is consumed positionally, but the OpenAI-compatible embeddings response carries a per-item index that clients are meant to honour. The count check closes the length hole; sorting by index when present closes the ordering one, which is the same class of bug this PR targets.

            batch_embeddings = []
            for item in sorted(
                response.get("data", []), key=lambda d: d.get("index", 0)
            ):
                embedding = item.get("embedding", [])
                batch_embeddings.append(embedding)

🟢 Dead guard left behind (src/gaia/rag/sdk.py:677)

_encode_query still checks if embedding.shape[0] > 0: before caching. _encode_texts can no longer return an empty array — it raises instead. Harmless, but it now reads as a live failure mode that doesn't exist.

Strengths

  • The alignment tests are the right ones: test_multiple_batches_preserve_every_text_position pins positional correctness across a 51-chunk / 3-batch run rather than just asserting a shape, and test_later_batch_cannot_change_dimension covers the cross-batch case the all_embeddings[0] comparison exists for.
  • test_short_embedding_batch_preserves_existing_document exercises the real transaction boundary — a failed second document leaves the first one intact — which is the property that actually matters to a user, not just that an exception was raised.
  • assert_called_once() in the failure tests directly pins the removed behaviour, so a reintroduced fallback fails the suite rather than passing quietly.
  • Error text follows CLAUDE.md's what-failed / what-to-do shape and names the model id.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Addressed the warm-up and alignment feedback in 5027a7e. Incomplete vectors now use the existing bounded retry loop for the same batch, response indices are validated and ordered, and errors include the token-limit/chunk-size remedy. All 27 focused alignment/transaction tests passed. A live Lemonade SDK run indexed a temporary document successfully with matching chunk and vector counts.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 17, 2026
Merged via the queue into amd:main with commit 3d57387 Sep 17, 2026
37 checks passed
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Sep 17, 2026
amd#3860 landed the same guard on main with different messages and a batch
retry in place of the one-by-one fallback; the invariant these pin — raise
rather than shift chunks against misaligned vectors — is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(rag): a short embedding batch misaligns chunks with vectors

2 participants