Repository navigation
perf(realtime): publish status for filtered events at most twice a second - #489
Conversation
…cond Every filtered realtime event built a full health snapshot and handed it to the status callback, which the MCP daemon deep-copies. In a burst of filtered events (an npm install, a junction to node_modules) that cost about 0.58 ms per event, 44% of what handling the event cost. A filtered event now publishes at most once per 0.5 s. The first event after a quiet interval publishes at once; the rest of the interval schedules one trailing publish on a timer, so the counters left by the burst's last event still reach the consumer when the burst ends. stop() cancels a pending trailing publish, since its own final update carries the same counters. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Summary: The throttle fixes a real hot-path cost. However, the trailing flush runs the snapshot builder on a threading.Timer thread that races the event-loop and watchdog threads, so it can silently drop the final update the PR promises to deliver. I read the PR diff but not its description or comments. gh pr view 489 returned "Could not resolve to a PullRequest" for this account, and --comments printed nothing. I did not run the tests or review the changes through subagents. The change is small and tightly coupled, so I read it myself as a single group: throttle logic, service.py state, the stop() hook, and the test. Strengths
Issues Major
Minor
Reusability
Decision: REQUEST CHANGES. Run the trailing flush on the event loop, or make snapshot building thread-safe. Add a test that proves the flush survives concurrent event-pressure mutation. |
Review on chunkhound#489: the trailing publish ran on a threading.Timer thread, so it built the health snapshot while the loop and the watchdog observer thread mutated _event_pressure_by_path. A RuntimeError from that race was swallowed and the burst's final counters were lost; the MCP status callback also ran on a thread it never ran on before. The trailing publish is now a transient task under the existing OwnedTaskSet: it sleeps out the interval and publishes on the loop, and stop()'s cancel_all() cancels it. The lock, the Timer and the cancel method are gone. stop() resets the throttle so the next filtered event after a restart publishes at once. The watchdog observer thread was the only caller that recorded source and filtered events off the loop, and on main it already mutated event-pressure state there. Its two bookkeeping callbacks now hop onto the loop through call_soon_threadsafe, the same path _queue_event uses. Callbacks run in the order scheduled, so a source event is still recorded before the event is queued. SimpleEventHandler's own contract is unchanged. Tests: the burst test freezes the pipeline clock, so it asserts exactly one leading and one trailing publish instead of a wall-clock bound. New tests cover the trailing publish running on the loop while event pressure changes, and stop() cancelling a pending publish. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review, and for tracing the thread interleaving; the Timer thread was the wrong place for the flush. Everything below is fixed in 48bd1b1, a new commit on top of the reviewed head ab41e01. Major: the trailing flush ran on a The watchdog observer thread: this PR now widens on purpose. Moving the flush onto the loop was not enough on its own. The watchdog observer thread calls the service's Docstring overstated "any other status update publishes the same counters". Removed. The docstring now describes only the leading and trailing publishes, and says the throttle runs on the loop.
Blank lines between methods. The new and changed methods are separated by blank lines. I left the existing methods in Import order. The The test's bound depended on wall-clock timing, and
All three fail on ab41e01 and pass on 48bd1b1. On ab41e01 the timer fires during the burst, giving Your reusability note. I did not extract a generic throttle helper. Checks.
🤖 Generated with Claude Code |
|
Summary: The new revision fixes the thread-race I raised earlier by moving the trailing flush and the watchdog bookkeeping onto the loop. The PR description is now stale, and one new test can fail on a fast machine. I read the diff and the surrounding events.py and startup.py. I did not run any tests; the pass counts below are the contributor's. Review scope: I treated this as one logical group, because all four files share a single throttle design. They are the throttle logic in pipeline.py, its state in service.py, the stop() reset and _forward_to_loop wiring in startup.py, and the tests. This was a judgment call, not a mechanical rule. The gh CLI in this checkout resolves to a fork, so I used the full PR URL for every call. Prior requested changes (verified in the diff)
Strengths
Issues Major
Minor
Reusability
Test results (contributor's report, not verified by me)
|
…arden throttle tests Review follow-up on chunkhound#489 (HananKavitzAmat, 2026-11-10): - forward_to_loop now lives in events.py beside SimpleEventHandler, which already owns the call_soon_threadsafe hand-off, and is public, so startup.py no longer imports a private helper. The rename also brings the call site under 88 columns. - The tests freeze only pipeline.time.monotonic: the stand-in delegates every other name to the real time module, so a time.time() in pipeline no longer raises AttributeError under the fixture. - The event-pressure test waits for the trailing publish against a wall-clock deadline instead of a 5000-iteration cap a fast machine can exhaust first. No behaviour change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@HananKavitzAmat thanks for the second pass. The fixes are in aa6f378, a new commit on top of 48bd1b1; nothing was rebased. Major: stale description. Rewritten. It now describes the loop-owned trailing publish and Minor:
Reusability:
Checks, run serially:
🤖 Generated with Claude Code |
VakninAriel
left a comment
There was a problem hiding this comment.
Code Review — PR #489
Verdict: ✅ Approve
Summary
Each filtered realtime event previously built and published a full health snapshot, making ignored-event bursts expensive for the daemon's deep-copying status consumer. This PR throttles filtered-event status publication to a half-second interval with a trailing update, and moves watchdog bookkeeping callbacks onto the service event loop.
What's good
- The throttle preserves a trailing publication of the latest counters, so reducing snapshot frequency does not leave the consumer stuck at the first count in a completed burst.
- Watchdog bookkeeping and the trailing flush are routed onto the event loop, and stop cancels the pending flush and resets throttle state while publishing the final counters.
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: aa6f378fc7ecfbe54b5769b6efe8647a18e7d248
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: #489
Title: perf(realtime): publish status for filtered events at most twice a second
Author: fstrasz · Branches: fix/realtime-filtered-status-throttle-main → main
Diff merge base: 42c5711
Review scope: Complete pinned merge-base 42c5711..aa6f378 diff: realtime/events.py, pipeline.py, service.py, startup.py and the new filtered-status-throttle tests. Reviewed event forwarding/order, Watchman ingestion, status counters, transient-task ownership and shutdown. No inherited #485 changes are present in this five-file PR diff.
Eligibility: Resource/correctness fix: limit filtered-event status churn and preserve thread ownership.
Overall assessment (audit only)
No confirmed actionable user-facing defect remains. Four introduced mypy diagnostics are verified nonblocking type-contract debt against an already-failing baseline, not a demonstrated runtime failure or newly-red enforced gate. Preserve them as observations rather than ready-to-post bugs. Native integration remains unverified.
Strength evidence
- {"strength_index": 0, "path": "chunkhound/services/realtime/pipeline.py; tests/realtime/test_realtime_filtered_status_throttle.py", "source": "pr-489.pinned.diff", "detail": "_emit_filtered_status_update schedules one _flush_filtered_status_update; test_filtered_burst_publishes_once_then_once_more_with_final_counts asserts [1, 1000] for a 1000-event burst. This describes inspected code/assertions, not a native-backed test pass."}
- {"strength_index": 1, "path": "chunkhound/services/realtime/events.py; chunkhound/services/realtime/startup.py", "source": "pr-489.pinned.diff", "detail": "forward_to_loop uses call_soon_threadsafe for source/filtered callbacks; stop resets _filtered_status_flush_pending and _filtered_status_last_emit after transient-task cancellation. The new test also checks loop thread IDs and no post-stop flush."}
Verification
- Reconciler verified both runner jobs succeeded, valid/error-free settled provenance, pinned worktree HEAD and metadata head, SHA256 of each complete report, and all captured assistant-message provider/model/responseModel identities; the two backend response models are distinct.
- Astra: git rev-parse HEAD and git merge-base 42c5711 HEAD matched the pins; git diff --full-index --binary 42c5711 aa6f378 > /tmp/chunkhound-pr-489-astra-a1-sxteiwqi/actual.diff followed by cmp against pr-489.pinned.diff exited 0. git diff --check 42c5711 HEAD exited 0; final status empty.
- 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-489-astra-a1-sxteiwqi/mypy-cache exited 1: 997 errors in 89 files (373 checked). Merge-base comparison extracted events, pipeline, service and startup via git show 42c5711:chunkhound/services/realtime/$f.py to /tmp/chunkhound-pr-489-astra-a1-sxteiwqi/base-$f.py. The same mypy command with --cache-dir=/tmp/chunkhound-pr-489-astra-a1-sxteiwqi/mypy-cache-base and four --shadow-file chunkhound/services/realtime/$f.py /tmp/chunkhound-pr-489-astra-a1-sxteiwqi/base-$f.py arguments exited 1: 993 errors in 89 files.
- Sonnet: 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-489-sonnet-a1-lqei3y0k/mypy-cache exited 1: 997 errors in 89 files; no baseline comparison reported.
- Astra and reconciler each ran: timeout 20s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync python /tmp/chunkhound-pr-489-astra-a1-sxteiwqi/isolated_checks.py. Both exited 0: threaded 1000-event burst published [1,1000] on loop thread with correct spacing; source/enqueue ordering passed; cancellation/final-count/reset sequence passed; no transient tasks without status callback. Reconciler inspected the script before rerun. It executes AST-extracted actual production definitions with lightweight collaborators, not a full service.
Limitations
- Astra: timeout 90s env UV_PROJECT_ENVIRONMENT=/home/e119870/views/g/my_chunkhound/.venv PYTHONDONTWRITEBYTECODE=1 uv run --no-sync pytest tests/realtime/test_realtime_filtered_status_throttle.py -p no:cacheprovider --basetemp=/tmp/chunkhound-pr-489-astra-a1-sxteiwqi/pytest-throttle exited 2: 0 collected, 1 collection error because chunkhound_native.chunkhound_native is absent.
- Sonnet reported timeout 300s env UV_PROJECT_ENVIRONMENT=… uv run --no-sync pytest -p no:cacheprovider --basetemp=/tmp/chunkhound-pr-489-sonnet-a1-lqei3y0k/bt tests/realtime/test_realtime_filtered_status_throttle.py tests/realtime/test_filter_consistency_realtime_cleanup.py -q: two collection errors from the same missing native extension, no tests ran. Ellipsis preserves the report’s abbreviation.
- Isolated checks cannot establish real service/database integration, Windows watchdog behavior, full stop() behavior or benchmark claims; the stop sequence is reproduced with a lightweight collaborator. Full suite, native builds, network tests and environment repair were not performed. Existing typecheck baseline remains failing.
- 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
- Rejected Sonnet’s low-confidence Minor callback-log flooding note: forwarding exceptions to asyncio’s exception handler is an intentional observability change and no realistic repeating exception trigger was substantiated. Pathological hypothetical failures and optional log hardening are insufficient for an actionable introduced bug.
- Final audit reclassifies the verified four added mypy diagnostics as nonblocking observations, preserving original evidence above. Concrete service initialization supplies the fields; no runtime failure or enforced typecheck CI gate is demonstrated (workflow search has no mypy/typecheck step). The documented review command is still worth running, but extra diagnostics on an already-failing baseline alone do not justify Needs Work under meaningful-bug-only scope. This is consistent with #485, #509 and #510 typing dispositions.
- No additional runtime issue was invented from native-module failures; those prevent integration verification rather than demonstrate a throttle defect.
Nonblocking observations (audit only)
- {"title": "Declare the throttle attributes on the mixin’s typed contract", "severity": "Minor", "path": "chunkhound/services/realtime/pipeline.py", "line_start": 79, "line_end": 84, "description": "The new helper accesses four attributes whose types are not declared on RealtimePipelineMixin: _status_callback, _filtered_status_flush_pending, _filtered_status_last_emit and _FILTERED_STATUS_INTERVAL_SECONDS. Although the concrete service initializes them at runtime, mypy checks the mixin independently. Running the documented mypy chunkhound command adds four diagnostics versus the merge-base production files (997 versus 993 errors). This is an introduced typecheck regression, not a newly broken previously-green check, and no runtime failure is inferred.", "suggested_fix": "Declare the required attribute types on RealtimePipelineMixin or use an appropriately typed service contract so these accesses can be checked without new attr-defined/has-type diagnostics.", "evidence": ["Astra’s HEAD and four-production-file merge-base shadow runs exited 1 with 997 and 993 errors respectively, both in 89 files; after line normalization the four diagnostics at lines 79,79,83,84 are the only additions.", "Reconciler inspected /tmp/chunkhound-pr-489-astra-a1-sxteiwqi/mypy.log and mypy-base.log, confirmed those locations, and verified the attributes are initialized only on concrete service code. Sonnet also observed new diagnostics but classified them as baseline-pattern noise."], "reviewers": ["astra"], "id": 1}
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}
- site-build: SUCCESS (COMPLETED)
- site-build-validation (ubuntu-latest): SUCCESS (COMPLETED)
- site-build-validation (macos-latest): SUCCESS (COMPLETED)
- site-build-validation (windows-latest): SUCCESS (COMPLETED)
- rust-checks (ubuntu-latest): SUCCESS (COMPLETED)
- rust-checks (macos-latest): SUCCESS (COMPLETED)
- rust-checks (windows-latest): SUCCESS (COMPLETED)
- native-wheel-smoke-arm64: SUCCESS (COMPLETED)
- native-dev-macos: SUCCESS (COMPLETED)
- watchman-runtime-validation (ubuntu-latest, 3.14): SUCCESS (COMPLETED)
- watchman-runtime-validation (windows-latest, 3.14): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (ubuntu-latest, 3.14, 3): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (macos-latest, 3.14, 3): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 1): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 2): SUCCESS (COMPLETED)
- tests (windows-latest, 3.14, 3): SUCCESS (COMPLETED)
- old-linux-wheel-smoke (Ubuntu 20.04 (glibc 2.31), UBUNTU_20_04_IMAGE, ca-certificates curl, 3.12): SUCCESS (COMPLETED)
- old-linux-wheel-smoke (Ubuntu 22.04 + Python 3.10, UBUNTU_22_04_IMAGE, ca-certificates curl pytho...: SUCCESS (COMPLETED)
- watchman-rollout-gate: SUCCESS (COMPLETED)
- pages-artifact: SKIPPED (COMPLETED)
- deploy: SKIPPED (COMPLETED)
Reviewed by Ariel Vaknin via pi.dev
Brings in chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in chunkhound#489, chunkhound#474, chunkhound#488, chunkhound#521, chunkhound#510, chunkhound#504 and chunkhound#534. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
Problem
Every filtered realtime event calls
_emit_status_update(), which builds a full health snapshot and hands it to the status callback; the MCP daemon's_update_realtime_statusdeep-copies it. A burst of filtered events (annpm install, a junction tonode_modules) therefore builds one snapshot per event. With the real service wiring and a deep-copying consumer, 5,000 handled events cost 1.31 ms each with the status callback and 0.73 ms without it: the snapshot was about 44% of a filtered event's cost.Fix
A filtered event publishes status at most once per 0.5 s (
_FILTERED_STATUS_INTERVAL_SECONDS).stop()cancels it throughcancel_all(), resets the throttle, and its own final update carries the same counters.The loop owns all of this state. The snapshot builder reads the event counters and the event-pressure map, and trims that map; the loop mutates them too. So the watchdog observer's source and filtered callbacks no longer run on the observer thread:
forward_to_loop(inevents.py, besideSimpleEventHandler) hands each one to the loop withcall_soon_threadsafe. Callbacks run in the order they were scheduled, so a source event is still recorded before the same event is queued.Behaviour change for every watchdog event, not just filtered ones: an exception raised inside the source/filtered bookkeeping used to be swallowed by
SimpleEventHandler._record_*on the observer thread. It now surfaces in the loop's exception handler. If the loop is already closed,call_soon_threadsaferaises inside the handler, and that is still swallowed there.Accepted events, processing transitions and every other status source are unchanged.
Measurements
Measured with the first revision of this change, which used a
threading.Timerfor the trailing publish; the throttle interval and the number of publishes are the same now. Setup: this change on top of #485 (the same change; this PR carries it onmain), a realRealtimeIndexingServicewith a deep-copying status callback, Windows, 10-core CPU. A junction to a realnode_modulestree (44,302 files) produced 48,255 filteredcreatedevents. Handler time is measured on the observer thread over the first 5,000 events.Combined with the per-directory exclusion memo (#490), the same 5,000 events take 0.537 ms each. The full 48,255-event burst drops from 66.86 s to 27.52 s, and its status snapshots from 48,254 to 108.
Tests
tests/realtime/test_realtime_filtered_status_throttle.pysends 1,000 filtered events into a realRealtimeIndexingServicewith a deep-copying status callback. It freezespipeline.time.monotoniconly (every othertimefunction stays real), so the number of publishes does not depend on how fast the machine runs the burst.test_filtered_burst_publishes_once_then_once_more_with_final_counts: exactly two publishes, with filtered counts[1, 1000]. Before the change: 1,000 publishes.test_trailing_publish_runs_on_loop_while_event_pressure_changes: while the trailing publish is pending, the loop keeps adding and trimming event-pressure entries until a 5 s wall-clock deadline. Both publishes happen on the loop thread, with counts[1, 1000].test_stop_cancels_pending_trailing_publish_and_carries_its_counts:stop()publishes the final counts, nothing publishes after it, and a later filtered event publishes at once.🤖 Generated with Claude Code