Skip to content

fix(rag): re-index a stale file before a file-scoped query serves it - #6937

Closed
rezamuliawijaya wants to merge 5 commits into
amd:mainfrom
rezamuliawijaya:fix/scoped-query-staleness
Closed

rezamuliawijaya wants to merge 5 commits into
amd:mainfrom
rezamuliawijaya:fix/scoped-query-staleness

Conversation

@rezamuliawijaya

Copy link
Copy Markdown
Contributor

Summary

query_specific_file now checks is_current once per call before searching. When the file's bytes changed since indexing, it re-indexes with the same foreground budget the index_document tool uses: a file that finishes in time is served current; one still indexing reports "in progress"; a failed re-index reports the error instead of serving stale text.

Why

#6932: a file-scoped query searched file_to_chunk_indices and the cached per-file index without any staleness check, so an edited document kept answering with its old text indefinitely — the re-index from #6911 only runs when something triggers it, and this path never did. The audit confirmed the gap and recommended exactly this direction (the index tool's own budgeted re-index, once per call, is_current hashing outside _state_lock so it does not contend with indexing) — implemented here pending @kovtcharov-amd's product call.

Linked issue

Closes #6932

Changes

  • query_specific_file (rag_tools.py): after target_file resolves and before the search keys are generated, a stale file re-indexes via _index_within_budget; budget exhaustion returns _indexing_in_progress(job), and a failed re-index returns an error naming the file and the SDK's error. A current file skips the re-index entirely.
  • The guard runs once per call, not per search key.

Test plan

  • New tests/unit/rag/test_scoped_query_staleness.py — 4 cases: stale file re-indexes and serves current text; current file skips the re-index (index_document not called); a slow re-index reports in_progress (0.2 s budget fixture, call returns within the 5 s deadline); a failed re-index reports the error.
  • The whole file fails on main (no guard, stale text served) — verified by stashing the source change.
  • tests/unit/rag/test_background_indexing.py + test_keyword_search_tools.py (the neighbouring tool-budget suites) — 8 passed; black --check clean.

query_specific_file resolved the target and searched its cached chunks without checking whether the file's bytes changed since indexing, so an edited document kept answering with its old text on every file-scoped query. The tool now checks is_current once per call and, when the file is stale, re-indexes it with the same foreground budget the index tool uses — a file too big to finish reports 'in progress' instead of serving stale text, and a failed re-index reports the error. Follows the audit's recommended direction on amd#6932, pending the maintainer's product call.
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Asking about one specific document now re-reads that document first if it was edited since it was indexed, so the agent stops answering from the old text. The fix is small, uses the same time budget and "still indexing" reply as the index tool, and comes with tests for each outcome.

One thing to fix before merge: when the re-index fails, the user gets a raw error instead of the specific advice the code right above already gives. "Close the file in the program that has it open" and "the embedding model isn't available" both get lost. A document someone has open in Word to edit is exactly the case this change now hits, so please reuse those two existing helpers.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change sits inside an agent tool and is covered only by mocked unit tests, so the verdict rests on static review. No live agent query against an edited document was run.

🔍 Technical details

Issues

🟡 The re-index failure drops the actionable error types (src/gaia/agents/tools/rag_tools.py:1194)
The auto-index branch at :1141-1146 sends embedding_unavailable to _index_embedding_error and _CACHE_LOCK_HINTS errors to _index_cache_error. The new branch collapses both into "Re-indexing X failed: <raw error>". Before this PR, a locked file (Word holds a lock on an open .docx) still answered from the old index. Now it fails with no remedy. Failing loudly is right here, but the error should still tell the user what to do.

                    if not result.get("success"):
                        if result.get("error_type") == "embedding_unavailable":
                            return _index_embedding_error(result)
                        if result.get("error_type") in _CACHE_LOCK_HINTS:
                            return _index_cache_error(result, str(target_file))
                        return {

Add a test case with error_type set to one of the lock hints.

🟡 Follow-up: un-scoped query_documents still serves an edited file's old text
query_documents and search_indexed_chunks have no is_current check. Issue #6932 notes the un-scoped path has the same shape. That's fine to leave out of this PR, but please file it (suggested title: "query_documents serves an edited document's old text until it is re-indexed") so it isn't lost.

🟢 Evicted documents aren't forgotten after a re-index (rag_tools.py:1191)
Both the index tool (:1755) and the auto-index branch (:1111) call _forget_evicted(self.indexed_files, result.get("evicted", [])) on success. If a re-index grows a document past the library cap, the evicted document stays in self.indexed_files, and the next index_document for it skips indexing (:1731). Calling _forget_evicted on success here would close that gap.

🟢 The comment is too long and cites the issue (rag_tools.py:1185-1189)
Per CLAUDE.md's comment rule, one line is enough, and issue numbers belong in the commit:

                # An edited file re-indexes first so the answer never uses old text.

🟢 Every scoped query hashes the whole file
is_current reads every byte, so a large PDF is re-hashed on every query_specific_file call, and twice right after an auto-index. This is acceptable for correctness. Worth keeping in mind if scoped-query latency on big documents comes up.

Tests: all four cases use a MagicMock RAG, so they prove the guard is wired in, not that a real edited file gets caught. The issue describes a deterministic real-SDK test (_write_keeping_stat, a same-size edit with the mtime restored). Adding it would cover the contract end to end.

Strengths

  • Reuses _index_within_budget / _indexing_in_progress rather than adding a new waiting mechanism, so a slow re-index behaves exactly like a slow first index.
  • The check sits once per call, after path resolution and before the search-key loop, which is the right place.
  • The tests cover all four outcomes (stale, current, slow, failed) and bound each call with a deadline, so a hang fails instead of stalling CI.

Review follow-ups: a scoped-query re-index failure now routes through the same helpers the index tool uses — embedding_unavailable and cache-lock errors keep their specific advice instead of collapsing into a raw error — and a successful re-index forgets documents the library evicted so a later index_document for them does not skip. The guard comment is shortened.
…eal SDK

The review asked for the issue's deterministic case: a same-size edit with the mtime restored defeats timestamp checks, and the scoped query re-indexes inside its budget and serves the edited text instead of the old one. Fails on main, passes with the guard.
@rezamuliawijaya

Copy link
Copy Markdown
Contributor Author

Added the end-to-end case the review asked for (test_a_real_sdk_serves_the_current_text_after_a_same_size_edit, now in the PR): a same-size edit with the mtime restored defeats timestamp checks, and a scoped query on the real SDK re-indexes inside its budget and serves the edited text. It fails on main and passes with the guard. This should close the last review item.

kovtcharov-amd added a commit that referenced this pull request Nov 7, 2026
A failed re-index during a search now returns the index tool's own advice
(start the embedder, wait for the busy document cache) instead of a generic
failure. A file left out of a library search no longer takes an unchanged
file's identical chunk with it: chunks are filtered by the file that owns
them, not by their text.

Adds the end-to-end same-size edit test from #6937.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Thank you for this, and for filing #6932 and #6939! #6947 has merged and fixes the stale-text bug on all three search paths. It brings in your work: the file-scoped fix, the specific error advice and your end-to-end test (#6937), plus the cheap stat check before hashing (#6942). You're credited as co-author on the commit. It builds the new version without holding the index lock, so other queries keep answering during a re-embed. That's why it went in instead of this branch.

kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Nov 7, 2026
…md#6947)

If you edited a document after indexing it, document search kept
answering from the old text, across the whole library and for a single
file, until something re-indexed it. Now each search checks the files it
covers and re-indexes any edited file before answering. If a file can't
be served up to date, the search leaves it out and says why, with the
same fix-it advice the index tool gives (embedder down, document cache
locked). It never quietly serves the old text.

Closes amd#6939, closes amd#6932

Builds on @rezamuliawijaya's work: amd#6937 (the file-scoped re-index, the
kept error advice, and the same-size end-to-end test) and amd#6942
(checking the file's stat before hashing it).

## Test plan
- [ ] `python -m pytest tests/unit/rag/test_query_staleness.py
tests/unit/rag/test_edited_document_reindex.py`. The bug-reproduction
tests fail on `main` for the library-wide, file-scoped and exact-text
searches, and pass here.
- [ ] In `gaia chat`, index a text file and ask about it. Edit the file,
ask again, and the answer reflects the edit with no re-index request.
- [ ] Ask the same question twice about an unchanged file. The second
answer comes back as fast as the first and nothing re-embeds.
- [ ] Delete an indexed file and ask about it. The agent says the file
no longer exists instead of quoting it.
- [ ] Eval: this changes the tool results the model sees (new
`files_left_out` field, `in_progress` / `error` for stale files). Tool
docstrings are unchanged. Re-run `rag_quality` and `gaia_rag` on the
next RC.

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

- **Cheap check:** `RAGSDK.freshness(path)` returns `current` /
`changed` / `missing` / `locked` / `unreadable` / `not_indexed`. It uses
a stat recorded at index time (size, mtime, inode, plus ctime on POSIX)
and hashes only when that stat changed, or when the file was written
within 2 s of being recorded. The 2 s rule covers the same-tick rewrite
that would otherwise fool the stat. Limitation: on Windows, which has no
change time, an edit that restores both size and mtime more than 2 s
after indexing passes the stat check. An explicit `index_document` still
catches it, because that path always hashes.
- **No global lock during the re-embed:** `index_document` on an edited
file no longer goes through `reindex_document`. It builds the new
generation outside `_state_lock` and swaps it in through the existing
`_drop_other_generation` publish step. The old text keeps serving until
the swap and stays if the re-index fails. A test probes the lock from
another thread mid-embed. `reindex_document` itself (the file-watcher
path) still holds the lock, so amd#6911 stays open for that path.
- **Budget:** edited files re-index through `_index_within_budget` and
share one 30 s deadline (`QUERY_REINDEX_BUDGET_S`) across the set.
- **What the model sees:**
- A file-scoped search on a file still re-indexing returns
`in_progress`.
- A failed re-index returns the index tool's own result:
`_index_embedding_error` (with `next_step`) or `_index_cache_error`
(with `hint`), or otherwise an `error` naming the cause.
  - A deleted or locked file returns `error`.
- Library-wide searches drop that file's chunks by owner (vector hits
through `_search_chunks`' indices, keyword hits and the small-index
"whole index" path through `chunk_to_file`). An unchanged file with an
identical chunk keeps it and is cited as the source. The skipped file is
listed in `files_left_out` (including any `error_type` and next step)
and named in the instruction. If every file is left out, the search
returns `error` / `in_progress`.
- **Adversarial tests:**
- An unchanged file is never re-embedded, whether recently written or
aged.
  - An aged unchanged file is never even hashed.
  - A touched but unchanged file is hashed once, then trusted.
  - Deleted, locked and failed re-index files are not served.
  - A failed re-index keeps the embedder or cache-lock advice.
  - A twin chunk in an unchanged file survives its left-out copy.
  - A slow re-index returns `in_progress` within the deadline.
- **Overlap:** besides amd#6937 and amd#6942, amd#6917 (lock-free re-index) and
the amd#6936 autofix cover parts of this. This PR covers all three search
paths in one change.
- **Regression run:** the RAG suites (`tests/unit/rag`,
`tests/test_rag.py`, the RAG tool, resolution, status, citation, cache
and library tests, `test_chat_reindex_locked.py`) pass with a temp HOME
after merging `main`. The earlier broad run also covered
`tests/unit/agents`, `tests/unit/chat/ui` and
`hub/agents/gaia/python/tests`. In that long combined run, some logging
and slot tests failed depending on test order. All 312 pass when their
files run alone. Black, isort and flake8 (repo settings) are clean on
the changed files.
</details>

Co-authored-by: rezamuliawijaya
<[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A file-scoped document query keeps serving an edited file's old text forever

2 participants