Skip to content

fix(agents): persist terminal session state after force-clearing stuck embedded runs - #112166

Merged
obviyus merged 5 commits into
openclaw:mainfrom
xialonglee:fix/gap-forceclear-session-terminal-state
Jul 27, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
xialonglee:fix/gap-forceclear-session-terminal-state

Conversation

@xialonglee

@xialonglee xialonglee commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Related to #108331: this PR fixes the missing terminal-state persistence after a forceClear, but does not close #108331.

What Problem This Solves

Fixes an issue where a stuck embedded-agent run that was force-cleared by heartbeat recovery (or cron timeout cleanup) left the persisted session entry in a non-terminal state. The next incoming message could not use the existing fast-recovery path in dispatch-from-config.lifecycle.ts, so a subsequent provider stall would again wait for the full heartbeat timeout instead of being reclaimed immediately. It also caused openclaw sessions to show stale or unknown token/runtime state for the affected session.

Why This Change Was Made

The force-clear path (forceClearEmbeddedAgentRun) only cleaned up in-memory registries (ACTIVE_EMBEDDED_RUNS, reply-run registry) and never wrote a terminal snapshot to the SQLite session entry. Normal run termination emits a lifecycle event that persists status, abortedLastRun, startedAt, endedAt, runtimeMs, etc.; force-clear skipped this entirely.

This change centralizes the terminal-state persistence inside abortAndDrainEmbeddedAgentRun: after a successful force-clear, it patches the session entry to status: "killed", abortedLastRun: true, and the corresponding ended/runtime timestamps. Both existing callers—heartbeat stuck-session recovery and cron timeout cleanup—benefit automatically.

The persistence helper guards against overwriting a newer session entry that has claimed the same session key: the sessionId check runs inside the updateSessionEntry callback, which executes under the store's serialized write lock, so the compare-and-write is atomic—a replacement session cannot interleave.

User Impact

  • Sessions that were force-cleared after a provider stall now appear as terminal (killed) in openclaw sessions and other session listings.
  • The next message into such a session can use the existing fast-recovery admission path, so a second provider stall is reclaimed promptly instead of waiting another heartbeat cycle.
  • No user-visible behavior change for successfully completing runs.

Evidence

  • New regression test: src/agents/embedded-agent-runner/runs.force-clear-terminal.test.ts
    • Verifies force-clear persists status: "killed", abortedLastRun: true, endedAt, and runtimeMs.
    • Verifies no failure when the session entry is absent.
    • Verifies no persistence when sessionKey is omitted.
    • Verifies that a replacement session entry under the same key is NOT overwritten by a stale force-clear (the atomic session-ID guard inside the serialized mutation returns null).
  • Extended existing test: src/auto-reply/reply/dispatch-from-config.stale-recovery.test.ts
    • Verifies that when the session entry is terminal/killed, a leftover active reply operation is force-cleared immediately and the new turn is dispatched without waiting for the stale-timeout threshold.

Real behavior proof

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/runs.force-clear-terminal.test.ts
 ✓ |agents| src/agents/embedded-agent-runner/runs.force-clear-terminal.test.ts (4 tests) 911ms
     ✓ persists killed status after a force-cleared run  475ms
     ✓ does not fail when the session entry is absent  29ms
     ✓ does not persist state when sessionKey is omitted  23ms
     ✓ does not overwrite a newer session entry under the same key  19ms

 Test Files  1 passed (1)
      Tests  4 passed (4)
node scripts/run-vitest.mjs src/agents/embedded-agent-runner/runs.test.ts
 ✓ |agents| src/agents/embedded-agent-runner/runs.test.ts (46 tests) 717ms
 Test Files  1 passed (1)
      Tests  46 passed (46)
node scripts/run-vitest.mjs src/auto-reply/reply/dispatch-from-config.stale-recovery.test.ts
 ✓ |auto-reply| src/auto-reply/reply/dispatch-from-config.stale-recovery.test.ts (3 tests) 35783ms
 Test Files  1 passed (1)
      Tests  3 passed (3)

Lint and format:

node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/embedded-agent-runner/runs.ts
oxfmt --check src/agents/embedded-agent-runner/runs.ts
Found 0 warnings and 0 errors.
All matched files use the correct format.

Revision log

  • rev 1 (9a86310): Added session ID guard — loadSessionEntry check before updateSessionEntry.
  • rev 2 (6efe3fa): Moved the session-ID guard inside the updateSessionEntry callback, making the compare-and-write atomic under the store's serialized write lock. Eliminates the TOCTOU race where a replacement session could interleave between the separate load and update.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Jul 21, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Jul 23, 2026
@clawsweeper

clawsweeper Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 27, 2026, 6:46 AM ET / 10:46 UTC.

ClawSweeper review

What this changes

The PR records a killed terminal snapshot when stuck embedded-agent runs are force-cleared and ensures cleanup affects only the run and reply operation that were current when recovery began.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This PR remains necessary: it addresses a concrete stale-session recovery gap and the latest branch preserves both ownership guards requested in earlier review cycles. The supplied terminal proof covers the new persistence and recovery cases, but the change writes terminal metadata into persisted session state, so it should remain with the assigned reviewer for normal merge review rather than be auto-closed or routed to an automated repair.

Priority: P1
Reviewed head: 4f3f5f80fac6035716b9d5de12f4812bde2d9029

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has focused terminal proof and directly addresses prior race findings with bounded ownership guards.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body provides after-fix terminal output from focused tests that exercise persisted terminal state, replacement-session protection, and dispatch recovery; the repository also labels the proof sufficient.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body provides after-fix terminal output from focused tests that exercise persisted terminal state, replacement-session protection, and dispatch recovery; the repository also labels the proof sufficient.
Evidence reviewed 5 items Current branch recovery change: The proposed recovery path captures the current embedded-run handle and reply operation before force-clearing, then persists terminal session metadata only for the matching session. The branch also replaces session-ID-only reply cleanup with object-identity cleanup to avoid clearing a replacement operation.
Replacement-operation safety: The registry change exposes the active reply operation and force-clears it only when that exact object is still the active mapping, covering the race identified in the preceding review cycle.
Focused regression coverage: The PR adds coverage for terminal persistence, absent entries, missing session keys, and replacement-session protection, plus terminal admission recovery and replacement reply-operation behavior.
Findings None None.
Security None None.

How this fits together

Embedded-agent recovery handles runs that stop making progress after a provider or execution stall. It clears active run registries and now also updates the matching persisted session entry so the next inbound message can take the terminal-state recovery path instead of treating a dead run as active.

flowchart LR
  A[Provider or agent stall] --> B[Heartbeat or cron recovery]
  B --> C[Capture current embedded run and reply operation]
  C --> D[Abort and drain recovery]
  D --> E[Persist matching session as killed]
  E --> F[Terminal session entry]
  F --> G[Next inbound message]
  G --> H[Fast recovery admission]
Loading

Before merge

  • Resolve merge risk (P1) - This changes persisted terminal session metadata on a recovery path; the captured-owner checks and the serialized session-ID predicate must remain intact so delayed cleanup cannot mark a replacement run or replacement session as killed.
  • Complete next step (P2) - The remaining action is assigned-reviewer confirmation of persisted terminal-state semantics and normal merge gating, not a discrete automated repair.
Agent review details

Security

None.

PR surface

Source +118, Tests +376. Total +494 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 2 125 7 +118
Tests 5 388 12 +376
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 513 19 +494

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #108331
Summary: This PR is a candidate fix for the force-clear persistence portion of the broader stuck-session report; the related issue retains distinct provider fallback, token-display, and session-recreation questions.

Members:

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

Merge-risk options

Maintainer options:

  1. Confirm terminal-state semantics before merge (recommended)
    Keep the current atomic ownership guards and merge once the assigned reviewer confirms that both force-clear callers should persist the same killed terminal session state.
  2. Pause if callers require distinct terminal meaning
    Pause the PR if heartbeat recovery and cron timeout cleanup need different persisted outcomes, then split that policy decision and its coverage before landing.

Technical review

Best possible solution:

Land the bounded recovery fix after the assigned reviewer confirms that killed is the intended terminal representation for both heartbeat and cron force-clears, retaining the atomic session-ID and reply-operation identity guards.

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

No live current-main failure was run in this read-only review, but the source-level path is concrete and the PR supplies focused regression tests for force-clear persistence, replacement-session safety, and terminal-state admission recovery.

Is this the best way to solve the issue?

Yes. Persisting the existing terminal representation at the shared force-clear boundary is narrower and safer than adding separate heartbeat and cron repair paths, provided the atomic ownership predicates remain in place.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 91b1f9676f9e.

Labels

Label justifications:

  • P1: A failed force-clear can leave a session appearing non-terminal and delay recovery of subsequent user messages after provider stalls.
  • merge-risk: 🚨 session-state: The PR writes terminal status, timestamps, and abort metadata to persisted session entries during recovery.
  • 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. Sufficient (terminal): The PR body provides after-fix terminal output from focused tests that exercise persisted terminal state, replacement-session protection, and dispatch recovery; the repository also labels the proof sufficient.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix terminal output from focused tests that exercise persisted terminal state, replacement-session protection, and dispatch recovery; the repository also labels the proof sufficient.

Evidence

What I checked:

  • Current branch recovery change: The proposed recovery path captures the current embedded-run handle and reply operation before force-clearing, then persists terminal session metadata only for the matching session. The branch also replaces session-ID-only reply cleanup with object-identity cleanup to avoid clearing a replacement operation. (src/agents/embedded-agent-runner/runs.ts:775, 4f3f5f80fac6)
  • Replacement-operation safety: The registry change exposes the active reply operation and force-clears it only when that exact object is still the active mapping, covering the race identified in the preceding review cycle. (src/auto-reply/reply/reply-run-registry.ts:1170, 4f3f5f80fac6)
  • Focused regression coverage: The PR adds coverage for terminal persistence, absent entries, missing session keys, and replacement-session protection, plus terminal admission recovery and replacement reply-operation behavior. (src/agents/embedded-agent-runner/runs.force-clear-terminal.test.ts:1, 4f3f5f80fac6)
  • Review continuity: The prior ClawSweeper review required an atomic session-ID predicate; the earlier revision moved that predicate inside the serialized session-entry update, and the latest commit additionally binds force-clear to the current captured owners. (src/agents/embedded-agent-runner/runs.ts:775, 4f3f5f80fac6)
  • Related incident scope: The related open report describes broader provider-stall session corruption and message blocking; this PR explicitly addresses the force-clear terminal-state portion rather than claiming to resolve all provider fallback, display, and session-recreation concerns.

Likely related people:

  • obviyus: Assigned to this PR and authored the latest branch commit that binds force-clear operations to their current owners after the earlier session-ID atomicity fix. (role: recent recovery-path contributor and assigned reviewer; confidence: high; commits: 4f3f5f80fac6; files: src/agents/embedded-agent-runner/runs.ts, src/auto-reply/reply/reply-run-registry.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-07-21T07:13:13.846Z sha 71f0000 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-24T23:40:00.539Z sha 71f0000 :: needs changes before merge. :: [P1] Guard the terminal write with the cleared session ID
  • reviewed 2026-07-25T04:23:12.888Z sha 9a86310 :: needs changes before merge. :: [P1] Make the session-ID guard atomic with the terminal write
  • reviewed 2026-07-25T09:03:46.700Z sha 6efe3fa :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 24, 2026
@clawsweeper clawsweeper Bot added 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 25, 2026
@obviyus obviyus self-assigned this Jul 27, 2026
@obviyus

obviyus commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 27, 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: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@obviyus

obviyus commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Maintainer confirmation: heartbeat recovery and cron timeout force-clears represent the same terminal outcome (killed). The exact session-entry snapshot and embedded/reply owner-identity guards remain required. Focused merged-tree tests pass; landing remains gated on exact-head CI.

@obviyus
obviyus merged commit 87b76d0 into openclaw:main Jul 27, 2026
116 of 119 checks passed
@obviyus

obviyus commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
…k embedded runs (openclaw#112166)

* fix(agents): persist terminal session state after force-clearing stuck embedded runs

* test(agents): use auto-cleanup temp dir tracker in force-clear test

* fix(agents): guard force-clear terminal-state write with session ID

* fix(agents): make force-clear session-ID guard atomic

* fix(agents): bind force-clear to current run owners

---------

Co-authored-by: Ayaan Zaidi <[email protected]>
@xialonglee
xialonglee deleted the fix/gap-forceclear-session-terminal-state branch July 29, 2026 02:28
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: 🚨 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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

Session state corrupted to 'unknown' after provider 503, permanently blocks new messages

2 participants