Repository navigation
Run @parcel/watcher in a self-healing child process - #250
Merged
Merged
Conversation
Run the recursive filesystem watcher in a forked child process behind the BB_WATCHER_SUBPROCESS flag (off by default, zero behavior change when off). When the child dies or stops answering liveness pings, the parent SIGKILLs it — reclaiming leaked inotify fds and parked threads wholesale, which in-process recovery cannot do — then respawns it and replays subscriptions, so a parcel inotify EINTR crash/hang degrades to a transparent restart instead of taking down the daemon. This mirrors how VS Code isolates the same library (forked watcher process, restart on exit). - Swap RootSubscription's direct @parcel/watcher import for a backend accessor (the single runtime chokepoint); default stays the real in-process watcher. - Add the subprocess backend: parent proxy (subscription registry, liveness ping, respawn + replay, bounded restart budget), child handler, JSON-safe IPC protocol, and fork channel. - Close the restart gap: replayed subscriptions carry a rescan flag so the new child re-emits the root's current entries and callers reconcile to on-disk state. - Emit the child as its own daemon bundle (bb-parcel-watcher-child.mjs); @parcel/watcher stays an external runtime require. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove the BB_WATCHER_SUBPROCESS flag. The daemon now installs the subprocess-isolated watcher backend at startup, so it is the actual behavior rather than an opt-in. Unit tests inject a fake watcher and stay on the in-process backend, so they can still mock parcel directly. Critically, recover from the bug instead of only containing it: a watch-error from the child (parcel's shared inotify backend dying on EINTR) now recycles the whole child. The SIGKILL lets the OS reclaim the leaked inotify fds and parked threads, and the respawn re-arms every watch on a fresh backend, so watches self-heal instead of going permanently dead. Respawn/recycle events are logged through the daemon's pino logger. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A multi-agent QA pass on this branch surfaced several merge-blocking defects; this commit fixes the critical + high-severity ones (all with regression tests). - PACKAGING (critical): the published bb-app `files` whitelist and the startup artifact check both omitted bb-parcel-watcher-child.mjs, so an `npx bb-app` install would throw on the first subscription and have permanently dead file watching. Add it to both. - SHUTDOWN (high): the proxy was never disposed and its ping interval was not unref'd, so a graceful daemon shutdown hung with the child orphaned — the same hang/leak class this change exists to prevent. Dispose the backend in shutdownRuntimes and unref the ping/respawn timers. - REPLAY vs pathExists (high): a transient missing path during respawn produced a child subscribe-failed that RootSubscription classified as TERMINAL (no retry), permanently killing the watch. Surface replay subscribe failures as the recoverable rescan signal so RootSubscription re-establishes via its existence-gated, backed-off retry. - RESTART LOOP (high): a permanent give-up after a fixed restart budget plus a no-backoff respawn loop could kill all watches for the daemon's lifetime. Replace with capped exponential backoff that resets when a child proves healthy, so the watcher always recovers and never permanently gives up. - DOUBLE-SUBSCRIBE (high): a subscribe landing in the spawn->ready window was sent eagerly AND replayed on ready, orphaning one parcel watch (leaked inotify fd) and double-delivering events. Gate the eager send on childReady so replay-on-ready is the single source. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ymichael
force-pushed
the
bb/investigate-inotify-watchers-thr_qcv8rurevn
branch
from
June 22, 2026 17:11
c6902c5 to
12cd9cf
Compare
ymichael
added a commit
that referenced
this pull request
Aug 28, 2026
## Human comments ## What was wrong `RootSubscription` already distinguishes the native FSEvents `File system must be re-scanned` condition from fatal watcher failures and performs targeted refresh/reconnect/refresh recovery. The subprocess boundary introduced by PR #250 erased that distinction: every parcel callback error became the same `watch-error`, and the parent unconditionally killed the shared watcher child, replayed every subscription, called `listEntries` for every root, and emitted synthetic updates to unaffected watches. Whole-child recycling is required for fatal Linux backend failures such as inotify `EINTR`, but it turns a recoverable subscription-specific FSEvents overflow into O(all active watches) work. Historical supporting evidence, separate from the controlled benchmark below: - Apr 20 commits `64c74f0a0` and `1283e636e` introduced targeted FSEvents recovery. - Jun 8 commit `2160f2838` moved that lifecycle into `RootSubscription`. - Jun 12 commit `9786b64d9` made fatal Linux inotify callback errors terminal in-process to prevent retry leaks. - Jun 22 PR #250 / commit `cba0b9e89` intentionally added whole-child recycling for fatal `EINTR`, child crashes, and hangs. Its interception was broad because the child protocol had no recovery classification, not because FSEvents overflow was intended to become global. - The investigation observed 57 ready environment watches in the affected deployment. That production observation selected the N=57 fixture; it is not included in the controlled timing data. ## What changed - Classify parcel callback errors in the watcher child as either `rescan-subscription` or `recycle-child`. - Route `rescan-subscription` only to the matching proxy callback with the original message, allowing the existing `RootSubscription` targeted recovery to run without replacing the child. - Keep all non-rescan callback errors on the existing whole-child recycle path. Child exits and liveness timeouts are unchanged. - Add a two-subscription regression, a deterministic proxy fan-out count harness, and an opt-in end-to-end N=57/N=100 recovery benchmark. This changes only the bundled parent/child watcher subprocess protocol. It does not change the server/host-daemon wire protocol, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. ## How you verified ### Controlled end-to-end benchmark Both revisions ran sequentially on the same machine with byte-identical benchmark code and generated fixture contents: macOS 26.5.1 / Darwin 25.5.0 arm64, Node 22.23.1, pnpm 9.15.0. “Before” is `origin/main` at `a2fcbaf55` with only the two benchmark files applied; “after” is `d3078ca4c`. Each scenario used 2 warm-ups and 20 measured iterations. Every iteration created a fresh real child process, IPC channel, native watcher set, `HostWatcher`, and `RootSubscription` set. Each root contains 8 directories with 16 × 4 KiB files each plus one 4 KiB trigger file: 129 files, 528,384 bytes, 9 top-level entries, and 137 recursive tree entries per root. | Roots | Nested directories | Files | Bytes | Recursive entries | | ---: | ---: | ---: | ---: | ---: | | 57 | 456 | 7,353 | 30,117,888 (28.72 MiB) | 7,809 | | 100 | 800 | 12,900 | 52,838,400 (50.39 MiB) | 13,700 | The measured path is: `real file write → real @parcel/watcher/FSEvents subscription in a forked child → production child handler and IPC channel → production proxy → HostWatcher.watchPathRoot → RootSubscription → production 250 ms reconnect retry and 75/500 ms callback scheduler → calibrated recursive readdir/read/SHA-256 downstream refresh` Root 0 alone receives the injected overflow. Measurement begins before the real trigger-file write and stops only after exact settled-work predicates pass. Before requires one child restart, all N proxy/native replay subscriptions, all N real `listEntries` calls, all N synthetic event callbacks, and all N recursive downstream scans. After requires the affected native unsubscribe/reconnect, both targeted rescan notifications, and both affected-root downstream scans. Subscribe/unsubscribe starts must equal completions, and a 100 ms quiescence assertion rejects late work after settlement. The controlled-load mode runs repeated SHA-256 work for 8 ms and yields for 8 ms on the benchmark process's event-loop thread. It is reproducible and does not load every CPU core or the live bb server. “Idle” means no intentional benchmark load, not a dedicated idle host. #### Settled recovery latency Milliseconds, p50 / p95 / max. The N=57 distributions mostly overlap because targeted recovery deliberately retains its retry and two debounce phases; the after idle p50 is higher. The scaling benefit becomes clear at N=100, especially under controlled load. | Roots | Mode | Before | After | | ---: | --- | ---: | ---: | | 57 | idle | 291.6 / 449.7 / 529.4 | 340.1 / 379.9 / 445.0 | | 57 | controlled CPU | 380.2 / 383.7 / 400.2 | 367.3 / 390.0 / 429.4 | | 100 | idle | 361.5 / 1,179.5 / 2,419.7 | 355.6 / 460.1 / 510.3 | | 100 | controlled CPU | 2,606.9 / 5,095.9 / 6,599.1 | 367.8 / 375.4 / 441.1 | #### Maximum event-loop delay per iteration Milliseconds, distribution of each iteration's maximum delay as p50 / p95 / max. | Roots | Mode | Before | After | | ---: | --- | ---: | ---: | | 57 | idle | 1.88 / 6.34 / 6.35 | 2.05 / 6.92 / 8.31 | | 57 | controlled CPU | 9.32 / 9.52 / 9.54 | 9.36 / 10.22 / 23.41 | | 100 | idle | 1.89 / 27.20 / 50.30 | 2.20 / 7.51 / 8.08 | | 100 | controlled CPU | 67.08 / 145.88 / 211.81 | 9.34 / 10.57 / 14.03 | #### Initial readiness Milliseconds from constructing the watcher graph until all HostWatcher `onReady` callbacks and all native subscriptions were ready, p50 / p95 / max. This happens before overflow injection and is recorded separately from recovery latency. | Roots | Mode | Before | After | | ---: | --- | ---: | ---: | | 57 | idle | 129.0 / 277.4 / 461.9 | 220.4 / 350.0 / 402.0 | | 57 | controlled CPU | 128.5 / 131.2 / 132.9 | 129.9 / 157.7 / 171.3 | | 100 | idle | 135.8 / 426.6 / 771.4 | 152.9 / 906.5 / 981.8 | | 100 | controlled CPU | 339.0 / 843.9 / 901.1 | 139.1 / 1,104.0 / 1,239.0 | #### Deterministic settled work Counts were identical across all 20 idle iterations and all 20 controlled-load iterations for each revision. “2 scans after” is the affected `RootSubscription`'s dropped-event refresh plus its post-reconnect refresh; zero `listEntries` means zero global proxy replay scans, not zero targeted recovery. | Metric after one overflow | 57 before | 57 after | 100 before | 100 after | | --- | ---: | ---: | ---: | ---: | | watcher-child restarts | 1 | 0 | 1 | 0 | | proxy subscribe messages | 57 | 1 | 100 | 1 | | proxy replay subscriptions | 57 | 0 | 100 | 0 | | proxy unsubscribe messages | 0 | 1 | 0 | 1 | | native subscribe starts / ready | 57 / 57 | 1 / 1 | 100 / 100 | 1 / 1 | | native unsubscribe starts / ready | 0 / 0 | 1 / 1 | 0 / 0 | 1 / 1 | | real `listEntries` calls / entries | 57 / 513 | 0 / 0 | 100 / 900 | 0 / 0 | | child event batches / events | 57 / 513 | 0 / 0 | 100 / 900 | 0 / 0 | | host event batches / events | 57 / 513 | 0 / 0 | 100 / 900 | 0 / 0 | | targeted rescan notifications | 0 | 2 | 0 | 2 | | affected / unaffected downstream scans | 1 / 56 | 2 / 0 | 1 / 99 | 2 / 0 | | downstream files read | 7,353 | 258 | 12,900 | 258 | | downstream bytes read | 30,117,888 | 1,056,768 | 52,838,400 | 1,056,768 | | downstream entries processed | 7,809 | 274 | 13,700 | 274 | | watcher errors | 0 | 0 | 0 | 0 | #### Remaining controlled substitutions and limitations - A native FSEvents overflow is not induced. At the narrowest deterministic seam, the benchmark child converts the real trigger-file event into the exact rescan-required callback error immediately before the production child handler. The native subscription, trigger event, process fork, IPC, handler, proxy, HostWatcher, RootSubscription, retry, reconnect, and filesystem work remain real. - The benchmark child entry is TypeScript under `tsx`, rather than the packaged production entry, so it can wrap the real parcel backend and emit telemetry. The child handler and IPC protocol under test are production code. - Running the full daemon/workspace callback graph safely would mix status/environment/server effects into a watcher-only PR. The downstream callback is explicitly calibrated: production debounce scheduling followed by recursive real filesystem reads and SHA-256 of every file. It does not include WatchManager status/environment work, database/server work, production logging, or production filesystem shape/cache state. - The load generator contends with the host-side watcher/recovery event loop only. It models event-loop pressure reproducibly; it is not a whole-machine production-load replay. Full per-iteration JSON, including event-loop utilization, per-iteration delay p50/p95/max, load cycles, readiness, latency, and all counters, is produced by `BB_WATCHER_BENCHMARK_OUTPUT`. Reproduction harness: `packages/host-watcher/test/root-recovery-benchmark.test.ts` and `packages/host-watcher/test/fixtures/parcel-recovery-benchmark-child.ts`. ```sh git worktree add /tmp/bb-watcher-before a2fcbaf git worktree add /tmp/bb-watcher-after d3078ca git -C /tmp/bb-watcher-before checkout d3078ca -- packages/host-watcher/test/root-recovery-benchmark.test.ts packages/host-watcher/test/fixtures/parcel-recovery-benchmark-child.ts pnpm --dir /tmp/bb-watcher-before install --frozen-lockfile pnpm --dir /tmp/bb-watcher-after install --frozen-lockfile BB_WATCHER_ROOT_RECOVERY_BENCHMARK=1 BB_WATCHER_BENCHMARK_ITERATIONS=20 BB_WATCHER_BENCHMARK_WARMUPS=2 BB_WATCHER_BENCHMARK_OUTPUT=/tmp/watcher-before.json pnpm --dir /tmp/bb-watcher-before exec turbo run test --filter=@bb/host-watcher --force --env-mode=loose -- --run test/root-recovery-benchmark.test.ts --silent=false BB_WATCHER_ROOT_RECOVERY_BENCHMARK=1 BB_WATCHER_BENCHMARK_ITERATIONS=20 BB_WATCHER_BENCHMARK_WARMUPS=2 BB_WATCHER_BENCHMARK_OUTPUT=/tmp/watcher-after.json pnpm --dir /tmp/bb-watcher-after exec turbo run test --filter=@bb/host-watcher --force --env-mode=loose -- --run test/root-recovery-benchmark.test.ts --silent=false ``` ### Regression and validation - Applying the new proxy test to `a2fcbaf55` fails with `expected [ Array(2) ] to have a length of 1 but got 2`; it passes on `d3078ca4c`: ```sh pnpm exec turbo run test --filter=@bb/host-watcher --force -- --run test/parcel-watcher-proxy.test.ts -t "routes rescan-required errors only to the affected subscription" ``` - `pnpm exec turbo run test --filter=@bb/host-watcher --force` — 47 passed, 3 opt-in/platform-skipped. - `pnpm exec turbo run typecheck --filter=@bb/host-watcher` — passed. - `pnpm exec turbo run build --filter=@bb/host-watcher --filter=@bb/host-daemon` — 5 Turbo tasks passed; watcher child bundle built at 1,945 bytes. - `pnpm exec turbo run test --filter=@bb/host-daemon --force -- --run src/watch-manager.test.ts test/parcel-watcher-not-loaded-in-parent.test.ts` — 19 passed. - The full host-daemon run reached 564/565 passing tests, but current `origin/main` and this branch both fail host-daemon typecheck at `host-branches-dispatch.test.ts:392` because `host.list_branches` is absent from the current command union. That unrelated daemon work is not changed here. No linked issue. > AGENT GENERATED
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
The host daemon's recursive filesystem watcher (
@parcel/watcher) throws on a benignpoll()EINTR in its inotify backend instead of retrying. One throw kills the shared native backend, leaks its inotify fds + threads, and can hang the daemon (requiring a manual restart); watches also die silently. There is no upstream fix to wait for: 2.5.6 is latest, issue #141 is open with no PR, and the bug is unchanged on the default branch.VS Code depends on the same library/version for recursive watching and runs it in a separate forked process it restarts on exit. This PR brings that pattern to bb.
What
Run
@parcel/watcherin a forked child process — installed by the daemon at startup (no flag). When the child dies, stops answering liveness pings, or reports a backend error (EINTR), the parentSIGKILLs it (the OS reclaims the leaked fds/threads wholesale) and respawns it, replaying subscriptions. The bug self-heals instead of taking down the daemon or leaving watches dead.RootSubscription(the only runtime importer of parcel) calls a backend accessor; the daemon installs the subprocess backend, tests stay in-process and mock parcel directly. Everything aboveRootSubscriptionis unchanged.subscribe/unsubscribeover IPC, holds the subscription registry, pings for liveness, and recovers on death/wedge/backend-error.RootSubscriptionre-establishes via its existence-gated retry.bb-parcel-watcher-child.mjs), in thefileswhitelist + startup artifact check; it exits itself when the parent IPC disconnects (no orphan). On shutdown the daemon disposes the proxy (SIGKILL child + unref timers) so the event loop drains.QA
Two adversarial multi-agent review passes (decompose → independent skeptics refute each finding → dynamic probes). The first found the happy path solid but surfaced 5 critical/high merge-blockers, since fixed in this PR (each with a regression test):
bb-apptarball omitted the child bundle (files+ artifact check) → permanently dead watching fornpxusers.unref'd → daemon hung on graceful shutdown with the child orphaned.pathExistsgate → a transient missing path during respawn became a permanently dead watch (terminal, no retry).A second focused re-QA of the fixes found no new defects (overall risk: low).
Testing
@bb/host-watchertests (9 proxy tests incl. crash/EINTR-recycle/ping-wedge/backoff/recoverable-replay/no-double-subscribe), 355@bb/host-daemon, 37bb-app; typecheck + full daemon build +check-bundlesgreen.SIGKILLchild → respawn (new pid) → events resume with no caller action; anddispose()reaps the child and the event loop drains on its own (shutdown no longer hangs).Deferred follow-ups (medium/low, not blocking)
refs/heads/*) and gap-window deletions aren't reconciled until the next real fs event (short, self-correcting). A precise fix is parcel'sgetEventsSincesnapshot API./proc; point it at the child pid.🤖 Generated with Claude Code