Skip to content

fix(realtime): a kernel inotify queue overflow requests a resync - #509

Merged
HananKavitzAmat merged 4 commits into
chunkhound:mainfrom
fstrasz:fix/inotify-overflow-upstream
Nov 18, 2026
Merged

HananKavitzAmat merged 4 commits into
chunkhound:mainfrom
fstrasz:fix/inotify-overflow-upstream

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Problem

When the kernel inotify queue overflows (fs.inotify.max_queued_events, 16384 by default), the kernel drops events and queues one IN_Q_OVERFLOW record with wd == -1. Neither watchdog version tells ChunkHound:

  • watchdog 6.0 discards it: Inotify.read_events skips wd == -1.
  • watchdog 7.1 keeps it: InotifyFD.handle_event calls on_queue_overflow() on every watch callback and InotifyWatchGroup rebuilds its recursive watches, but no FileSystemEvent is emitted.

So the realtime service never requests a resync, and files written during the overflow stay stale or missing until something touches them again. A large checkout, branch switch or build output can trigger it.

Change

  • chunkhound/services/realtime/inotify_overflow.py (new): on Linux, create_inotify_observer(on_overflow) builds an InotifyObserver whose InotifyFD is an _OverflowSignalingInotifyFD. Its handle_event runs watchdog's own handling first, so the watches are rebuilt before anything else, then calls on_overflow for an overflow record. A failing callback is logged and never kills the inotify thread.
  • startup.py: _create_watchdog_observer(on_overflow) returns (observer, detection). The callback hops to the event loop with call_soon_threadsafe. Detection is set when the observer is adopted, on the loop, and reset on the polling fallback and on stop().
  • pipeline.py: _record_inotify_overflow() requests realtime_loss_of_sync with {"backend": "watchdog", "loss_of_sync_reason": "inotify_queue_overflow", "overflow_count": n}, the same reason Watchman uses for a loss of sync, and does nothing while the service is stopping.
  • service.py: daemon_status gains inotify_overflow: detection (active / unavailable / not_applicable), count, last_at, and a hint when detection is unavailable on Linux.

watchdog has no public overflow hook, so detection is by capability, and nothing changes in the dependencies: off Linux, on an unsupported libc, or on watchdog < 7 (no InotifyFD), the backend uses the plain Observer as before and reports detection: "unavailable" / "not_applicable". On watchdog 6.0 an overflow therefore stays undetected, as it is today.

Tests

Two new tests in tests/realtime/test_realtime_inotify_overflow.py:

  1. test_kernel_overflow_reaches_the_service (Linux, watchdog >= 7.1): the real observer's FD handles an IN_Q_OVERFLOW record and the callback runs once.
  2. test_overflow_requests_a_loss_of_sync_resync (any OS): the overflow callback, called from another thread, produces one realtime_loss_of_sync request and the inotify_overflow status block.

Measured against this base (c12f05a4):

  • Linux (python:3.12-slim container, watchdog 7.1.0): both tests fail on main (no hook) and pass with this change.
  • Windows (the repo's lock, watchdog 6.0.0): test 2 fails on main and passes with this change; test 1 skips.
  • Suites (tests/realtime, tests/test_realtime_functional.py, tests/test_realtime_failures.py, serial, Windows): main 125 passed / 34 skipped; this branch 126 passed / 35 skipped (+1 test 2, +1 test 1 skipped); 0 failed on both.

End to end

Measured on a fork that carries this change (same code), Linux container, watchdog 7.1.0, fs.inotify.max_queued_events=64, a real chunkhound mcp --no-daemon --no-embeddings, 500 files written in ~0.2 s into a directory that already existed:

  • Before: 57/500 files indexed, no resync requested, no warning.
  • After: the overflow was detected and a realtime_loss_of_sync / inotify_queue_overflow resync requested in 4 of 4 runs.
  • Caveat: only 2 of 4 runs then indexed 500/500. In the other two (327/500, 44/500), the resync's directory scan failed in the Rust-pipeline handover while a realtime per-file write transaction was open (release_for_rust_pipeline → Cannot CHECKPOINT: the current transaction has transaction local changes), and a failed resync is not retried. That is a separate, pre-existing issue in the resync path (any resync reason can hit it, including event_queue_overflow); I am investigating it separately. This change makes the overflow visible and requests the resync. Whether the resync then completes depends on that fix.

Note for the measurement: writing the burst into a new directory hides the bug, because the directory's created event makes ChunkHound scan that directory.

Relation to other PRs

Standalone on main. It touches _create_watchdog_observer and the schedule call sites near #504 (event_filter) and #505 (ignore_windows_last_access). Whichever of these merges second needs a small, mechanical rebase in startup.py and in the two existing tests that call _create_watchdog_observer / stub _bootstrap_fs_monitor (test_realtime_readonly_events.py, test_realtime_windows_attrib.py, which those PRs add).

When the kernel inotify queue overflows (fs.inotify.max_queued_events), the
kernel drops events and queues one IN_Q_OVERFLOW record (wd == -1). watchdog
6.0 discards it (Inotify.read_events skips wd == -1). watchdog 7.1 keeps it:
InotifyFD.handle_event calls on_queue_overflow on every watch callback, and
InotifyWatchGroup rebuilds its recursive watches, but no FileSystemEvent is
emitted. Either way the realtime service never learns that changes were lost,
and files written during the overflow stay stale or missing until touched
again.

The watchdog backend now builds its Linux observer through
create_inotify_observer: an InotifyObserver whose InotifyFD is an
_OverflowSignalingInotifyFD. Its handle_event runs watchdog's own handling
first (so the watches are rebuilt before anything else happens) and then, for
an overflow record, calls on_overflow, which hops to the event loop. There
_record_inotify_overflow requests a realtime_loss_of_sync resync with
{"backend": "watchdog", "loss_of_sync_reason": "inotify_queue_overflow"},
the same path Watchman uses for a loss of sync, unless the service is
stopping.

watchdog has no public overflow hook, so detection is by capability: off
Linux, on an unsupported libc, or on watchdog < 7 (no InotifyFD) the backend
uses the plain Observer as before. daemon_status reports the result in a new
inotify_overflow block: detection ("active", "unavailable",
"not_applicable"), count, last_at, and a hint when detection is unavailable
on Linux. It is set when the observer is adopted, on the loop, and reset on
the polling fallback and on stop.

Tests: test_kernel_overflow_reaches_the_service (Linux, watchdog >= 7.1:
the real observer's FD handles an IN_Q_OVERFLOW record and the callback runs)
and test_overflow_requests_a_loss_of_sync_resync (any OS: the overflow
callback, called from another thread, produces one realtime_loss_of_sync
resync request and the status block). Both fail before the change.

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

Copy link
Copy Markdown
Collaborator

Summary: The overflow detection fits the existing resync design and I found no blocking bug, but the class swap into watchdog internals is fragile and a few robustness gaps should be closed before merge.

Grouping (the PR is small and its pieces depend on each other, so I reviewed it myself instead of spawning Task agents):

  1. The overflow hook in inotify_overflow.py.
  2. Wiring in startup.py and service.py.
  3. The resync request in pipeline.py.
  4. Tests.

I read the diff and compared it with the Watchman resync path, request_resync, and the watchdog import-isolation test. I did not run the tests or check watchdog 7.1's source. Claims about InotifyFD.handle_event and event.is_queue_overflow come from the PR description and are unverified. The PR also has no comments or reviews, so there were no requested changes to verify.

Strengths

  • It reuses the realtime_loss_of_sync resync path that Watchman already uses, instead of adding a new one.
  • watchdog stays lazily imported, so the import-isolation test should still hold.
  • daemon_status now reports detection: unavailable on watchdog < 7.1, so the gap is visible instead of silent.
  • The thread hop goes through call_soon_threadsafe, and the callback runs after watchdog rebuilds its watches. A failing callback is logged and cannot kill the inotify thread.
  • The description says plainly that the end-to-end resync only works 2 of 4 times.

Issues

Major

  • inotify_overflow.py:66: fd.class = _OverflowSignalingInotifyFD mutates a private attribute (observer._inotify_fd) of a third-party object. Watchdog's constructor could change in any minor release.
    • The isinstance guard fails safe, because detection is then reported as unavailable.
    • Pin or document a tested watchdog range, since pyproject.toml:77 allows watchdog>=4.0.0.
    • Add a test that fails if the private shape changes. Right now only the Linux-only test 1 covers it, and CI on Windows skips it.
  • pipeline.py (_record_inotify_overflow): the request_resync(...) coroutine goes to _start_transient_task with no exception handling.
    • Watchman's _schedule_resync_request (adapters/watchman.py:~970) wraps the same call in try/except and calls set_error.
    • An exception here becomes an unretrieved task error with no status update.
    • Mirror Watchman's handling.
  • The PR admits that a failed resync is not retried and can leave a burst only partly indexed (327/500 and 44/500 files in two runs). The detection works, but the user-visible fix does not reliably deliver. The PR description says the separate fix is still being investigated. I'd either wait for it or link a tracking issue.

Minor

  • startup.py: detection is a bare string ("active", "unavailable", "not_applicable"), and the callers unpack a 3-tuple, which is easy to get wrong. Use a Literal or an enum, or a small dataclass for (observer, event_handler, detection).
  • _handle_watchdog_bootstrap_done uses bootstrap_result[0], which is inconsistent with the unpacking used elsewhere.
  • _set_warning("kernel inotify queue overflowed; resyncing") overwrites _last_warning, and nothing visible here clears it. Confirm that a successful resync clears it.
  • The daemon_status hint says "watchdog < 7.1", but create_inotify_observer's docstring and the PR text elsewhere say "< 7". The hint also covers non-watchdog-version causes of unavailable (unsupported libc, ImportError), so it can be misleading. Make the wording accurate for each cause.
  • service.py: the inotify_overflow status block is built in default_health_snapshot and again in _build_health_snapshot. That follows the existing pattern, but it is another place to keep in sync.
  • Existing tests that stub _bootstrap_fs_monitor with 2-tuples need updating. tests/test_realtime_functional.py:2198 happens to work only because that stub's result is never unpacked, since the observer is stopped as a late result. The PR says the suites pass, but I haven't run them.
  • Test 2 polls with for _ in range(200): sleep(0.01). A bounded asyncio.wait_for on an event would be cleaner.

Reusability

  • Extract the "request a loss-of-sync resync" logic that Watchman and this PR both implement. A shared helper on the service or context, for example request_loss_of_sync(backend, reason, **extra), would hold the error handling and the stopping guard in one place.
  • Share the thread-to-loop hop with the existing event-queue overflow handling (_record_event_queue_overflow) if one is available.

Decision: REQUEST CHANGES (add the exception handling around the resync task, document or pin the watchdog constraint, and replace the string detection values). The resync-completion gap should be fixed or tracked before merge.

…g bootstrap

- A shared service helper, _schedule_loss_of_sync_resync, starts the
  loss-of-sync resync request as a transient task and records a failure
  as "<source> resync request failed: <error>". Watchman's scheduled
  resync and the inotify overflow path both use it, so an overflow
  resync request no longer runs without error handling.
- Detection is an InotifyOverflowDetection Literal, and
  _bootstrap_fs_monitor returns a frozen WatchdogBootstrap dataclass
  instead of a 3-tuple; every consumer reads its fields.
- The inotify_overflow module documents the tested watchdog version
  (7.1.0) and the private internals the hook relies on. The hook test
  gates on watchdog's VERSION_INFO: below 7.1 it skips, from 7.1 on it
  requires the hook, so changed internals fail instead of skipping.
- The "unavailable" status hint now holds for every cause.
- The overflow resync test waits on an event with a bounded timeout
  instead of polling.

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

fstrasz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@HananKavitzAmat thanks for the careful read. The fixes are in f0188a7, a new commit on top of 9e7a1c9; nothing was rebased.

Major

  1. The __class__ swap into watchdog internals: pin or document the range. Documented, deliberately not pinned:
    • The pin problem. uv.lock pins watchdog 6.0.0, which has no InotifyFD. So in CI and in every lockfile install the hook is never installed, detection reports unavailable, and the Linux hook test skips. Meanwhile pip/uv tool install on Python 3.11+ resolves 7.1.0, because watchdog>=4.0.0 has no upper bound.
    • Why not move the lock to 7.1 here. On Windows, watchdog 7 reports most in-place writes as attrib, which main doesn't handle yet; fix(realtime): index Windows in-place writes reported as attrib; reads raise no event #505 (on fix(realtime): read-only watcher events never take an event-queue slot #504) fixes that. Moving the lock before fix(realtime): index Windows in-place writes reported as attrib; reads raise no event #505 lands would make Windows CI and dev setups miss writes. Once fix(realtime): index Windows in-place writes reported as attrib; reads raise no event #505 is merged, I'll bump the lock to 7.1 for Python ≥ 3.11 with a lock-only change. uv already splits the lock by Python version without touching the pyproject.toml floor, so 3.10 keeps 6.0.
    • Documented in inotify_overflow.py's docstring:
      • tested with watchdog 7.1.0;
      • the two private internals it relies on (InotifyFD.handle_event, observer._inotify_fd);
      • every case that reports unavailable.
    • A test that fails if the private shape changes. test_kernel_overflow_reaches_the_service now skips only when watchdog.version.VERSION_INFO < (7, 1). From 7.1 on it requires detection active and the callback firing on a real IN_Q_OVERFLOW event through watchdog's own handle_event, so a renamed or reshaped class fails instead of skipping. It runs on the Linux CI shard as soon as the lock resolves 7.1, and it re-checks the internals whenever the lock moves to a newer watchdog. Versions nobody has tested yet degrade visibly to unavailable rather than silently.
  2. No exception handling around the resync task. Fixed, and shared with Watchman as you suggested:
    • _schedule_loss_of_sync_resync(source, details) on the service (exposed on RealtimeServiceContext) starts the transient task and turns an exception into last_error ("<source> resync request failed: …", which degrades the service).
    • Watchman's _schedule_resync_request now calls it with "Watchman", so its error text is byte-identical. The overflow path calls it with "Watchdog".
    • In practice request_resync doesn't raise (it records state and schedules the debounced dispatch), so this is parity with Watchman rather than a fix for an observed failure. I didn't add a mock-only test for it.
  3. A failed resync isn't retried, so a burst can stay partly indexed. Fixed by two open PRs:

Minor

  1. String detection and the 3-tuple.
    • InotifyOverflowDetection = Literal["active", "unavailable", "not_applicable"].
    • _bootstrap_fs_monitor returns a frozen WatchdogBootstrap(observer, event_handler, inotify_overflow_detection), and every caller reads fields.
  2. bootstrap_result[0]. Now .observer.
  3. _set_warning never cleared. That's how every warning works here: last_warning/last_warning_at record the most recent warning with its time, nothing clears them for any source, and they don't drive service_state. Whether the resync happened is in the resync block (request_count, last_completed_at, last_error).
  4. Hint wording.
    • Docstrings now say 7.1 consistently.
    • The unavailable hint is true for every cause: older watchdog, untested newer internals, or no usable inotify.
  5. The status block built in two places. Left as is: every block in the snapshot follows that pattern, and I'd rather not change one of them here.
  6. 2-tuple stubs. The late_bootstrap stub in test_realtime_functional.py returns a WatchdogBootstrap now, and its future's annotation matches.
  7. Polling loop in test 2. It now waits with asyncio.wait_for on an event set by a wrapper around service.request_resync, the same pattern the Watchman loss-of-sync tests use.

Reusability

Checks. Serial, Windows, before → after:

  • tests/realtime: 77 passed, 28 skipped → same.
  • test_realtime_functional.py: 41 passed, 7 skipped → same.
  • test_realtime_failures.py: 8 passed → same.
  • test_watchdog_import_isolation.py: 3 passed → same.
  • test_smoke.py: 14 passed.
  • ruff: the same findings on the changed files as at 9e7a1c9.
  • Upstream's CI test matrix (Ubuntu, macOS, Windows, all 9 shards) passed on this commit on my fork (run) before I pushed here.
  • The Linux-only hook test still skips under the locked 6.0.0, as described above.

🤖 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 #509

Verdict: ✅ Approve

Summary

Linux inotify queue overflow can drop file changes without producing a watchdog event that ChunkHound can consume. At the reviewed pinned head, this PR adds a capability-detected overflow hook that requests the existing loss-of-sync resync and exposes detection availability and overflow counters in status; it does not itself guarantee that the subsequent scan succeeds.

What's good

  • The overflow callback is handed to the service event loop with call_soon_threadsafe, and the service rejects late notifications during shutdown before requesting a resync.
  • Unsupported watchdog/platform combinations retain the ordinary observer fallback and report detection as unavailable or not applicable instead of implying overflow recovery is active.

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 0
🟢 Minor 0

Findings

No retained findings. This is not a guarantee that the code is defect-free.


Review metadata and audit

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

Pinned head SHA: 9e7a1c97fc56bbf707fe7161e9a66a7ec0528620

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: #509

Title: fix(realtime): a kernel inotify queue overflow requests a resync

Author: fstrasz · Branches: fix/inotify-overflow-upstream → main

Diff merge base: c12f05a

Review scope: Entire pinned PR diff against main merge base c12f05a through 9e7a1c9; relevant callers, lifecycle and tests inspected. Consolidation of independent Sonnet and Astra reviews, not an additional independent model review.

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

Overall assessment (audit only)

No substantiated runtime bug found. The new Linux overflow callback hops onto the service loop, observes shutdown guards, and requests the existing debounced resync. Central watchdog 7.1 execution remains unverified locally; speculative hardening, formatting and existing protocol-type concerns are not blocking findings.

Strength evidence

  • {"strength_index": 0, "path": "chunkhound/services/realtime/startup.py; chunkhound/services/realtime/pipeline.py", "source": "pr-509.pinned.diff", "detail": "on_overflow schedules _record_inotify_overflow on the loop; that method checks stopping/stopped state and supplies the inotify_queue_overflow reason to request_resync."}
  • {"strength_index": 1, "path": "chunkhound/services/realtime/inotify_overflow.py; chunkhound/services/realtime/service.py", "source": "pr-509.pinned.diff", "detail": "create_inotify_observer checks Linux, imports and InotifyFD availability; the status block distinguishes detection modes and provides a Linux unavailability hint."}

Verification

  • Reconciler verified both completed statuses, provenance validity, exact pinned metadata/worktree HEAD, full-index diff bytes, report SHA-256 hashes and distinct actual assistant-message provider/model/responseModel identities.
  • Sonnet and Astra each ran uv run --no-sync mypy chunkhound: 995 errors in 91 files. Sonnet full archive baseline reported 989 errors in 93 files; Astra changed-file shadow baseline reported 985 errors in 90 files. These are different baseline methods, not equivalent counts.
  • Sonnet targeted pytest stopped at one native-extension collection error; Astra targeted pytest reported two native-extension collection errors. No application tests passed.
  • Astra isolated runpy check passed lazy-import and unsupported-hook behavior with watchdog 6.0.0, creating no callback or extra thread; active hook not exercised.
  • Reconciler ran uv run --no-sync ruff check --no-cache --select E301 chunkhound/services/realtime/pipeline.py: exit 0, with explicit warning that E301 has no effect without preview. Project configuration does not enable preview.
  • Reconciler inspected late_bootstrap test and startup.py completion callback: the late two-tuple is accessed only by index zero after timeout, so the tuple-size change does not break that test path.

Limitations

  • Shared environment lacks chunkhound_native.chunkhound_native; application tests could not collect and were not repaired.
  • Installed watchdog 6.0.0 has no InotifyFD hook. Real watchdog 7.1 overflow detection/rebuild and kernel-loss recovery were not locally reproduced.
  • Typechecking is not clean and adds diagnostics related to mixins/protocol compatibility; no runtime consequence was established.
  • Snapshot CI is green, not a new CI verification by the reconciler.
  • 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 missing-blank-line candidate rejected as formatting-only; moreover the alleged E301 CI failure is not supported by actual configured Ruff behavior (preview disabled).
  • Sonnet unavailable-status hint candidate has a real wording limitation for unsupported internals/libc, but no current supported-version functional failure was demonstrated. Loose str typing and logging suggestions are quality/hardening notes, not ready-to-post bug findings.
  • Sonnet new inotify_overflow.py return-type diagnostic is acknowledged in limitations; it extends the preexisting RealtimeObserver protocol mismatch and does not establish a runtime defect. Suppression is not prescribed as a correctness fix.
  • Sonnet event.is_queue_overflow candidate explicitly depends on an unverified hypothetical watchdog API combination. No supported version lacking the attribute was demonstrated; do not post it as an emitter-thread failure.
  • Sonnet late_bootstrap tuple concern resolved by source trace: timed-out completion takes bootstrap_result[0], not three-value unpacking.
  • Astra identified unchanged resync-retry and Rust-handover behavior; these are outside this one-commit diff and are not attributed to #509.

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 2 commits November 13, 2026 05:13
Resolves the import conflict in realtime/startup.py with chunkhound#489's
forward_to_loop: both imports are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
@fstrasz

fstrasz commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Merged main into this branch, bringing in #521, #510, #504 and #534.

realtime/startup.py conflicted only in its imports, and both are kept. The merge also adapts one test from #504, test_watches_are_scheduled_without_read_only_events, to this PR's new shapes. It faked _create_watchdog_observer with no arguments and unpacked _bootstrap_fs_monitor as a tuple. This PR changes both: the factory takes on_overflow and returns the observer with its overflow detection, and the bootstrap returns WatchdogBootstrap. The test now fakes and reads them the way this PR's own inotify tests do. Its assertions are unchanged.

One unrelated flake showed up while testing the merge: test_polling_monitor_detects_size_change_when_mtime_is_constant sometimes times out at its 2.5 s wait. Measured locally, it failed 1 of 10 runs on unchanged main (96a604c) and 0 of 10 on this branch. The failing run took 28 s, against about 4 s for a passing run.

🤖 Generated with Claude Code, reviewed by FStrasz

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

looks good

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 18, 2026
Merged via the queue into chunkhound:main with commit a0fc61b Nov 18, 2026
52 of 53 checks passed
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 18, 2026
…er factory

Main's _create_watchdog_observer (chunkhound#509) now takes the inotify overflow callback and returns (observer, detection). The test's assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 18, 2026
…s raise no event (chunkhound#505)

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

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]>

* fix(realtime): index Windows in-place writes reported as attrib; reads raise no event

On Windows, watchdog 7 classifies a FILE_ACTION_MODIFIED as `attrib` whenever
the record's LastChangeTime is ahead of its LastModificationTime. An in-place
append usually is: measured on NTFS, 26 of 30 appends arrived as `attrib` only
and 4 as `modified` only. The consumer acts on created/modified/deleted, so
most in-place writes were never indexed by the watcher.

watchdog also subscribes to FILE_NOTIFY_CHANGE_LAST_ACCESS, so with last-access
updates on, every read of a file not read for an hour raises an event (7:
`attrib`, 6: `modified`) that takes an event-queue slot; ChunkHound's own
start-up scan reads every file.

- events.py: WATCHDOG_TO_CONSUMER_EVENT replaces CONTENT_EVENT_TYPES as the one
  place a watchdog type is admitted, mapping attrib to modified. On Linux,
  watchdog 6 already reports IN_ATTRIB as modified, so this is that behaviour
  on watchdog 7 too.
- events.py: ignore_windows_last_access() clears the last-access bit from
  watchdog's module-global notify flags, which both 6.0 and 7.1 read on every
  ReadDirectoryChangesW call; called where the observer is created.

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

* test(realtime): a write after an indexing read is indexed with reads 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]>

* fix(realtime): a suppressed duplicate write still refreshes a pending 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]>

* refactor(realtime): resolve the debounce key only for a suppressed write

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]>

* test(realtime): fit the Windows attrib test to main's watchdog observer factory

Main's _create_watchdog_observer (chunkhound#509) now takes the inotify overflow callback and returns (observer, detection). The test's assertions are unchanged.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 23, 2026
chunkhound#509's overflow test builds the realtime service with no database provider
and reads its health. The status read computed the stalled Rust hold before
deriving the live state, so every read touched the provider, and that test
failed with "'NoneType' object has no attribute 'rust_pipeline_store_phase'".

The state derivation now reads the hold itself, after the degraded and
uninitialized checks, and returns it with the state, so the state and its
hint still come from one read. A degraded or uninitialized service no longer
touches the provider. The hint uses the hold only for a stalled state, so no
reported state or hint changes.

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