Skip to content

Fix: fix(rag): query_documents ranks any keyword hit above every semantic match, and slows down at scale - #8737

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
SIDDARTHAREDDY8:oss-bhai-2026-11-21-p1
Nov 21, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
SIDDARTHAREDDY8:oss-bhai-2026-11-21-p1

Conversation

@SIDDARTHAREDDY8

@SIDDARTHAREDDY8 SIDDARTHAREDDY8 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixed amd/gaia #4737 in both query_documents and query_specific_file. The fixed 0.6-0.8 keyword boost (which outranked every dense score, typically 0.3-0.6) is replaced by reciprocal rank fusion (k=60) in shared helpers _fuse_dense_and_keyword / _fuse_extra_scores / _adaptive_max: each ranking contributes 1/(k+rank), so the top dense and top keyword matches compete on equal terms and a chunk both rankings like wins outright.

Why

A keyword hit ranked above every semantic match, so retrieval returned lexically matching but semantically weaker chunks first, and the ranking slowed down at scale.

Linked issue

Fixes #4737

Changes

Test plan

  • New tests/unit/rag/test_query_keyword_fusion.py: 10 passed (incl. a new test that relevance_score stays in 0-1) (fusion order, keyword hit no longer outranks top dense match in both tools, chunk both rankings like wins, keyword pool covers all slots, debug indices).
  • Related suites pass: test_keyword_search.py, test_keyword_search_tools.py, test_query_balances_documents.py (incl. multi-document spread/budget), test_retrieval_bench_harness.py, test_lemonade_reranking.py (47 passed).
  • Full tests/unit/rag/: 791 passed, 58 failed, 52 skipped; the 58 failures are all pre-existing in untouched epub/html/image extraction modules (verified: failure list with the fix was identical to pristine main before dep installs; remaining are env/library issues, e.g. pixel-value assertion in image extraction).
  • Black + isort pass on both changed files (repo pyproject config).
  • Eval category to watch on the next RC: rag_quality (this change alters which passages fill the context).
  • The rag_quality eval and gaia eval retrieval --suite full could NOT be run here: they need the Lemonade embedding server/models, unavailable in this VM. Closest runnable proxies passed: the retrieval bench harness (both pipelines find labelled evidence) and the new tests, which directly assert the reported failure mode (keyword hit above every semantic match) is gone.

Evidence

  • Agent exposed in the Agent UI (Chat, Email, ...) — N/A: this change touches internal RAG ranking logic only, no Agent UI surface.
  • MCP tools / servers — N/A: no MCP surface changed.
  • CLI — N/A: no CLI surface changed; the gaia eval retrieval CLI could not run here (needs the Lemonade embedding server/models, unavailable in this VM).
  • HTTP API / REST — N/A: no HTTP API surface changed.
  • Evidence for this internal change: the new fusion tests directly assert the reported failure mode is gone, and the retrieval bench harness passes (both pipelines find labelled evidence).

Checklist

  • I have linked a GitHub issue above (Closes #N / Fixes #N / Refs #N).
  • I have described why this change is being made, not just what changed.
  • I have run linting and tests locally (python util/lint.py --all, pytest tests/unit/).
  • I have attached real-world evidence matched to the surface I changed (see Evidence above), or marked each surface N/A.
  • I have updated documentation if user-visible behavior changed (see CONTRIBUTING.md).

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

The ranking fix is sound: keyword matches now compete with meaning-based matches instead of always winning, and both search tools get it. One side effect needs fixing before merge. The new scores are tiny (about 0.02 to 0.03), and they still go out as each passage's "relevance" score. The model now sees every passage scored near zero, and the Agent UI's sources panel shows 0.02 beside every chunk.

  • Scores near zero: keep the new scores for ordering, but report a score on a 0–1 scale, either the meaning-match score or the fused score rescaled.
  • Stale spec: the RAG tools spec still documents the old fixed keyword boost and the dedupe step. Update it in the same change.
  • Eval not run: this changes which passages the model reads, and the rag_quality eval couldn't run here. Name rag_quality in the PR as the category to watch on the next RC.

Real-world evidence

N/A: no evidence bundle was produced for this PR (internal ranking change, and inference is deferred to the strix-halo lane). The verdict rests on static review alone. I couldn't run the new tests here because pytest isn't installed on this runner.

🔍 Technical details

🟡 Fused RRF score is reported as relevance_score (src/gaia/agents/tools/rag_tools.py:1637, :2133)
sorted_items now carries 1/(60+rank) sums, so the top chunk scores at most 2/61 ≈ 0.033. That value flows unchanged into:

  • relevance_score on every chunk the model reads, and debug_info["score_distribution"]
  • sse_handler.py:1081, which rounds it to 0.02/0.03; AgentActivity.tsx:1203 renders that as the chunk badge

Before this PR those fields held dense similarities (0.3–0.6) or keyword boosts (0.6–0.9). The smallest fix is to rescale inside _fuse_dense_and_keyword and _fuse_extra_scores, so a chunk ranked first by both lists scores 1.0. The ordering doesn't change. One fix covers both tools:

    return sorted(
        ((chunk, score * (_RRF_K + 1) / 2) for chunk, score in fused.items()),
        key=lambda item: (
            -item[1],
            -dense_scores.get(item[0], 0.0),
            ranks.get(item[0], len(keyword) + 1),
        ),
    )

Apply the same * (_RRF_K + 1) / 2 to fused in _fuse_extra_scores, and update test_extra_scores_rank_after_the_dense_list's 1/66 / 1/67 expectations. The alternative is to report the dense score where one exists. Either way, add a test that relevance_score stays in a 0–1 range.

🟡 Doc drift: docs/spec/rag-tools-mixin.mdx:517-528
The "Hybrid Search Architecture" snippet still shows all_scores.append(boost_score) ("five best matches … scored 0.6-0.9") and the hash-based dedupe that keeps the higher score. Both are gone now. Lines 30, 99 and 218 ("Keyword boost for exact term matches") should become "fused with the semantic ranking by reciprocal rank fusion".

🟡 Eval coverage (LLM-affecting retrieval path)
This changes which chunks fill the context in query_documents and query_specific_file. List rag_quality in the PR body as the category to watch on the next RC. A retrieval change was the cause of #1030.

🟢 Debug counts no longer list keyword chunks (rag_tools.py:1513-1521, :2023-2031)
total_chunks_before_dedup now adds len(keyword_chunks), but chunks_before_dedup_indices covers only all_chunks. The count and the list disagree (the test pins 3 against [0, 1]). Either append the keyword chunks' indices or say in the field name that the list covers dense results only.

Sibling paths checked: both tools that had the boost (query_documents, query_specific_file) are converted. _spread_over_documents and top_or_whole_index work on order alone, so they're unaffected. The whole-index fill's 0.0 scores are still hidden by the UI's > 0 check.

Strengths

  • RRF is the right fix for mixing two scores on different scales. The tie-break toward the better dense score keeps the semantic top-1 stable.
  • _adaptive_max removes the duplicated tier ladder, and the keyword pool now fills every slot, a real recall gain on large libraries.
  • The tests assert the reported failure directly, in both tools, including a chunk that both rankings like.

@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes labels Nov 21, 2026
@SIDDARTHAREDDY8

Copy link
Copy Markdown
Contributor Author

Addressed the review in 31b1bb3 (stacked on fce6ccf): fused scores are now rescaled by (k + 1) / 2 in both _fuse_dense_and_keyword and _fuse_extra_scores, so a chunk ranked first by both lists scores 1.0 and relevance_score stays on a 0-1 scale (ordering unchanged); docs/spec/rag-tools-mixin.mdx now documents rank fusion instead of the old fixed boost; chunks_before_dedup_indices now lists the keyword chunks too. Added a test asserting the 0-1 range; test_query_keyword_fusion.py is 10/10, black + isort clean. Also named rag_quality in the PR body as the category to watch on the next RC. The rag_quality eval itself still could not run here (needs the Lemonade server/models).

Signed-off-by: SIDDARTHA REDDY <[email protected]>
Signed-off-by: Siddartha Reddy Chinthala <[email protected]>
…te spec (amd#4737)

Fused RRF scores topped out at 2/61 (~0.03) but were reported unchanged
as relevance_score, so the model and the Agent UI saw every passage
scored near zero. Rescale by (k + 1) / 2 in both fusion helpers so a
chunk ranked first by both lists scores 1.0 (ordering unchanged);
update the spec, which still documented the old fixed keyword boost
and hash dedupe; list keyword chunks in chunks_before_dedup_indices
so the list matches total_chunks_before_dedup; add a test that
relevance_score stays in 0-1.

Signed-off-by: SIDDARTHA REDDY <[email protected]>
Signed-off-by: Siddartha Reddy Chinthala <[email protected]>
@kovtcharov-amd
kovtcharov-amd merged commit 1f47ded into amd:main Nov 21, 2026
45 of 68 checks passed
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Rank fusion is such a clean fix for this, and that turnaround on review was impressive. Thank you @SIDDARTHAREDDY8!

kovtcharov-amd added a commit that referenced this pull request Nov 21, 2026
…8745)

The release RAG retrieval benchmark has failed on every tag since
v0.26.0-rc26 because a single stale evidence label aborted the whole run
about eleven questions in, leaving most of the benchmark (technical
docs, XQuAD, the scale tiers, the hard cases) unmeasured. Now a bad
label is recorded against its own question while the run carries on, so
one stale quote can no longer hide everything after it, and the job
still fails at the end when any label error occurred. The two stale
quotes themselves are fixed in #8755.

<details>
<summary>🔍 Technical details</summary>

- A question with a label error is left out of the scores, listed in
`results.json` (`label_errors` per dataset and in `meta`) and under
**Label errors** in the report, and `gaia eval retrieval` exits 1. Any
other exception still aborts the run. Scale tiers get the same handling;
a tier where every label fails is reported instead of crashing on its
summary line.
- The report, the harness docstring and `docs/reference/eval.mdx` no
longer describe the agent path as a "keyword boost"; it has used rank
fusion since #8737.
</details>

## Test plan
- [x] `pytest tests/unit/rag/test_retrieval_bench_harness.py
tests/unit/eval/test_retrieval_bench.py` (new: a bad label mid-dataset,
every label bad, a label on a missing page, a non-label failure still
aborting, scale tiers with some/all bad labels, report section, CLI exit
code)
- [ ] After merge (with #8755): dispatch `eval_retrieval.yml` on main
and confirm it runs through every dataset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(rag): query_documents ranks any keyword hit above every semantic match, and slows down at scale

2 participants