Skip to content

fix: clear expired CLI session binding using latest session entry - #208278

Open
thomsjack wants to merge 2 commits into
openclaw:mainfrom
thomsjack:fix/208264-clear-cli-session-stale-entry
Open

thomsjack wants to merge 2 commits into
openclaw:mainfrom
thomsjack:fix/208264-clear-cli-session-stale-entry

Conversation

@thomsjack

@thomsjack thomsjack commented Nov 29, 2026 •

Copy link
Copy Markdown

Closes #208264

What Problem This Solves

When a resumed CLI session fails with a recoverable session-expired error, onBeforeFreshCliSessionRetry reads the latest session entry from the store (readConsistency: "latest"), verifies that the failing retry.sessionId is still bound, and then calls clearCliBinding(retry.sessionId) without forwarding currentEntry.

clearCliSessionInStore then falls back to the stale cached params.sessionStore[params.sessionKey] entry, which can still hold an earlier activeWriterRunId from before run admission. patchCliSessionBindingInStore compares sameCliSessionWriter(entry, expected) and rejects the clear, returning undefined so onBeforeFreshCliSessionRetry returns false and skips the fresh CLI session retry.

User Impact

CLI turns whose expired native session binding should be cleared and retried fresh now recover cleanly instead of aborting when the live store entry's activeWriterRunId has advanced past the stale in-memory cache. Concurrent or unrelated writer runs remain protected and cannot have their CLI session bindings cleared.

Why This Change Was Made

  • Added canClearCliSessionEntryForFreshRetry and createBeforeFreshCliSessionRetryHandler in src/agents/command/attempt-execution.helpers.ts to validate currentEntry against expectedSessionId, lifecycleRevision, activeWriterRunId (must match params.runId or cachedEntry.activeWriterRunId when present), and retry.sessionId.
  • Updated clearCliBinding in src/agents/command/attempt-execution.ts to accept an optional activeSessionEntry and forward a mutable clone (structuredClone(currentEntry)) into clearCliSessionInStore, avoiding frozen-object mutation in clearCachedEntries while preserving the latest writer identity.
  • Added focused unit tests in src/agents/command/attempt-execution.cli-fresh-retry.test.ts (with importOriginal mock-factory spreads) and an unmocked runCliAgent child-process end-to-end recovery test in src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts.

Evidence

  • Unmocked runCliAgent multi-turn recovery proof (src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts, commit 0b229d1aea): exercises real runAgentAttempt → runCliAgent → runWithCliSessionRecovery → child CLI process + SQLite session store and transcript:
    1. Turn 0 establishes native session binding (expired-native-session) in SQLite.
    2. Turn 1 receives stale cached entry (activeWriterRunId: "prior-run"), advances SQLite activeWriterRunId to "current-admitted-run" on execution start, spawns --resume expired-native-session -> fails (session expired), triggers onBeforeFreshCliSessionRetry -> clears stale binding -> retries fresh (resumeId: null) with <conversation_history> (hasPriorTurn: true) -> recovers "recovered after fresh retry" and persists "fresh-native-session" in SQLite.
    3. Turn 2 spawns --resume fresh-native-session and completes with "resumed:fresh-native-session" (4 real CLI subprocess invocations verified).
  • Focused checks after latest commit (0b229d1aea):
    • node --import tsx scripts/check-test-mock-exports.mts --base upstream/main -> Mock factory ratchet OK: 6074 grandfathered factories.
    • pnpm exec oxfmt --check src/agents/command/attempt-execution.cli-fresh-retry.test.ts src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts -> clean.
    • pnpm exec oxlint src/agents/command/attempt-execution.ts src/agents/command/attempt-execution.helpers.ts src/agents/command/attempt-execution.cli-fresh-retry.test.ts src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts -> 0 warnings, 0 errors.
    • pnpm vitest run src/agents/command/attempt-execution.cli-fresh-retry.test.ts src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts -> Test Files 2 passed (2), Tests 4 passed (4) (79.74s).
  • Previously verified on 85ced7dc8d (source unchanged in 0b229d1aea):
    • pnpm tsgo:core -> exit 0.
    • pnpm vitest run src/agents/cli-session-store.test.ts src/agents/command/attempt-execution.cli.test.ts -t "fresh|clear|binding|retry" --maxWorkers=2 -> 2 test files passed, 31 passed.

@clawsweeper

clawsweeper Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Nov 29, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment 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. clawsweeper:intake:needs-environment 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: needs real behavior proof before merge.

What this changes

This PR passes the latest session entry into the guarded binding clear so an expired CLI session can retry fresh despite an older cached writer ID.

Example: The cache names writer prior-run, the stored row names current-admitted-run, and expired-native-session returns session_expired.

  • Before: The writer comparison rejects the clear, suppressing fresh-session recovery.
  • After: The clear uses the latest matching row, allowing recovery to replace the expired native binding.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The source-supported repair has distinct regression coverage and no established blocking code defect, but required runtime and existing-state upgrade proof are absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
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 can repeatedly fail after its backend loses the native session because stale cached writer metadata prevents the intended fresh-session retry.
Reason: The change restores documented recovery through existing owners and introduces no new setting, public API, or default.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this PR addresses a concrete recovery failure still present on current main; no introduced correctness defect was established.

Reviewed head: 85ced7dc8d9a1dcacd841279dd45f78196255148

Before merge

  • Add real behavior proof - The body and comments supply test/check claims, but the new regression mocks runCliAgent and manually calls its preparation callback, so it cannot establish actual fresh retry or subsequent resume; provide terminal output or logs from the changed Gateway path and redact IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted isolated-Gateway evidence of session_expired with differing cached and current writer IDs, one history-seeded fresh retry, and next-turn resume, including an upgrade from latest stable with existing settings and session data intact; the claimed base-red/head-green regression also lacks an attached run artifact.
Agent review details

How this fits together

The command agent adapter connects admitted turns to CLI backends; recovery reads session state, clears invalid native continuity through the session-store owner, and lets the runner retry with saved history.

flowchart TD
  A[Admitted command turn] --> B[CLI runner]
  B --> C[Expired session recovery]
  C --> D[Latest session entry]
  D --> E[Guarded binding clear]
  E --> F[Fresh CLI attempt]
  F --> G[Persist replacement binding]
Loading

Technical review

Best possible solution:

Use the latest matching session entry for the existing guarded clear while preserving lifecycle, writer, native-binding, and media-replay protections.

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

Current source establishes the failure when the persisted writer advances beyond the cache: the clear returns no committed entry and recovery declines the retry; this read-only review ran no target code.

Is this the best way to solve the issue?

Forwarding the already-read latest entry repairs the incorrect expected-session input without another database read or weakening the store's compare-and-swap checks.

AGENTS.md: found and applied where relevant.

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

Provenance checked

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:495 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)
  • Vito Cappello: Raw commit 5ae8a4f adds src/agents/command/attempt-execution.ts:866 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5ae8a4f4f98c; 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)

PR surface

Source +78, Tests +230. Total +308 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 109 31 +78
Tests 1 230 0 +230
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 339 31 +308

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 directly attempts the stale cached writer repair described by the open canonical issue.

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: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Capture the Gateway recovery and latest-stable upgrade scenario described in missingE2e.
  • Establish completed 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 follows the weaker of proof and patch quality; ✨ 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.

Reviewed November 29, 2026, 7:10 AM ET / 12:10 UTC.

@thomsjack

Copy link
Copy Markdown
Author

Added an unmocked multi-turn runCliAgent subprocess recovery E2E test (src/agents/command/attempt-execution.cli-fresh-retry.real.test.ts) and fixed importOriginal spreads in attempt-execution.cli-fresh-retry.test.ts in commit 0b229d1aea.\n\n@clawsweeper re-review

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:auth-provider Auth, provider routing, model choice, or SecretRef resolution may break. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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