Skip to content

Keep profile saving alive after a stalled main loop - #25318

Merged
AmethystLiang merged 4 commits into
mainfrom
unable-to-save-profile
Oct 6, 2026
Merged

AmethystLiang merged 4 commits into
mainfrom
unable-to-save-profile

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​838 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​823
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​600 $\color{#cf222e}{\Huge{\mathbf{−}}}$​132 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​468

ELI5

After sleep or a blocked main process, Orca could stop saving even though its background helper had already saved successfully. Queued replies now get a chance to arrive before Orca declares a timeout. A helper that remains unresponsive still times out after a bounded amount of extra time.

What Changed

  • Request deadlines use a monotonic clock. Suspended requests and timers delayed by at least five seconds can receive another timeout window. Resume events share the same limit of three extensions per request.
  • Before the final timeout, one cancellable setImmediate lets queued worker replies drain. This also covers short stalls below the five-second grace threshold, without granting every slightly late timer a full extra window.
  • Closing waits for the worker's actual exit, including when an acknowledged close later times out. Termination being requested does not release ownership of the database.
  • Save failures retain diagnostics and the existing failure alert, with background-launch and window-parenting behavior covered by tests.
  • The real Electron stall regression runs in the Linux and Windows package jobs. Headless Node qualification excludes Electron-only tests because its compatibility containers do not provide a display.

Why

A delayed reply does not prove that a save failed. Raising the timeout only moves the race, and restarting a healthy worker unnecessarily can exhaust the recovery budget in #25319. Letting queued replies run addresses that race; bounded grace accommodates sleep while preserving failure detection. Confirmed worker exit prevents another owner from proceeding while termination is still in progress.

Linked Issue

N/A — internal report; no existing linked issue.

Visual Proof

N/A — the new regression test launches a hidden Electron main process with no windows and checks persisted SQLite state. Alert behavior is covered by automated tests; a rendered user-flow demonstration has not been performed.

Testing

  • Reproduced failing queued-reply, repeated-resume, and close-before-exit cases before fixing them.

  • 102 targeted tests across deadline, close, sleep, worker protocol, authority, coordination, and maintenance suites pass on macOS.

  • Real Electron main-process test passes with the production 30-second timeout: four consecutive stalls just beyond the deadline, then another successful save; durable revision 6, one worker, no failure alerts. The normal two-second fixture also passes.

  • pnpm tc:node, changed-code quality, runtime Electron import ratchet, lint/format checks for the changed TypeScript files, and git diff --check pass.

  • CI: the Electron regression passed in the Windows package job and the Linux Electron lifecycle step. The persistence matrix passed on macOS, Linux, and Windows, each on x64 and ARM. These results precede the final test-routing-only commit. That CI run also exposed the Electron test being selected in the headless glibc container (xvfb-run was missing). The runner now excludes Electron probes; a file-selection check confirms all 59 headless persistence test files remain selected. Full CI is rerunning on the latest head.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Check cancellation of the final timeout callback, the shared grace budget, and the worker-exit ownership barrier. Successful writes do not schedule the extra callback; it runs only when a deadline expires.

Agent skill upstream boundary

  • Not applicable; no upstream skill source is copied.

Notes

No database schema or wire-protocol changes. Persistence remains on the execution host, including SSH/headless use. The cause of the original main-process stall remains unproven; this fixes how persistence handles that stall. #25319 adds bounded recovery when a worker really needs replacement.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Visual-proof scope and limitations explained above
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and compatibility impact considered
  • Full lint, typecheck, tests, and build pass in CI

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8cc28d38-49a5-454a-a61f-1424f7fdf81a
📥 Commits

Reviewing files that changed from the base of the PR and between 9d94268 and 68e8daf.

📒 Files selected for processing (1)
  • config/scripts/run-node-server-tests.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The profile-state writer now uses power-aware request deadlines and a thread wrapper for worker messaging, exit waits, and termination. Diagnostics record deadline events, writer faults, and failure-report presentation states. Write-failure dialogs distinguish indeterminate outcomes from confirmed-safe earlier changes and wait for a visible main window. Runtime startup-failure reporting now uses the shared window-visibility helper. New unit and Electron tests cover deadline behavior during stalls and suspend, worker close behavior, and writes across simulated stalls.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 68e8d

The PR improves profile-save resilience during stalls and keeps Electron probes out of headless qualification. No material user-impacting regression introduced by this change is established; it is ready to merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 68e8d

Saving now tolerates sleep and delayed replies without releasing ownership before background work finishes. No introduced security issue was established in the inspected paths, but coverage was not complete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The direct persistent asset remains the database admitted through the authority's database path, profile identity and revision. Shared power events can affect deadlines across subscribers, while grace budgets and worker-exit ownership are maintained per deadline and writer instance.

Trust Boundaries and Controls

  • observed — The parent validates worker responses against the pending request and expected revision. The worker rejects malformed, duplicate or concurrent requests, and replacement initialization revalidates the admitted revision on disk. These existing controls remain between main-process scheduling and live SQL authority.

Resilience and Maintainability Implications

  • observed — A fault retires the connection, settles the active request and requests termination; subsequent dispatch rejects the stored failure rather than retrying an indeterminate write. Abort awaits exit, and acknowledgedRevision refuses to expose a failed writer's revision for maintenance re-admission.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.95% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 29 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 clearly and concisely describes the main change: keeping profile saving active after a stalled main loop.
Description check ✅ Passed The description covers the ELI5 summary, changes, rationale, linked-issue status, visual-proof rationale, testing, review notes, and checklist. It also clearly states that full CI is still running and…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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: Advanced
  • Run ID: 1fdc7ad4-c950-4e20-9a88-fac207863a34
📥 Commits

Reviewing files that changed from the base of the PR and between a753aff and 4a58d3c86a4c8795f0a45f24a648009046e33ae8.

📒 Files selected for processing (25)
  • src/main/persistence/profile-state/profile-state-database-schema.ts
  • src/main/persistence/profile-state/profile-state-documents.ts
  • src/main/persistence/profile-state/profile-state-domain-writes.ts
  • src/main/persistence/profile-state/profile-state-revision-readmission.ts
  • src/main/persistence/profile-state/profile-state-revision.ts
  • src/main/persistence/profile-state/profile-state-sqlite-authority.ts
  • src/main/persistence/profile-state/profile-state-worker-authority.ts
  • src/main/persistence/profile-state/profile-state-write-operation.test.ts
  • src/main/persistence/profile-state/profile-state-writer-connection.ts
  • src/main/persistence/profile-state/profile-state-writer-deadline.test.ts
  • src/main/persistence/profile-state/profile-state-writer-deadline.ts
  • src/main/persistence/profile-state/profile-state-writer-diagnostics.ts
  • src/main/persistence/profile-state/profile-state-writer-protocol.ts
  • src/main/persistence/profile-state/profile-state-writer-recovery-fixture.ts
  • src/main/persistence/profile-state/profile-state-writer-recovery.test.ts
  • src/main/persistence/profile-state/profile-state-writer-request.ts
  • src/main/persistence/profile-state/profile-state-writer-sleep.test.ts
  • src/main/persistence/profile-state/profile-state-writer-supervisor.ts
  • src/main/persistence/profile-state/profile-state-writer-thread.ts
  • src/main/persistence/profile-state/profile-state-writer-worker-entry.ts
  • src/main/runtime/runtime-rpc-startup-failure.ts
  • src/main/startup/profile-state-write-failure.test.ts
  • src/main/startup/profile-state-write-failure.ts
  • src/main/system-power-lifecycle.ts
  • src/main/window/wait-for-window-to-show.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one robustness gap in the new deadline plus a stale comment below.

Reviewed changes

Initial review of 4a58d3c against main.

  • Deadline grace (profile-state-writer-deadline.ts) — a request that expires ≥5s late, or while the system reports suspended, now re-arms (up to 3 graces) instead of permanently faulting the writer; this is what rescues the overnight-stall incident.
  • Safe recovery (profile-state-writer-supervisor.ts, profile-state-revision-readmission.ts) — each committing write records <connection token>:<requestId> atomically with its revision, so a replacement can prove from SQLite whether the interrupted write committed and either adopt or replay it, refusing on any foreign revision.
  • Main-window alert (profile-state-write-failure.ts, new src/main/window/wait-for-window-to-show.ts) — failure alert is parented to the visible main window, deferred while hidden, never reveals/activates, and never stacks; background/serve stay silent.
  • Diagnostics (profile-state-writer-diagnostics.ts) — payload-free durable breadcrumbs for grace, timeout, fault, recovery, and alert presentation.
  • Tests — real worker threads + temp SQLite with fault injection (hang, dropped reply, exit-after-write, failed start, delayed start) and a controlled-clock sleep suite; the regression test reproduces the reply-queued-behind-overdue-timer incident.

I traced the op-id handoff and could not construct a duplicate-replay, false-adoption, or lost-attribution interleaving: the token is per connection and never reused by a replacement, request ids are monotonic, and the key is written only inside the committing transaction, so a stale value cannot match a new interrupted id at exactly revision + 1; concurrent writers fail closed.

ℹ️ Nitpicks

  • ProfileStateWriterThread.waitForExit and the ProfileStateWriterConnection delegate both say "within one awake deadline", but they reuse createProfileStateWriterDeadline, which now grants grace, so they can take up to four windows before resolving false.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

After a long main-loop stall (overnight sleep, dark wakes), the profile
writer's overdue 30s timeout could run before an acknowledgement that was
already queued, permanently retiring the writer until restart. Terminal
creation then failed because pane bindings could not be saved.

- Writer deadlines measure lateness on the monotonic clock and grant a
  bounded fresh window when the callback is overdue or the system reports
  suspended; resume re-arms without spending grace. Applies to
  initialization, every command, and the close/exit wait.
- The "Saving stopped" alert is parented to a visible main window (never a
  parentless synchronous macOS alert), deferred until shown, deduplicated,
  and says whether the latest change is unconfirmed.
- Timeouts, grace, writer faults, and alert presentation leave sanitized
  durable breadcrumbs.
@AmethystLiang
AmethystLiang force-pushed the unable-to-save-profile branch from 4a58d3c to 923b365 Compare October 4, 2026 22:51
@AmethystLiang AmethystLiang changed the title Keep profile saving alive after sleep and recover stalled writers safely Keep profile saving alive after a stalled main loop Oct 4, 2026

@pullfrog pullfrog 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.

✅ No new issues found in the incremental delta.

Reviewed changes

Incremental review of 923b365 against the prior pullfrog review at 4a58d3c. The branch was re-created on the same parent (2b3b692) to descope it: the safe-recovery work was extracted to the stacked #25319, leaving deadline grace, the parented alert, and diagnostics.

  • Removed the safe-recovery supervisor and the <token>:<requestId> op-id handoff, plus the recovery fixture/test files (moved to #25319). profile-state-documents, -domain-writes, -revision, -revision-readmission, -sqlite-authority, -worker-authority, -writer-protocol, and -writer-worker-entry revert to main.
  • Simplified ProfileStateWriterConnection and ProfileStateWriterRequest to their pre-recovery shape: dropped the per-connection operation token, the faulted/interrupted fault state, admitted, the waitForExit delegate, and the mayAdvance revision rule; retained lastAcknowledgedRevision for diagnostics.
  • Dropped recordProfileStateWriterRecovery from the diagnostics module.
  • No dangling references to the removed symbols remain, and the retained deadline/sleep/alert suites still pass (profile-state-writer-deadline, -sleep, -write-failure — 26 tests).

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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: Advanced
  • Run ID: e184e889-6922-4485-af6b-054edeb55139
📥 Commits

Reviewing files that changed from the base of the PR and between 4a58d3c86a4c8795f0a45f24a648009046e33ae8 and 923b365.

📒 Files selected for processing (3)
  • src/main/persistence/profile-state/profile-state-writer-connection.ts
  • src/main/persistence/profile-state/profile-state-writer-diagnostics.ts
  • src/main/persistence/profile-state/profile-state-writer-request.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Incremental review of 9d94268 against the prior pullfrog review at 923b365. The delta adds the queued-reply drain, caps resume-driven re-arms, and holds close until the worker actually exits.

  • Added a one-tick setImmediate drain before a final timeout, letting an already-queued worker reply settle the request first (profile-state-writer-deadline.ts).
  • Routed onResume through grantGrace, folding resume re-arms into the shared three-grace budget — this resolves the prior open thread about uncapped resume re-arms.
  • Made finishClose await the thread's actual exit after waitForExit, so a timed-out close still retains ownership until the worker exits (profile-state-writer-connection.ts:131).
  • Added close, repeated-resume/grace-budget, and Electron main-process stall regression tests, and wired the stall test into the Linux and Windows package jobs.

Verified locally: profile-state-writer-deadline (12), -close (3), and -sleep (15) suites pass.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Incremental review of 68e8daf against the prior pullfrog review at 9d94268. The delta is the headless test-selection fix for the new Electron stall probe.

  • Excluded **/*.electron.test.ts from the headless node-server test selection in config/scripts/run-node-server-tests.mjs, so the new Electron stall probe is no longer pulled in by the src/main/persistence/profile-state directory selector in compatibility containers that have no display.

I verified with vitest list --config config/vitest.config.ts src/main/persistence/profile-state --exclude '**/*.electron.test.ts' that the stall probe drops out and the remaining suite stays selected. The probe still runs in the always-on unit test job (UNIT_INCLUDE) and in the Linux/Windows package jobs wired in 9d94268, so no coverage is lost.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@AmethystLiang
AmethystLiang merged commit f7c542c into main Oct 6, 2026
38 checks passed
Fanzzzd added a commit to Fanzzzd/orca that referenced this pull request Oct 9, 2026
Picks up upstream's profile-state writer fixes (stablyai#25318, stablyai#26444, stablyai#26447).
Brings the offscreen-page file drop, iroh SAFETY/device-grant cleanups and
extension e2e typing in line with their current PR branches.

Claude-Session: https://claude.ai/code/session_01DvNJ16LEPYmdEkpQWtDL7n
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