Skip to content

fix(utils): report a watched file once it has finished being written - #5385

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-j-watcher-settle
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-j-watcher-settle

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

When a file was copied into a folder the chat agent watches, it was reindexed at the first file event, often while still half-written. Later changes within two seconds were ignored, so the finished file was never indexed and search answered from a truncated copy. The reindex also ran on the file watcher's own thread, so one slow reindex held up every other change. Now a file is reindexed once it has stopped changing (no events, and no change in size or modification time, for the debounce window). That happens on a separate thread, and a burst of saves gives one reindex.

Reproduced by tests/unit/test_file_watcher_settle.py; it fails on main and passes here.

🔍 Technical details
  • FileChangeHandler now has a lazily started dispatch thread:
    • created/modified paths wait in _pending until settled;
    • deleted/moved go straight into an ordered _ready queue and cancel a pending report for the path;
    • a file that disappears before it settles is dropped, because its delete event reports it.
  • debounce_seconds now means "unchanged for this long", not "ignore repeats for this long". The leading-edge _is_debounced cache is gone.
  • New methods: wait_idle(timeout), close() and reopen(). FileWatcher.stop() closes the dispatcher and start() reopens it.
  • A callback that raises is logged with its traceback, where before only the message was logged. A PermissionError from a writer still holding the file exclusively is retried after 1, 2 and 4 windows, then given up on with an error. An exception in dispatch itself is logged and dispatch continues.
  • close() stops the batch being dispatched before its next callback, and waits only for the one already running. A file that can't be checked for any reason other than being gone is logged as a warning.
  • Existing handler tests use real files and wait_idle, since dispatch is asynchronous. The headline "written in pieces" test polls instead, so on main it fails on the half-written report itself.
  • The chat agent keeps its handlers and stop_watching closes them; its CHANGELOG names the change.
  • Docs updated: docs/sdk/utils/file-watcher.mdx and docs/spec/file-change-handler.mdx (feature list, interface sketch, test example and implementation notes).

Test plan

  • python -m pytest tests/unit/test_file_watcher.py tests/unit/test_file_watcher_settle.py tests/unit/test_skills_manager.py tests/test_chat_agent.py tests/unit/test_chat_fix_contracts.py: 166 passed, three runs in a row
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes
  • In the Agent UI, watch a folder, copy a large PDF into it, then ask about its last page.

FileChangeHandler ran its callback on the watchdog observer thread at the
first event for a path, then ignored that path's events for
debounce_seconds. A file being copied into a watched folder was reindexed
half-written, its final content never was, and a slow reindex held up
delivery of every other event.

Callbacks now run on the handler's own dispatch thread. A created or
modified file is reported once it has gone debounce_seconds with no events
and no change in size or mtime, so a burst of saves becomes one callback;
deletes and moves are reported in order and cancel a pending report. A
callback that raises is logged with its traceback. wait_idle() and close()
let callers and tests drain or stop the dispatcher; FileWatcher.stop()
closes it.
…se the chat agent's handlers

Review follow-ups: os.stat no longer runs under the dispatcher lock, so a
slow share cannot stall the observer; a still-changing file is rechecked no
sooner than every 50 ms, so a zero window does not spin; the chat agent
keeps its handlers and stop_watching closes them, so reindexing stops when
watching does. Docs note that a file that never pauses is not reported.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This fixes a real bug: a file copied into a watched folder used to be reindexed while it was still half-written, and later changes inside two seconds were dropped, so search could answer from a cut-off copy. The watcher now waits until the file stops changing, then reindexes on its own thread so one slow reindex no longer holds up other changes. The threading looks correct: I traced how deletes, re-creates and late events interleave and found no ordering bug. Nothing blocks merge.

Two small things worth doing:

  • If the watcher can't check a file for any reason other than "it's gone", it skips that file with only a debug log. Report other errors loudly and keep the silent skip for files that were deleted.
  • After the watcher is stopped, the batch it was already working on still runs to the end. A slow reindex can then keep going for up to 5 seconds after stop_watching returns, while the agent is shutting down.

The Agent UI check in the test plan (copy a large PDF in, ask about its last page) isn't ticked yet. Most users are on Windows, so it's worth running there before release: Windows may not update a file's size and timestamp while it is being copied the way Linux does.

Real-world evidence

N/A: no evidence bundle for this run. There's no CLI or API surface to exercise here, and the Agent UI end-to-end check is still open in the PR's test plan. This verdict rests on reading the code. I also couldn't run the tests, because pytest isn't installed on this runner. The author reports 161 passing.

🔍 Technical details

Issues found

🟢 A failed stat silently drops the file (src/gaia/utils/file_watcher.py, _signature)
except OSError: return None treats PermissionError and other I/O errors as "file vanished". _settle then deletes the pending entry and logs only at debug level. No delete event will ever report it, so the reindex just never happens, which goes against CLAUDE.md's fail-loudly rule. Keep the silent skip only for files that are actually gone:

    @staticmethod
    def _signature(file_path: str):
        try:
            st = os.stat(file_path)
        except FileNotFoundError:
            return None
        return (st.st_size, st.st_mtime_ns)

This makes other OSErrors propagate out of the dispatch loop's try, which would kill the dispatcher thread. So either catch them around the stat step in _dispatch_loop and log them with logger.exception there, or have _signature log at warning level before returning None.

🟢 Callbacks keep running after close() (src/gaia/utils/file_watcher.py, _dispatch_loop)
items is taken from the queue under the lock and then run in full. close() clears only the queues and calls join(timeout=5.0), so if a reindex was in progress, the rest of the batch still runs after ChatAgent.stop_watching() has returned. A cheap fix is to check _closed before each callback:

                for item in items:
                    with self._cond:
                        if self._closed:
                            break
                    self._run_callback(*item)

🟢 Dependency timing (no action if this lands before 0.25.0 final). stop_watching now calls FileChangeHandler.close(), which exists only in core from this PR on, and the chat agent pins amd-gaia>=0.25.0. Core is still at 0.25.0 RCs, so the pin holds as long as this merges before the final tag. If it lands after, bump the pin.

Strengths

  • The settle check compares file size and modification time as well as event timing, so a copy whose events lag behind the writes isn't reported early. test_a_file_still_growing_without_events_is_not_reported_yet pins that down.
  • Races are handled carefully. stat runs outside the lock (on both the observer and dispatcher paths), and the self._pending.get(path) is not entry identity check discards stale settle results when a delete or a newer event arrives mid-check. Deletes go through the same ordered queue, so delete → re-create stays in order.
  • The new test file reproduces the original bug through a real FileWatcher and real files rather than mocks. The existing tests were moved onto real temp files with wait_idle instead of being deleted.

kovtcharov-amd and others added 5 commits October 18, 2026 23:07
…on close

A file the watcher could not stat for a reason other than being gone (for
example a permission error) was dropped with only a debug log, so it was
never reindexed and nobody was told. It now logs a warning naming the file.
Closing the watcher also stops the rest of a batch the dispatcher had
already taken, so reindexing no longer continues after stop_watching
returns.
…patch alive

Review follow-ups.

- close() did not stop the batch already being dispatched: every queued
  callback still ran, and close() blocked until they had. Dispatch now checks
  for close before each callback, so close() waits only for the running one.
- A callback that hit PermissionError because the writer still held the file
  exclusively (Windows) was never retried until another event arrived. It is
  now retried after 1, 2 and 4 windows, then given up on with an error.
- An exception in dispatch itself, outside a callback, ended the thread with
  a traceback on stderr. It is now logged and dispatch continues.
- The headline test waits by polling rather than wait_idle(), so on main it
  fails on the half-written report itself.
- docs/spec/file-change-handler.mdx described the old leading-edge debounce
  in its interface sketch, test example and implementation notes; every
  description now matches the settling behaviour.
The chat agent pins amd-gaia>=0.25.0, and a core without close() reindexes
inline, so stop_watching now closes only handlers that have it. An agent that
never ran __init__ no longer logs a missing file_handlers error at GC.
The core unit lane has no gaia_agent_chat, so the file skipped there.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit c91dc17 Oct 19, 2026
35 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-j-watcher-settle branch October 19, 2026 16:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants