Skip to content

fix(agents): pass admitted sessionEntry to clearCliSessionInStore during CLI recovery - #208637

Open
zsicheng0214 wants to merge 1 commit into
openclaw:mainfrom
zsicheng0214:fix/cli-session-recovery-stale-expected-208264
Open

zsicheng0214 wants to merge 1 commit into
openclaw:mainfrom
zsicheng0214:fix/cli-session-recovery-stale-expected-208264

Conversation

@zsicheng0214

@zsicheng0214 zsicheng0214 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #208264

What Problem This Solves

When a CLI backend reports session_expired and triggers fresh-session recovery (onBeforeFreshCliSessionRetry), clearCliBinding in src/agents/command/attempt-execution.ts called clearCliSessionInStore without passing activeSessionEntry: params.sessionEntry. As a result, clearCliSessionInStore fell back to params.sessionStore[sessionKey] — the stale entry cached before turn admission, which still held an older activeWriterRunId. patchCliSessionBindingInStore then rejected the patch because sameCliSessionWriter requires sessionId, lifecycleRevision, and activeWriterRunId to match the admitted store row, causing fresh-session retry to be skipped permanently until /reset.

User Impact

CLI backends using freshSessionRecovery: "invalidated-only" now clear their invalidated native CLI session binding and execute the fresh-session retry when the durable store holds the current admitted writer, while still refusing to clear if a concurrent replacement writer or /reset supersedes the session after admission. No configuration changes or migrations are required.

Why This Change Was Made

In src/agents/command/attempt-execution.ts:

  • withAdmittedCliCandidate already reads the latest admitted session row (turn.sessionEntry, assigned to params.sessionEntry), which carries the current admitted activeWriterRunId and lifecycleRevision (and receives writer updates during history preparation).
  • Passing activeSessionEntry: params.sessionEntry to clearCliSessionInStore inside clearCliBinding matches the sibling auto-reply candidate (src/auto-reply/reply/agent-runner-cli-candidate.ts) and persistStoppedFirstSession / settleResult in the same file, avoids an extra database read, and preserves all three sameCliSessionWriter guards (sessionId, lifecycleRevision, activeWriterRunId) as well as expectedCliSessionId.

Evidence

1. Live Isolated Gateway End-to-End Proof (Reviewed Head 61c1054e9, Node v24.22.3, Real Spawned CLI Subprocess — No runCliAgent Mock)

Started an isolated OpenClaw Gateway (startGatewayWithClient) configured with a real spawned local CLI backend (freshSessionRecovery: "invalidated-only", reseedFromRawTranscriptWhenUncompacted: true, sessionMode: "existing") and sent 3 sequential WebSocket agent RPC turns on agent:main:main:

  • Turn 1: "Remember the secret code: ALPHA-7." -> spawns fresh native session native-sess-1.
  • Expire native session: removes native-sess-1 from the backend's active session store so --resume native-sess-1 fails with session_expired.
  • Turn 2: "What was the secret code?" -> attempt 1 fails with session_expired; Gateway clears the expired binding using the admitted session entry, retries once on fresh native-sess-2 with saved history (ALPHA-7), and returns the recovered answer.
  • Turn 3: "Confirm resumed session." -> resumes native-sess-2 directly on the first attempt without retrying.

Redacted Gateway logs (OPENCLAW_LOG_LEVEL=warn)

[diagnostic] lane task error: lane=cli:custom-cli durationMs=71 error="Error: No conversation found with session ID: native-sess-1 (session_expired)" errorName=FailoverError
[agents/agent-command] CLI session failed, clearing before fresh retry: provider=custom-cli sessionKey=agent:main:main reason=session_expired
[agent/cli-backend] cli session recovery retry: provider=custom-cli reason=session_expired sessionKey=agent:main:main

Turn payloads & CLI subprocess invocation trace

{
  "turn1Payloads": [
    { "text": "Recovered with saved history (ALPHA-7) on native-sess-1.", "mediaUrl": null }
  ],
  "turn2Payloads": [
    { "text": "Recovered with saved history (ALPHA-7) on native-sess-2.", "mediaUrl": null }
  ],
  "turn3Payloads": [
    { "text": "Resumed native-sess-2 ok.", "mediaUrl": null }
  ],
  "cliInvocations": [
    { "resumeId": null, "promptHasAlpha7": true, "outcome": "fresh", "sessionId": "native-sess-1", "hasHistory": true },
    { "resumeId": "native-sess-1", "promptHasAlpha7": false, "outcome": "session_expired" },
    { "resumeId": null, "promptHasAlpha7": true, "outcome": "fresh", "sessionId": "native-sess-2", "hasHistory": true },
    { "resumeId": "native-sess-2", "promptHasAlpha7": false, "outcome": "resumed", "sessionId": "native-sess-2" }
  ]
}
 ✓  gateway-core  proves isolated Gateway fresh-session recovery and next-turn resume with a real spawned CLI backend 82971ms
 Test Files  1 passed (1)
      Tests  1 passed (1)

2. Base-Red / Head-Green Unit & SQLite Session Store Verification (61c1054e9)

  1. Base (origin/main) fails the new stale-cached-writer regression test:

    $ ./node_modules/.bin/vitest run --pool=forks src/agents/command/attempt-execution.cli.test.ts -t 'activeWriterRunId'
    × CLI attempt execution > clears the CLI binding before fresh-session retry when cached sessionStore has an older activeWriterRunId than the admitted session
      AssertionError: expected false to be true
    ✓ CLI attempt execution > refuses to clear the CLI binding before fresh-session retry when a newer writer replaces activeWriterRunId after admission
    Test Files  1 failed (1)
         Tests  1 failed | 1 passed | 87 skipped (89)
    
  2. Fix (61c1054e9) passes all 89 tests in src/agents/command/attempt-execution.cli.test.ts:

    $ ./node_modules/.bin/vitest run --pool=forks src/agents/command/attempt-execution.cli.test.ts
    Test Files  1 passed (1)
         Tests  89 passed (89)
    
  3. Lint & format:

    • oxlint src/agents/command/attempt-execution.ts src/agents/command/attempt-execution.cli.test.ts — Found 0 warnings and 0 errors. (kept attempt-execution.ts within the 700-line limit).
    • oxfmt --check src/agents/command/attempt-execution.ts src/agents/command/attempt-execution.cli.test.ts — All matched files use the correct format.

@clawsweeper

clawsweeper Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Pull request received.

ClawSweeper review complete

ClawSweeper finished reviewing this revision.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Nov 29, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 29, 2026
@clawsweeper

clawsweeper Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR passes the admitted session entry to the existing guarded CLI binding clear before fresh-session recovery.

Example: native-sess-1 expires while the cached writer differs from the admitted writer.

  • Before: The binding clear fails, so subsequent messages keep failing with session_expired.
  • After: Recovery clears the expired binding, retries with saved ALPHA-7 history on native-sess-2, and the next turn resumes native-sess-2.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with production-boundary recovery evidence and distinct regression coverage; required product CI remains incomplete.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The new reviewed-head logs and subprocess trace exercise Gateway agent RPC through the production CLI runner and binding-store owner, showing injected expiration, one history-seeded retry, and next-turn resume; this resolves the earlier proof request. Existing cliSessionBindings, cliSessionIds, and claudeCliSessionId formats and their persistence owner remain unchanged, establishing a no-migration case.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A chat repeatedly fails after its CLI backend loses the native session because the intended fresh-session recovery cannot clear the expired binding.
Reason: The patch restores existing recovery behavior with one additional argument and no new product contract.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a concrete recovery failure still present on current main, with no introduced correctness defect found.

Reviewed head: 61c1054e973943f43f256dfe81d2f4815aa036ea

Before merge

None.

Findings

None.

Agent review details

How this fits together

The command agent adapter connects admitted turns to CLI backends; the session-store owner guards binding updates, and the CLI runner performs eligible fresh retries.

flowchart TD
  A[Gateway agent request] --> B[Admitted CLI candidate]
  B --> C[CLI subprocess]
  C --> D[Expired session recovery]
  D --> E[Guarded binding clear]
  E --> F[Fresh history seeded attempt]
  F --> G[Persist replacement binding]
Loading

Technical review

Best possible solution:

Use the admitted working entry for the existing guarded clear while preserving writer, lifecycle, native-binding, and media-replay checks.

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

Current-main source establishes the stale-writer mismatch and suppressed retry; the contributor supplies a failing baseline regression, but this read-only review executed no target code.

Is this the best way to solve the issue?

Passing the already-admitted mutable entry fixes the incorrect expected-writer input through the existing owner without another database read or weaker write guards.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d31aefeac1a1.

Provenance checked

  • Runner-owned fresh-session recovery keeps the original intent (e8c7c93: Move bounded stale-session recovery inside the CLI runner so hooks observe the final outcome and the stale stored binding is cleared before retry.)
  • Admitted candidate and guarded binding ownership keeps the original intent (b543922: Share placement-scoped binding acquisition and settlement while preserving lifecycle, writer, fork, and exceptional-cleanup contracts.)
  • Binding-clear wrapper keeps the original intent (e1dbb59: Consolidate repeated runtime preparation and cleanup without changing user-visible behavior or persisted shapes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b543922 adds src/agents/command/attempt-execution.ts:513 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b543922ae225; files: src/agents/command/attempt-execution.ts)
  • brokemac79: Raw commit e8c7c93 adds src/agents/command/attempt-execution.ts:594 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: e8c7c933f8c1; files: src/agents/command/attempt-execution.ts)
  • RoboClaw: Raw commit 7cb8975 adds src/agents/command/attempt-execution.ts:417 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 7cb897599c9d; files: src/agents/command/attempt-execution.ts)

PR surface

Source 0, Tests +66. Total +66 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 11 11 0
Tests 1 66 0 +66
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 77 11 +66

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #208264
Summary: This PR and the competing open repair address the canonical report's stale cached writer during CLI recovery.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the repository's required product CI for the reviewed head.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall readiness starts with the lower of the proof and patch scores. It is capped at 3/6 if the fix is partial, the change offers little benefit, a product decision is still open, or the PR reverses an earlier decision without saying why. ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-29T23:37:31.048Z sha 61c1054 :: needs real behavior proof before merge. :: none

Reviewed November 29, 2026, 7:09 PM ET / November 30, 2026, 00:09 UTC (Revision 2).

@zsicheng0214

Copy link
Copy Markdown
Contributor Author

Added redacted isolated Gateway end-to-end logs and 3-turn CLI subprocess invocation trace on 61c1054e9 (no runCliAgent mock), demonstrating:

  1. Turn 1 binds native-sess-1 (ALPHA-7),
  2. After native-sess-1 expires, Turn 2 hits session_expired, logs CLI session failed, clearing before fresh retry -> cli session recovery retry, clears the expired binding, and retries once on native-sess-2 seeded with saved history (ALPHA-7),
  3. Turn 3 resumes native-sess-2 directly on the first attempt.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. labels Nov 30, 2026

This branch has not been deployed

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

Labels

agents Agent runtime and tooling impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CLI fresh-session retry after session_expired never runs: clearCliSessionInStore compares a stale cached session entry

1 participant