Skip to content

feat(diagnostics): record OS suspend/resume so sleep gaps aren't read as freezes - #10530

Merged
nwparker merged 5 commits into
mainfrom
nwparker/sleep-attribution-breadcrumbs
Jul 25, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/sleep-attribution-breadcrumbs

Conversation

@nwparker

@nwparker nwparker commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Why

Correction (post-merge). The framing below is wrong in one important way, and the record should say so.

The user's actual report was: "Orca keeps freezing on me after closing my laptop and coming back to it." The gap being sleep-shaped does not contradict that — sleep is the precondition, and the freeze is at the tail of the gap, on wake. This PR proved the gap was sleep and wrongly treated that as evidence no freeze occurred.

A mechanism was already found and fixed independently: v1.4.152 does not contain #10253, so it shipped forceRepaint() calling window.setSize(width + 1, height) synchronously from window.on('restore')/on('show') (src/main/window/createMainWindow.ts:66 at that tag). #10253 carries a kernel-confirmed spindump showing exactly that re-entrant frame mutation self-deadlocking the main thread in FrontBoardServices on macOS 26's scene-backed windows. Lid-open fires restore/show; the user was on Darwin 25.5.0 (Tahoe). That matches the report mechanism-for-mechanism, and it explains the absence of any crash report: a main thread deadlocked in AppKit cannot run the JS that would record one.

So #10473/#10485/#10487 are most likely the actual fix, not unconfirmed extras. This PR's value is unchanged and narrower than claimed: it makes sleep spans explicit so a future gap is attributable instead of ambiguous.

Caveat: a synthetic repro driving show()/minimize()/restore() on macOS 26.3.1 did not reproduce the hang (6/6 clean, harness validated to fire the handlers). Programmatic window-state changes do not reproduce a genuine FrontBoardServices lid-open wake, so this is weak counter-evidence against a kernel-confirmed spindump — but it is not nothing, and the deadlock remains inferred rather than reproduced.

The uber-crash investigation hinged on a 109-minute renderer_memory heartbeat gap that read as a wedged renderer. It isn't diagnostic:

  • The same session had a 122-minute gap 11 hours earlier (10:31→12:34) with identical heap on both sides — then ran fine for another 9 hours.
  • A healthy machine's full-fidelity trace has a 427-minute mid-session gap with reason=interval, plus 35 more over 90s. Nearly every one contains pmset sleep events.

Renderer timers stop across OS sleep, so "app frozen" and "laptop closed" produce a byte-identical hole in the telemetry. powerMonitor.on('resume') was already wired here for renderer wake recovery but left no breadcrumb, so nothing in a crash report could separate the two.

What

Suspend stamps a timestamp. Resume emits a single system_slept breadcrumb carrying the measured suspendedForMs, past a 60s threshold.

Two details are load-bearing, both driven by the same fact: powerMonitor's resume maps to NSWorkspaceDidWake, which does not fire for dark wake.

1. Suspend keeps the earliest stamp (suspendedAt ??= now()). macOS routinely delivers suspend → (dark wake, no resume) → suspend → resume. Overwriting the stamp would report only the trailing segment — and when that segment falls under the gate, a 90-minute sleep records nothing at all, leaving exactly the unexplained gap this PR exists to rule out. The mutation test for this asserts the breadcrumb is present, not merely smaller.

2. The 60s gate. A sleep shorter than the renderer's 60s RENDERER_MEMORY_SAMPLE_INTERVAL_MS only delays a heartbeat; it cannot open a multi-minute gap, so recording it spends a slot in the 30-entry ring without explaining anything.

Measured by replaying 6 days of this machine's real pmset history (78 Sleep, 29 full Wake, 51 DarkWake) through the shipped state machine:

value
breadcrumbs / 6 days 29 (~5/day)
worst 60-min burst 4
ring capacity 30
dropped by the gate 3 events (12s, 8s, 4s)

Note this corrects an earlier revision of this description, which claimed ~70 cycles and a worst burst of 7 and justified the gate as flood control. That was wrong: it counted Wake Requests scheduling lines as wakes. Maintenance sleeps overwhelmingly resolve as DarkWake, which never fires resume — so they never recorded a breadcrumb in the first place. There was no flooding risk to solve; the gate's real job is the narrower one above.

Testing

7 unit tests, all mutation-verified — each mutation below fails at least one test:

mutation caught by
suspendedAt = now() instead of ??= (dark-wake truncation) dark-wake test (breadcrumb vanishes entirely)
remove the 60s threshold 20-cycle sub-heartbeat test
never reset suspendedAt repeated-cycles (spurious trailing resume)
record even when no suspend was seen resume-without-suspend
teardown detaches a foreign closure unsubscribe (off calls deep-equal on calls)
drop the resume broadcast broadcast + resume-without-suspend

The off mock is identity-aware, so detaching a different closure than the one registered fails the suite — for 'suspend' that leak is otherwise unobservable through the public API.

Full suite: 35813 passed. The 2 failures in src/relay/agent-exec-handler.test.ts reproduce on clean main with this change stashed — pre-existing and unrelated. Typecheck clean on all three projects; lint clean.

Scope

Main-process only, no platform branches — powerMonitor suspend/resume is supported on macOS, Linux, and Windows. Registered once at src/main/index.ts:1875 with a paired teardown at :2488; suspendedAt is closure-scoped, so re-registration cannot cross-contaminate.

Note on the earlier PRs

This does not revert #10473 / #10485 / #10487. Those fix a real macOS 26 frame-mutation hazard that v1.4.152 genuinely shipped — and per the correction above, that hazard is now the best-supported explanation for this user's freeze, not merely a latent extra. This PR closes the instrumentation gap that made the attribution unfalsifiable in the first place.

… as freezes

Renderer timers stop across OS sleep, so a multi-hour `renderer_memory`
heartbeat gap looks identical to a wedged renderer. That ambiguity sent the
uber-crash investigation down a deadlock path that the telemetry later
disproved -- and a healthy machine's own trace shows a 427-minute mid-session
gap with reason=interval, so the gap alone proves nothing either way.

powerMonitor 'resume' was already wired for renderer wake recovery but left no
breadcrumb. Stamp suspend and report the measured span on resume so the next
freeze report can be told apart from a laptop lid.
@coderabbitai

coderabbitai Bot commented Jul 25, 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

The registerSystemResumeBroadcast function now tracks elapsed time between OS suspend and resume events using an optional injectable clock. It records a system_slept crash breadcrumb when the duration reaches 60 seconds, including suspendedForMs, then broadcasts the resume channel to renderer windows. The event source supports both suspend and resume listeners, and cleanup removes both. Tests cover lifecycle events, breadcrumb timing, short sleeps, repeated cycles, and unsubscribe behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers motivation, behavior, and testing, but it omits required template sections like Summary, Screenshots, AI Review Report, Security Audit, and Notes. Add the missing template sections and include the required AI review, security audit, notes, and screenshots status ('No visual change' if applicable).
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed It clearly summarizes the main change: recording OS suspend/resume events to distinguish sleep gaps from freezes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/system-resume-broadcast.test.ts (1)

24-26: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

off mock ignores callback identity, so unsubscribe assertions can't catch a reference mismatch.

off deletes by event key only (_callback unused), so toHaveBeenCalledWith(event, expect.any(Function)) can't verify the exact listener passed to off matches the one registered via on. A regression where cleanup detaches a different closure than the one registered (which would leak a real powerMonitor listener) wouldn't fail this suite.

♻️ Optional strengthening
   const source = {
     on: vi.fn((event: PowerLifecycleEvent, callback: ResumeListener) => {
       listeners.set(event, callback)
     }),
-    off: vi.fn((event: PowerLifecycleEvent, _callback: ResumeListener) => {
-      listeners.delete(event)
+    off: vi.fn((event: PowerLifecycleEvent, callback: ResumeListener) => {
+      if (listeners.get(event) === callback) {
+        listeners.delete(event)
+      }
     })
   }

Also applies to: 76-79


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5639c1ce-5261-4733-bafb-e47028979d44

📥 Commits

Reviewing files that changed from the base of the PR and between d8e0f11 and d00a2c9.

📒 Files selected for processing (2)
  • src/main/system-resume-broadcast.test.ts
  • src/main/system-resume-broadcast.ts

Adversarial review flagged that the first cut would flood the 30-entry
breadcrumb ring and evict the crash evidence it exists to explain. Measured on
7 days of pmset history: 70 user-visible sleep cycles, worst 60-min burst of 7.
Median span is 2 SECONDS -- only ~24% run past 60s, so most of that traffic
could never explain a gap anyway.

Cycles are counted Sleep -> next FULL Wake, since powerMonitor's resume maps to
NSWorkspaceDidWake, which does not fire for dark wake.

Drop the suspend breadcrumb (suspend now only stamps a timestamp) and emit a
single `system_slept` on resume, gated at 60s. That cuts 70 cycles to 17 over
the same week (worst burst 3) while still catching every sleep long enough to
swallow a 60s renderer heartbeat.
@nwparker
nwparker force-pushed the nwparker/sleep-attribution-breadcrumbs branch from 68ce852 to ac8497d Compare July 25, 2026 09:45
nwparker and others added 3 commits July 25, 2026 02:49
The off mock deleted by event name alone, so teardown detaching a
different closure than the one registered still passed -- a leak of the
real powerMonitor listener would have gone unnoticed. For 'suspend' that
leak has no other observable effect through the public API.

Co-authored-by: Orca <[email protected]>
powerMonitor 'resume' maps to NSWorkspaceDidWake, which does not fire for
dark wake, so macOS can deliver suspend -> suspend -> resume. Overwriting
the stamp reported only the trailing segment, and when that segment fell
under the 60s gate a 90-minute sleep recorded nothing at all -- leaving
the gap looking like the unexplained freeze this is meant to rule out.

Co-authored-by: Orca <[email protected]>
The comment claimed maintenance sleeps would flood the ring. Re-measuring
pmset over 6 days (78 sleeps, 29 full wakes, 51 dark wakes) shows they
resolve as DarkWake, which never fires 'resume', so they never recorded a
breadcrumb at all. Real rate is 29 breadcrumbs / 6 days, worst 60-minute
burst 4 against a 30-entry ring. The gate's actual job is narrower: skip
sleeps shorter than the 60s heartbeat, which cannot open a gap to explain.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker merged commit f8b9b5c into main Jul 25, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/sleep-attribution-breadcrumbs branch July 25, 2026 10:12
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… as freezes (stablyai#10530)

* feat(diagnostics): record OS suspend/resume so sleep gaps aren't read as freezes

Renderer timers stop across OS sleep, so a multi-hour `renderer_memory`
heartbeat gap looks identical to a wedged renderer. That ambiguity sent the
uber-crash investigation down a deadlock path that the telemetry later
disproved -- and a healthy machine's own trace shows a 427-minute mid-session
gap with reason=interval, so the gap alone proves nothing either way.

powerMonitor 'resume' was already wired for renderer wake recovery but left no
breadcrumb. Stamp suspend and report the measured span on resume so the next
freeze report can be told apart from a laptop lid.

* fix(diagnostics): only record sleeps long enough to hide a heartbeat

Adversarial review flagged that the first cut would flood the 30-entry
breadcrumb ring and evict the crash evidence it exists to explain. Measured on
7 days of pmset history: 70 user-visible sleep cycles, worst 60-min burst of 7.
Median span is 2 SECONDS -- only ~24% run past 60s, so most of that traffic
could never explain a gap anyway.

Cycles are counted Sleep -> next FULL Wake, since powerMonitor's resume maps to
NSWorkspaceDidWake, which does not fire for dark wake.

Drop the suspend breadcrumb (suspend now only stamps a timestamp) and emit a
single `system_slept` on resume, gated at 60s. That cuts 70 cycles to 17 over
the same week (worst burst 3) while still catching every sleep long enough to
swallow a 60s renderer heartbeat.

* test(diagnostics): assert resume listeners detach by identity

The off mock deleted by event name alone, so teardown detaching a
different closure than the one registered still passed -- a leak of the
real powerMonitor listener would have gone unnoticed. For 'suspend' that
leak has no other observable effect through the public API.

Co-authored-by: Orca <[email protected]>

* fix(diagnostics): span from the first suspend across dark wake

powerMonitor 'resume' maps to NSWorkspaceDidWake, which does not fire for
dark wake, so macOS can deliver suspend -> suspend -> resume. Overwriting
the stamp reported only the trailing segment, and when that segment fell
under the 60s gate a 90-minute sleep recorded nothing at all -- leaving
the gap looking like the unexplained freeze this is meant to rule out.

Co-authored-by: Orca <[email protected]>

* docs(diagnostics): correct the threshold rationale to match measurement

The comment claimed maintenance sleeps would flood the ring. Re-measuring
pmset over 6 days (78 sleeps, 29 full wakes, 51 dark wakes) shows they
resolve as DarkWake, which never fires 'resume', so they never recorded a
breadcrumb at all. Real rate is 29 breadcrumbs / 6 days, worst 60-minute
burst 4 against a 30-entry ring. The gate's actual job is narrower: skip
sleeps shorter than the 60s heartbeat, which cannot open a gap to explain.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Orca <[email protected]>
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