Repository navigation
fix(gateway): settle same-run terminal lifecycle events past the stale guard - #119456
harjothkhara wants to merge 3 commits into
Conversation
…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.
…rojection run-id normalization
A late predecessor terminal with the recorded run id must not bypass the timestamp guard after recovery admission rewrites the row to running.
|
Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 12:07 AM ET / 04:07 UTC. ClawSweeper reviewWhat this changesThe 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 provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readinessKeep 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 Review scores
Verification
How this fits togetherGateway 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]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +50, Tests +59. Total +109 across 15 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
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. |
What Problem This Solves
Fixes #119407.
Since 7c1d5dc (#117731),
isStaleLifecycleEventForSessionrejects any lifecycle event whosestartedAtis older than the row's persistedstartedAt. But one embedded run mints two clocks: the command attempt captures the authoritativestartedAtfirst (src/agents/command/run-embedded-attempt.ts:152), and the subscribe layer later stamps its ownDate.now()on the lifecyclestartevent (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 canonicallyrunning, and the next gateway restart's interruption recovery rewrites it asfailedwithtranscript tail is not resumable(3/3 repro in the issue).Why This Change Was Made
The guard uses
startedAtordering as a run-identity proxy, but every lifecycle event already carries a realrunId— the row just never recorded which run owns its current state. This change records that fact where it happens and uses it:SessionEntry/GatewaySessionRowgain an optionallifecycleRunId: the run id that last wrote the row's lifecycle status. Persisted inside the existing SQLiteentry_jsonblob — purely additive, no DDL, no schema-version bump, no doctor migration (an absent field simply keeps today's timestamp behavior).isStaleLifecycleEventForSessiontreats 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).persistGatewaySessionLifecycleEventand theserver-chatUI projection) pass run identity.startedAt/statuson sessionId rotation or in-place terminal recovery (sqlite-checkpoint,sqlite-message-cut,terminal-status,clearRotatedSessionMetadata,agent-session-patch) clearlifecycleRunIdwith them, so a recycled row cannot inherit a stale owner.Threading the command-layer
startedAtinto 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-layerstartedAt, 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
runningin the canonical session store after completing and delivering their reply. Gateway restarts no longer misclassify those completed sessions as interrupted, flip them tofailed, or surfaceUnknown errorin 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 realpersistGatewaySessionLifecycleEvententry point:Real-behavior proof: a tsx harness drives the production
persistGatewaySessionLifecycleEventagainst a real isolated SQLite session store (no product code mocked) with the exact two-clock scenario — start persistsstartedAt = T+5, the same run's terminal carriesstartedAt = T.Unfixed
main(negative control):This branch:
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.