Skip to content

fix(rag): resolve the exact indexed file instead of the first substring hit - #4613

Merged
kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:kalin/rag-exact-file-match
Oct 4, 2026
Merged

kovtcharov-amd merged 2 commits into
amd:mainfrom
kovtcharov:kalin/rag-exact-file-match

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Asking about report.pdf with q3_report.pdf also indexed could answer from the wrong document, with no sign anything was off — the per-file tools took the first substring match from an unordered set. Now an exact path or filename match wins, and when a request still matches several indexed files the tool returns an "Ambiguous filename" error listing the candidates, so the model retries with a full path instead of guessing. Applies to per-file query, summarize, and dump.

Test plan

  • pytest tests/unit/test_rag_file_resolution.py — exact match beats substring, true ambiguity returns the error with candidates, a single substring match still resolves (12 tests)
  • pytest on every tests/unit file importing rag_tools — 475 passed, 15 skipped
  • black, isort, pylint (repo config) clean on the touched files
  • gaia eval agent --category rag_quality on AMD hardware — required because this changes tool results the LLM sees; not run (no AMD hardware available)

…ng hit

Asking about report.pdf could answer from q3_report.pdf: query_specific_file,
summarize_document and dump_document substring-matched the request against the
index and silently took whichever match came first (from an unordered set).

Files now resolve by exact path, then exact filename / trailing path
components, then substring. If more than one indexed file still matches, the
tool returns an "Ambiguous filename" error with a candidates list so the model
retries with a full path instead of guessing.
@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes tests Test changes agents labels Oct 4, 2026
@github-actions

github-actions Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this PR, asking about report.pdf while q3_report.pdf was also indexed could quietly answer from the wrong document. Now the per-file query, summarize and dump tools prefer an exact match. When a name still fits several files, they return an "ambiguous" error that lists the candidates. The logic is correct and replaces a silent guess with a clear error. I found no blocking bugs.

Two things to close out before or soon after merge:

  • Run the RAG eval. The model now sees a new error shape and fewer silent picks. The PR's own test plan leaves gaia eval agent --category rag_quality unchecked. Run it on AMD hardware before relying on this in a release.
  • Add one summarize test. Summarize got the same ambiguity handling as query and dump, but it's the only one of the three with no test.

Real-world evidence

N/A: the evidence bundle wasn't produced for this run. The change is internal to the RAG tools, and its only user-visible effect needs real inference (the strix-halo lane). The verdict rests on static review alone. I couldn't run the new tests here either, because pytest isn't installed in the review environment.

🔍 Technical details

Issues

🟡 LLM-facing tool results changed, eval not run (src/gaia/agents/tools/rag_tools.py:667, :680, :1464, :1790)
Every ambiguous request now gets the _ambiguous_file_error dict instead of the first match. A bare stem like report also errors when report.pdf and q3_report.pdf are both indexed, because both only match at the substring tier. That's the right behaviour, but it changes what the model has to recover from. CLAUDE.md asks for gaia eval agent --category rag_quality on this kind of change.

🟢 No test for summarize_document ambiguity (tests/unit/test_rag_file_resolution.py)
query_specific_file and dump_document are covered; summarize_document (rag_tools.py:1464) isn't. A single test mirroring TestDumpDocument would lock it in.

🟢 Redundant second ambiguity check (rag_tools.py:667 and :680)
Inside the if not matching_files: branch, the new if len(matching_files) > 1 returns early. Then the same check runs again right after the branch. The second check alone covers both paths, so the inner one can go. It's harmless, just duplicated.

Edge cases I checked (all fine)

  • Auto-index re-match: resolved comes from os.path.realpath, so it's a str, and _path_parts won't get a Path. The exact tier selects the newly indexed file before the basename query can add other same-name files.
  • Absolute-path guesses: a guess like C:\Users\foo\doc.md still reaches the basename fallback, because the suffix tier compares every query component and won't match. That keeps the fallback meaningful.
  • Empty file_path: it now resolves to "not found" instead of matching every file through "" in f. That's an improvement.
  • Candidate order: candidates are sorted, so the error text and candidates are deterministic. The old code picked from a set, so its choice was effectively random.

Strengths

  • One tiered resolver replaces three slightly different inline matchers, so the three tools can no longer drift apart.
  • It follows the fail-loudly rule: the old TODO: Let user disambiguate silent pick is gone, and the error gives the model the exact candidates to retry with.
  • The tests assert which file was actually searched (via _retrieve_chunks_from_file call args), not just that a call happened.

The ambiguity check after the not-found branch already covers the auto-index path, so the inner copy went.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

The RAG eval still needs a run on AMD hardware before this ships in a release: the model now gets an "ambiguous file" error with candidates where it used to get a silent first match, and that can't be scored locally.

🔍 Technical details
  • Rerun gaia eval agent --category rag_quality on the strix-halo lane, plus any other document-Q&A category, and check scenarios that name a file by a bare stem.
  • No committed flagship baseline exists yet, so read the scorecard for INFRA_ERROR or a sharp drop on file-scoped questions rather than a regression diff.
  • The summarize test and the duplicate-check cleanup are in the latest commit.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 4, 2026
Merged via the queue into amd:main with commit 418dc8d Oct 4, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/rag-exact-file-match branch October 4, 2026 16:24
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 5, 2026
File tools now all check the same allowed-folders rule. Before,
`read_file` and `write_file` checked a path against the session's
allowed folders (asking the user when it was outside), but several
neighbouring tools did not: folder browsing and directory search, recent
files, document and code indexing, folder watching, `list_files`, and
the paths screenshots, transcripts, speech and exports are saved to. Now
every one goes through the same check and the same approval prompt, so a
chat scoped to its documents behaves the same whichever tool the model
picks.

- **One rule, not a second one.** Tools call the existing
`PathValidator.validate_read` / `validate_write` through a thin helper.
The validator now expands `~` before resolving symlinks and `..`, so it
judges the path the tool actually opens.
- **Approving a folder now covers document indexing too.** The chat
agent's RAG SDK kept a separate validator, so a folder approved in the
chat was still refused at indexing time. It now shares the agent's.
- **Wider on purpose, and documented:** name search over the common
document folders (it returns paths only, and opening one is checked),
GAIA's own output folders, and `capture_skill`, which asks the user on
every call.

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

- Helper: `gaia.agents.tools.path_access` (`read_access_error`,
`write_access_error`, `readable_entry`). Folder walks call
`readable_entry` per file, which never prompts.
- Model-visible changes: refusal text from these tools is now the
validator's standard message, `list_recent_files` reports
`locations_not_searched`, and `search_directory` with no root searches
the allowed folders instead of the whole home folder. No tool docstrings
changed.
- Overlap with amd#4642: both PRs add the same `~` expansion to
`browse_directory`, `get_file_info`, `analyze_data_file` and
`search_file_content`, with identical lines, so either merge order
applies cleanly. Merging amd#4642 first is the simplest order.
- Nearby open PRs: amd#4613 and amd#4648 (`rag_tools.py`), amd#4644
(`code_index_tools.py`), amd#4626 (`filesystem_tools.py`), and amd#4647
(flagship CHANGELOG). Their hunks don't overlap these, but whichever
lands second may need a trivial rebase.
</details>

## Test plan
- [x] `pytest tests/unit/test_file_tools_allowed_folders.py
hub/agents/chat/python/tests/test_chat_file_tools_allowed_folders.py`:
66 tests. For each tool, a path outside the allowed folders (direct,
through `..`, and through a symlink) goes through the approval prompt
and is refused, and a path inside still works. 41 of them fail on main.
The ChatAgent tests live in the chat package, so the chat-agent lane
runs them; the core unit lane has no `gaia_agent_chat`.
- [x] Existing file, RAG, audio, screenshot, code-index, security and
chat-agent unit tests pass. The two local failures
(`test_persisted_grants_are_not_unioned_into_a_host_scope`,
`test_backups_directory_is_owner_only`) also fail on main on this
machine.
- [x] black, isort, flake8 and pylint are clean on the changed files.
- [ ] Follow-up after the core release that ships `path_access`: raise
the chat and flagship `amd-gaia` floors to it, as the chat CHANGELOG
records.
- [ ] CI eval re-run, since refusal text and the default search scope
are model-visible: `gaia_files`, `gaia_core`, `gaia_data`,
`tool_selection`.

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
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.

2 participants