Skip to content

fix(chat): retry a watched document another program has open - #5458

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/chat-reindex-locked-retry
Oct 21, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/chat-reindex-locked-retry

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

On Windows, a watched document that another program held exclusively, or had partly locked, was tried once and never reindexed, so chat kept answering from the old copy. Indexing a locked Word, PowerPoint or Excel file directly was worse: it was reported as corrupted, with advice to re-download it. The file watcher already retries a locked file, but the chat agent caught every error itself, and RAG reported a locked read as a plain failure, so that retry never ran. Now a locked watched document is retried 1, 2 and 4 windows later, including one saved by renaming a temp file onto it. After the third retry the watcher gives up and logs one error telling the user to close the program and save the file again. Indexing a locked document in any format reports it as locked. A program that only denies writes (for example, an editor that keeps the file open but still lets others read it) never blocked indexing and still doesn't.

The watcher covers its default types: PDF, text, Markdown, reStructuredText, CSV, JSON, logs, and common code and config files. It doesn't watch Word, PowerPoint or Excel files at all; #5478 tracks adding them.

Reproduced by hub/agents/chat/python/tests/test_chat_reindex_locked.py and tests/unit/rag/test_locked_read.py; fails on main, passes here.

🔍 Technical details
  • RAG checks for a lock at two points:
    • It already reads every byte of a document to hash it before parsing. index_document now treats a lock refused on that read as error_type: "file_locked", before any parser can misreport it. Other callers of _content_key keep the path-only key.
    • A lock taken after hashing is caught around text extraction. Parsers wrap the OS error (python-docx reports a lock as "File is not a zip file"), so RAG walks the exception chain for it. A cancelled index stays cancelled.
    • A cache write that fails with EACCES stays a plain failure.
  • ChatAgent.reindex_file reads one byte before indexing, and raises PermissionError on a lock or on RAG's file_locked, so the watcher retries. Any other exception is logged with its traceback; a failed index is logged with RAG's error.
  • Lock detection lives in one core function, gaia.utils.file_lock.held_by_another_program. It is Windows-only, because POSIX reads are never blocked by another program. Windows uses the same EACCES for a missing read permission, so the user-facing messages name both causes. A lock is logged as a warning in RAG and in the extractors a lock reaches; only the watcher's final give-up is an error.
  • FileChangeHandler changes:
    • A locked on_moved destination is retried as a modification.
    • The retry count is read and written under the handler's lock.
    • A change queued during a locked read isn't counted as a retry.
    • A new event, a delete, or a move clears a path's count.
    • The give-up error is logged once.
  • Every fix has a test that fails when the fix is reverted (25 reverts checked).
  • The chat package now needs core 0.25.1, which ships the watcher retry, RAG's file_locked and held_by_another_program. The agent imports that function at start. tests/test_chat_dependency_floor.py guards it, so the 0.25.1 release fails until the chat floor rises. The existing wrong floor is tracked in chat agent: amd-gaia>=0.25.0 floor no longer imports on core 0.25.0 #5470.
  • Docs:
    • docs/spec/rag-sdk.mdx documents error_type, along with the lemonade_unreachable and embedder_busy flags that come with embedding_unavailable.
    • The chat-agent spec lists exactly which formats are watched.
    • The SDK guide no longer teaches except Exception around callbacks.

Test plan

  • python -m pytest hub/agents/chat/python/tests/test_chat_reindex_locked.py tests/unit/rag/test_locked_read.py tests/unit/test_file_watcher_settle.py. On Windows, real msvcrt locks cover .txt through a real RAGSDK; .docx and .pptx with whole-file and partial locks; and a lock taken after the hash read on .txt, .pdf, .docx, .pptx, .xlsx, .csv and .json.
  • Real locks, before and after the hash read, partial and whole-file, on all 7 formats: every one reports file_locked, and none logs an ERROR
  • Chat lane and touched suites: python -m pytest hub/agents/chat/python/tests/ tests/unit/rag/ tests/unit/test_file_lock.py tests/unit/test_file_watcher.py tests/test_chat_agent.py tests/unit/agents/test_registry.py tests/test_sdk.py tests/test_rag.py
  • python util/lint.py --all, with this checkout's src on PYTHONPATH, and python util/check_doc_links.py
  • Revert check: each of the 25 fixes reverted in turn is caught by a test
  • Manual, Windows: with gaia chat watching a folder, hold a .txt or .pdf there with an exclusive (share-mode 0) handle, save a change, and confirm it reindexes once the handle is released. Keep the handle open past the three retries and confirm a single "Gave up on … Close the program using …" error.

A document open in another program on Windows was tried once and never
reindexed, because ChatAgent.reindex_file caught every error and the file
watcher's locked-file retry never ran.

- reindex_file probes the file and lets a lock propagate as PermissionError;
  errors inside RAG are logged with their traceback and not retried.
- The watcher retries a locked move destination as a modification (Office
  saves by rename), resets the retry count on a new event or delete, and logs
  its give-up once, with the traceback and a remedy.
- The SDK guide no longer teaches `except Exception` around callbacks; specs
  and the chat CHANGELOG match.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

Before this change, chat tried a watched document that another program had open (Word or Excel on Windows) only once. After that it kept answering from the stale copy. Now the chat agent passes the locked-file error up to the file watcher, which retries 1, 2 and 4 windows later, including saves that rename a temp file onto the document. If the file is still locked after the last retry, the watcher logs one actionable error. I found no blocking issues. The retry stays bounded, unrelated failures are still logged with their traceback instead of being retried, and the docs, specs and CHANGELOG all say the same thing.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change only matters with a Windows file lock, which this Linux CI runner can't reproduce. I couldn't run the tests here either, because pytest isn't installed on this runner. This verdict rests on static review alone. The PR's manual Windows check (lock a watched .txt, save, confirm it reindexes or gives up once) is still the proof that matters, and it's worth recording on the PR before merge.

🔍 Technical details

Issues found

🟢 A file that stays locked can be retried indefinitely if it keeps changing (src/gaia/utils/file_watcher.py:365). _schedule_settle now clears _locked_retries on every new event. If a program fires modify events while it holds the lock, each event starts a fresh set of 3 retries, so the give-up error may never fire. Each new event is a real change, so this is defensible. A short comment or a test would pin it as intended.

🟢 The rename-save retry calls a different callback than the original event (file_watcher.py:487, _locked_retry_kind). A locked move destination is re-reported through on_modified (or on_created), not on_moved. That's correct for ChatAgent, where both callbacks reindex the destination. A third-party FileWatcher user whose on_moved does extra work, such as updating a path map, won't get that work redone on retry. The SDK guide does say "as a modification", so this is documented, just easy to miss.

Checks I made

  • No loop between retry and reset: _retry_locked writes _pending directly and never goes through _schedule_settle, so the new reset can't zero the counter on each retry.
  • The 0.25.0 compatibility note holds: _retry_locked first landed in c91dc17 (fix(utils): report a watched file once it has finished being written #5385), which no release tag contains yet. On an older core, a raised PermissionError falls into the generic except Exception and is logged once.
  • On POSIX, a real EACCES is logged with its traceback, not retried (_held_by_another_program checks os.name == "nt"), which matches the spec.

Strengths

  • The one-byte read before handing the file to RAG is the right fix: RAGSDK.reindex_document turns read errors into a failed-result dict, so the lock would otherwise never reach the watcher.
  • The give-up error is now logged once, with its traceback, and tells the user what to do (close the program using the file, then save again), where before it was logged twice.
  • Good tests: an end-to-end run through a real FileChangeHandler (retry, give-up, rename-save, plain OSError with winerror 32), a parametrized check that failures inside RAG aren't retried, and a real msvcrt byte-range lock test on Windows.

A document with a byte-range lock further in than the probe reads, or one
locked between the probe and RAG, was still logged once and never retried,
because RAG reported a locked read as a plain failure.

- RAG tags a failed read of the document itself as error_type "file_locked"
  (a cache write that fails with EACCES stays a plain failure), and
  _safe_open keeps the errno of a failed open. reindex_file raises on the
  tag so the watcher retries.
- Lock detection is one core function, gaia.utils.file_lock
  .held_by_another_program, Windows-only, with messages naming both causes
  Windows reports as EACCES. The agent's copy and its unreachable
  plain-OSError branch are gone.
- The watcher reads and writes retry counts under its lock, does not count
  a retry over a newer queued change, and clears a moved file's source
  count.
- CHANGELOG says the change needs core 0.25.1 (no 0.25.0 claim); the
  chat-agent spec's stale hand-rolled handler is replaced; the wording no
  longer says a file open in Office blocks reads.
@github-actions github-actions Bot added rag RAG system changes performance Performance-critical changes labels Oct 21, 2026
kovtcharov and others added 3 commits October 21, 2026 00:46
…upted

A .docx or .pptx that another program had locked was reported as corrupted
and the user was told to re-download it, because the zip parsers hide the OS
error (a whole-file lock even reads as "File is not a zip file"). The file
watcher never retried it.

- index_document now detects a lock in the hash read it already does before
  any parser runs, so every format reports error_type "file_locked". Other
  callers of _content_key keep the path-only key.
- A lock is logged as a warning; the caller gets error_type and decides.
- The chat package's floor test guards held_by_another_program, which only
  core 0.25.1 ships.
- docs/spec/rag-sdk.mdx documents error_type; the chat CHANGELOG names the
  formats covered and what is logged with a traceback.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Ran the manual Windows check and both cases behave as described: a file held with an exclusive handle reindexes once the handle is released, and one held past every retry logs a single "Gave up on … Close the program using …" error. On the two review notes: a new change restarting the retries is intended (the retries still run out once the program stops changing the file), and I added a comment saying so; re-reporting a locked rename as a modification is already documented in the SDK guide, so no change there.

🔍 Technical details
  • Manual check: real watchdog FileWatcher + ChatAgent.reindex_file (RAG stubbed) on a temp folder, with the file held through CreateFileW share mode 0. Released after 2.5 s: retry 1/3, 2/3, then reindexed. Held 12 s: retries 1/3 to 3/3, then one Gave up error with the PermissionError traceback, and no reindex.
  • Restart-on-new-change is pinned by test_a_new_change_to_a_locked_file_restarts_its_retries.
  • Merged main; chat lane + rag + watcher suites: 599 passed. lint.py --all clean.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 21, 2026
Merged via the queue into amd:main with commit d80736b Oct 21, 2026
38 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/chat-reindex-locked-retry branch October 21, 2026 09:23
kovtcharov-amd added a commit that referenced this pull request Oct 21, 2026
The chat agent's retry for a document another program has open (#5458) landed on main after the 0.3.1 entry was written, and it ships in this release's binary.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 23, 2026
…d#5480)

On Windows, a Word, PowerPoint or Excel file that another program locked
while GAIA was reading it could still be reported as corrupted, with
advice to re-download it, so nothing retried it. Now the lock is
reported as locked (`error_type: "file_locked"`) in every format,
including a lock taken just before Word or PowerPoint opens the file.
The read failure is logged as a warning, not an error. A genuinely
corrupt file still reports as corrupt, even when an unrelated temp
file's permission error is in its traceback. A stopped index, or a
cancelled wait for the model, stays stopped instead of being reported as
locked. This finishes amd#5458, which was merged before this last round of
fixes. Its CHANGELOG also said watched Office files were retried, but
the chat agent's watcher doesn't watch them at all; the docs now list
exactly the extensions it watches, and amd#5478 tracks adding Office files.

Reproduced by `tests/unit/rag/test_locked_read.py`; fails on main,
passes here. The tests that reproduce it are the chain-walk, stop and
per-parser log tests,
`test_a_lock_taken_after_the_hash_read_is_reported_as_file_locked` and
`test_a_real_lock_taken_just_before_the_library_opens_is_reported_as_locked`.

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

- amd#5458 detects a lock in RAG's hash read, before parsing. A lock taken
after that read reaches the parser instead:
- Given a path, python-docx and python-pptx call `zipfile.is_zipfile`,
which swallows the OS error and leaves nothing to find. RAG now opens
the file itself and hands the library the stream. Both read every part
at construction, so the stream closes straight after.
- openpyxl and the text, CSV and JSON readers keep the OS error in the
chain. Text extraction walks it the way Python prints it: `__cause__`,
then `__context__` unless `__suppress_context__` is set.
- The walk only accepts a lock that names no file (a read of a locked
range) or names the document. "Names the document" is decided by
`os.path.samefile`, so case, 8.3, UNC, `\\?\` and hard-link spellings
all count. A file that can't be stat'd falls back to
`normcase(realpath)`. An EACCES on a temp or cache file is not the
document's lock.
- Any stop in the chain, `IndexingStopped` or `LeaseWaitCancelled`, is
re-raised as the stop before the walk. The stop walk respects
`__suppress_context__` too.
- The parsers a lock reaches (text, CSV, JSON, Excel, Word, and the two
PowerPoint open paths) log it as a warning through `_log_read_failure`.
The warning names both causes Windows can mean and shows only the lock,
not the parser's "corrupted, re-download" advice. The PDF sites are
unchanged, because a PDF lock never reaches them.
- The chat CHANGELOG and `docs/spec/chat-agent.mdx` list the exact
watched extensions. A test pins the spec's list and the file-watcher
guide's to `FileChangeHandler.DEFAULT_EXTENSIONS`, and fails with a
message if a doc anchor moves. `docs/spec/rag-sdk.mdx` documents the
`lemonade_unreachable` and `embedder_busy` flags that come with
`embedding_unavailable`.
- Revert check: each fix reverted in turn makes a test fail on Windows.
- With the Windows-only tests deselected, as on Linux and macOS CI,
every revert is caught except two. The fallback's `realpath` is caught
by a symlink test, which runs on Linux CI but needs a privilege on
Windows. The fallback's `normcase` does nothing on POSIX.
- The per-parser tests patch each parser's open to raise a Windows lock,
so they run everywhere.
</details>

## Test plan

- [x] `python -m pytest tests/unit/rag/test_locked_read.py`. On Windows,
it also runs real `msvcrt` locks:
- taken after the hash read, on `.txt`, `.pdf`, `.docx`, `.pptx`,
`.xlsx`, `.csv` and `.json`, whole-file and partial;
- byte-range and no-share locks taken just before Word and PowerPoint
open the file.

  Every case reports `file_locked` and logs no ERROR.
- [x] Revert check on Windows (all caught), and with the Windows-only
tests deselected (all caught except the two platform-bound fallback
reverts above)
- [x] `python -m pytest hub/agents/chat/python/tests/ tests/unit/rag/
tests/unit/test_file_lock.py tests/unit/test_file_watcher.py
tests/unit/test_file_watcher_settle.py tests/test_chat_agent.py
tests/test_rag.py tests/test_sdk.py`
- [x] `python util/lint.py --all`, with this checkout's `src` on
`PYTHONPATH`, and `python util/check_doc_links.py`

---------

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

documentation Documentation changes performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants