Skip to content

fix(rag): kick background re-indexes for edited files before un-scoped queries - #6942

Closed
rezamuliawijaya wants to merge 4 commits into
amd:mainfrom
rezamuliawijaya:fix/unscoped-query-staleness
Closed

rezamuliawijaya wants to merge 4 commits into
amd:mainfrom
rezamuliawijaya:fix/unscoped-query-staleness

Conversation

@rezamuliawijaya

Copy link
Copy Markdown
Contributor

Summary

query_documents and search_indexed_chunks now start a background re-index for every indexed file whose bytes changed since indexing, and name those files in the response (reindexing_files). The query itself may still serve an edited file's old generation this once — the swap happens when the background re-index finishes, and the next query serves the current text.

Why

#6939 (filed from the #6937 review): the scoped path re-indexes stale files before answering, but the un-scoped paths had no staleness handling at all.

Design notes

  • The kick is non-blocking by construction: each stale file goes through _index_within_budget with a zero budget, which starts the job and returns immediately; a file that is already being indexed rejoins its running job instead of starting a second one.
  • The SDK's own changed-file handling performs the re-index — including delegating to reindex_document with the Re-indexing a large edited document blocks every document query #6911 lock guidance — so no new locking or publishing logic lives in the tool.
  • A whole-library query must not block for minutes behind a large stale file, so this path kicks and reports rather than waiting, unlike the scoped path where the whole answer is about that one file.

Linked issue

Closes #6939

Test plan

  • New tests/unit/rag/test_query_documents_staleness.py — 4 cases: the kick runs and names the file; everything current skips it (no index_document call); search_indexed_chunks kicks too; and an end-to-end case on the real SDK — the first query serves the old text with reindexing_files set, and the next query (after the background job finishes) serves the edited text with no note.
  • Three of the four fail on main (no kick, no field); the current-file case passes trivially.
  • black --check clean.

…d queries

query_documents and search_indexed_chunks served an edited document's old generation until something re-indexed it (amd#6939). Both now start a background re-index for every indexed file whose bytes changed — a zero-budget _index_within_budget start, rejoining a running job when one exists — and name the files whose old generation the query may still serve. The SDK's own changed-file handling performs the swap with the amd#6911 lock guidance, so the next query serves the current text.
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This PR makes whole-library document searches notice files edited since they were indexed: it starts a background re-index and tells the model which files are being refreshed. The idea is right and the end-to-end test is good. Three things need fixing first:

  • Lint will fail. The diff adds a second, identical copy of an existing helper function, and flake8 and pylint both reject the duplicate. Delete the copy.
  • A file that can't be re-indexed breaks unrelated searches. If an indexed file is deleted, locked or fails to index, its background job fails. The next search picks up that failure and returns "Document search failed", even though the search itself was fine. On calls where it doesn't fail, the file is reported as "being refreshed" indefinitely and re-indexed again on every other call. Ignore the outcome of a job this path started, and stop re-kicking a file whose last attempt failed.
  • Every search now reads every indexed file in full. The staleness check hashes every byte of every document before each search. For a library of large PDFs that adds seconds to each query that weren't there before. Use a cheap check (file size and modified time) first, and hash only when those changed.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review alone. I couldn't run the new tests either, because this runner has no pytest, flake8 or pylint installed.

🔍 Technical details

🔴 Duplicate _rag_not_available fails lint (src/gaia/agents/tools/rag_tools.py:259)
It is already defined at :234, and the hunk re-adds it after _kick_stale_reindexes. flake8 F811 and pylint E0102 are both enabled in util/lint.py, so this fails CI. Delete the second def _rag_not_available() and its return line, just below _kick_stale_reindexes.

🟡 Background re-index errors surface in unrelated queries, and failing files are never dropped (rag_tools.py:238-256)
_index_within_budget(..., budget=0) leaves the job in _INDEX_JOBS until some caller finds it done. The next _kick_stale_reindexes call for that path is that caller: job.done.wait(0) is True, the job is deleted, and raise job.error runs. That raise lands inside query_documents' try, at :1065, and comes back as "Document search failed: …". Separately:

  • a deleted or unreadable indexed file stays is_current() == False forever (_content_key returns a _notfound key), so it is re-kicked on every other query
  • it is listed in reindexing_files on every query, even though nothing will ever refresh it
  • a failed {"success": False, "error": …} result is silently dropped, which goes against Fail Loudly

Fix: in the kick path, don't let _index_within_budget re-raise. Either reap finished jobs separately or catch the job's error and log it with context. Report files whose last re-index failed under their own key (e.g. reindex_failed) instead of reindexing_files, and don't re-kick them until their bytes change again. Add a test where the indexed file is deleted after indexing and two consecutive queries both succeed.

🟡 Full-content hash of the whole library on every query (rag_tools.py:252-253)
RAGSDK.is_current → _content_key reads every byte of the file (sdk.py:1132-1138). The loop runs it over every rag.indexed_files entry before each query_documents and search_indexed_chunks, on the foreground thread. That makes query cost scale with total library size on disk. Gate it with a stat check: record (st_size, st_mtime_ns) at index time and hash only when that changed. Or do the check in the background thread. One caveat: the PR's own end-to-end test deliberately keeps mtime unchanged (_write_keeping_stat), so a stat-only gate would need that test reconsidered. A cached stat plus a periodic full hash is one option.

🟢 Mock tests race the background thread (tests/unit/rag/test_query_documents_staleness.py:88,121)
With budget=0, index_document runs on a thread that may not have reached the call by the time rag.index_document.assert_called_once() runs. Wait on the job first, e.g. poll documents_still_indexing(rag) until it is empty, or patch _index_within_budget and assert on its call.

🟢 The model gets a field but no instruction (rag_tools.py:1044)
reindexing_files is added, but the instruction doesn't tell the model what to do with it. Smaller models tend to ignore unexplained fields, so the user won't hear that the answer may reflect the old version. Add one sentence to the instruction when the list is non-empty.

Strengths

  • It reuses _index_within_budget's job dedup and the SDK's existing changed-file re-index, so no new locking or publish logic lives in the tool.
  • The real-SDK test proves the behaviour a user would see: old text once, flagged, then new text with no flag.

…ct the model

Review follow-ups on amd#6939: the staleness kick gates on the stat recorded at index time (stored in file_stat_keys at publish and cleared on removal), hashing a file only when its stat changed; a kick job's error is logged and the file is reported under reindex_failed instead of surfacing in unrelated searches, and a failed file is not re-kicked until its bytes change again; the responses carry an instruction telling the model those files are being refreshed and may be reflected in their previous version.
@github-actions github-actions Bot added rag RAG system changes performance Performance-critical changes labels Nov 7, 2026
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Two of the three blockers are fixed: the duplicate helper is gone, and searches now hash a file only after its size or modified time changes. One is only half fixed.

🟡 A file that won't re-index is still reported as "being refreshed" forever. The new failure tracking only sees errors that are raised. The document library reports most failures (a locked file, a file emptied after indexing, an unsupported type) as a "not successful" result instead. Those files are never marked failed. They are shown as re-indexing on every search and re-indexed again on every other one. Treat a "not successful" result the same as a raised error.

🟡 The new failure tests depend on timing. They expect the very first search to report the failure. That only happens if the background thread finishes before the search checks on it, so on a busy CI runner they will fail at random.

🔍 Technical details
  • rag_tools.py _kick_stale_reindexes: _result from _index_within_budget(rag, path, budget=0) is discarded. A reaped job whose result.get("success") is falsy goes to reindexing, not _KICK_FAILURES. RAGSDK.index_document returns stats with success: False for an empty file, a locked file (PermissionError from _content_key(..., raise_locked=True)), an unsupported type and a failed remove. Record failures[path] and log result.get("error") in that case too.
  • The job is reaped, and its outcome seen, only on the next kick. On the first query job.done.wait(0) is usually False, so the file goes to reindexing. test_a_failed_reindex_is_reported_without_breaking_the_query and test_a_deleted_indexed_file_does_not_break_searches assert reindex_failed == ["doc.txt"] on that first call, which passes only if the thread wins the race. The first import of gaia.daemon.broker_client inside _run makes losing it likely. Either assert reindexing_files on the first call and reindex_failed on the second, after _wait_no_jobs, or reap finished jobs before the kick loop.

@rezamuliawijaya

Copy link
Copy Markdown
Contributor Author

All five review items are fixed in 7bcb55b:

  • Duplicate _rag_not_available — the second copy is gone; the module defines it once.
  • Background job failures — the kick catches the job's error and logs it; failed files move to reindex_failed in the response and are not re-kicked until their bytes change again (tracked per stat), and a deleted indexed file reports reindex_failed on consecutive queries while both searches succeed (test_a_deleted_indexed_file_does_not_break_searches).
  • Hash cost — the SDK now records (st_size, st_mtime_ns) at publish (file_stat_keys, cleared on removal), and the kick stats each file first: the content hash only runs when the stat changed. The e2e test now uses a plain (mtime-changing) edit — the same-size/restored-mtime case remains covered end to end by the scoped path in fix(rag): re-index a stale file before a file-scoped query serves it #6937.
  • Mock races — the kick tests wait on documents_still_indexing before asserting.
  • Instruction — both responses append a sentence naming the files being re-indexed and the ones that failed, so the model tells the user the answer may reflect the previous version.

6/6 in the new file, 41 passed across the neighbouring rag suites, black clean.

…ilures stably

Review round-2 follow-ups: finished kick jobs are reaped before the kick loop so their outcomes are seen on the next query (a not-successful result records a failure like a raised one); the staleness check is gated on the stat recorded at index time (file_stat_keys, populated at publish and cleared on removal) so a query hashes a file only after its size or mtime changed; a deleted indexed file reports reindex_failed on consecutive queries without breaking them and without starting a kick; and the tests tolerate the scheduling race between starting a job and checking on it.
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Both earlier findings are fixed: a "not successful" result now counts as a failure, and finished jobs are collected before the check, so the first search no longer races the background thread.

🟡 A file that fails to re-index is now listed twice. On the search after the failure, the file is added to the failed list once when its finished job is collected, then again when the loop sees the same failed bytes. The model is told "could not be re-indexed: doc.txt, doc.txt", and the new failure test's second-call check should fail on every run. Count each file once.

🔍 Technical details

rag_tools.py _kick_stale_reindexes: the reap block calls _record_failure(path, _safe_stat(path), …), which stores failures[path] = "size:mtime" and appends the name. The loop over rag.indexed_files then hits failed_stat == f"{st.st_size}:{st.st_mtime_ns}" for the same path and appends it again. test_a_failed_reindex_is_reported_without_breaking_the_query asserts second.get("reindex_failed") == ["doc.txt"], which this gives as ["doc.txt", "doc.txt"]. The third call is fine. Fix: in the reap block, record failures[path] and log without appending (the loop then reports it), or collect failed as a set and return sorted(failed). I couldn't run pytest on this runner, so this comes from reading the code.

Review round-2: the reap pass recorded the failure and appended the name, and the loop then appended the same name again when it matched the recorded failed stat. The reap now records and logs without reporting; the loop reports each failed file exactly once.
@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 performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

query_documents serves an edited document's old text until it is re-indexed

2 participants