Repository navigation
perf(main): move hang watchdog into a worker thread - #11344
Conversation
Keep main-thread hang detection independent of the blocked Electron event loop without paying for a second ELECTRON_RUN_AS_NODE process. Preserve the marker and telemetry contract while moving timing configuration and heartbeats onto a bundled worker entry.
Greptile SummaryThis PR moves the main-thread hang watchdog from a forked
Confidence Score: 4/5Safe to merge; the execution-boundary change is well-reasoned and the lifecycle handling is correct. The worker lifecycle is handled correctly: construction failure is fail-open, the exit handler guards heartbeat timers, shutdown is idempotent, and worker.unref() prevents the worker from extending app lifetime. The only findings are documentation gaps — the critical 'a false positive would kill a live main thread mid-write' explanation was stripped from both the file header and the test, and the node:child_process mock in the entry test is now dead code that no longer connects to anything the module uses. Files Needing Attention: src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts — stale mock and removed safety comment
|
| Filename | Overview |
|---|---|
| src/main/hang-watchdog/main-thread-hang-watchdog.ts | Replaces child_process.fork with Worker; adds worker.unref(), idempotent stop, and exit-event cleanup — lifecycle handling is correct |
| src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts | Rewired to worker_threads (parentPort/workerData); runWatchdog now uses port.close() for clean shutdown; isHangWatchdogWorkerData guard correctly validates all fields including positive-int checks |
| src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts | Tests cover the core safety contract but retain a stale node:child_process mock and lost the critical comment explaining why the no-kill guarantee is essential |
| src/main/hang-watchdog/hang-watchdog-worker-path.ts | Correctly drops the .asar.unpacked substitution (workers load from inside asar unlike fork); dev adjacent-entry detection preserved |
| src/main/hang-watchdog/hang-watchdog-worker-protocol.ts | New file defining shared timing constants and typed worker message protocol; clean and minimal |
| build-plugins/plain-node-entry-guard.ts | Correctly removes main-thread-hang-watchdog-entry from plain-Node guard; the entry now runs in a worker thread where require('electron') is valid |
| config/electron-builder.config.cjs | Removes watchdog entry from asarUnpack; worker_threads loads directly from app.asar so unpacking is no longer needed |
Comments Outside Diff (2)
-
src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts, line 7-13 (link)Stale
child_processmock leftover from fork-based implementationThe entry no longer imports
node:child_processat all, sospawnMockis never populated andexpect(spawnMock).not.toHaveBeenCalled()on line 77 is trivially true regardless of what the code does. The guard that was meant to catch rogue process-spawning inrecordHangObservationis now a dead assertion. The relevant escalation surface for the new worker design would beparentPort.postMessage(which can't signal the parent process), but the test no longer coversspawnin any meaningful way — if the module were to re-introduce it, the Vitest module mock would still intercept it, but the intent is obscured.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
-
src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts, line 70-80 (link)Removed safety-critical test documentation
The removed comment read: "Why: this is the safety contract of the whole PR. Observing a hang must never kill, relaunch, or exit — a false positive would SIGKILL a live main thread mid-write. If a future change reintroduces recovery, this test must fail loudly rather than ship silently." Without it, a future developer has no signal that weakening this test could silently enable a behaviour that kills a live main thread during an I/O flush. The companion file-level comment in
main-thread-hang-watchdog-entry.tswas also replaced with a much shorter one-liner, losing the "all of the downside sits in the misfire" rationale. Both removals reduce the bus-factor safety of this design.
Reviews (1): Last reviewed commit: "perf(main): move hang watchdog into a wo..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (14)
💤 Files with no reviewable changes (4)
📝 WalkthroughWalkthroughThe hang watchdog detection loop API was renamed and given shared worker protocol types, timing constants, and path resolution. Watchdog execution moved from a forked child process to a worker thread with heartbeat, shutdown, validation, exit handling, and updated tests. The watchdog entry was removed from plain-Node Electron-require scanning and Electron Builder’s unpack list, with the packaging regression test updated accordingly. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
Keep main-thread hang detection independent of the blocked Electron event loop while reducing watchdog memory from 47.1 MiB to 11.5 MiB. Preserve marker, recovery, and telemetry behavior with a bundled worker-thread entry.
Summary
Follow-up to #10256: keep measuring macOS main-thread hangs without paying for a second always-on Electron-as-Node process.
The watchdog now runs in a Node worker thread inside the Electron main process. The worker has its own V8 isolate and event loop, so it keeps checking heartbeats and writing the existing marker while AppKit blocks the Electron main thread. The hang threshold, sleep suppression, self-recovery classification, marker format, startup consumption, breadcrumb, and telemetry event are unchanged.
This removes the
child_process.fork()boundary,ELECTRON_RUN_AS_NODEenvironment plumbing, plain-Node entry registration, and the watchdog-specificasarUnpackentry. The worker loads its bundled entry directly fromapp.asar, following Orca's existing worker-entry pattern.Performance
Measured against the actual bundled
out/main/main-thread-hang-watchdog-entry.jsunder Orca's Electron 43.1.0 runtime on macOS:ELECTRON_RUN_AS_NODEchild (#10256)Measurement waited for
app.whenReady(), allowed Electron startup to settle, forced GC before and after worker startup, and sampledprocess.memoryUsage().rss. The measured worker was the production-built entry, not an inline synthetic worker.Reliability contract
selfRecovered: true.unref()and idempotentwill-quitshutdown prevent the worker from extending app lifetime.The deliberate tradeoff is that a worker cannot observe a whole-process suspension such as
SIGSTOP. The captured macOS 26 failure is an AppKit main-thread lock inversion, and crashes already have their own reporting path, so the worker preserves the failure coverage this telemetry is intended to measure.Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm test— focused watchdog and packaging suite run instead: 62 tests passedpnpm build—pnpm exec electron-vite buildpassed; native helper builds are untouchedAdditional verification:
detectedWhileMainBlocked: true,resolvedAfterHeartbeat: true.pnpm exec oxfmt --checkpassed for every changed source/config file.git diff --checkpassed.Coverage includes platform/dev gating, packaged and development worker paths, worker data and timing overrides, heartbeat cadence, idempotent shutdown, worker exit, constructor failure, sleep suppression, repeated hangs, marker overwrite, strict telemetry schema, plain-Node guard configuration, and Electron builder packaging.
AI Review Report
The review focused on the execution-boundary change and checked:
will-quit, posting after exit, and process-lifetime retention.app.asar, development path fallback, Rollup entry output, and removal of obsolete plain-Node/asarUnpackwiring.node:path; Linux and Windows remain no-ops. No shortcuts, labels, shell commands, SSH behavior, folder-workspace assumptions, Git commands, or provider-specific behavior changed.The review also considered reusing the parcel-watcher child. That process is lazy, may be torn down when idle, deliberately restarts after native watcher faults, and can have multiple instances, so coupling hang telemetry to it would weaken coverage. Stale "child loop" names were renamed to describe the detection state machine rather than the old process topology.
No unresolved correctness or maintainability findings remain.
Security Audit
userDatawithpath.join; no renderer or remote path can select it.heartbeatandshutdownmessages.No security follow-up is required.
Notes
This intentionally optimizes for the observed main-thread AppKit deadlock. If field evidence later shows process-wide wedges that leave other threads unable to run, a small signed native monitor would be the next isolation boundary, but that complexity is not justified by the current failure evidence.