Repository navigation
fix(watcher): isolate @parcel/watcher in a forked process so native crashes can't kill the app (#7547) - #7757
Conversation
watcher.node fail-fasts the whole main process (0xc0000409 on Windows, 5x in 25min for the reporter; same class as #5377/#6635). Root cause, confirmed by harness minimisation: unsubscribe() racing active event delivery — Subscription::stop() runs off the backend thread, CancelIo is thread-bound so it no-ops, and CloseHandle + free leave a pending ReadDirectoryChangesW completion pointing at the freed Subscription. Deletion/churn alone never crashed; adding unsubscribe crashed <3s. Local subscriptions now run in a forked ELECTRON_RUN_AS_NODE child (parcel-watcher-process-entry). The host client respawns it on crash, resubscribes every live root, and fires onInterruption so the renderer gets an overflow refresh across the gap. A crash loop (3/30s) degrades to watching-disabled with cooldown recovery instead of fork-bombing. The child also self-restarts via a canary watch when event delivery wedges silently (Debounce::notify vs ~Watcher lock-order inversion deadlocks parcel's single delivery thread: subscribes still ack but no events ever flow). Repro + verification harness in tools/repro-watcher-crash-7547: the in-process pattern crashes 7/7 in under 3s; the same load through the forked architecture passes 6/6 with contained child crashes and a functional watcher at the end.
📝 WalkthroughWalkthroughChangesThis PR isolates native Sequence Diagram(s)Diagrams included in the hidden review stack artifact illustrate subscribe/unsubscribe message flow and crash-respawn recovery between the host module and forked child process. Related issues: Suggested labels: electron, filesystem-watcher, crash-fix Suggested reviewers: (none specified) 🐰 A watcher forked off to roam alone, 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
tools/repro-watcher-crash-7547/README.md (1)
12-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSpecify language for fenced code blocks.
Both fenced code blocks (lines 12 and 38) lack a language specifier, triggering MD040. Add
bashorshellto the opening fence.📝 Proposed fix
-``` +npx electron-vite build node tools/repro-watcher-crash-7547/fixed-child.cjs 15000 -``` +```bash +npx electron-vite build node tools/repro-watcher-crash-7547/fixed-child.cjs 15000 +```Also applies to: 38-38
Source: Linters/SAST tools
tools/repro-watcher-crash-7547/run.cjs (1)
23-35: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueMissing
errorhandler on spawned child process.If
spawnemits an'error'event (e.g.,process.execPathis unexpectedly unavailable), the promise inrunOncenever resolves and the runner hangs silently. Adding an error handler is a one-liner safety net.🔒️ Proposed fix
child.stderr.on('data', (d) => { stderr += d process.stderr.write(d) }) + child.on('error', (err) => resolve({ code: -1, signal: null, stderr: String(err) })) child.on('exit', (code, signal) => resolve({ code, signal, stderr }))src/main/ipc/parcel-watcher-process-entry.ts (1)
44-107: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winCanary thresholds may false-positive under sustained heavy churn.
The wedge detector requires
CANARY_MAX_MISSES(2) consecutive probes where the touch event isn't delivered withinCANARY_EVENT_TIMEOUT_MS(5s), i.e. ~20–25s of undelivered canary events while roots are subscribed. Under the heavy multi-worktree churn this PR targets, parcel's single process-wide debounce thread can be backlogged, so a healthy watcher's canary event could legitimately arrive late for two consecutive probes, triggeringprocess.exit(2)and a full respawn + resubscribe of all roots — reintroducing churn precisely when the system is already loaded.Please confirm the 5s/2-miss budget is comfortably above worst-case debounce latency under churn, or consider widening the timeout / requiring more consecutive misses.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 426edfeb-7b48-4aab-8d2f-a216a77e98e2
📒 Files selected for processing (12)
config/electron-builder.config.cjsconfig/scripts/electron-builder-config.test.mjselectron.vite.config.tssrc/main/ipc/filesystem-watcher.tssrc/main/ipc/parcel-watcher-process-entry.tssrc/main/ipc/parcel-watcher-process.test.tssrc/main/ipc/parcel-watcher-process.tstools/repro-watcher-crash-7547/.gitignoretools/repro-watcher-crash-7547/README.mdtools/repro-watcher-crash-7547/child.cjstools/repro-watcher-crash-7547/fixed-child.cjstools/repro-watcher-crash-7547/run.cjs
| '__pycache__' | ||
| ] | ||
| const IGNORE = IGNORE_DIRS.flatMap((dir) => [`**/${dir}`, `**/${dir}/**`]) | ||
| const OPTS = { ignore: IGNORE, backend: 'windows' } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
backend: 'windows' is hardcoded, making the harness Windows-only.
The coding guidelines require scripts to remain compatible with macOS, Linux, and Windows. While the README states this is a "Windows-focused harness," the hardcoded backend: 'windows' will throw on non-Windows platforms since the Windows backend isn't available there. Consider guarding it with a runtime platform check so the harness can at least run (or gracefully skip) on other OSes.
🛡️ Proposed fix
-const OPTS = { ignore: IGNORE, backend: 'windows' }
+const OPTS = {
+ ignore: IGNORE,
+ ...(process.platform === 'win32' ? { backend: 'windows' } : {})
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const OPTS = { ignore: IGNORE, backend: 'windows' } | |
| const OPTS = { | |
| ignore: IGNORE, | |
| ...(process.platform === 'win32' ? { backend: 'windows' } : {}) | |
| } |
Source: Coding guidelines
| const meaning = KNOWN[code] || (code === 0 ? 'clean exit' : 'unexpected') | ||
| console.log(`=== [${s}] iter ${i}: exit=${code} (${hex(code ?? -1)}) signal=${signal} ${meaning} after ${elapsed}ms`) | ||
| results.push({ scenario: s, iteration: i, code, signal, elapsed }) | ||
| if (code !== 0 && code !== null) { | ||
| crashed = true | ||
| console.log(`\n*** NATIVE CRASH REPRODUCED in scenario "${s}" (exit ${hex(code)}) ***`) | ||
| break outer | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Non-crash exit codes (2, 3) are misreported as native crashes.
child.cjs exits with code 2 for unknown scenarios and code 3 for harness errors. The runner's check code !== 0 && code !== null treats these as native crashes, printing "NATIVE CRASH REPRODUCED" and stopping. This is misleading when a scenario name is mistyped.
🐛 Proposed fix
- if (code !== 0 && code !== null) {
+ if (code !== 0 && code !== null && !KNOWN[code] && code !== 2 && code !== 3) {Alternatively, check KNOWN[code] directly to only stop on known native crash codes.
…rashes can't kill the app (stablyai#7547) (stablyai#7757)
Fixes #7547 (Windows main-process crash in
watcher.node,0xc0000409fail-fast, 5x in ~25 min). Same crash class as #5377 (macOS) and #6635 (Linux serve).Root cause
@parcel/watcher2.5.6 has native teardown races. A reproduction harness (included, see below) reproduced the crash in under 3 seconds, 7/7 runs, and minimisation isolated the trigger:unsubscribe()while the backend thread is actively delivering events.unsubscribe()Orca must perform (worktree switch grace teardown, worktree deletion, error paths): crash within seconds.Mechanism (
src/windows/WindowsBackend.cc):Subscription::stop()runs on a non-backend thread;CancelIoonly cancels the calling thread's I/O so the pendingReadDirectoryChangesWsurvives;CloseHandle+ object free leave the kernel completing into a danglingOVERLAPPEDon the backend thread → UAF → heap corruption. That surfaces as0xC0000005or, with heap reuse, the reporter's0xc0000409fail-fast. Since Orca cannot stop unsubscribing (Windows keeps watched dirs locked, blockinggit worktree remove), no in-process usage pattern avoids this.The harness also exposed a second failure mode: a lock-order inversion (
Debounce::notifyholds the debounce mutex and wants the watcher mutex;~Watcherunderunwatch/notifyErrorholds the watcher mutex and wants the debounce mutex) deadlocks parcel's single process-wide delivery thread — subscriptions still ack but no events ever flow again.Fix (what the issue requested — VS Code-style isolation)
All local
filesystem-watcher.tssubscriptions now run in a disposable forked child (ELECTRON_RUN_AS_NODE, mirroring the computer-sidecar/daemon pattern):parcel-watcher-process-entry.ts— hosts the native module; exits on host disconnect so process death releases handles without running the crash-prone napi teardown. Includes a canary self-check (watches a private temp dir, touches a probe file every 10s; two missed deliveries → self-exit) that converts the silent-wedge deadlock into a clean restart.parcel-watcher-process.ts— host client: lazy fork, crash → respawn + transparent resubscribe of every live root,onInterruption→ overflow refresh so the renderer re-reads past the event gap, crash-loop breaker (3 crashes/30s → watching disabled, recovers after cooldown), in-process fallback when the built entry is absent (tests/unbuilt trees).filesystem-watcher.tsswaps the direct native subscribe for the client; app shutdown now just kills the child.asarUnpack(locked by a config test — a missing unpack would silently reintroduce the in-process crash).Out of scope, same crash family (possible follow-ups): runtime
file-watcher-worker.ts(worker_threads, non-Windows paired-client path) and macOSworktree-git-common-watch.tsnarrow watch; both could migrate to this client. Windows runtime file-explorer already avoids parcel. The UAF + deadlock are also clean upstream reports for parcel-bundler/watcher.Verification
Harness in
tools/repro-watcher-crash-7547/(manual, Windows; all churn underos.tmpdir()):node tools/repro-watcher-crash-7547/run.cjs delete-root→ host process native crash in 0.6–3s, 7/7 runs (0xC0000005; the corruption also manifests as the reporter's0xC0000409depending on heap state).node tools/repro-watcher-crash-7547/fixed-child.cjsdrives the identical load through the real client + real forked entry: 6/6 PASS — contained watcher-child crashes observed (the native bug still fires), host survives every time, roots resubscribed, and a final health check confirms events still flow, including recovery after the crash-loop breaker trips.Also addresses the issue's secondary effect: worktrees vanishing after relaunch were caused by the main process dying mid-write of workspace state — contained child crashes no longer take the state writer down.