Skip to content

perf(main): move hang watchdog into a worker thread - #11344

Merged
nwparker merged 1 commit into
mainfrom
nwparker/main-hang-watchdog-worker
Jul 29, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/main-hang-watchdog-worker

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

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_NODE environment plumbing, plain-Node entry registration, and the watchdog-specific asarUnpack entry. The worker loads its bundled entry directly from app.asar, following Orca's existing worker-entry pattern.

Performance

Measured against the actual bundled out/main/main-thread-hang-watchdog-entry.js under Orca's Electron 43.1.0 runtime on macOS:

Design Watchdog memory cost
Merged ELECTRON_RUN_AS_NODE child (#10256) 47.1 MiB RSS
This PR's worker thread 11.5 MiB incremental RSS
Reduction 35.6 MiB / 75.6%

Measurement waited for app.whenReady(), allowed Electron startup to settle, forced GC before and after worker startup, and sampled process.memoryUsage().rss. The measured worker was the production-built entry, not an inline synthetic worker.

Reliability contract

  • A worker thread continues while the Electron main thread is synchronously blocked; the built entry detected a forced 1.2 second main-thread stall at a 500 ms test threshold.
  • The unresolved marker was present before the main thread resumed.
  • The first resumed heartbeat rewrote the marker with selfRecovered: true.
  • Worker startup/runtime failure remains fail-open and cannot affect app startup.
  • unref() and idempotent will-quit shutdown 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 lint
  • pnpm typecheck
  • pnpm test — focused watchdog and packaging suite run instead: 62 tests passed
  • pnpm build — pnpm exec electron-vite build passed; native helper builds are untouched
  • Added or updated high-quality tests that would catch regressions

Additional verification:

  • Production Electron build emits a 2.78 kB watchdog worker entry.
  • Live Electron test against the built entry: detectedWhileMainBlocked: true, resolvedAfterHeartbeat: true.
  • pnpm exec oxfmt --check passed for every changed source/config file.
  • git diff --check passed.

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:

  • Whether a worker remains live during the actual target failure. Verified with a synchronous main-thread block against the production-built worker.
  • Whether replacing process IPC changes hang timing, marker contents, recovery classification, telemetry, or consent behavior. Those contracts remain unchanged.
  • Worker lifecycle races: construction failure, runtime error, early exit, repeated will-quit, posting after exit, and process-lifetime retention.
  • Packaged path resolution through app.asar, development path fallback, Rollup entry output, and removal of obsolete plain-Node/asarUnpack wiring.
  • Cross-platform behavior: the watchdog remains macOS-only and packaged-only unless explicitly forced; all paths use 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

  • No new dependency, network request, command execution, shell interpolation, authentication path, secret handling, or external input was added.
  • Worker data is internal and validated before arming: positive integer PID, string marker path, and finite positive timing values.
  • The marker path still derives from canonical userData with path.join; no renderer or remote path can select it.
  • Worker messaging is limited to internal structured heartbeat and shutdown messages.
  • The worker remains observation-only: it never signals, kills, relaunches, or exits the parent.
  • Marker and telemetry fields are unchanged, so no additional PII reaches disk or the wire.

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.

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-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR moves the main-thread hang watchdog from a forked ELECTRON_RUN_AS_NODE child process to a Node Worker thread, reducing the memory overhead by ~75% (47 MiB → 11.5 MiB incremental RSS) while preserving the same heartbeat/marker contract for detecting macOS AppKit deadlocks.

  • The worker now loads its bundled entry directly from app.asar (no asarUnpack needed), sends workerData in place of env-var plumbing, and shuts down cleanly via port.close() after receiving a shutdown message; worker.unref() ensures the worker cannot extend process lifetime.
  • Supporting files are updated consistently: hang-watchdog-child-loop is renamed to hang-watchdog-detection-loop, the entry is removed from the plain-node-entry-guard (it may now safely reach Electron modules), and the asarUnpack entry in electron-builder.config.cjs is removed.
  • Test coverage is thorough, adding worker-exit, construction-failure, timing-override, and idempotent-shutdown cases.

Confidence Score: 4/5

Safe 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

Important Files Changed

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)

  1. src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts, line 7-13 (link)

    P2 Stale child_process mock leftover from fork-based implementation

    The entry no longer imports node:child_process at all, so spawnMock is never populated and expect(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 in recordHangObservation is now a dead assertion. The relevant escalation surface for the new worker design would be parentPort.postMessage (which can't signal the parent process), but the test no longer covers spawn in 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!

  2. src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts, line 70-80 (link)

    P2 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.ts was 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

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 78b85f36-e5a7-4d51-9b5c-0c345fd8fa37

📥 Commits

Reviewing files that changed from the base of the PR and between ef55429 and 8091fe9.

📒 Files selected for processing (14)
  • build-plugins/plain-node-entry-guard.ts
  • config/electron-builder.config.cjs
  • config/scripts/electron-builder-config.test.mjs
  • electron.vite.config.ts
  • src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts
  • src/main/hang-watchdog/hang-watchdog-detection-loop.ts
  • src/main/hang-watchdog/hang-watchdog-entry-path.ts
  • src/main/hang-watchdog/hang-watchdog-worker-path.test.ts
  • src/main/hang-watchdog/hang-watchdog-worker-path.ts
  • src/main/hang-watchdog/hang-watchdog-worker-protocol.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog.test.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog.ts
💤 Files with no reviewable changes (4)
  • src/main/hang-watchdog/hang-watchdog-entry-path.ts
  • build-plugins/plain-node-entry-guard.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts
  • config/electron-builder.config.cjs

📝 Walkthrough

Walkthrough

The 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)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: moving the hang watchdog to a worker thread.
Description check ✅ Passed All required sections are present and substantive, including testing, review, security, and notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

@nwparker
nwparker merged commit 3f37e32 into main Jul 29, 2026
33 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant