Repository navigation
fix(rag): unblock the release retrieval eval (image chunks, pypdf labels) - #5490
Conversation
Indexing a PDF page with two or more images fused the last word of each
image's text onto the next image or page marker ("battery.[Page 2]").
The chunks no longer matched the document's own text, which is why the
release retrieval benchmark stops with "4/59 chunks could not be
located" on every run where the vision model loads. The chunker now
keeps the whitespace that followed each image block when it swaps the
block out and back in.
Page citations were never affected: page lookup does not need a space
before the marker. Documents already in the RAG cache keep their old
chunks until they are re-indexed.
|
Verdict: Approve This fixes the RAG chunker that glued the last word of each image's text onto the next image or page marker ( Nothing blocks merge. One thing to know: documents already in the index keep their fused chunks until someone re-indexes them. The PR description says this is deliberate, and it's a reasonable call since page citations were never affected. Real-world evidenceN/A: this PR doesn't change a CLI, API or MCP surface (the evidence bundle says the same). The verdict rests on reading the code. I couldn't run the new tests here because pytest isn't installed on this runner. The PR reports 397 tests passing, and its test plan still has an open item: dispatching "Eval — RAG retrieval" on this branch. Running that before merge would confirm the fix end to end. 🔍 Technical detailsIssues found 🟢 Redundant Correctness check
Strengths
|
Two evidence quotes from the Attention paper ended in math that pypdf
spaces differently between releases ("df f = 2048" vs "df f= 2048",
"0.1" vs "0 .1"). Each matched only one release, so the benchmark
stopped with a LabelError on whichever one CI installed. The quotes now
end before the math, which still pins the same passage.
Skill audit
✅ All audited skills cleared the tier they claim. Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the |
…md#5548) The release retrieval eval still stops on FinanceBench after amd#5490. SEC filings repeat whole passages. When a chunk followed the short tail of a chunk split for the embedder, the benchmark's locator matched a repeat hundreds of pages later, and every chunk after it in that filing counted as unlocated (644 chunks across four filings, over the 1% limit). The nearby copy now wins. Placements in every other filing are unchanged. This follows amd#5490, which merged before this commit landed on its branch. Benchmark code only; no user-facing behavior changes. ## Test plan - [x] The four failing filings (American Water 2022 10-K, JPMorgan 2021 Q1 10-Q and 2022 10-K, PepsiCo 2023 8-K): 644 unlocated chunks before, 0 after - [x] Old vs new placements on six filings: only chunks that had jumped to a far-later duplicate moved; 3M and AMD 10-Ks are identical - [x] New test fails on the old locator: an overlap through a split tail beats a later repeat, a chunk only the repeat explains stays there, and absent text stays unlocated - [x] `pytest tests/unit/eval/test_retrieval_bench.py tests/unit/rag/test_retrieval_bench_harness.py` (87 passed), `python util/lint.py --all`
## Summary Two quotes in `technical_docs.json` stopped matching the text GAIA indexes from the PDFs, which is what killed the release RAG benchmark. This re-points them at the same answers. Questions, answers and pages are unchanged. ## Why The benchmark checks that every labelled quote can be found on its page, and it stops at the first one it can't. That's the `LabelError` on tech-012 in the issue. - **tech-012:** the old quote (`MAX POWER 550W or 760W 750W 1000W`) is the table cells in plain order. Since #8116 (`39606a8a4`) GAIA indexes table rows as `Header: value | ...`, so it no longer matches. I bisected with pypdf 7.1.0: it resolves at `39606a8a4~1` and fails at `39606a8a4`. - **tech-023:** the run stops at the first failure, so it never got this far. The old quote (`SR-IOV , up to 8 partitions`) has a space before the comma. The PDF doesn't (I checked page 1), and pypdf 7.1.0 extracts it without one, but pypdf 6.21.1 (the version #5490 names as CI's) does add the space. So the quote matches on one pypdf version and not the other. It fails under 7.1.0 even before #8116, so #8116 isn't the cause. The new quote starts after the comma, so it resolves under both. I checked both against the PDFs: the Max Power row on page 25 of the CDNA 3 white paper, and the SR-IOV row on page 1 of the MI300X datasheet. One thing I noticed but didn't touch: on the tech-012 page the extractor treats the FORM FACTOR row (`SH5 Socket | OAM | OAM`) as the header, so rows read `FORM FACTOR: MAX POWER | SH5 Socket: ...`. The values still sit next to their labels, so I don't think it breaks retrieval, but it reads oddly. I can open a separate issue if you'd consider it a bug. ## Linked issue Refs #8407 The issue also asks for a fast, no-model check that runs on PRs, so a stale quote fails where it's edited. I'd like to do that in a second PR, but I'm happy to fold it into this one if you'd rather. ## Changes - tech-012: the quote now matches the current table-row text: `MAX POWER | SH5 Socket: 550W or 760W | OAM: 750W | OAM: 1000W` - tech-023: the quote is now `up to 8 partitions *The MI200 Series`. It starts after the comma, so pypdf's spacing doesn't matter, and it still contains the answer. It runs on into the footnote under that row because the dataset test requires quotes of at least 20 characters, and `up to 8 partitions` alone is 18. ## Test plan - [x] Ran a script (below) that resolves every evidence quote against the extracted text: all 55 in `technical_docs.json` (including the table-tagged items from the bot's list) and the 8 PDF-backed labels in `repo_docs.json` (repo-001 and repo-007 among them). Before: 2 of 55 failed. After: 0 of 55 under pypdf 6.21.1 and 7.1.0, and 0 of 8 for `repo_docs` under 7.1.0. VLM off, pypdfium2 5.15.2. repo-028 is a `.txt`, which the PDF table rewrite doesn't touch, so I didn't scan it. - [x] `python -m pytest tests/unit/eval/test_retrieval_bench.py -q` after the final edit: 77 passed, including the dataset well-formedness test - [x] `python -m pytest tests/unit/eval -q`: 2096 passed, 34 skipped (run before the tech-023 quote changed) - [x] `python util/lint.py --all --fix`: only two Pylint `os.getuid` errors, which are Windows-only and in files this PR doesn't touch. I didn't run the full `tests/unit/` locally since this is a data-only change; CI covers it. - [ ] Not run: the full `gaia eval retrieval --suite full` benchmark. It needs Lemonade and the VLM, which my machine can't run. Could someone confirm it on the release runner? It would also help to know which pypdf version that runner uses. ## Evidence The script isn't a `gaia` subcommand: it's `python scan_labels.py` from the repo root, and the source is in the details block below. Before, on `main` with pypdf 7.1.0: ```text 2 of 55 evidence labels do not resolve tech-012 doc=amd_cdna3_whitepaper page=25 tags=['pdf', 'table', 'spec'] quote : 'MAX POWER 550W or 760W 750W 1000W' page : ...FORM FACTOR | SH5 Socket | OAM | OAM FORM FACTOR: THERMAL | SH5 Socket: Passive and Liquid | OAM: Passive and Liquid | OAM: Passive and Liquid FORM FACTOR: MAX POWER | SH5 Socket: 550W or 760W | OAM: 750W | OAM: 1000W ... tech-023 doc=amd_mi300x_datasheet page=1 tags=['pdf', 'table', 'spec', 'numeric'] quote : 'SR-IOV , up to 8 partitions' page : ...AND VIRTUALIZATION Decoders† JPEG/MJPEG CODEC Virtualization support 4 groups for HEVC/H.265, AVC/H.264, V1, or AV1 32 cores, 8 cores per group SR-IOV, up to 8 partitions *The MI200 Series does not support TF32, FP8, or sparsity* †Video codec acceleration (including at least the HEVC (H.265), H.264, VP9, and AV1 codecs... ``` After, under pypdf 6.21.1 and 7.1.0: ```text 0 of 55 evidence labels do not resolve ``` Other surfaces: N/A, eval data change only. <details><summary>scan_labels.py</summary> ```python """Lists every answer-key quote that no longer matches the indexed PDF text. Run from the root of a gaia checkout, after `gaia eval retrieval --fetch-only`: python scan_labels.py # technical_docs, all PDFs python scan_labels.py --doc amd_cdna3_whitepaper python scan_labels.py --dump scan_out # also write extracted text per doc Does not need Lemonade, an embedder or a VLM (it logs a health-check warning if Lemonade isn't running).. Text comes from the same RAGSDK._extract_text_from_pdf the benchmark indexes with, VLM off, so a quote that lives only in an image shows up here too; check those by hand. """ from __future__ import annotations import argparse import re from pathlib import Path from gaia.eval.retrieval import corpus, sources from gaia.eval.retrieval.locate import DocText, Evidence, LabelError, norm, resolve_evidence def window(doc: DocText, page, quote: str, radius: int = 160) -> str: """Text on the labelled page around the quote's longest word, to compare by eye.""" try: text = doc.page_text(page) if page is not None else doc.text except LabelError as e: return f"(no such page: {e})" for word in sorted(set(re.findall(r"\w{4,}", quote)), key=len, reverse=True): at = text.find(word) if at >= 0: return text[max(at - radius, 0) : at + radius] return text[: 2 * radius] def scan(dataset, texts: dict) -> list: """Resolve every evidence label; return one record per failure (never stops early).""" failures, total = [], 0 for q in dataset.questions: for ev in q.evidence: doc = texts.get(ev["doc"]) if doc is None: continue # not a PDF, or filtered out total += 1 page, quote = ev.get("page"), ev.get("quote") try: hint = 0 if ev.get("near"): hint = doc.text.find(norm(ev["near"])) if hint < 0: raise LabelError("'near' text is not in the document as indexed") resolve_evidence(Evidence(ev["doc"], page, quote), doc, hint) except LabelError as e: failures.append( {"q": q.id, "tags": q.tags, "doc": ev["doc"], "page": page, "quote": quote, "why": str(e), "window": window(doc, page, quote or "")} ) return failures, total def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--dataset", default="technical_docs") ap.add_argument("--doc", action="append", help="only this document id (repeatable)") ap.add_argument("--dump", help="directory to write each document's extracted text to") args = ap.parse_args() sources.set_repo_root(Path.cwd()) dataset = corpus.load_labelled(args.dataset, offline=True) from gaia.rag.sdk import RAGConfig, RAGSDK # imported late: heavy rag = RAGSDK(RAGConfig(use_vlm=False, show_stats=False)) texts = {} for d in dataset.documents: if args.doc and d.id not in args.doc: continue if d.path.suffix.lower() != ".pdf": print(f"[skip] {d.id}: not a PDF ({d.path.suffix})") continue print(f"[extract] {d.id} ...", flush=True) full_text = rag._extract_text_from_pdf(str(d.path))[0] texts[d.id] = DocText.from_full_text(str(d.path), full_text) if args.dump: Path(args.dump).mkdir(parents=True, exist_ok=True) (Path(args.dump) / f"{d.id}.txt").write_text(full_text, encoding="utf-8") failures, total = scan(dataset, texts) print(f"\n{len(failures)} of {total} evidence labels do not resolve\n") for f in failures: print(f"{f['q']} doc={f['doc']} page={f['page']} tags={f['tags']}") print(f" quote : {(f['quote'] or '')[:140]!r}") print(f" page : ...{f['window']}...\n") if __name__ == "__main__": main() ``` </details> ## Checklist - [x] I have linked a GitHub issue above (`Closes #N` / `Fixes #N` / `Refs #N`). - [x] I have described **why** this change is being made, not just what changed. - [x] I ran linting and tests locally (lint, tests/unit/eval; full tests/unit/ left to CI) - [x] I have attached **real-world evidence matched to the surface I changed** (see Evidence above), or marked each surface N/A. - [x] I have updated documentation if user-visible behavior changed (see [CONTRIBUTING.md](../CONTRIBUTING.md)). N/A: eval data only
The release RAG retrieval eval fails on v0.25.1-rc1 and rc2, and has never completed a real run. The v0.25.0-rc17–19 "passes" were
[skip eval]tags. Three latent defects were stacked, each found only after the one before it was fixed:battery.[Page 2]). The benchmark correctly reported "4/59 chunks could not be located". This PR fixes the chunker, not the check. Page citations were never affected.df f = 2048vsdf f= 2048), so each matched only one version. Both now end before the math.A fourth problem, filings dense with no-break spaces overflowing the embedder, is a separate product bug tracked in #5547. The eval records it as a refusal rather than stopping.
Test plan
pytest tests/unit/rag tests/unit/eval tests/test_rag.py,python util/lint.py --all🔍 Technical details
_split_text_into_chunksreplaced each[Page N] ### 🖼️ IMAGE kmatch (which includes its trailing whitespace) with a bare placeholder. The whitespace is now kept after the placeholder. The cache fingerprint is unchanged, so previously cached VLM documents keep their fused chunks until re-indexed. The defect is cosmetic, so forcing everyone to re-index isn't worth it.locate_chunksnow checks for a copy that starts after the chunk before the previous one and runs past the previous chunk's start, and prefers it over a forward match. Old vs new placements on six filings: only the chunks that had jumped to a far-later duplicate moved.