Skip to content

fix(realtime): read-only watcher events never take an event-queue slot - #504

Merged
HananKavitzAmat merged 5 commits into
chunkhound:mainfrom
fstrasz:fix/watcher-readonly-events-upstream
Nov 16, 2026
Merged

HananKavitzAmat merged 5 commits into
chunkhound:mainfrom
fstrasz:fix/watcher-readonly-events-upstream

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On Linux, the watchdog backend reports every plain read of an indexable file, and each read takes a realtime event-queue slot.

_bootstrap_fs_monitor (and _add_directory_watch) schedule the observer with no event_filter, so watchdog's inotify emitter watches WATCHDOG_ALL_EVENTS, which includes IN_OPEN, IN_CLOSE_NOWRITE and IN_CLOSE_WRITE. Every read therefore produces opened + closed_no_write. What happens next:

  1. SimpleEventHandler.on_any_event admits any event type on an indexable path, and _should_admit_realtime_event filters by path only.
  2. Each event takes one of the 1,000 queue slots (_EVENT_QUEUE_MAXSIZE).
  3. _consume_events acts only on created / modified / deleted / dir_*, so it then drops these.

ChunkHound's own start-up scan reads every file, so it can fill the queue, hit event_queue_overflow and request a full resync. A type-check, test or lint run over the tree does the same.

Fix

The fix works at the source, before the queue.

  1. events.py: CONTENT_EVENT_TYPES is the one list of event types that can mean a content change. on_any_event drops every other type first, with no source or filtered callback, so a read costs nothing. watchdog_event_filter() derives the watchdog classes from that list, importing watchdog lazily so the module stays importable without it.
  2. startup.py (_bootstrap_fs_monitor) and pipeline.py (_add_directory_watch) pass that filter to observer.schedule.
    • On inotify the filter narrows the kernel watch mask (get_event_mask_from_filter), so reads are never reported at all.
    • Both call sites use the same filter on purpose: watchdog 7 shares one inotify fd per observer, and each inotify_add_watch replaces the inode's mask.
    • The mask keeps IN_MOVE, IN_CREATE (new-directory watches), IN_MODIFY, IN_ATTRIB, IN_DELETE and IN_DELETE_SELF.
  3. pipeline.py (_consume_events): when the consumer drops a duplicate created/modified for a path whose change is waiting in debounce, it refreshes that debounce horizon, exactly as add_file would. The duplicate check itself is unchanged.

The consumer never acted on closed, and a write also yields modified, created or moved. The one exception is an mmap write, which inotify reports only on close, and which was not handled before either. Without the open and close events, though, two writes reach the consumer as modified, modified, and its duplicate check must handle that:

  • A write made while the file is being processed is kept, so it gets a follow-up pass. That is fix(realtime): never drop a duplicate event while the path's change is being processed #507's rule, now on main.
  • A duplicate save dropped while the change waits in debounce still pushes the debounce back (item 3). Otherwise a burst of saves on Linux was indexed part-way through and again afterwards. This applies on every backend that goes through the consumer: a burst is indexed once, after the last save, and a file rewritten without pause is indexed once it goes quiet, as the debounce documents.

attrib is deliberately kept. On Windows, watchdog 7.1 reports an in-place append as attrib when the change time is ahead of the write time (3 of 3 appends in a direct probe), so for some writes it is the only event. The consumer does not act on attrib today. That, and Windows last-access updates arriving as attrib, are left for a separate change. Windows behaviour is unchanged here: a start-up scan queued the same 1,418 attrib events before and after.

Measured

Setup: Linux (WSL2 Ubuntu 24.04, python:3.12-slim, watchdog 7.1.0), a real chunkhound mcp --no-daemon with the watchdog backend, on a 1,418-file TypeScript repository on ext4. Each run starts the server, waits for query_ready and a quiet queue, then runs tsc --noEmit over the tree.

before (3 runs) after (3 runs)
events queued during start-up scan 2,106 / 2,418 / 5,648 (all read-only) 0 / 0 / 0
queue overflows 1 of 3 runs (1,727 dropped, sample closed_no_write) 0
resync requests 1 of 3 runs 0
events queued during tsc --noEmit ~1,800 per run 0
live_indexing_state when quiet busy (undrained backlog of read events) idle

After the fix, an in-place edit, a new file, an atomic temp-file rename-over and a delete were each found (or no longer found) by regex search 0.9-2.1 s after the write.

Tests

tests/realtime/test_realtime_readonly_events.py adds four tests. Each fails without the part of the change it covers:

  1. test_read_only_events_take_no_queue_slot: 1,500 each of opened / closed_no_write / closed through a SimpleEventHandler on a 1,000-slot queue, then one modified. The queue holds just the modified, with no queue_full result and no callbacks for the reads. On main the queue fills with 1,000 opened.
  2. test_watches_are_scheduled_without_read_only_events: a fake observer captures both schedule calls. Each passes an event_filter that contains the content classes and none of the open/close classes. On main there is no event_filter.
  3. test_write_after_an_indexing_read_is_indexed: the real handler, consumer and process loop see the Linux sequence write, the indexing run's read, then a second write inside the duplicate window. Both versions are processed. It times out without fix(realtime): never drop a duplicate event while the path's change is being processed #507's rule.
  4. test_a_burst_of_saves_is_indexed_once: 8 saves 0.25 s apart, with a 1.5 s debounce, are indexed in one pass with the final content. Without the debounce refresh it indexes ['x = 6', 'x = 8'].

The repository's uv.lock pins watchdog 6.0.0, while a fresh install (pip / uv tool install) resolves 7.1.0. I ran the realtime suites (tests/realtime, tests/test_realtime_functional.py, tests/unit/test_watchdog_import_isolation.py, tests/test_language_extensions.py) on Windows, Python 3.13, against both versions: 180 passed, 34 skipped on each. event_filter exists in watchdog since 4.0, which matches the watchdog>=4.0.0 bound.

This change does not depend on any other open PR.

Related: #104 ("Failed to queue event" on a large project): read-only watcher events no longer take event-queue slots.

🤖 Generated with Claude Code, reviewed by FStrasz

On Linux, watchdog's inotify emitter was scheduled with no event_filter, so
it watched IN_OPEN / IN_CLOSE_NOWRITE / IN_CLOSE_WRITE and every plain read
of an indexable file produced `opened` + `closed_no_write`. The handler
admitted any event type on an indexable path, so each read took one of the
1,000 event-queue slots before the consumer, which acts only on created /
modified / deleted / dir_*, dropped it. ChunkHound's own start-up scan reads
every file, so it could overflow the queue and request an
event_queue_overflow resync; a type-check or test run over the tree does the
same.

Fix, at the source:
- events.py: CONTENT_EVENT_TYPES is the single list of event types that can
  mean a content change; on_any_event drops every other type first, with no
  callback. watchdog_event_filter() derives the watchdog classes from it.
- startup.py (_bootstrap_fs_monitor) and pipeline.py (_add_directory_watch)
  pass that filter to observer.schedule. On inotify it narrows the kernel
  watch mask, so reads are never reported at all. Both call sites use the
  same filter because watchdog 7 shares one inotify fd per observer and each
  inotify_add_watch replaces the inode's mask.

`attrib` is kept. On Windows, watchdog 7.1 reports an in-place append as
`attrib` when the change time is ahead of the write time (3 of 3 appends in
a probe), so for some writes it is the only event. The consumer does not act
on `attrib` today; that, and Windows last-access updates arriving as
`attrib`, are left for a separate change. Windows behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

#505 is stacked on this PR, and it fixes Windows in-place writes going unindexed for anyone whose install resolves watchdog 7.1 (any Python 3.11+ install from PyPI). Details are in #505's comment. Reviewing this one first unblocks it.

🤖 Generated with Claude Code

@VakninAriel VakninAriel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review — PR #504

Verdict: 🚫 Request Changes

Summary

Linux watchdog open/close notifications for ordinary reads were filling the realtime queue even though the consumer did not index them. This PR rejects those notifications before queue admission and narrows the observer event filter at both initial and dynamically added watches.

What's good

  • Read-only event rejection occurs before source/filtered callbacks and queue submission, avoiding both queue slots and bookkeeping work for those discarded events.
  • Initial and dynamically added directory watches use the same lazily imported event-filter helper, avoiding divergent filters on overlapping watches while preserving optional watchdog imports.

Freshness warning: Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.

Severity Count
🔴 Critical 0
🟠 High 0
🟡 Medium 1
🟢 Minor 0

Findings

🟡 [Preserve follow-up indexing when filtering consecutive write events] (#1 · Medium)

Location: chunkhound/services/realtime/events.py — lines 198–200

With Linux watchdog, write an existing file, let indexing read that version, then write it again before processing completes and within the two-second event-dedup window. The new handler gate and observer filter remove intervening open/close events. Those events previously changed _recent_file_events even though they did not index anything. Now _consume_events sees modified after modified and drops the second write before add_file can reserve a follow-up for the active mutation. The accepted-event callback only refreshes an existing pending mutation; it cannot reserve active-work follow-ups, and completion only clears the dedup entry after the event was lost. The older content can remain searchable until another accepted event or rescan. This is an introduced interaction with preexisting deduplication, not a request to restore read-only queue pressure.

Suggested fix:

Keep read-only events out of the queue, but route repeated content changes through the existing debounce/coalescing and active follow-up logic rather than discarding them before add_file. Add a handler-to-consumer regression test that holds the first indexing pass after its read, performs a second write, then verifies a follow-up indexes the second version.

Review metadata and audit

Draft review for human approval. Nothing has been posted to GitHub.

Pinned head SHA: e930c397d3509a34257e9f9033c14ab83455b1eb

Package freshness checked 2026-11-11T15:38:58.574960+00:00: STALE: included heads/eligibility changed; see overview and freshness audit before posting. This report applies only to its pinned SHA.

PR: #504

Title: fix(realtime): read-only watcher events never take an event-queue slot

Author: fstrasz · Branches: fix/watcher-readonly-events-upstream → main

Diff merge base: 98be86f

Review scope: Full main...HEAD contribution, merge base 98be86f through pinned head e930c39; all four changed files (realtime events, pipeline, startup and read-only-event tests), plus consumer deduplication, pending/active mutation lifecycle and installed watchdog 6 inotify behavior. This is one commit directly above the merge base.

Eligibility: Bug fix addressing existing behavior; no new feature.

Overall assessment (audit only)

The queue-pressure fix introduces a Linux watchdog regression: consecutive modifications during an active indexing pass can be dropped before follow-up scheduling. One Medium finding retained after static tracing and an isolated base-versus-head reproduction.

Strength evidence

  • {"strength_index": 0, "path": "chunkhound/services/realtime/events.py; tests/realtime/test_realtime_readonly_events.py", "source": "pr-504.pinned.diff", "detail": "on_any_event returns early for types outside CONTENT_EVENT_TYPES; test_read_only_events_take_no_queue_slot sends more read events than queue capacity and asserts only the control modification is queued. It does not cover an in-flight second write."}
  • {"strength_index": 1, "path": "chunkhound/services/realtime/startup.py; chunkhound/services/realtime/pipeline.py; chunkhound/services/realtime/events.py", "source": "pr-504.pinned.diff", "detail": "Both observer.schedule call sites pass watchdog_event_filter(); watchdog.events is imported inside that helper and missing version-specific classes are checked with hasattr."}

Finding #1 evidence

  • Pinned events.py:198-200 drops non-content events; startup.py:817 applies the same filter at the emitter. pipeline.py:1061-1081 suppresses same-type events before dispatch, while :957-964 reserves active follow-ups only in add_file.
  • pipeline.py:171-190 refreshes only an existing pending mutation; :512-518 releases pending ownership on dequeue; :564-580 drains only explicitly reserved generations; :1561 clears dedup history on completion without replaying dropped events.
  • Reconciler reran the inspected Astra probe using actual base/head handler definitions, production consumer and watchdog 6/Linux events: base add_file snapshots included value = 2; head snapshots contained only value = 1 and three modified events were suppressed. Exit 0. This observes admission loss with a simplified in-flight processing sink, not a completed native index.

Reviewer keys: astra

Verification

  • Reconciler: git -C /tmp/chunkhound-pr-reviews-20261111/pr-504 rev-parse HEAD matched manifest; git diff --check 98be86f e930c39 and git status --short exited 0 with no output. Both completed reports were read. All assistant-message provider/model/responseModel identities, successful runner statuses, valid provenance, pinned heads and report SHA256 values were checked; two distinct response models confirmed.
  • Astra: timeout 120s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync mypy chunkhound --cache-dir=/tmp/chunkhound-pr-504-astra-a1-qgip5bgl/mypy-cache -> exit 1, 993 errors in 89 files (374 checked). Merge-base shadow-file run for events.py, startup.py and pipeline.py -> exit 1, same counts; line-normalized diagnostics had no additions/removals.
  • Astra: timeout 90s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync pytest -p no:cacheprovider --basetemp=/tmp/chunkhound-pr-504-astra-a1-qgip5bgl/pytest-readonly tests/realtime/test_realtime_readonly_events.py tests/unit/test_watchdog_import_isolation.py -q -> exit 2, two native-import collection errors, zero tests executed.
  • Astra originally ran timeout 20s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync python /tmp/chunkhound-pr-504-astra-a1-qgip5bgl/probe.py -> exit 0. Reconciler reran timeout 25s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync python /tmp/chunkhound-pr-504-astra-a1-qgip5bgl/probe.py from the pinned worktree -> exit 0; reproduced second-write suppression, preserved content mask bits, and verified 4500 read-only events consume no slots while modified survives.
  • Sonnet reports 993 mypy errors in 89 files; its tail pipeline hid the actual mypy exit status, so its displayed exit 0 is not a passing typecheck. Both attempted realtime/import-isolation pytest selections failed during native-dependent collection.

Limitations

  • Native-dependent tests did not execute successfully: the shared environment lacks chunkhound_native.chunkhound_native. No native build, dependency installation, network call, source edit or environment repair was performed. CI is only the captured green snapshot, not a fresh run.
  • Supplemental probes extract production definitions and use real external libraries/processes with simplified surrounding state. They are not end-to-end native indexing or MCP verification.
  • Runtime probe covered Linux/watchdog 6.0.0 only; watchdog 4/7, Windows and macOS behavior was not executed. Author performance measurements were not reproduced.
  • CI is a captured snapshot, not a fresh run or a guarantee of current branch status.
  • Model identities are verified declarations supplied by the reconciler; the renderer does not inspect raw reports or provenance events.

Disposition of discarded / merged findings

  • Sonnet found no actionable issues and treated open/close events as inert because the consumer does not dispatch them. Rejected that no-regression conclusion: the consumer updates last-event state for them before dispatch; the base/head repro and active-follow-up trace substantiate Astra’s finding without requiring reviewer consensus.
  • Windows attrib admission and mmap/close-only limitations were already present or explicitly unchanged, so they are not retained as introduced defects.
  • Sonnet attempt 1 timed out; only succeeded attempt 2 and its validated report/provenance are used. Stale runner error history does not describe the completed attempt.

Independent reviewer provenance

  • sonnet — provider: amat-tfy; requested model: standard-chat-dev/claude-sonnet-5.5; verified response model: aws-aidev-models/us.anthropic.claude-sonnet-5-5. Identity evidence · Raw report
  • astra — provider: amat-tfy; requested model: frontier-chat-dev/gpt-6-astra; verified response model: gpt-6-astra. Identity evidence · Raw report

CI snapshot

Captured: 2026-11-11T14:18:23.581921+00:00. Eligibility green: True. Counts: {"SKIPPED": 2, "SUCCESS": 23}

Reviewed by Ariel Vaknin via pi.dev

fstrasz and others added 4 commits November 12, 2026 06:56
Brings in chunkhound#507 (never drop a duplicate event while the path's change is
being processed), which the review's stale-index finding needs, and chunkhound#489.
One conflict, in the startup.py import from .events: both names kept
(forward_to_loop from main, watchdog_event_filter from this branch).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…filtered

With read-only events dropped, two writes reach the consumer as
modified, modified, with no open or close between them. The test drives
the real handler with the Linux sequence (write, the indexing run's read,
a second write inside the duplicate-event window) through the real
consumer and process loop, and checks the second write is processed.
It fails without the consumer's rule that a path being processed never
has a duplicate dropped (chunkhound#507).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… debounce

With read-only events dropped, every save after the first reaches the
consumer as a duplicate `modified` and is suppressed before add_file,
which is what pushed the pending debounce back. On Linux a burst of saves
was then indexed part-way through and again afterwards (10 saves 0.3 s
apart: 5 passes instead of 1, each queueing an embed pass). The
suppression branch now refreshes the debounce horizon for a write
whose change is waiting in debounce.

Tests: a burst of saves closer than the debounce delay is indexed once,
with the final content; the write-after-read test now uses fake services,
a long duplicate window so it always exercises the rule, and gathers its
tasks on the way out. The events.py comment no longer says dropping
`closed` changes nothing indexed: that holds only with the consumer's
two rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-up to the debounce refresh. The duplicate check is back to
main's exact condition, so a repeated delete or directory event no
longer resolves its path; only a suppressed write looks up its debounce
key. The refresh applies on every backend that goes through the
consumer (watchdog on any OS, Watchman): a burst of saves is indexed
once, and a file written without pause is indexed once it goes quiet,
which is what the debounce documents.

The burst test now waits for the indexing pass instead of a fixed
sleep, so a stalled runner cannot end it before the pass runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@VakninAriel thanks: the finding was right at the head you reviewed. It's fixed by merging main, and while testing it I found and fixed a second effect of the same filter.

Finding #1: a second write is dropped once read-only events are filtered

  • Reproduced at e930c39. That head sits on 98be86f, and there _consume_events drops any same-type event inside the 2 s window, whether or not the path is being processed. With opened/closed/closed_no_write filtered out, nothing separates two writes. Write, then the indexing run's read, then a second write: the consumer sees modified, modified and drops the second before add_file can reserve the follow-up.

  • fix(realtime): never drop a duplicate event while the path's change is being processed #507, merged to main on 11-11, adds the consumer rule this needs: while a path's change is being processed, a duplicate created/modified is never dropped, so add_file reserves the follow-up for the newer write. Merging main brings it in: af4c6ab. The only conflict was the startup.py import from .events; both names are kept.

  • test_write_after_an_indexing_read_is_indexed (8aa88ea) drives the real SimpleEventHandler, wired as startup.py wires it, through the real consumer and process loop. It replays the Linux inotify sequence:

    1. write v1: opened, modified, closed;
    2. the indexing run's read: opened, closed_no_write;
    3. write v2 inside the window: opened, modified, closed.

    It checks that v1 and then v2 are processed, and fails with a timeout if fix(realtime): never drop a duplicate event while the path's change is being processed #507's rule is removed.

"Repeated content changes should reach debounce"
You asked for this too, and it was a real gap. While a change was still waiting in debounce (before any processing), every later save was dropped as a duplicate before add_file, and add_file is what pushes the debounce back. On main the open/close events between saves kept each save distinct, so this only shows up with the filter. On Linux, a burst of saves was then indexed part-way through and indexed again afterwards. Nothing went stale, but there were extra passes, each queueing an embed pass.

  • 96b9c9b and 4e10023: when the consumer drops a duplicate created/modified for a path whose change is waiting in debounce, it now refreshes that debounce horizon, exactly as add_file would. The duplicate is still counted as suppressed. The duplicate check itself is unchanged from main; only a suppressed write looks up its debounce key.
  • This applies on every backend that goes through the consumer, watchdog on any OS and Watchman, which never had read events between saves. On those backends a burst was indexed every ~0.5 s while it lasted. It is now indexed once, after the last save. A file rewritten without pause is indexed once it goes quiet, which is what the debounce documents; Linux watchdog already behaved that way on main. If you'd rather cap the wait (for example, index once a change has been pending for N × the delay), I can add that.
  • test_a_burst_of_saves_is_indexed_once: 8 saves 0.25 s apart, with a 1.5 s debounce. Only the final content is indexed, in one pass. Without the refresh it indexes ['x = 6', 'x = 8']. It waits for the indexing pass rather than a fixed time.
  • Both tests now use fake services instead of DuckDB, a duplicate window long enough that they always exercise the rule, and cancel-and-gather cleanup.
  • The events.py comment no longer claims that dropping closed changes nothing indexed. That only holds with these two consumer rules.

Checks

#505 is stacked on this branch and gets the same merge; I'll reply there separately.

🤖 Generated with Claude Code, reviewed by FStrasz

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Looks good to me!

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 16, 2026
Merged via the queue into chunkhound:main with commit 11d1753 Nov 16, 2026
25 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 16, 2026
Brings in chunkhound#504's squash (11d1753) and chunkhound#510. This branch already carries chunkhound#504's final head (4e10023), and the squash is byte-identical to that head merged onto 84ab53d, so the conflicts in realtime/events.py and realtime/startup.py resolve to this branch merged with 84ab53d, which merges cleanly. No other conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
Brings in chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 17, 2026
Brings in chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534 on top of the earlier merge of main. realtime/startup.py conflicted only in its imports: chunkhound#504 adds watchdog_event_filter to the .events import and this PR adds the .inotify_overflow import; both are kept. chunkhound#504's event_filter reaches this PR's InotifyObserver through the same schedule() call.

One semantic conflict, no textual one: chunkhound#504's test_watches_are_scheduled_without_read_only_events faked _create_watchdog_observer with no arguments and unpacked _bootstrap_fs_monitor as a tuple. This PR changed both (the factory takes on_overflow and returns the observer with its overflow detection; the bootstrap returns WatchdogBootstrap), so the test now fakes and reads them that way, as this PR's own inotify tests do. Its assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants