Skip to content

fix(agents): add cross-boot retry budget to restart recovery - #96307

Closed
zhangqueping wants to merge 1 commit into
openclaw:mainfrom
zhangqueping:fix/issue-95750-recovery-retry-budget
Closed

zhangqueping wants to merge 1 commit into
openclaw:mainfrom
zhangqueping:fix/issue-95750-recovery-retry-budget

Conversation

@zhangqueping

@zhangqueping zhangqueping commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Problem: When a main-session turn wedges, flags the entry and retries it on every boot. There's no persistent retry counter or quarantine—a wedged session death-loops the gateway across restarts until systemd exhausts StartLimitBurst. See #95750 for the full production incident report (6 cycles before operator intervention).

Solution: Add abortedLastRunAttempts (persistent counter) with a > MAX_RECOVERY_RETRIES ceiling. When exceeded, quarantine the session instead of resuming it. On successful resume, reset the counter and clear quarantine. The quarantine check runs AFTER all existing skip/routing/owner/dedupe guards to avoid suppressing owning recovery paths in configured or duplicate stores.

What changed (4 files, +140/−22):

  • src/config/sessions/types.ts: +10 — abortedLastRunAttempts, quarantinedAt, quarantineReason
  • src/plugins/session-entry-slot-keys.ts: +3 — register new fields in compile guard
  • src/agents/main-session-restart-recovery.ts: +61/−7 — increment at 4 mark sites, quarantine AFTER guards with > MAX_RECOVERY_RETRIES, reset on success
  • src/agents/main-session-restart-recovery.test.ts: +88/−15 — quarantine + counter increment + successful-resume reset tests

What did NOT change: In-process retry orchestration, subagent-orphan-recovery (already bounded with SUBAGENT_RECOVERY_MAX_AUTOMATIC_ATTEMPTS), channel dispatch, model routing, auth.

Fixes #95750. Supersedes #86239.

Behavioral contract

Condition Before After
1st restart Re-marked, resumed attempts=1, resumed
2nd restart Re-marked, resumed attempts=2, resumed
3rd restart Re-marked, resumed attempts=3, resumed (last valid retry)
4th restart Re-marked, resumed (loop!) Quarantined: abortedLastRun=false, quarantinedAt set, WARN logged
Successful auto-resume abortedLastRun=false + attempts=0, quarantine cleared
Existing sessions (no field) resumed attempts starts at 0, backward-compatible

MAX_RECOVERY_RETRIES = 3 is reused from the existing in-process budget. The gate is > MAX_RECOVERY_RETRIES, so the 3rd restart is the last valid retry (attempts=3), and the 4th triggers quarantine (attempts=4).

Real behavior proof

Runtime: Node 24.13, Linux x86_64 — Branch: fix/issue-95750-recovery-retry-budget @ 242d856dc7 — Vitest: 4.1.8

Proof A — Real sessions.json state transitions

Script exercises the exact recovery functions against a temp directory (full source at proof-recovery-budget.ts on the branch):

=== Phase 1: Quarantine (4th restart, attempts=4 > MAX=3) ===

-- Before --
{ "status": "running", "abortedLastRun": true, "abortedLastRunAttempts": 4 }

recoverRestartAbortedMainSessions result: {"recovered":0,"failed":0,"skipped":0,"quarantined":1}

[main-session-restart-recovery] quarantined agent:main:telegram:dm after 4
  aborted-restart attempts (>= 3); the session will not be auto-resumed

-- After --
{ "status": "running", "abortedLastRun": false, "abortedLastRunAttempts": 4,
  "quarantinedAt": 1782288650123, "quarantineReason": "exceeded_restart_retry_budget" }

=== Phase 2: Counter increment (3→4, crosses ceiling) ===

-- Before --
{ "status": "running", "abortedLastRun": false, "abortedLastRunAttempts": 3 }

markRestartAbortedMainSessions → "marked 1 interrupted main session(s)"

-- After --
{ "status": "running", "abortedLastRun": true, "abortedLastRunAttempts": 4 }

=== Phase 3: Backward-compatible defaults ===

-- Before (no abortedLastRunAttempts field) --
{ "status": "running", "abortedLastRun": false }

-- After mark (undefined → 1 via ?? 0) --
{ "status": "running", "abortedLastRun": true, "abortedLastRunAttempts": 1 }

Proof B — Full test suite (36/36 passed)

$ node scripts/run-vitest.mjs run src/agents/main-session-restart-recovery.test.ts --reporter=verbose
[test] starting test/vitest/vitest.agents.config.ts
 RUN  v4.1.8
 ✓ marks only matching running main sessions by active session key
 … (33 existing tests pass unchanged)
 ✓ quarantines sessions that exceed the cross-boot retry budget (regression #95750)
 ✓ increments abortedLastRunAttempts at each mark phase (regression #95750)
 Test Files  1 passed (1)
      Tests  36 passed (36)
[test] passed 1 Vitest shard in 19.25s

Proof C — Custom-store recovery resets counter on success

$ node scripts/run-vitest.mjs run src/agents/main-session-restart-recovery.test.ts   -t "marks active sessions in a configured custom session store" --reporter=verbose

 ✓ marks active sessions in a configured custom session store
   └─ asserts: abortedLastRunAttempts === 0, quarantinedAt === undefined

Observed result: The fourth restart quarantines instead of resuming. The counter correctly increments through all four mark sites. Successful auto-resume clears the counter and quarantine. Existing sessions without the field start at 0.

What was not tested: Live gateway restart with systemd supervision (not reproducible here). Proof covers every lifecycle boundary via real filesystem operations and 36 dedicated tests.

Risk checklist

Highest-risk area: Counter increment at mark sites and quarantine gate ordering.

Risk level: Medium — 3 new persistent SessionEntry fields. Existing entries default safely. Quarantine check runs AFTER guards. Operator intervention for quarantined sessions is better than a death-loop.

Mitigation: All 4 mark sites instrumented. Reset on success. 36 tests cover all boundaries. session-entry-slot-keys.ts compile guard prevents drift.

Merge risk:

  • session-state — 3 new SessionEntry fields, backward-compatible defaults (counter=0)
  • availability — quarantine skips auto-recovery, intentional (death-loop is worse)
  • compatibility — existing sessions without the field default to 0, upgrade-safe

All ClawSweeper P1 findings resolved

  1. ✅ Move quarantine after guards — check now runs after skip/routing/owner/dedupe guards
  2. ✅ Honor retry budget boundary — changed >= MAX_RECOVERY_RETRIES to > MAX_RECOVERY_RETRIES; 3rd restart is last valid retry, 4th triggers quarantine
  3. ✅ Reset on progress — successful resumeMainSession clears abortedLastRunAttempts, quarantinedAt, quarantineReason

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes agents Agent runtime and tooling size: S labels Jun 24, 2026
@zhangqueping
zhangqueping force-pushed the fix/issue-95750-recovery-retry-budget branch from ea0f7c4 to 6a713e5 Compare June 24, 2026 06:12
@openclaw-barnacle openclaw-barnacle Bot removed docs Improvements or additions to documentation cli CLI command changes labels Jun 24, 2026
@zhangqueping
zhangqueping force-pushed the fix/issue-95750-recovery-retry-budget branch 2 times, most recently from e125e47 to 39d24fb Compare June 24, 2026 06:35
@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close: this PR targets the same restart-recovery retry-budget bug as #96230, but this branch is now conflicting and stale against current main while the sibling PR is open, clean, proof-positive, and covers the current lifecycle cleanup path.

Canonical path: Route maintainer review to the single clean canonical candidate, #96230, and avoid landing competing retry/quarantine field variants for the same session-state contract.

So I’m closing this here and keeping the remaining discussion on #96230.

Review details

Best possible solution:

Route maintainer review to the single clean canonical candidate, #96230, and avoid landing competing retry/quarantine field variants for the same session-state contract.

Do we have a high-confidence way to reproduce the issue?

Yes. At source level, current main recovers running abortedLastRun main-session rows without a persisted attempt ceiling, matching the production incident in #95750; I did not run the full Telegram/systemd loop.

Is this the best way to solve the issue?

No. The durable budget is the right solution shape, but this PR is stale against current main and is superseded by a cleaner proof-positive PR for the same root cause.

Security review:

Security review cleared: The diff changes session recovery, reply session-state cleanup, tests, and type/slot metadata only; I found no concrete security or supply-chain concern.

AGENTS.md: found and applied where relevant.

What I checked:

  • Root and scoped policy read: Root AGENTS.md plus the touched src/agents and src/plugins scoped guides were read and applied to the agents/session and plugin-slot review. (AGENTS.md:1, 56d95b18f4bc)
  • Current-main recovery gap: Current main still selects running abortedLastRun main-session rows for recovery without a persisted attempt ceiling, so the central bug remains real but needs one canonical fix. (src/agents/main-session-restart-recovery.ts:751, 56d95b18f4bc)
  • Current-main user-progress path: Current main calls applySessionHints with sessionEntryHandle; this is the active hint-clearing path a current-main-compatible fix must update. (src/auto-reply/reply/get-reply-run.ts:772, 56d95b18f4bc)
  • This PR is stale/conflicting: Live GitHub reports this PR head as CONFLICTING/DIRTY, and the PR head's applySessionHints file is based before current main's sessionEntryHandle branch. (src/auto-reply/reply/body.ts:31, 5c226e3ae997)
  • Canonical replacement PR: fix(session): stop repeated restart recovery after retry budget #96230 is open, clean, proof-positive, and its diff covers the same durable retry-budget/quarantine family plus current-main cleanup and stale-cache regression coverage. (83e151227f4b)
  • Feature history: GitHub commit history for the central restart-recovery file shows recent work by jalehman, ooiuuii, joshavant, and related session-store contributors. (src/agents/main-session-restart-recovery.ts:1)

Likely related people:

  • jalehman: Recent commits on the central file added restart-recovery lifecycle and transcript-reader seams used by this recovery path. (role: recent recovery seam contributor; confidence: high; commits: d216f7c876dd, fd8e3bf65201, 8ded75628437; files: src/agents/main-session-restart-recovery.ts, src/auto-reply/reply/body.ts)
  • ooiuuii: Authored recent gateway/main-session restart marker work that writes the abortedLastRun state this PR attempts to budget. (role: restart marker contributor; confidence: high; commits: d20fdf3b3842; files: src/agents/main-session-restart-recovery.ts, src/gateway/session-lifecycle-state.ts, src/config/sessions/types.ts)
  • joshavant: Authored the recent main-session startup recovery change in the central affected file history. (role: main-session recovery contributor; confidence: high; commits: e1978cf73cbd; files: src/agents/main-session-restart-recovery.ts)
  • openperf: Authored a recent session-lifecycle persistence fix on the cleanup-adjacent gateway lifecycle path. (role: adjacent session lifecycle contributor; confidence: medium; commits: 613f51a7aa91; files: src/gateway/session-lifecycle-state.ts)

Codex review notes: model internal, reasoning high; reviewed against 56d95b18f4bc.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jun 24, 2026
@zhangqueping
zhangqueping force-pushed the fix/issue-95750-recovery-retry-budget branch from 39d24fb to 70a41e4 Compare June 24, 2026 07:36
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jun 24, 2026
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Jun 24, 2026
@zhangqueping
zhangqueping force-pushed the fix/issue-95750-recovery-retry-budget branch from 70a41e4 to 242d856 Compare June 24, 2026 08:24
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 24, 2026
When a channel main-session turn wedges and the gateway is restarted
(via SIGUSR1 or systemd), the recovery pass unconditionally re-retries
every restart-aborted session on every boot. There is no per-session
retry counter or quarantine, so a repeatedly-wedged session death-loops
the gateway until systemd exhausts StartLimitBurst.

Add abortedLastRunAttempts (persistent counter) and quarantinedAt /
quarantineReason fields to SessionEntry.

- Every mark site that sets abortedLastRun=true now also increments
  abortedLastRunAttempts (4 sites: markRestartAbortedMainSessions,
  markStartupOrphanedMainSessionsForRecovery,
  markPendingFinalDeliveryAsAborted,
  markRestartAbortedMainSessionsFromLocks)

- The resume gate in recoverStore checks (abortedLastRunAttempts >=
  MAX_RECOVERY_RETRIES) and quarantines overrun entries by clearing
  abortedLastRun, setting quarantinedAt + quarantineReason, and
  emitting a WARN log line. Quarantined sessions skip auto-recovery.

- clearQuarantine resets the counter when a new inbound turn clears
  the quarantine (prepared for future use in session-accessor paths).

MAX_RECOVERY_RETRIES (3) is reused as the cross-boot ceiling — the
same value that bounds in-process retries.

Fixes openclaw#95750
@zhangqueping
zhangqueping force-pushed the fix/issue-95750-recovery-retry-budget branch from 242d856 to 5c226e3 Compare June 25, 2026 05:50
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jun 25, 2026
@clawsweeper

clawsweeper Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Main-session restart-recovery has no cross-boot retry budget — wedged sessions death-loop the gateway across reboots (2026.6.9)

1 participant