Skip to content

fix(watcher): isolate @parcel/watcher in a forked process so native crashes can't kill the app (#7547) - #7757

Merged
Jinwoo-H merged 1 commit into
mainfrom
Jinwoo-H/bug-windows-main-process-crash-in-native-file-wa
Jul 8, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
Jinwoo-H/bug-windows-main-process-crash-in-native-file-wa

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Fixes #7547 (Windows main-process crash in watcher.node, 0xc0000409 fail-fast, 5x in ~25 min). Same crash class as #5377 (macOS) and #6635 (Linux serve).

Root cause

@parcel/watcher 2.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.

  • Deleting a watched worktree root alone: no crash.
  • Heavy churn alone: no crash.
  • Adding the 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; CancelIo only cancels the calling thread's I/O so the pending ReadDirectoryChangesW survives; CloseHandle + object free leave the kernel completing into a dangling OVERLAPPED on the backend thread → UAF → heap corruption. That surfaces as 0xC0000005 or, with heap reuse, the reporter's 0xc0000409 fail-fast. Since Orca cannot stop unsubscribing (Windows keeps watched dirs locked, blocking git worktree remove), no in-process usage pattern avoids this.

The harness also exposed a second failure mode: a lock-order inversion (Debounce::notify holds the debounce mutex and wants the watcher mutex; ~Watcher under unwatch/notifyError holds 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.ts subscriptions 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.ts swaps the direct native subscribe for the client; app shutdown now just kills the child.
  • Packaging: new vite entry + 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 macOS worktree-git-common-watch.ts narrow 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 under os.tmpdir()):

  • Before: 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's 0xC0000409 depending on heap state).
  • After: node tools/repro-watcher-crash-7547/fixed-child.cjs drives 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.
  • 9 new client regression tests (crash→respawn→resubscribe→interruption, in-flight subscribe across respawn, breaker, unsubscribe acks); all existing watcher suites pass unchanged via the in-process fallback (71 passed). Typecheck + oxlint clean.

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.

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.
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

This PR isolates native @parcel/watcher file-watching into a forked child process to prevent native crashes from taking down Electron's main process. It adds a new watcher-process entry script and a host module (parcel-watcher-process.ts) implementing subscribe/unsubscribe IPC, a canary watchdog, crash-cooldown/respawn/resubscribe logic, and an in-process fallback. filesystem-watcher.ts is updated to use the new host APIs and dispose the child on shutdown. Build/packaging configs are updated to bundle and unpack the new entry script, with accompanying regression tests. Standalone reproduction and verification harness scripts are added under tools/repro-watcher-crash-7547.

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: #7547 (native crash in @parcel/watcher on Windows backend)

Suggested labels: electron, filesystem-watcher, crash-fix

Suggested reviewers: (none specified)

🐰 A watcher forked off to roam alone,
so crashes in the wild won't shake the throne.
Canaries chirp when signals go astray,
and respawned processes carry on the day.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits required template sections like Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the missing template sections, including screenshots/no visual change, testing checklist, AI review notes, security audit, and platform-specific notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately describes the main change: isolating @parcel/watcher in a forked child process to prevent native crashes from taking down the app.
Linked Issues check ✅ Passed The PR matches #7547 by isolating the watcher in a forked process, resubscribing after crashes, and adding packaging/tests to prevent app-wide failure.
Out of Scope Changes check ✅ Passed The added harness, tests, config, and docs support the watcher isolation fix and its regression coverage; no clear unrelated changes stand out.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
tools/repro-watcher-crash-7547/README.md (1)

12-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Specify language for fenced code blocks.

Both fenced code blocks (lines 12 and 38) lack a language specifier, triggering MD040. Add bash or shell to 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 value

Missing error handler on spawned child process.

If spawn emits an 'error' event (e.g., process.execPath is unexpectedly unavailable), the promise in runOnce never 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 win

Canary 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 within CANARY_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, triggering process.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

📥 Commits

Reviewing files that changed from the base of the PR and between 37ba94a and d4aff8c.

📒 Files selected for processing (12)
  • config/electron-builder.config.cjs
  • config/scripts/electron-builder-config.test.mjs
  • electron.vite.config.ts
  • src/main/ipc/filesystem-watcher.ts
  • src/main/ipc/parcel-watcher-process-entry.ts
  • src/main/ipc/parcel-watcher-process.test.ts
  • src/main/ipc/parcel-watcher-process.ts
  • tools/repro-watcher-crash-7547/.gitignore
  • tools/repro-watcher-crash-7547/README.md
  • tools/repro-watcher-crash-7547/child.cjs
  • tools/repro-watcher-crash-7547/fixed-child.cjs
  • tools/repro-watcher-crash-7547/run.cjs

'__pycache__'
]
const IGNORE = IGNORE_DIRS.flatMap((dir) => [`**/${dir}`, `**/${dir}/**`])
const OPTS = { ignore: IGNORE, backend: 'windows' }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
const OPTS = { ignore: IGNORE, backend: 'windows' }
const OPTS = {
ignore: IGNORE,
...(process.platform === 'win32' ? { backend: 'windows' } : {})
}

Source: Coding guidelines

Comment on lines +54 to +61
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant