Skip to content

fix(gateway): settle same-run terminal lifecycle events past the stale guard - #119456

Closed
harjothkhara wants to merge 3 commits into
openclaw:mainfrom
harjothkhara:fix/session-lifecycle-same-run-stale
Closed

harjothkhara wants to merge 3 commits into
openclaw:mainfrom
harjothkhara:fix/session-lifecycle-same-run-stale

Conversation

@harjothkhara

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #119407.

Since 7c1d5dc (#117731), isStaleLifecycleEventForSession rejects any lifecycle event whose startedAt is older than the row's persisted startedAt. But one embedded run mints two clocks: the command attempt captures the authoritative startedAt first (src/agents/command/run-embedded-attempt.ts:152), and the subscribe layer later stamps its own Date.now() on the lifecycle start event (src/agents/embedded-agent-subscribe.handlers.lifecycle.ts:52). The start event's later timestamp is what gets persisted, so the same run's terminal event — which carries the earlier command-layer timestamp (src/agents/command/lifecycle.ts) — is classified as an "older run" and dropped. The successful run stays canonically running, and the next gateway restart's interruption recovery rewrites it as failed with transcript tail is not resumable (3/3 repro in the issue).

Why This Change Was Made

The guard uses startedAt ordering as a run-identity proxy, but every lifecycle event already carries a real runId — the row just never recorded which run owns its current state. This change records that fact where it happens and uses it:

  • SessionEntry/GatewaySessionRow gain an optional lifecycleRunId: the run id that last wrote the row's lifecycle status. Persisted inside the existing SQLite entry_json blob — purely additive, no DDL, no schema-version bump, no doctor migration (an absent field simply keeps today's timestamp behavior).
  • isStaleLifecycleEventForSession treats an event from the row's own run as never stale, before falling back to the existing timestamp ordering for events from other runs (the overlapping-runs protection fix: prevent lost subagent replies, stale runs, and Codex turn stalls #117731 added is unchanged — its tests still pass verbatim).
  • Both guard call sites (persistGatewaySessionLifecycleEvent and the server-chat UI projection) pass run identity.
  • The sibling entry-reset sites that clear startedAt/status on sessionId rotation or in-place terminal recovery (sqlite-checkpoint, sqlite-message-cut, terminal-status, clearRotatedSessionMetadata, agent-session-patch) clear lifecycleRunId with them, so a recycled row cannot inherit a stale owner.

Threading the command-layer startedAt into the subscribe-layer start emitter was considered and rejected: it needs 8+ files of parameter plumbing, fixes only this one producer pair, and leaves the timestamp-as-identity proxy fragile for every other lifecycle emitter (ACP, worker live runtime, dispatch-error synthesis all mint their own clocks). The dual clock at the producer remains a cosmetic oddity — while a run is live the row shows the subscribe-layer startedAt, and its terminal rewrites it to the earlier command-layer value — worth a follow-up only if the divergence ever becomes user-visible.

User Impact

Successful channel-backed runs no longer stay running in the canonical session store after completing and delivering their reply. Gateway restarts no longer misclassify those completed sessions as interrupted, flip them to failed, or surface Unknown error in the Control UI for runs that succeeded.

Production LOC delta: +50 / −9 (guard restructure + one recorded fact at its owning boundary); tests +59.

Evidence

Regression tests (fail on main, pass here) in src/gateway/session-lifecycle-state.test.ts, driven through the real persistGatewaySessionLifecycleEvent entry point:

node scripts/run-vitest.mjs src/gateway/session-lifecycle-state.test.ts
 Tests  37 passed (37)

Real-behavior proof: a tsx harness drives the production persistGatewaySessionLifecycleEvent against a real isolated SQLite session store (no product code mocked) with the exact two-clock scenario — start persists startedAt = T+5, the same run's terminal carries startedAt = T.

Unfixed main (negative control):

  [PASS] SETUP: canonical session row exists
  [PASS] START: row running with subscribe-layer startedAt — status=running startedAt=1785898374949
  [FAIL] TERMINAL: same run's end settles the row (bug: stays running) — status=running
  [FAIL] TERMINAL: endedAt recorded — endedAt=undefined
RESULT: FAIL — 2 check(s) failed (bug signature: row stays running)

This branch:

  [PASS] SETUP: canonical session row exists
  [PASS] START: row running with subscribe-layer startedAt — status=running startedAt=1785898361446
  [PASS] TERMINAL: same run's end settles the row (bug: stays running) — status=done
  [PASS] TERMINAL: endedAt recorded — endedAt=1785898421441
RESULT: PASS — same-run terminal event settles the canonical session

Also green locally: pnpm tsgo:core, pnpm tsgo:core:test, node scripts/run-vitest.mjs src/gateway/server-chat.agent-events.test.ts src/gateway/server.chat.gateway-server-chat.test.ts src/gateway/session-utils.test.ts src/config/sessions.test.ts src/config/sessions/reset.test.ts.

Not tested: a live channel-backed gateway upgrade roundtrip (the issue's original Telegram + Codex-runtime smoke path); the harness reproduces the same persisted-state transition through the same production persistence entry point.


This PR was AI-assisted (Claude + local review tooling); the diff was human-reviewed before opening.

…e guard

A run's lifecycle start persists the subscribe-layer clock while its terminal
carries the earlier command-attempt clock, so the timestamp-only stale guard
dropped the run's own end and left completed sessions running until restart
recovery marked them failed (openclaw#119407). Record the owning lifecycleRunId on the
session row and treat the row's own run as never stale; other-run events keep
the existing timestamp ordering.
A late predecessor terminal with the recorded run id must not bypass the
timestamp guard after recovery admission rewrites the row to running.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: S labels Aug 5, 2026
@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. 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 Aug 5, 2026
@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 12:07 AM ET / 04:07 UTC.

ClawSweeper review

What this changes

The PR records the run that owns a gateway session lifecycle row so that run’s terminal event can settle the row even when its start timestamp is earlier.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open. Current main still has the timestamp-only guard that can drop a same-run terminal event; this focused PR records durable run ownership at the lifecycle writer and has no blocking review finding.

Priority: P1
Reviewed head: 8ff053687f7ac3f2cba259f0414a348222fcb0b6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused owner-boundary repair with real persisted-state proof and no blocking correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body shows an isolated SQLite before/after run through production persistence, with the exact stale-terminal failure on main and a settled terminal row on the submitted head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body shows an isolated SQLite before/after run through production persistence, with the exact stale-terminal failure on main and a settled terminal row on the submitted head.
Evidence reviewed 6 items Two-clock root cause: The command attempt captures its start time before the embedded subscription emits the same run’s lifecycle start with a new timestamp; terminal events retain the earlier attempt time.
Current-main stale admission: The current guard rejects an earlier event start time after checking session identity, before persistence can apply terminal state.
Exact-head owner-boundary repair: The submitted head records lifecycleRunId on start, admits matching-run events before timestamp comparison, and passes the identity through both durable persistence and the server-chat projection.
Findings None None.
Security None None.

How this fits together

Gateway lifecycle events persist session state used by the Control UI and restart recovery. The stale-event guard prevents older or rotated runs from overwriting that durable state.

flowchart LR
A[Agent run] --> B[Lifecycle events]
B --> C[Gateway stale-event guard]
C --> D[Durable session row]
D --> E[Control UI]
D --> F[Restart recovery]
Loading

Before merge

  • Resolve merge risk (P1) - This adds one optional persisted session field; existing rows keep timestamp-based stale filtering until their next accepted lifecycle start records an owner.
  • Complete next step (P2) - This open contributor PR already owns the narrow repair; no separate automated fix branch is appropriate.
Agent review details

Security

None.

PR surface

Source +50, Tests +59. Total +109 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 14 59 9 +50
Tests 1 59 0 +59
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 118 9 +109

Review metrics

Metric Value Why it matters
Production versus regression coverage production +59/-9, tests +59 The production growth establishes one durable ownership fact and clears it at lifecycle boundaries, with dedicated same-run regression coverage.

Stored data model

Persistent data-model change detected: serialized state: src/agents/command/session.ts, serialized state: src/config/sessions/session-accessor.sqlite-checkpoint.ts, serialized state: src/config/sessions/session-accessor.sqlite-message-cut.ts, serialized state: src/config/sessions/session-transcript-turn-lifecycle.types.ts, serialized state: src/config/sessions/terminal-status.ts, serialized state: src/config/sessions/types.ts, and 6 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #119407
Summary: This PR is the concrete candidate repair for the reported same-run lifecycle stale-guard regression.

Members:

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

Merge-risk options

Maintainer options:

  1. Land with the additive-row fallback (recommended)
    Accept the compatible rollout: old rows retain timestamp filtering until a new start records lifecycle ownership, while all inspected reuse and recovery paths clear it.

Technical review

Best possible solution:

Land the durable run-owner repair with its timestamp fallback for existing rows and retain the reset coverage that clears ownership before a row is reused.

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

Yes. Current source proves the same run can emit a later lifecycle-start timestamp and an earlier terminal timestamp, and the reported SQLite harness exercises that persisted transition.

Is this the best way to solve the issue?

Yes. Recording the authoritative run identity at the lifecycle row owner is more durable than plumbing one producer’s timestamp through every lifecycle emitter.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 9214e6381d49.

Labels

Label justifications:

  • P1: Completed agent runs can remain active and later be falsely marked failed during gateway restart recovery.
  • merge-risk: 🚨 session-state: The patch persists lifecycle run ownership and changes which terminal events may update a session row.
  • 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 shows an isolated SQLite before/after run through production persistence, with the exact stale-terminal failure on main and a settled terminal row on the submitted head.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body shows an isolated SQLite before/after run through production persistence, with the exact stale-terminal failure on main and a settled terminal row on the submitted head.

Evidence

What I checked:

Likely related people:

  • vincentkoc: Current-main blame attributes the timestamp stale predicate to this revision. (role: recent lifecycle-guard contributor; confidence: high; commits: 9518564e30; files: src/gateway/session-lifecycle-state.ts)
  • steipete: Authored the related merged lifecycle and stale-run work in commit 7c1d5dc. (role: merged stale-run feature author; confidence: high; commits: 7c1d5dc7ef58; files: src/gateway/session-lifecycle-state.ts, src/gateway/server-chat.ts)
  • openperf: Introduced the earlier pre-reset lifecycle guard that this path extends. (role: original session-rotation guard contributor; confidence: medium; commits: 613f51a7aa91; files: src/gateway/session-lifecycle-state.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 (1 earlier review cycle)
  • reviewed 2026-08-05T03:29:50.514Z sha 8ff0536 :: needs maintainer review before merge. :: none

@hannesrudolph

Copy link
Copy Markdown
Member

Closing as superseded by merged PR #119752. The merged maintainer repair adopts the same durable run-identity insight while extending ownership handling across terminal settlement, restart recovery, pending-final delivery, reset, rotation, fork, checkpoint, and forced-cleanup paths, and keeps the internal ownership field out of public projections. Thank you for independently identifying the missing invariant and providing the focused implementation; #119752 explicitly credits 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 gateway Gateway runtime 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: 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.

[Bug]: same-run terminal lifecycle event is dropped as stale, leaving successful sessions running

2 participants