Repository navigation
fix(gateway): Gateway crash-loops when restart recovery replays the turn that crashed it - #160434
masatohoshino wants to merge 2 commits into
Conversation
…breaker is tripped
|
🦞👀 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: blocked before merge. Reviewed September 28, 2026, 1:12 PM ET / 17:12 UTC (Revision 4). ClawSweeper reviewWhat this changesThe branch pauses automatic replay of interrupted main-session turns on a breaker-tripped Gateway boot, while retaining session marking, explicit resume, and recovery guidance. Merge readiness⛔ Blocked before merge - 3 items remain This remains a useful fix for a demonstrated Gateway crash loop. The patch has no discrete correctness finding, and its published-release upgrade trace supports the containment behavior. Maintainer acceptance is still needed for leaving paused turns unfinished when channels recover in the same running Gateway. Priority: P0 Review scores
Verification
How this fits togetherGateway startup reads persisted boot history to decide whether its crash-loop breaker has tripped. Main-session recovery then marks interrupted turns and either replays them or leaves them for a later message or Gateway start. flowchart TD
A[Persisted boot history] --> B[Crash-loop breaker]
B --> C[Gateway startup]
C --> D[Mark interrupted sessions]
D --> E{Breaker tripped?}
E -->|Yes| F[Pause automatic replay]
E -->|No| G[Replay interrupted turns]
F --> H[New message or later boot resumes]
Decision needed
Why: The PR deliberately favors containment over automatic completion, and source confirms that channel auto-start can recover in the same process without rescheduling those turns. Before merge
Agent review detailsSecurityNone. PR surfaceSource +51, Tests +47, Docs +10. Total +108 across 7 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep crash-loop containment in the existing boot and session-recovery owners, preserve transcripts and explicit resume, and provide a visible Doctor or Fix path for operators to find paused sessions. Do we have a high-confidence way to reproduce the issue? Yes for the replay loop: current-main source still schedules recovery without consulting the breaker, and the PR records a pre-fix Gateway run that repeatedly replays the turn. The specific macOS descriptor abort was not reproduced. Is this the best way to solve the issue? Yes for crash-loop containment: the patch uses the existing breaker and recovery owners without changing the retry allowance or stored schema. The same-process completion policy still needs maintainer acceptance. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 46a227c51867. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
…tripped (#166238) * fix(gateway): pause restart recovery while the crash-loop breaker is tripped Quarantine interrupted main-session turns while the crash-loop window is active, preserving their entries and retry budget. Re-arm the existing recovery scheduler in the same healthy process when the window drains, with the original cutoff and lifecycle ownership. Reuse the breaker owner and rotate the boot segment before replay. Run runtime state access in workers and preserve manual channel stops and environment suppression during recovery. Supersedes #160434. Co-authored-by: Masato Hoshino <[email protected]> * fix(gateway): break the channel autostart recovery import cycle * fix(gateway): type autostart recovery suppression by identity * test(agents): await recovery admission before testing suspended stop The crash-loop check now reads breaker state through a worker before startup recovery reaches Gateway root admission. Advancing fake timers by zero does not wait for that I/O or its cancellation cleanup, so the old immediate stopped flag assertion could fail without a shutdown hang. Observe the real admission request through the existing call-through helper, then await stop while suspension remains closed. Only reopen admission after stop settles and retain the no-dispatch and unchanged interrupted-entry assertions. This preserves the shutdown contract and removes an incidental fake-clock ordering assumption; production cancellation behavior does not change. * fix(gateway): scope restart preparation to active crash-loop suppression Use the channel manager's prepared boot suppression instead of inspecting breaker storage on every startup or exact-target recovery call. Keep the healthy path synchronous and admit startup before recovery preparation. Return the owner's deadline to the existing scheduler. Let the Gateway cancel shared recovery work while individual callers cancel only their waits, and retain a committed boot identity if close overtakes its reply. The integration fixture forwards its virtual clock through the writer's existing time input because SQLite workers do not inherit fake timers. --------- Co-authored-by: Masato Hoshino <[email protected]>
|
Thank you @masatohoshino! Your crash-loop recovery pause landed as part of #166238 (squash 49c1815), with you credited as co-author. That version keeps your core idea: restart recovery is quarantined while the restart-loop breaker is tripped. It also adds the automatic in-process re-arm when the breaker window clears, which was the open semantics question here, and it rebuilds the change on current main. Closing this one as superseded. |
…tripped (#166238) * fix(gateway): pause restart recovery while the crash-loop breaker is tripped Quarantine interrupted main-session turns while the crash-loop window is active, preserving their entries and retry budget. Re-arm the existing recovery scheduler in the same healthy process when the window drains, with the original cutoff and lifecycle ownership. Reuse the breaker owner and rotate the boot segment before replay. Run runtime state access in workers and preserve manual channel stops and environment suppression during recovery. Supersedes #160434. Co-authored-by: Masato Hoshino <[email protected]> * fix(gateway): break the channel autostart recovery import cycle * fix(gateway): type autostart recovery suppression by identity * test(agents): await recovery admission before testing suspended stop The crash-loop check now reads breaker state through a worker before startup recovery reaches Gateway root admission. Advancing fake timers by zero does not wait for that I/O or its cancellation cleanup, so the old immediate stopped flag assertion could fail without a shutdown hang. Observe the real admission request through the existing call-through helper, then await stop while suspension remains closed. Only reopen admission after stop settles and retain the no-dispatch and unchanged interrupted-entry assertions. This preserves the shutdown contract and removes an incidental fake-clock ordering assumption; production cancellation behavior does not change. * fix(gateway): scope restart preparation to active crash-loop suppression Use the channel manager's prepared boot suppression instead of inspecting breaker storage on every startup or exact-target recovery call. Keep the healthy path synchronous and admit startup before recovery preparation. Return the owner's deadline to the existing scheduler. Let the Gateway cancel shared recovery work while individual callers cancel only their waits, and retain a committed boot identity if close overtakes its reply. The integration fixture forwards its virtual clock through the writer's existing time input because SQLite workers do not inherit fake timers. --------- Co-authored-by: Masato Hoshino <[email protected]> Backport notes (release/2026.10.1): no prerequisites taken. Startup orphan marking still lives in startGatewaySidecars on this line, so the crash-loop suppression guard is applied there, extracted to server-startup-main-session-orphans.ts to keep the over-cap file from growing (regression test in server-startup-main-session-orphans.test.ts), and the release-only main-session-restart-dispatch-capacity.test.ts fixture gains prepareRestartRecovery. The recovery runtime keeps the release structure and takes only this fix's gate, pause loop, and rotation handler; state registries and the worker inventory take only the gatewayBoot entries. (cherry picked from commit 49c1815)
…tripped (openclaw#166238) * fix(gateway): pause restart recovery while the crash-loop breaker is tripped Quarantine interrupted main-session turns while the crash-loop window is active, preserving their entries and retry budget. Re-arm the existing recovery scheduler in the same healthy process when the window drains, with the original cutoff and lifecycle ownership. Reuse the breaker owner and rotate the boot segment before replay. Run runtime state access in workers and preserve manual channel stops and environment suppression during recovery. Supersedes openclaw#160434. Co-authored-by: Masato Hoshino <[email protected]> * fix(gateway): break the channel autostart recovery import cycle * fix(gateway): type autostart recovery suppression by identity * test(agents): await recovery admission before testing suspended stop The crash-loop check now reads breaker state through a worker before startup recovery reaches Gateway root admission. Advancing fake timers by zero does not wait for that I/O or its cancellation cleanup, so the old immediate stopped flag assertion could fail without a shutdown hang. Observe the real admission request through the existing call-through helper, then await stop while suspension remains closed. Only reopen admission after stop settles and retain the no-dispatch and unchanged interrupted-entry assertions. This preserves the shutdown contract and removes an incidental fake-clock ordering assumption; production cancellation behavior does not change. * fix(gateway): scope restart preparation to active crash-loop suppression Use the channel manager's prepared boot suppression instead of inspecting breaker storage on every startup or exact-target recovery call. Keep the healthy path synchronous and admit startup before recovery preparation. Return the owner's deadline to the existing scheduler. Let the Gateway cancel shared recovery work while individual callers cancel only their waits, and retain a committed boot identity if close overtakes its reply. The integration fixture forwards its virtual clock through the writer's existing time input because SQLite workers do not inherit fake timers. --------- Co-authored-by: Masato Hoshino <[email protected]>
Closes #144772
What Problem This Solves
Fixes: the Gateway crash-loops forever when a main-session turn that was in flight during a crash crashes the process again each time startup restart recovery replays it (#144772).
User Impact
User impact: once the restart-loop breaker trips (3 unclean boots within 5 minutes), the Gateway stays up instead of replaying the crashing turn on every boot. The interrupted session and its transcript are kept and stay marked for recovery; the operator can inspect it, then resume it by sending a new message in that session, or let the first Gateway start after the breaker recovers resume it automatically. No session has to be deleted to break the loop.
Why This Change Was Made
A turn that reaches its runtime refreshes the main-session recovery allowance, which is intentional so planned restarts keep long work alive. The same refresh means a turn that crashes the Gateway after it starts is never exhausted, and the crash-loop breaker only suppressed channel auto-start, so replay continued.
This follows the recommendation in ClawSweeper's review on the issue ("Extend crash-loop containment: use the existing boot-lifecycle breaker to pause automatic session replay and provide explicit operator recovery without deleting transcripts"), which the reporter also endorsed there. A boot that starts with the breaker tripped still runs startup orphan marking but skips automatic dispatch and logs a warning that says how to resume. Explicit resume reuses the existing path: a new message in an interrupted session already resumes its turn through reply admission. The documented safe-mode contract in
docs/gateway/restart-recovery.mdanddocs/gateway/index.mdnow lists this.Deliberately left out: the allowance refresh on started turns and the three-attempt budget are unchanged, so healthy planned restarts behave as before; no new config, state field, or tombstone rule is added; the underlying native abort from the report is not addressed here. The startup scheduling call moved from
server-startup-post-attach.tsinto a small sibling module so that file does not grow past its line-cap ratchet.Trade-off for maintainers to decide: if a breaker-tripped Gateway stays up for the whole breaker window, the breaker restores channel auto-start in that same process, but this PR does not resume the paused sessions there. Those interrupted turns stay unfinished until someone sends a new message in the session or the Gateway starts again after the window; nothing replays them on its own in the meantime. The alternative, replaying them automatically when channels come back, would re-run the turn that just crashed the Gateway inside the process that has only just proven stable, and would restart the loop. This PR chooses containment over automatic completion. If same-process replay after recovery is preferred, it could hang off the breaker's existing in-process recovery point; this PR does not change that behavior.
Evidence
Tested at
ef7c6c66419(baseupstream/main988be486074); the later head8b378a98eb6only fixes a docs paragraph break.Linux x64, Node 24, built CLI, an isolated Gateway profile and state directory on loopback, and a keyless OpenAI-compatible mock model on loopback that streams slowly. A
chat.sendtoagent:main:mainstarts a longexecturn and the Gateway is SIGKILLed mid-turn. Each following boot is SIGKILLed as soon as the recovered turn sends its model request (a stand-in for the reported process abort during the replayed turn); a boot that sends no model request within 25 s is left running. Session state is read read-only from the agent database.Before (base
988be486074), boot 3 with the breaker tripped; boots 4 to 6 are identical withchargedAttempts/startedAttemptclimbing to 6/6:After (this PR), same steps:
Observed result: on the base every boot replays the turn, including every breaker-tripped boot, and the allowance never drains. With this change boots 1 and 2 still replay, boot 3 trips the breaker and only marks the session (
abortedLastRun=true), the Gateway keeps running, and a new message in the session resumes it and the session settles (status=done).Upgrade from the published release with existing interrupted state
Published driver
[email protected](currentlatest) installed with npm into an isolated global prefix, with its ownHOME,OPENCLAW_PROFILE, loopback ports, and the same mock model. The published build seeds the interrupted turn and crash-loops on its replay until the breaker trips. Then the published updater installs the candidate package (this branch atef7c6c66419, packed withscripts/package-openclaw-for-docker.mjs) in place withopenclaw update --tag <candidate.tgz> --yes --json --no-restart, and the candidate Gateway starts on the same state (service management is skipped for an isolated profile, so the restart is manual). Session and boot-lifecycle rows are read read-only.Observed result: the candidate reads the breaker history and the recovery marks the published build wrote. The unclean boots recorded by 2026.9.6 trip the breaker on the first candidate boot, so it pauses instead of replaying the crashing turn a fourth time. The update and the paused boot keep every transcript event, including the original seeded message, and do not change the recovery counters. A new message then resumes the session and it settles; the transcript only grows. The published build, on the other hand, replays on its breaker-tripped boot 3.
Not covered: the reported macOS descriptor abort itself (SIGKILL stands in for it), a launchd- or systemd-supervised restart loop and an updater-driven service restart (the upgrade cell restarts manually), and a channel-delivered resume message (the resume was sent with
chat.send; channels are suppressed while the breaker is tripped).CI failures on the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269) are unrelated to this change; each is a timeout or flake in code this PR does not touch:
checks-ui-e2e (4/9):ui/src/e2e/session-progress-widget.e2e.test.ts"keeps target liveness when the selected agent scope changes" fails the same way on many other PRs the same day, for example https://github.com/openclaw/openclaw/actions/runs/36420533414/job/108922762236 and https://github.com/openclaw/openclaw/actions/runs/36423194499/job/108931618992. This PR has no UI changes.checks-node-changed-4:test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts(Slack preview, 120 s timeout) also fails on https://github.com/openclaw/openclaw/actions/runs/36425002059/job/108937584825 and https://github.com/openclaw/openclaw/actions/runs/36421420600/job/108926216611.checks-node-changed-compact-large-15:src/gateway/server-close.model-acquisition.test.tsalso fails on https://github.com/openclaw/openclaw/actions/runs/36421405475/job/108926318536; it passes locally on this branch.checks-node-changed-compact-large-2:test/plugins/codex-model-catalog.gateway.test.tstimed out at 120 s; it passes locally on this branch.checks-node-changed-compact-large-24:src/gateway/server.agent-late-admission.test.tsfailed with a shared-state worker admission error during secret startup; it passes locally on this branch. Neither test enables the crash-loop breaker, so the changed dispatch path does not run.checks-node-changed-1:src/agents/subagents/registry/subagent-registry.requester-wake.e2e.test.tsfailed on a worker task timeout during subagent cleanup; that suite does not start the Gateway startup path this PR changes.openclaw/ci-gate: aggregate of the above.CI failures on the second run (https://github.com/openclaw/openclaw/actions/runs/36433302448, head
8b378a98eb6) are also unrelated. That head differs fromef7c6c66419only indocs/gateway/restart-recovery.md, and every test below passed on the first run with the same code. None of these tests trips the crash-loop breaker, so the new pause branch (pauseAutomaticDispatch) never runs in them; with the breaker untripped, the moved scheduling call passes the same arguments as before.checks-node-changed-compact-large-8: insrc/auto-reply/reply/reply-turn-admission.recovery.test.tsthe first case ("keeps deferred owner release retries from retaining a successor", which installs fake timers) hit the 120 s timeout. After it, seven of the other cases timed out too, and two (settles or defers visible input according to recovery failure: false/true) reportedretryRestartAbortedMainSessionRecoverycalled twice. That fits leftover work from the abandoned case still running into the next cases' spies. The PR does not changeretryRestartAbortedMainSessionRecoveryor reply admission. The file passed 11/11 in the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269/job/108920382957). Locally on this branch it passes 11/11 on its own, and also when replaying the failing shard's 19 files in CI order with one worker (202/202). The same job also timed outsrc/gateway/server.encrypted-tool-continuation.test.tsat 90 s; that test passed in the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269/job/108920382609) and passes locally.checks-node-changed-compact-large-21:src/gateway/server-methods/models-dispatch.lifecycle.integration.test.tsgot anagent.waitclient timeout (35 s) and then saw the stalebefore-replacementrun. It passed in the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269/job/108920382832) and passes locally.checks-node-changed-compact-large-24:src/gateway/server.chat.gateway-server-chat.test.ts("chat.send accepts the backing session id returned by chat.history", statustimeout) andsrc/gateway/server.sessions.store-paths.projection.test.ts(an unexpected state-directory probe) failed in the same shard. Both passed in the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269/job/108920382608), and both pass locally.checks-node-changed-extensions-bundle-9:extensions/whatsapp/src/monitor-inbox.reply-context.test.ts"prepopulates image previews for inbound sendMedia replies" (mock called 0 times) is in a WhatsApp plugin this PR does not touch. It passed in the first run (https://github.com/openclaw/openclaw/actions/runs/36419819269/job/108920382352) and passes locally.openclaw/ci-gate: aggregate of the above.Full before/after output and focused tests
Before:
After:
Focused tests:
src/agents/main-session-recovery/main-session-restart-recovery-admission.test.ts: new case "marks but does not replay interrupted sessions while the crash-loop breaker is tripped" (8/8 pass). It fails on the base (callGatewayis called once by automatic replay). Cost:pnpm test src/agents/main-session-recovery/main-session-restart-recovery-admission.test.ts --maxWorkers=1wall 53.3 s for the whole file; the new case takes about 1.5 to 1.9 s, in line with its sibling startup-recovery cases. CI (run https://github.com/openclaw/openclaw/actions/runs/36419819269, jobchecks-node-changed-compact-large-14): 18.3 s for the file's 8 cases, 1.4 s for the new case.src/gateway/server-startup-post-attach.test.ts: 115/115 pass (unchanged; covers the moved scheduling call).pnpm check:changed --base upstream/main: pass.pnpm build: pass.autoreviewskill on the branch: no findings.