Repository navigation
feat(main): record main-thread hangs so we can measure them - #10256
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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)
✅ Passed checks (3 passed)
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b9dcd4cf-adbe-4261-8f1f-155c53e74341
📒 Files selected for processing (1)
src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts
| 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) |
There was a problem hiding this comment.
🎯 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.
| 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) | |
| }) |
|
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
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. |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.tssrc/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
| 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 |
There was a problem hiding this comment.
🩺 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.
| 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 | |
| } |
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
build-plugins/plain-node-entry-guard.jsconfig/electron-builder.config.cjsconfig/scripts/electron-builder-config.test.mjselectron.vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- config/electron-builder.config.cjs
- electron.vite.config.ts
| 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' | ||
| ] |
There was a problem hiding this comment.
🩺 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.
| 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.
0585d2c to
358e7c8
Compare
|
Taking this over from @brennanb2025 as the new owner. Rebased onto current Verified the change actually works rather than trusting the fake-timer unit tests. Ran a live Electron instance with
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 Full numbers and the scenario table are in the PR description. One note for whoever reviews: |
|
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:
|
| writeHangDetectionMarker(options.markerPath, { | ||
| detectedAt: Date.now(), | ||
| parentPid: options.parentPid, | ||
| unresponsiveMs: options.unresponsiveMs, | ||
| selfRecovered: options.selfRecovered | ||
| }) |
There was a problem hiding this comment.
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.
| if (tickGap > config.checkIntervalMs * 3) { | ||
| lastHeartbeatAt = now | ||
| return | ||
| } |
There was a problem hiding this comment.
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 SummaryThis PR adds a plain-Node watchdog child process (forked with
Confidence Score: 4/5Safe 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: Files Needing Attention:
|
| 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)
Reviews (1): Last reviewed commit: "feat(main): record main-thread hangs so ..." | Re-trigger Greptile
|
Correcting a number in the description above. I reported the watchdog's memory as 47.1 MB RSS with a 44.9 MB Measured 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. |
…#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.
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:
_setFrameCommon:display:**fromServer:**, a window-server-delivered update, so removing our ownsetSizemay not have moved the needle at all. A per-version count settles it. Right now we would never know.self_recoveredcounts 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.unresponsive_msis 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.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_hang_detecteddurable crash breadcrumb, and emits amain_thread_hang_detectedtelemetry event withunresponsive_msandself_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:
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.tsSIGKILL-race fixes for #217,durable-file-write.tsfor 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.tsasserts that observing a hang never spawns, signals, or exits, so that has to be a deliberate decision rather than drift.Misfire guards
ORCA_HANG_WATCHDOG_FORCE=1for testing).will-quitfiring twice is handled (stop is idempotent).Because nothing is killed, a misfire now costs one inaccurate data point.
Testing
pnpm typecheckclean (all three projects);oxlintclean; 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):SIGSTOPped (artificial freeze)parentPid= the real frozen Electron pid,unresponsiveMs: 8093SIGCONT— app resumesselfRecovered: true,unresponsiveMs: 17442null, so a stall is never double-reportedAlso verified against the built
out/main/main-thread-hang-watchdog-entry.jswith a parent whose event loop is hard-blocked by a busy spin:unresponsiveMstracks the real freeze duration (5696ms measured for a 5500ms freeze).Performance
Measured rather than asserted, since this adds a permanent process and two always-on timers:
ELECTRON_RUN_AS_NODEfloor (empty child baseline) — ~2.2 MB is the watchdog itselfAgainst the
/perfchecklist: 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; andwill-quitclears the timer and disconnects idempotently, so nothing leaks on the close path. The 44.9 MB floor is the same cost already paid by theparcel-watcherchild this mirrors.Notes for review
hang-recovery-marker→hang-detection-marker: it no longer recovers anything.electron.vite.config.ts, in the plain-node entry guard, and inasarUnpack, so the build fails if the watchdog's module graph ever gains arequire('electron').mainand collapsed to a single commit; the branch previously carried merge commits and conflicted. Resolution was additive only — the sole conflict was intelemetry-events.ts, wheremainaddedruntime_rpc_start_failedin the same spot as this PR's schema; both are kept.