Skip to content

feat(main): record main-thread hangs so we can measure them - #10256

Merged
nwparker merged 1 commit into
mainfrom
brennanb2025/main-hang-watchdog
Jul 28, 2026
Merged

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

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Sometimes Orca freezes solid on newer macOS. Not slow — completely stuck. The window stops painting, nothing responds, and the only way out is force-quit.

The cause is a bug in Apple's code, not ours. Two pieces of macOS window machinery end up waiting on each other, and neither can go first, so they wait forever. Like two people in a doorway both saying "after you" — nobody moves, and they stand there all day. We reported it to Apple (FB24004458) and to Electron, but we can't fix it ourselves.

Here's the awkward part: when this happens, we never find out. Orca doesn't crash — crashes leave a report. It just sits there. So a user force-quits, reopens, mutters something, and gets on with their day. We have exactly one confirmed case ever, and no idea whether that means it's a freak accident or something hitting people every week.

So this PR adds a tiny second program that sits beside Orca and listens for a "still alive" ping every 2 seconds. If the pings stop for 45 seconds, it writes a note to disk. Next time Orca starts, it reads the note and tells us: Orca was frozen for 90 seconds. It also notices if Orca wakes back up on its own, which separates "genuinely dead" from "was just really busy for a while."

We thought about having this watchdog kill and restart Orca automatically when it goes quiet. We decided not to. If it ever guessed wrong, it would be shooting a perfectly healthy app in the head — quite possibly right in the middle of saving your work. Measuring is safe; killing is not. So we measure first, and only build the killer if the numbers say it's actually needed.

Why we want this

We do not know how often Orca's main thread freezes. We have exactly one confirmed incident (macOS 26.5.1, kernel-confirmed spindump, unresponsive 1305+s) plus one third-party report. That is the entire dataset, and every decision downstream of it is currently a guess.

The reason it is a guess is structural, not incidental: a deadlocked main thread never crashes. There is no crash report, no exception, no exit code. No JS runs in the main process, so the app cannot self-report. The user force-quits and reopens, and nothing anywhere records that it happened. These freezes are invisible to us by construction, and they always have been.

This PR makes them visible. Concretely, it answers:

  1. Is this real? Incidence per release, per macOS version. Today "Orca froze" is an unfalsifiable support report; after this it is a confirmed event with a duration.
  2. Did fix(window): defer the repaint size nudge and skip it on macOS 26 #10253 actually help? We shipped the jiggle removal in 1.4.156 believing it shrank the trigger surface — but the captured deadlock enters from _setFrameCommon:display:**fromServer:**, a window-server-delivered update, so removing our own setSize may not have moved the needle at all. A per-version count settles it. Right now we would never know.
  3. Is auto-recovery safe to build? self_recovered counts stalls that cleared on their own. Every one of those is a SIGKILL an auto-recovery design would have gotten wrong. If they dominate, killing was never viable and we should not build it. If unresolved stalls dominate, recovery is justified — and we would know that from data rather than from n=1.
  4. Is 45s the right threshold? unresponsive_ms is kept raw, so the cutoff can be calibrated against the real distribution instead of judgement. The one incident sat dead for 21 minutes; we have no idea what the near-miss tail looks like.
  5. Evidence for Apple and Electron. [Bug]: macOS 26 (Tahoe): permanent browser-process main-thread deadlock in AppKit/FrontBoardServices scene update (_setFrameCommon:fromServer: → FBSScene _sendUpdate: → performAsyncAndWait self-wait) electron/electron#52437 is blocked on a repro nobody has produced, and FB24004458 is one spindump. "This affects N users per week on macOS 26.x, median stall X seconds" is materially harder to dismiss than a single stack, and it is obtainable without a repro.
  6. Regression detection. If a future Electron bump or window change reintroduces exposure, the count moves. Without it we would learn from sporadic user reports of a bug that produces no artifact.

And the cheap outcome is a real outcome: if the count comes back zero over a few releases, we delete this and close the issue. That is a decisive result, and today we cannot reach it.

What this does

A plain-Node watchdog child, forked with ELECTRON_RUN_AS_NODE (same crash-isolation pattern as the parcel-watcher child; it survives a deadlocked parent because it is its own process):

  • Main thread sends a heartbeat every 2s over Node IPC.
  • After 45s of silence the child writes a marker to userData. If heartbeats later resume, it rewrites the marker as resolved.
  • The next launch consumes the marker, records a main_thread_hang_detected durable crash breadcrumb, and emits a main_thread_hang_detected telemetry event with unresponsive_ms and self_recovered.

The telemetry event is load-bearing, not redundant: the breadcrumb rides crash reports and a local trace span, and since a hang is not a crash, that data would never leave the user's machine. It fires after initTelemetry — track() drops silently until the client and store are wired.

Schema is .strict() with a duration and a boolean. No pid, path, or window title reaches the wire, and it rides existing consent (track() resolves consent per call and no-ops on non-official builds).

What this deliberately does not do

An earlier revision SIGKILLed the silent parent and relaunched it. That is removed, because the risk is asymmetric:

  • True positive: the main thread is already deadlocked, so anything in the persistence debounce window is unreachable no matter what. Killing recovers nothing the user does not get by force-quitting — it only saves them the discovery.
  • False positive: it SIGKILLs a live main thread that was merely blocked. A 45s main-thread stall is most plausibly blocked I/O, which means writes are in flight — the misfire lands exactly when killing is most destructive.

The entire downside sits in the failure mode while the upside even when correct is modest. This codebase has already paid for arbitrary-moment process death twice (persistence.ts SIGKILL-race fixes for #217, durable-file-write.ts for the torn-write class in #1158); the removed design manufactured that hazard deliberately, on a timer, with no runtime off switch.

If the field data shows real deadlocks dominate, recovery can be built on evidence — off by default, renderer-corroborated, staged. main-thread-hang-watchdog-entry.test.ts asserts that observing a hang never spawns, signals, or exits, so that has to be a deliberate decision rather than drift.

Misfire guards

  • macOS-only; packaged-only (dev debugger pauses would trip it; ORCA_HANG_WATCHDOG_FORCE=1 for testing).
  • 45s threshold — the real incident sat dead for 21+ minutes.
  • Suspend detection: a huge gap between check ticks means system sleep, not a hang; the wait restarts from zero after wake.
  • The tick clock keeps advancing during an outstanding hang, so the first tick after one clears is not misread as a sleep gap (this was a live bug — it silently disarmed detection of any second hang in a session).
  • Clean quit disarms via shutdown message + IPC disconnect; will-quit firing twice is handled (stop is idempotent).
  • Watchdog death is non-fatal: the app runs without it, no restart loop.

Because nothing is killed, a misfire now costs one inaccurate data point.

Testing

  • Unit: child loop (detection, resolution, measured duration, sleep-gap, re-arming after a resolved hang), marker round-trip including the absent-flag case, watchdog fork/heartbeat/stop, telemetry schema including strict-mode rejection, and the no-spawn/no-signal/no-exit contract.
  • pnpm typecheck clean (all three projects); oxlint clean; 54 unit tests pass.

End-to-end verification against a genuinely frozen app

Unit tests use fake timers, so they can only prove the loop's arithmetic — not that a real watchdog observes a real freeze from its own process. Verified empirically against a live Electron instance, with the main process halted via SIGSTOP (no JS runs and no heartbeats can be sent — the same externally-observable state as the AppKit deadlock, and reversible):

Scenario Result
Healthy app, heartbeats flowing no marker written
Main process SIGSTOPped (artificial freeze) marker written, parentPid = the real frozen Electron pid, unresponsiveMs: 8093
SIGCONT — app resumes marker rewritten selfRecovered: true, unresponsiveMs: 17442
App killed while frozen (force-quit) marker survives on disk, 0 orphaned watchdogs
Next launch marker consumed and deleted; re-consuming returns null, so a stall is never double-reported

Also verified against the built out/main/main-thread-hang-watchdog-entry.js with a parent whose event loop is hard-blocked by a busy spin:

  • Measured unresponsiveMs tracks the real freeze duration (5696ms measured for a 5500ms freeze).
  • Re-arm after a resolved hang: first hang detected → cleared → second hang in the same session still detected. This is the bug the tick-clock fix addresses; confirmed it now re-arms rather than silently disarming.
  • Clean quit is silent: both the graceful path (shutdown message + disconnect) and the disconnect-only path exit the child with code 0 and write no marker, waiting well past the threshold.

Performance

Measured rather than asserted, since this adds a permanent process and two always-on timers:

Metric Measured
Watchdog RSS 47.1 MB total, of which 44.9 MB is the ELECTRON_RUN_AS_NODE floor (empty child baseline) — ~2.2 MB is the watchdog itself
CPU, sustained idle 0.03s child CPU per 60s (~0.05%); parent-side heartbeats 23.8ms user / 7.6ms sys per minute
Startup marker read (common case, absent) 3.3 µs
Startup marker read (post-hang) 9.0 µs

Against the /perf checklist: the fork is async and off the critical path; heartbeats cannot queue during a hang (a blocked event loop means the timer never fires); marker writes happen only on detect/resolve, not per tick; the child holds no unbounded buffers; and will-quit clears the timer and disconnects idempotently, so nothing leaks on the close path. The 44.9 MB floor is the same cost already paid by the parcel-watcher child this mirrors.

Notes for review

  • hang-recovery-marker → hang-detection-marker: it no longer recovers anything.
  • The recovery notification and its five locale strings are gone — nothing restarts, so there is nothing to explain. Easy to restore if we later want to surface the event.
  • Entry is registered in electron.vite.config.ts, in the plain-node entry guard, and in asarUnpack, so the build fails if the watchdog's module graph ever gains a require('electron').
  • Rebased onto current main and collapsed to a single commit; the branch previously carried merge commits and conflicted. Resolution was additive only — the sole conflict was in telemetry-events.ts, where main added runtime_rpc_start_failed in the same spot as this PR's schema; both are kept.
  • Stale comment on the vite entry ("can force-relaunch the app") updated to match the observe-only design.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a macOS main-thread hang watchdog that runs as a plain-Node child process, receives heartbeats, detects prolonged main-thread silence, records recovery state, relaunches the application, and terminates the frozen parent. Main-process startup installs the watchdog, consumes recovery markers, records breadcrumbs, and displays a localized notification. The new entry is included in the Vite build, unpacked from the application archive, and covered by build, runtime, recovery, and watchdog-loop tests.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it omits the required Screenshots, AI Review Report, and Security Audit sections from the template. Add the missing template sections, including a screenshots note, an AI review summary with cross-platform checks, and a security audit.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately reflects the main change: measuring main-thread hangs.

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b9dcd4cf-adbe-4261-8f1f-155c53e74341

📥 Commits

Reviewing files that changed from the base of the PR and between 19eaa12 and 9c90282.

📒 Files selected for processing (1)
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts

Comment on lines +64 to +73
it('still kills the parent when there is no bundle path or the marker write fails', () => {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '',
markerPath: join(dir, 'missing-subdir', 'marker.json'),
unresponsiveMs: 45_000
})
expect(spawnMock).not.toHaveBeenCalled()
expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
expect(exitSpy).toHaveBeenCalledWith(0)

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

Split the fallback cases so marker-write failure is actually tested.

Both failure conditions are configured at once, so this test does not prove that a marker-write error independently still kills and exits the parent. Use separate cases with a valid bundle path for the write-failure test and a valid marker path for the no-bundle-path test.

Proposed test split
-it('still kills the parent when there is no bundle path or the marker write fails', () => {
+it('still kills the parent when there is no bundle path', () => {
   recoverFrozenParent({
     parentPid: 4242,
     appBundlePath: '',
-    markerPath: join(dir, 'missing-subdir', 'marker.json'),
+    markerPath: join(dir, 'marker.json'),
     unresponsiveMs: 45_000
   })
   expect(spawnMock).not.toHaveBeenCalled()
   expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
   expect(exitSpy).toHaveBeenCalledWith(0)
 })
+
+it('still kills the parent when the marker write fails', () => {
+  recoverFrozenParent({
+    parentPid: 4242,
+    appBundlePath: "/Applications/Or ca's.app",
+    markerPath: join(dir, 'missing-subdir', 'marker.json'),
+    unresponsiveMs: 45_000
+  })
+  expect(spawnMock).not.toHaveBeenCalled()
+  expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
+  expect(exitSpy).toHaveBeenCalledWith(0)
+})
📝 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
it('still kills the parent when there is no bundle path or the marker write fails', () => {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '',
markerPath: join(dir, 'missing-subdir', 'marker.json'),
unresponsiveMs: 45_000
})
expect(spawnMock).not.toHaveBeenCalled()
expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
expect(exitSpy).toHaveBeenCalledWith(0)
it('still kills the parent when there is no bundle path', () => {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '',
markerPath: join(dir, 'marker.json'),
unresponsiveMs: 45_000
})
expect(spawnMock).not.toHaveBeenCalled()
expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
expect(exitSpy).toHaveBeenCalledWith(0)
})
it('still kills the parent when the marker write fails', () => {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: "/Applications/Or ca's.app",
markerPath: join(dir, 'missing-subdir', 'marker.json'),
unresponsiveMs: 45_000
})
expect(spawnMock).not.toHaveBeenCalled()
expect(killSpy).toHaveBeenCalledWith(4242, 'SIGKILL')
expect(exitSpy).toHaveBeenCalledWith(0)
})

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live E2E on macOS 26.5 (the affected OS) — full recovery loop verified, one real bug found and fixed.

Method: ran the built app isolated via the E2E userData contract with fast watchdog timings, then SIGSTOP'd the main process — freezes all JS exactly like the real deadlock while the watchdog child (separate process) keeps running.

  • Freeze → watchdog SIGKILL at +6s (configured timeout) → marker written with correct pid → app relaunched and stayed up. Also verified the false-positive path live: continuous heartbeats for 2.5× timeout → parent untouched; clean shutdown disarms.
  • Bug caught by the E2E (fixed in a40566c): open propagates the caller's environment, and the watchdog child always runs with ELECTRON_RUN_AS_NODE=1 — so the relaunched app booted as bare Node and exited immediately. Kill+marker worked; the app never came back. The relauncher now spawns with a scrubbed env (drops ELECTRON_RUN_AS_NODE and ORCA_HANG_WATCHDOG_*). Re-ran the E2E after the fix: relaunch confirmed (fresh instance up and stable).

Remaining gap: the marker-consume → recovery-notice leg is unit-tested but not yet E2E'd against a packaged build (dev relaunch opens the bare Electron shell, not Orca). Worth one packaged-build QA pass before stable.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f4858f82-5cc2-4687-a181-241672dac26d

📥 Commits

Reviewing files that changed from the base of the PR and between 9c90282 and a40566c.

📒 Files selected for processing (2)
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts

Comment on lines +65 to +76
process.env.ELECTRON_RUN_AS_NODE = '1'
process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = '6000'
try {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '/Applications/Orca.app',
markerPath: join(dir, 'marker.json'),
unresponsiveMs: 45_000
})
} finally {
delete process.env.ELECTRON_RUN_AS_NODE
delete process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS

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

Restore pre-existing environment values after the test.

The finally block always deletes both variables. If either was set by the test runner or setup, this test silently removes it and can affect later tests. Capture the original values and restore them, deleting only when they were previously undefined.

Proposed fix
+    const previousRunAsNode = process.env.ELECTRON_RUN_AS_NODE
+    const previousTimeout = process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
     process.env.ELECTRON_RUN_AS_NODE = '1'
     process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = '6000'
     try {
       recoverFrozenParent({
         parentPid: 4242,
         appBundlePath: '/Applications/Orca.app',
         markerPath: join(dir, 'marker.json'),
         unresponsiveMs: 45_000
       })
     } finally {
-      delete process.env.ELECTRON_RUN_AS_NODE
-      delete process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
+      if (previousRunAsNode === undefined) delete process.env.ELECTRON_RUN_AS_NODE
+      else process.env.ELECTRON_RUN_AS_NODE = previousRunAsNode
+      if (previousTimeout === undefined) delete process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
+      else process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = previousTimeout
     }
📝 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
process.env.ELECTRON_RUN_AS_NODE = '1'
process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = '6000'
try {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '/Applications/Orca.app',
markerPath: join(dir, 'marker.json'),
unresponsiveMs: 45_000
})
} finally {
delete process.env.ELECTRON_RUN_AS_NODE
delete process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
const previousRunAsNode = process.env.ELECTRON_RUN_AS_NODE
const previousTimeout = process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
process.env.ELECTRON_RUN_AS_NODE = '1'
process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = '6000'
try {
recoverFrozenParent({
parentPid: 4242,
appBundlePath: '/Applications/Orca.app',
markerPath: join(dir, 'marker.json'),
unresponsiveMs: 45_000
})
} finally {
if (previousRunAsNode === undefined) delete process.env.ELECTRON_RUN_AS_NODE
else process.env.ELECTRON_RUN_AS_NODE = previousRunAsNode
if (previousTimeout === undefined) delete process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS
else process.env.ORCA_HANG_WATCHDOG_TIMEOUT_MS = previousTimeout
}

@brennanb2025 brennanb2025 changed the title feat(main): watchdog that recovers from a deadlocked main thread on macOS feat(main): record main-thread hangs so we can measure them Jul 27, 2026

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 851b8f76-f789-4b5e-9f9e-9b20ad19b9e0

📥 Commits

Reviewing files that changed from the base of the PR and between a40566c and fdb8010.

📒 Files selected for processing (4)
  • build-plugins/plain-node-entry-guard.js
  • config/electron-builder.config.cjs
  • config/scripts/electron-builder-config.test.mjs
  • electron.vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • config/electron-builder.config.cjs
  • electron.vite.config.ts

Comment thread build-plugins/plain-node-entry-guard.js Outdated
Comment on lines +14 to +20
const PLAIN_NODE_ENTRY_NAMES = [
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls',
'codex/codex-app-server-grant-entry'
];
const ELECTRON_REQUIRE_RE = /require\(\s*["']electron["']\s*\)/;
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls',
'codex/codex-app-server-grant-entry'
]

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 | 🟠 Major | ⚡ Quick win

Register the watchdog entry with the plain-Node guard.

main-thread-hang-watchdog-entry runs under ELECTRON_RUN_AS_NODE, but it is missing from PLAIN_NODE_ENTRY_NAMES. Its reachable chunks therefore skip assertNoElectronRequire, so a future Electron import could ship undetected and prevent hang detection from starting.

Suggested fix
 const PLAIN_NODE_ENTRY_NAMES = [
+  'main-thread-hang-watchdog-entry',
   'daemon-entry',
📝 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 PLAIN_NODE_ENTRY_NAMES = [
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls',
'codex/codex-app-server-grant-entry'
];
const ELECTRON_REQUIRE_RE = /require\(\s*["']electron["']\s*\)/;
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls',
'codex/codex-app-server-grant-entry'
]
const PLAIN_NODE_ENTRY_NAMES = [
'main-thread-hang-watchdog-entry',
'daemon-entry',
'parcel-watcher-process-entry',
'computer-sidecar',
'agent-hooks/managed-agent-hook-controls',
'codex/codex-app-server-grant-entry'
]
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawnSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process)

A deadlocked main thread never crashes, so it leaves no crash report and no
artifact — incidence has been unmeasurable (n=1 confirmed, macOS 26.5.1,
FB24004458 / electron#52437). This forks a plain-Node watchdog sibling under
ELECTRON_RUN_AS_NODE that survives the deadlock, listens for a 2s heartbeat,
and after 45s of silence writes a marker to userData. The next launch consumes
it, records a durable crash breadcrumb, and emits a main_thread_hang_detected
telemetry event carrying unresponsive_ms and self_recovered.

Observes only — it never kills or relaunches the parent. A true positive
recovers nothing force-quitting wouldn't, while a false positive would SIGKILL
a live main thread mid-write. self_recovered counts exactly the stalls such a
killer would have gotten wrong, so recovery can be built on evidence if the
field numbers justify it.

macOS-only, packaged-only (ORCA_HANG_WATCHDOG_FORCE=1 to test), with sleep-gap
suppression and idempotent shutdown on will-quit.
@nwparker
nwparker force-pushed the brennanb2025/main-hang-watchdog branch from 0585d2c to 358e7c8 Compare July 28, 2026 23:31
@nwparker nwparker self-assigned this Jul 28, 2026
@nwparker

Copy link
Copy Markdown
Contributor

Taking this over from @brennanb2025 as the new owner.

Rebased onto current main and collapsed to a single commit. The branch had drifted into CONFLICTING/DIRTY with merge commits from main mixed into the history; it is now MERGEABLE/CLEAN, one commit ahead and zero behind. The only real conflict was in telemetry-events.ts, where main landed runtime_rpc_start_failed in the same location as this PR's schema — resolution was purely additive, both are kept. Also fixed a stale comment on the vite entry that still described the removed force-relaunch behavior.

Verified the change actually works rather than trusting the fake-timer unit tests. Ran a live Electron instance with ORCA_HANG_WATCHDOG_FORCE=1 and artificially froze the main process with SIGSTOP — no JS runs and no heartbeats can be sent, which is the same externally-observable state as the AppKit deadlock, and it is reversible:

  • healthy app → no marker
  • frozen → marker written with parentPid = the real frozen Electron pid, unresponsiveMs: 8093
  • SIGCONT → rewritten selfRecovered: true
  • killed while frozen → marker survives, 0 orphaned watchdogs
  • next launch → consumed and deleted; re-consuming returns null, so no double-reporting

Against the built entry with a hard-blocked event loop, the measured duration tracks the real freeze (5696ms for a 5500ms freeze), the re-arm fix holds (a second hang in the same session is still detected — this is the bug that previously disarmed detection silently), and clean quit is silent on both the graceful and disconnect-only paths.

No /perf issues. Measured, since this adds a permanent process and two always-on timers: ~0.05% CPU sustained idle, 3.3µs for the startup marker read in the common absent case, and of the 47.1 MB RSS, 44.9 MB is the ELECTRON_RUN_AS_NODE floor — an empty child measures the same, so ~2.2 MB is actually the watchdog. That floor is already paid by the parcel-watcher child this mirrors. Marker writes happen only on detect/resolve rather than per tick, heartbeats cannot queue during a hang (the blocked loop means the timer never fires), and will-quit clears the timer and disconnects idempotently.

Full numbers and the scenario table are in the PR description.

One note for whoever reviews: pnpm lint's react-doctor step fails locally on a stale node_modules plugin version (Rule 'no-create-store-in-render' not found). It reproduces on a pristine main checkout with no changes applied, so it is pre-existing and unrelated — flagging it rather than leaving it to look like fallout from this PR.

@nwparker

Copy link
Copy Markdown
Contributor

These three CodeRabbit comments are stale — they predate the refactor that removed the kill-and-relaunch design, and I confirmed each against the current tree:

  1. "Register the watchdog entry with the plain-Node guard" (Major) — already registered (build-plugins/plain-node-entry-guard.ts:24; the comment targets the old .js path). Verified empirically rather than by inspection: grep -rn electron over the built out/main/main-thread-hang-watchdog-entry.js and its runtime chunk returns nothing, so the graph is genuinely plain Node. Also confirmed the entry and out/main/chunks/** are both in asarUnpack, so the entry's require("./chunks/hang-detection-marker-*.js") resolves inside app.asar.unpacked — worth calling out, since an unpacked entry with a packed chunk would fail to load in exactly the packaged-only mode this ships in.
  2. "Split the fallback cases so marker-write failure is actually tested" — that test no longer exists. There is no bundle path and no kill, so the case it describes is gone; the replacement asserts process.kill/process.exit/spawn are never called.
  3. "Restore pre-existing environment values" — the only finally block left is the withPlatform helper, which does capture and restore the original value.

@nwparker
nwparker merged commit 747b241 into main Jul 28, 2026
32 checks passed
Comment on lines +28 to +33
writeHangDetectionMarker(options.markerPath, {
detectedAt: Date.now(),
parentPid: options.parentPid,
unresponsiveMs: options.unresponsiveMs,
selfRecovered: options.selfRecovered
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 detectedAt reflects resolution time for self-recovered hangs

recordHangObservation always stamps detectedAt: Date.now() at call time. When invoked from onHangResolved, that timestamp is the moment heartbeats resumed, not the moment the hang was first detected — the original detection timestamp is silently overwritten. The field name detectedAt and its documentation imply the detection moment, so a self-recovered marker ends up with a semantically incorrect value. Neither telemetry nor the breadcrumb payload currently forward detectedAt, so there is no impact today, but any future consumer of the marker file would read the wrong timestamp for resolved hangs.

Comment on lines +40 to +43
if (tickGap > config.checkIntervalMs * 3) {
lastHeartbeatAt = now
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Sleep-gap threshold resets hang detection on the same tick as detection

When detected is already true and the system then sleeps, tick() returns early at line 36 before reaching the sleep-gap check — so lastHeartbeatAt is not reset on wake. This is actually the correct behaviour for that case (the hang is already recorded and should stay recorded until a heartbeat arrives).

The subtle risk is the opposite direction: on a heavily CPU-bound system that never sleeps, the watchdog child's setInterval could fire more than checkIntervalMs * 3 = 15 s late (e.g., OS jitter or CPU starvation), which would falsely reset lastHeartbeatAt to now and restart the 45-second countdown, potentially delaying or skipping detection of a real deadlock. Given this is macOS-only and the threshold is 3× the interval, the practical exposure is low, but a larger multiplier (e.g., 10× or a fixed upper bound like 60 s) would reduce the false-negative surface without increasing false-positive risk.

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!

@greptile-apps

greptile-apps Bot commented Jul 28, 2026

Copy link
Copy Markdown

Greptile Summary

This PR adds a plain-Node watchdog child process (forked with ELECTRON_RUN_AS_NODE) that monitors the Electron main thread via 2-second IPC heartbeats and writes a main-thread-hang.json marker to userData if silence exceeds 45 seconds. On the next launch, the marker is consumed, a durable crash breadcrumb is recorded, and a main_thread_hang_detected telemetry event is emitted — making previously invisible main-thread freezes (the macOS 26 AppKit/FrontBoardServices deadlock) measurable for the first time.

  • Observation-only design: the watchdog deliberately never kills the parent. A 45 s threshold, suspend-gap detection (3× check interval), idempotent stop, and IPC-disconnect exit together guard against false markers, with the only misfire cost being one inaccurate data point.
  • Telemetry schema uses .strict() with unresponsive_ms (int, non-negative) and self_recovered (boolean), keeping PID, path, and window title off the wire; the self_recovered split is the key measurement for deciding whether future auto-recovery is safe to build.
  • Build wiring is complete: entry registered in electron.vite.config.ts, added to PLAIN_NODE_ENTRY_NAMES guard, and to asarUnpack so ELECTRON_RUN_AS_NODE can resolve it outside the asar.

Confidence Score: 4/5

Safe to merge — the watchdog is observation-only, failures are non-fatal, and the marker is consumed and deleted on next launch, so at worst a misfire produces one extra telemetry event.

The design is well-reasoned and the unit test coverage is thorough. Two minor concerns: recordHangObservation always stamps detectedAt: Date.now(), so for self-recovered hangs the marker records resolution time rather than detection time (the field isn't forwarded to telemetry today, but it's semantically wrong for future consumers); and the sleep-gap threshold of 3× check interval (15 s) could trigger on a heavily CPU-bound system, resetting hang detection mid-stall. Neither affects correctness of the measurement that reaches the wire.

Files Needing Attention: hang-watchdog-child-loop.ts (sleep-gap multiplier) and main-thread-hang-watchdog-entry.ts (detectedAt stamping in recordHangObservation) are the two spots worth a second look.

Important Files Changed

Filename Overview
src/main/hang-watchdog/hang-watchdog-child-loop.ts Pure-Node detection loop with solid state machine; sleep-gap threshold (3× check interval = 15 s) is somewhat tight for heavily-loaded systems
src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts Entry shim correctly guards module-level side effects behind a PID check; recordHangObservation always stamps detectedAt at write time, which means resolved markers record resolution time rather than original detection time
src/main/hang-watchdog/main-thread-hang-watchdog.ts Fork/heartbeat/stop lifecycle looks correct; macOS+packaged guard, idempotent stop, IPC race handling are all present
src/main/hang-watchdog/hang-detection-marker.ts Marker read/write/consume logic is robust; handles missing file, corrupt JSON, missing selfRecovered field, and deletion failures correctly
src/main/index.ts Watchdog installed and marker consumed at app-ready; telemetry track correctly deferred until after initTelemetry; breadcrumb and track calls use correct fields
src/shared/telemetry-events.ts New main_thread_hang_detected schema correctly uses .strict() with int+nonnegative duration and boolean; no PII fields
src/main/hang-watchdog/hang-watchdog-entry-path.ts Path resolution correctly handles both packaged (asar.unpacked) and dev builds with a pathExists injection for testability

Sequence Diagram

sequenceDiagram
    participant Main as Main Thread (Electron)
    participant WD as Watchdog Child (ELECTRON_RUN_AS_NODE)
    participant Disk as userData/main-thread-hang.json
    participant NextLaunch as Next Launch (index.ts)

    Main->>WD: fork() with PID + marker path env
    loop Every 2s (healthy)
        Main->>WD: "IPC { type: heartbeat }"
        WD->>WD: recordHeartbeat() — reset lastHeartbeatAt
    end

    Note over Main: Main thread deadlocks (AppKit scene-update)
    loop Every 5s tick, no heartbeat
        WD->>WD: tick() — unresponsiveMs grows
    end
    WD->>Disk: "writeHangDetectionMarker({ selfRecovered: false })"

    alt Heartbeats resume (self-recovered stall)
        Main->>WD: "IPC { type: heartbeat }"
        WD->>Disk: "overwrite marker { selfRecovered: true, unresponsiveMs }"
    end

    alt Clean quit
        Main->>WD: "IPC { type: shutdown } + disconnect()"
        WD->>WD: process.exit(0)
    else Force-quit / parent dies
        Note over Main,WD: IPC channel closes
        WD->>WD: process.exit(0) via disconnect event
    end

    NextLaunch->>Disk: consumeHangDetectionMarker() — read + delete
    NextLaunch->>NextLaunch: recordDurableCrashBreadcrumb(unresponsiveMs, selfRecovered)
    NextLaunch->>NextLaunch: track(main_thread_hang_detected)
Loading

Reviews (1): Last reviewed commit: "feat(main): record main-thread hangs so ..." | Re-trigger Greptile

@nwparker

Copy link
Copy Markdown
Contributor

Correcting a number in the description above. I reported the watchdog's memory as 47.1 MB RSS with a 44.9 MB ELECTRON_RUN_AS_NODE floor. RSS is the wrong metric for "what does adding this process cost" — it counts file-backed Electron framework pages that are already resident for the main process, so it charges shared memory to the child.

Measured phys_footprint instead:

Footprint: 13 MB
  Dirty      Clean    Category
 13 MB      31 MB     TOTAL
    phys_footprint: 13 MB

The real marginal cost is ~13 MB, not ~47 MB — the other 31 MB is clean, shared, reclaimable. My decomposition was directionally right (most of the RSS isn't the watchdog) but the metric overstated the true cost by ~3.6x. Flagging it because 13 MB vs 47 MB is exactly the kind of number a future "is this still worth keeping" decision would turn on, and the overstatement argues against keeping it.

Everything else in the perf section stands: ~0.05% CPU sustained idle, 3.3 µs startup marker read, writes only on detect/resolve.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#10256)

A deadlocked main thread never crashes, so it leaves no crash report and no
artifact — incidence has been unmeasurable (n=1 confirmed, macOS 26.5.1,
FB24004458 / electron#52437). This forks a plain-Node watchdog sibling under
ELECTRON_RUN_AS_NODE that survives the deadlock, listens for a 2s heartbeat,
and after 45s of silence writes a marker to userData. The next launch consumes
it, records a durable crash breadcrumb, and emits a main_thread_hang_detected
telemetry event carrying unresponsive_ms and self_recovered.

Observes only — it never kills or relaunches the parent. A true positive
recovers nothing force-quitting wouldn't, while a false positive would SIGKILL
a live main thread mid-write. self_recovered counts exactly the stalls such a
killer would have gotten wrong, so recovery can be built on evidence if the
field numbers justify it.

macOS-only, packaged-only (ORCA_HANG_WATCHDOG_FORCE=1 to test), with sleep-gap
suppression and idempotent shutdown on will-quit.
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.

2 participants