Repository navigation
fix(gateway): resume main sessions after missed restart markers - #168651
Conversation
Keep restart-aborted registrations eligible for shutdown marking and recover orphaned interruption state without a claim at startup. Preserve live owners and terminal cancellations, and report archived recovery candidates separately.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR preserves shutdown recovery markers for restart-aborted runs and recovers interrupted main sessions whose marker was missed. Example: The Gateway restarts while agent:main:dashboard:main is working, leaving status=interrupted and abortedLastRun=true without a recovery claim.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it repairs an evidenced restart-recovery failure still present on current main, and no actionable introduced defect remains after review. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway shutdown and startup feed persisted session facts into the existing main-session recovery owner, which checks ownership and delivery state before admitting an ordinary agent continuation. flowchart TD
A[Gateway restart] --> B[Shutdown marker]
B --> C[SQLite session state]
C --> D[Startup orphan reconciliation]
D --> E[Ownership and completion checks]
E --> F[Existing recovery admission]
F --> G[Agent continuation and reply]
Technical reviewBest possible solution: Land the focused repair through the existing recovery owner while retaining completion, cancellation, live-owner, and delegated-authority safeguards. Do we have a high-confidence way to reproduce the issue? The reported cancellation-before-marking sequence matches the shutdown source, and current main excludes claimless interrupted rows; the supplied regressions reportedly fail before the fix, but this read-only review ran no target code. Is this the best way to solve the issue? The repair addresses both missed shutdown marking and startup reconciliation through existing owners, preserves the prior terminal-receipt fix, and retains the preparation-aware flow. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7562fd2b9012. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +56, Tests +191, Docs +8. Total +255 across 9 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (5 earlier review cycles)
Reviewed October 10, 2026, 8:14 PM ET / October 11, 2026, 00:14 UTC (Revision 6). |
|
Maintainer note on the "Add data-model compatibility proof" item: this PR does not change any stored data model. It reads fields that already exist on every persisted session entry ( |
Keep delivered claimless continuations settled by checking their exact terminal run identities. Cover historical-only receipts as a recoverable sibling and align archived admission diagnostics without changing startup concurrency or shutdown custody.
Merge origin/main while preserving its preparation-aware work-start flow. Classify archived recovery inside the shared block decision, retain pending preparation handling, and combine the recovery documentation.
…ed head (#168818) * fix(pr): record merged receipts for auto-merged pushed heads GitHub's auto-merge head precondition applies only at submission. When a collaborator pushes after an accepted auto request, GitHub keeps the request armed and merges the pushed head, and the retained intent head no longer matches the merged head. merge-run, merge-recover --cancel-auto, and merge-complete all refused, leaving the outcome at phase intent forever (2026-10-11, #168651). Add an explicit operator route, merge-recover --merged-head <SHA>, that records a validated MERGED receipt as a CAS successor with phase merged, landed, and headDrift {actor, outcome, mergedHead}. It requires the exact current accepted non-queue auto intent without a cancellation record, the MERGED PR with retained identity and base, the explicitly selected head equal to GitHub's authoritative head and strictly descending from the retained head, a landed commit reachable from main, and a landed tree that reconstructs under the retained method. head stays the prepared intent head; the merged head object is retained as a parent. Reconciliation prints the exact command when it observes this drift. Every other drift keeps its refusal; nothing is dispatched, cancelled, re-armed, or cleared. The landed-receipt verification moves into one helper shared by reconciliation and the new route, and squash receipts now require a single-parent landed commit so the retained method stays checkable. * test(scripts): cover the merged-head recovery argument The wrapper argument-vector tests pin merge_run's exact parameters; account for the new --merged-head slot, reject it alongside incompatible recovery flags, and pass an explicitly selected merged head through to recovery.
…claw#168651) * fix(gateway): always recover interrupted main sessions after restart Keep restart-aborted registrations eligible for shutdown marking and recover orphaned interruption state without a claim at startup. Preserve live owners and terminal cancellations, and report archived recovery candidates separately. * fix(recovery): preserve terminal receipts during claimless startup Keep delivered claimless continuations settled by checking their exact terminal run identities. Cover historical-only receipts as a recoverable sibling and align archived admission diagnostics without changing startup concurrency or shutdown custody.
…ed head (openclaw#168818) * fix(pr): record merged receipts for auto-merged pushed heads GitHub's auto-merge head precondition applies only at submission. When a collaborator pushes after an accepted auto request, GitHub keeps the request armed and merges the pushed head, and the retained intent head no longer matches the merged head. merge-run, merge-recover --cancel-auto, and merge-complete all refused, leaving the outcome at phase intent forever (2026-10-11, openclaw#168651). Add an explicit operator route, merge-recover --merged-head <SHA>, that records a validated MERGED receipt as a CAS successor with phase merged, landed, and headDrift {actor, outcome, mergedHead}. It requires the exact current accepted non-queue auto intent without a cancellation record, the MERGED PR with retained identity and base, the explicitly selected head equal to GitHub's authoritative head and strictly descending from the retained head, a landed commit reachable from main, and a landed tree that reconstructs under the retained method. head stays the prepared intent head; the merged head object is retained as a parent. Reconciliation prints the exact command when it observes this drift. Every other drift keeps its refusal; nothing is dispatched, cancelled, re-armed, or cleared. The landed-receipt verification moves into one helper shared by reconciliation and the new route, and squash receipts now require a single-parent landed commit so the retained method stays checkable. * test(scripts): cover the merged-head recovery argument The wrapper argument-vector tests pin merge_run's exact parameters; account for the new --merged-head slot, reject it alongside incompatible recovery flags, and pass an explicitly selected merged head through to recovery.
) (extracted hotfix) Extracted from #168651 (4754d39): took only the src/gateway/server-run-shutdown.ts hunk (isRestartRecoveryRun) plus its regression case in server-run-shutdown.recovery.test.ts. The connection-close prelude can abort a main run with a restart reason before the shutdown marker runs; the branch then skipped that run, so the session stayed "interrupted" and never resumed. Left out the claimless startup-recovery store/marking changes, diagnostics, and docs: they conflict on the branch and pair with #168650, which was not approved. Extracted-from: 4754d39 Co-authored-by: Peter Steinberger <[email protected]>
Release provenance: 89329f6 -> #168587 Release provenance: e6a9022 -> #168905 Release provenance: 15f3f12 -> #162266 Release provenance: 20805b8 -> #169430 Release provenance: 568fec8 -> #169102 Release provenance: 39dba6d -> #160440 Release provenance: 5df28c7 -> #168393 Release provenance: 10bcd8e -> #168164 Release provenance: dc5f1f5 -> #168446 Release provenance: 9f1e441 -> #168044 Release provenance: 5a235fc -> #168651
) (2026.10.5 backport) Startup restart recovery treated a session that was still initializing or preparing its workspace as a terminal operator block and never revisited it, so turns interrupted by an update restart stayed stranded. The work-start owner now reports whether the block is retryable; startup recovery retains those candidates and rechecks them after session preparation commits, using the existing bounded retry and exact-target admission. Grouped with the remaining startup-recovery half of #168651 (4754d39), which pairs with this change: shutdown/startup marking now also recovers an interrupted main session that persisted abortedLastRun/status "interrupted" without a recovery claim (crash or early restart abort), skips archived sessions with their own diagnostic, preserves already-delivered terminal receipts, and logs why a shutdown marked zero sessions. The src/gateway/server-run-shutdown.ts hunk of #168651 is already on the branch as 5a235fc and is not repeated. Backport adaptation: the store import block conflicted only because main imports session-source-authority helpers the branch does not use; kept the branch imports and added resolveSessionWorkStartBlock. Extracted-from: 00daf0f Extracted-from: 4754d39 Co-authored-by: Peter Steinberger <[email protected]>
…claw#168651) Adapt the released restart recovery invariant to this branch's consolidated server-close coverage. Co-authored-by: RomneyDa <[email protected]>
What Problem This Solves
Main dashboard/WebChat/channel sessions that are working when the Gateway restarts must resume automatically. A production restart on 2026-10-10 left two dashboard main turns interrupted indefinitely until a human sent another message.
Abbreviated timeline, UTC (c18792f → 3050cdc): SIGTERM at 19:36:27; drain exhausted at 19:37:12.385; both reply admissions released for
restart-abortat 19:37:12.408, before the shutdown marker; startup at 19:37:45 reportedstarted=0. The affected rows retainedstatus: interruptedandabortedLastRun: true, but no recovery claim. Separately, 51 archived recovery rows were repeatedly reported aswork_start_blockedrequiring operator action.User Impact
A main chat session (dashboard, WebChat, or channel) that is mid-turn when the Gateway restarts for a deploy, crash, or kill now resumes on the next boot without anyone typing a follow-up. Before, a restart whose connection cleanup ran a few milliseconds ahead of the shutdown marker left the session showing
interruptedforever. Operators also stop seeing archived sessions reported as blocked recovery work on every boot.Why This Change Was Made
The close prelude calls
runtime.connectionWork.beginClose(createAgentRunRestartAbortError())insrc/gateway/server-lifecycle.ts:402before calling shutdown preparation.AsyncWorkScope.beginClosesynchronously cancels inherited work, and the reply-admission listener insrc/auto-reply/reply/reply-turn-admission.ts:551releases its database lease on that signal. This ordering exists in the old production revision too.Shutdown collection and its subsequent owner recheck excluded already-aborted controllers, even when the reason was restart. Startup then required an existing recovery claim, so it could not repair the missed marker. Archived rows reached the generic work-start refusal before being classified separately.
Fix
abortedLastRunalso describes killed turns, so an unclaimed completed outcome remains unchanged.archived, deferred with no next owner, before work-start checks. Document the automatic resume guarantee and startup safety net. No schema, config, or changelog changes.Evidence
Merge validation —
fa4f746dacfdMerged
origin/mainat6cc0e8460192without rebasing or amending. Resolved the overlap with #168650 by retaining dispatch-target resolution beforeresolveSessionWorkStartBlock. Its distinctarchivedreason is non-retryable; only that reason selectsskip("archived")inside the existing block branch. The branch still recordsdecision.reasonand preserves pending/blocked behavior andonPreparationPending. The separate early archived check is removed.Diagnostics retain both
work_start_pendingand archived/deferred/no-owner handling. The docs retain main's Session preparation paragraph and the recovery guarantee/startup safety net, with the combined skip-reason list and archived-deferred sentence. Main's new admission cases are unchanged, and the existing continue case still expects archived/deferred/none.pnpm test src/agents/main-session-recovery/main-session-restart-recovery-admission.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-startup-recovery.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-restart-recovery-marking.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-restart-abort.integration.test.ts --maxWorkers=1pnpm test src/gateway/server-run-shutdown.recovery.test.ts --maxWorkers=1All 51 tests passed. Times use
/usr/bin/time -pand include existing compilation/import and SQLite fixture costs. Changed-file oxfmt and oxlint,pnpm tsgo:core, the canonicalcore-test-agents-sessionsandcore-test-gateway-servertype graphs, andgit diff --checkpassed.node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mtspassed. Codex autoreview against the new merge base6cc0e8460192d6dae2f1f3622665755d09b908b7was scoped-clean with no actionable P0–P2 findings. No PR merge or manual CI action was performed.Follow-up validation —
0503ea4969e6Fixed the two findings from head
f26dc47e2329, with no other changes. Claimless startup now preserves a terminal receipt for the interrupted continuation, checking its lifecycle, writer, or delivery-source run ID. The regression pairs that delivered row with a claimless interruption whose receipts belong only to other runs; only the latter is marked. The admission test now expectsarchived/deferred/none, while retaining its startup-concurrency and shutdown-custody assertions.pnpm test src/agents/main-session-recovery/main-session-restart-abort.integration.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-restart-recovery-admission.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-startup-recovery.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-restart-recovery-marking.test.ts --maxWorkers=1pnpm test src/gateway/server-run-shutdown.recovery.test.ts --maxWorkers=1All five files passed (46 tests). Times use
/usr/bin/time -pand include existing compilation/import and worker-backed SQLite fixture costs; no new timers, sleeps, polling, or Gateway boots. The new focused regression failed before the fix (marked=2, expected1; 46.73 s).Changed-file oxfmt and oxlint checks passed.
pnpm tsgo:coreandnode scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-sessions"]'passed.git diff --checkpassed. The isolated Codex autoreview helper reviewed only the delta fromf26dc47e2329and found no actionable P0–P2 findings. No merge or manual CI action was performed.Initial validation
pnpm test src/gateway/server-run-shutdown.recovery.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-startup-recovery.test.ts --maxWorkers=1pnpm test src/agents/main-session-recovery/main-session-restart-recovery-marking.test.ts --maxWorkers=1All wall times use
/usr/bin/time -p. The final marking run used a separate filesystem module cache while static checks ran. These files exercise real worker-backed SQLite ownership, persistence, and dispatch admission using existing fixtures; no new sleeps, polling, or per-test Gateway boots. Wall time includes compilation/imports and host contention; the marking file previously passed in 45.70 s. Hosted CI seconds are not yet available.The shutdown and claimless-startup regressions failed against the original behavior. After startup marking was fixed, archive classification failed independently. An added cancellation control also failed before preserving the terminal-outcome check. All now pass. Independent isolated review found no actionable P0–P2 issues.
Changed-file formatting and lint, production types, all 28 selected test-type graphs, and the remaining policy/schema/import/authorization checks passed.
pnpm check:changed --base HEAD(run before committing) initially caught a test-fixture literal widened tostring; an explicit session-entry type fixed it. The five unfinished type graphs then passed throughnode scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-sessions","core-test-services-cron","core-test-ui-app","core-test-ui-components","core-test-ui-e2e-chat"]'(41.40 s), and the remaining checks ran through the same exported changed-check planner.One inherited check remains red:
node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mtsreports 16 unused exports in model-auth/prepared-model files andtools/solid-lint/index.mjs(98.79 s). The same command reproduced the exact same 16 findings on unchanged baselineb66d8da2938din an isolated checkout (131.84 s). No changed file is in that list. The full-tree export scan passes. These unrelated findings were not suppressed or edited.Risk
Startup deliberately discovers more interrupted rows, so the important boundary is unfinished work versus a completed/cancelled turn or a current live owner. Those controls are covered and retained. Recovery uses the existing store, dispatch, retry, and delivery owners; it does not automatically replay an uncertain external side effect.
The historical lease log does not identify whether
operation.abortSignalor inheritedworkSignalfired first for each turn. The prelude's inherited restart cancellation is identified from source and precedes marking; the fix tolerates either signal order and a missing shutdown marker. No live Gateway was modified or restarted for this work. This PR remains a draft.