Skip to content

fix(gateway): stopping a turn publishes two terminal lifecycle events for the same run - #165483

Merged
steipete merged 3 commits into
mainfrom
codex/stab-abort-lifecycle
Oct 6, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/stab-abort-lifecycle

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Maintainer decision (2026-10-05): approved approach. Keep the abort handler's immediate terminal and suppress the execution owner's late lifecycle events for a run that has already ended. This replaces the earlier version of this PR, which moved the terminal to the execution owner and made managed-worker chat.abort settlement hang in CI. The branch was rewritten from current main.

What Problem This Solves

Fixes: stopping a running turn on the built-in runtime published two terminal lifecycle events for the same run. Clients saw end and then, up to two seconds later, model, model, and a second terminal error, so a client that trusts the first terminal saw a clean stop followed by more activity.

User Impact

User impact: a stopped turn now publishes exactly one lifecycle terminal, end with status: "cancelled", aborted: true, and the caller's stop reason (rpc for Stop; restart and timeout keep theirs). Nothing is published after it. chat aborted is still immediate. Execution settlement, cleanup, and managed-worker chat.abort settlement are unchanged; only client publication changed.

Why This Change Was Made

The abort handler correctly publishes the immediate terminal, while the model-fallback chain and run teardown keep emitting lifecycle phases as they unwind. Instead of moving terminal ownership (the earlier approach), the shared agent-event owner now records per-run publication state. After a definitive end or error has been admitted for client publication, later lifecycle events for that run are not published to clients. Retryable attempt errors leave the lifecycle open. Internal settlement observers still receive every event.

The state lives on the run's registered context, so it survives the synchronous context retirement that abort hooks perform. Before cancelling the run, the abort handler reserves the client terminal. A definitive terminal emitted by a synchronous abort callback therefore cannot displace it, and the visible terminal keeps the caller's stop reason. One publication decision per event covers every client projection: agent events, chat.final, progress snapshots, and session lifecycle. A suppressed duplicate end cannot produce a second chat.final, and a late start cannot reopen the session. Sequence numbers come from the retained run state, so they stay monotonic when abort cleanup retires the context and across re-registration.

Evidence

Live (dev Gateway, OpenAI-backed agents; start a tool-using turn, wait for three tool results, chat.abort):

Build Built-in runtime events for the run after Stop Codex runtime
main 2983dfcfb319 chat aborted, lifecycle end, model, model, error (reproduced 2/2) single terminal
this branch chat aborted, lifecycle end {status: "cancelled", aborted: true, stopReason: "rpc"}, nothing after (3/3) chat aborted, single end

The Control UI renders the stopped session the same before and after (composer idle, partial tool summary kept, no console errors).

Tests (TMPDIR=/private/tmp/oc-abort-terminal, --maxWorkers=1):

owner regression with production restored to main:    4 failed / 10 passed (4.02 s)
owner regression on this branch:                       14 passed (4.76 s)
focused suites (incl. both that hung under the old approach, all 8 managed-worker chat.abort settlement cases): 329 passed (62.31 s)
sibling suites:                                        47 passed (22.79 s)
after the stop-reason correction: server-chat.agent-events, server-worker-placement-cancel, chat-abort-lifecycle-internal, agent-events.routing, worker.chat-abort, session-lifecycle-state: 187 passed (77.2 s)

Review follow-up (third commit), each with a regression that fails on the previous head. Sequences are preserved through context retirement (the old head produced [1,2,1,2,3]). The abort terminal is reserved before synchronous abort callbacks. Suppression covers chat.final and session lifecycle projections (5 cases). The PR tooling's wrapper source inventory gains packages/normalization-core/src/agent-run-terminal-outcome.ts. In server.chat.acp-completion.test.ts, the explicit-stop case expected an obsolete second error terminal: no assistant text had reached the client before Stop, and its transcript and cancellation assertions are kept.

server-chat.lifecycle-publication.test.ts   5 passed   32.6 s (cold compile)
agent-events.routing.test.ts               16 passed    2.4 s
server-chat.agent-events.test.ts           82 passed   14.4 s
server.chat.acp-completion.test.ts         12 passed   59.4 s
all requested suites incl. the four former hang cases: 278 passed, 1 platform skip (513.8 s)

Live re-check on the final head: 3 Stops, each a single end {cancelled, aborted, rpc} with nothing after (built-in x2, Codex x1). queueMode: "interrupt" still stops the old run (98-219 ms) and finishes the new one on both runtimes.

Scoped types, oxlint, oxfmt, ratchets, and the import-cycle check pass. Autoreview was scoped-clean through P2 for each commit. The second commit keeps the caller's stopReason: agent.wait and the Control UI background notice use rpc to label a stopped run "Killed" rather than "Failed".

Production +157/-77, tests +288/-7, docs +10/-0, PR tooling inventory +1.

Inherited CI failure and landing exception

CI run 37435923222, attempts 1 and 2, is red on exact head d946653025125e1ceb53c16f00b8ee1087d820c4. Attempt 2 has only one failed root job, checks-node-changed-compact-large-15, plus its aggregating openclaw/ci-gate: src/gateway/server-methods/agent.test.ts terminates with SQLite WAL sidecar identity mismatch; terminating without SQLite cleanup, then SIGKILL at 67/395 tests. All other jobs pass or are skipped; security-fast passes. This is not a chat.abort or worker-settlement timeout.

Independent Linux qualification ran the same ten-file selection on one host: the PR head passes 512/512 (295.96 s); plain main 253b51435c850480c702133e5e8bccdd330b90c3 and the actual CI merge 71f44b369632928d9b9f94845e5e9c3e525cc178 fail identically at 67/395 (257.85 s and 258.64 s). The CI checkout log identifies that exact merge and both parents.

The inherited cause is main commit b8b094b57a113f676ce8f76e77a93e5638d2701a (#165680): agent-session-prepare admits a real database before dispatch, while agent.base.test-utils.ts uses filesystem-only withTestDir cleanup. The cached database connection outlives directory removal; restoring the fixture clock makes WAL maintenance due, exposing the deleted Linux sidecar. The fixture, database/cache, and WAL/scheduler inputs are unchanged by this PR. The affected fixture mocks agent event emission and does not enter the abort/publication path. A separate test-only repair owns this red-main defect.

Peter explicitly authorized the native inherited-failure admin exception for this sole attributed failure and its aggregate. Review and preparation retain the failed CI result; no green current-head CI claim is made. ClawSweeper revision 6 reviewed this exact head with no findings, and the exact-head independent autoreview is scoped-clean through P2. Execution settlement, cleanup, managed-worker chat.abort settlement, and durable session-stop receipts remain unchanged.

@clawsweeper

clawsweeper Bot commented Oct 5, 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. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 5, 2026 09:30
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 4:30 AM ET / 08:30 UTC (Revision 6).

ClawSweeper review

What this changes

The PR prevents duplicate terminal and late lifecycle notifications after a stopped turn while preserving immediate cancellation and internal execution cleanup.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary on current main. The rewritten approach addresses the earlier settlement blockers, and no blocking correctness finding remains in the pinned diff.

Priority: P2
Reviewed head: d946653025125e1ceb53c16f00b8ee1087d820c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with relevant live evidence and regressions, with no blocking defect found.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Captured dev-Gateway observations exercise the changed abort and event-publication owners through chat.abort: final-head Stops produce one cancelled end with the caller's reason, and interrupt-mode replacement turns complete. Focused regressions supplement that live evidence. No stored-data model changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Captured dev-Gateway observations exercise the changed abort and event-publication owners through chat.abort: final-head Stops produce one cancelled end with the caller's reason, and interrupt-mode replacement turns complete. Focused regressions supplement that live evidence. No stored-data model changes require migration proof.
Evidence reviewed 10 items Pinned introduced change: Reviewed the merge-base-to-head delta, preserving the distinction between PR changes and base-branch drift. The supplied test merge is stale and was not used to infer removal of current-main behavior.
Abort terminal reservation: The abort handler reserves publication before synchronous cancellation callbacks, then emits the immediate cancellation terminal with the caller's original stop reason.
Publication and settlement remain separate: Per-registration state survives captured routing. Lifecycle publication admission suppresses later client events, while dispatch still notifies internal observers. Gateway finalization gates chat finals and session notifications without skipping persistence and cleanup.
Findings None None.
Security None None.

How this fits together

The Gateway turns agent runtime events into chat updates and session notifications. Its event owner now separates client publication from the internal events used to settle execution and persist outcomes.

flowchart TD
  A[Stop request] --> B[Abort handler]
  C[Runtime lifecycle events] --> D[Shared event owner]
  B --> D
  D --> E[Single terminal publication decision]
  E --> F[Chat and session clients]
  D --> G[Internal settlement and persistence]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +80, Tests +281, Docs +10, Other +1. Total +372 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 6 157 77 +80
Tests 3 288 7 +281
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 11 456 84 +372

Review metrics

Metric Value Why it matters
Production versus regression coverage production net +80 lines; tests net +281 lines Production growth implements shared publication state and projection gating, with distinct routing and Gateway-boundary regressions.

Technical review

Best possible solution:

Keep one immediate cancellation terminal across client projections while preserving execution-owned settlement and persistence.

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

Yes: the captured live reproduction starts a tool-using built-in turn and invokes chat.abort, observing end followed by model updates and error. Current-main source retains that unsuppressed path; this review did not execute it.

Is this the best way to solve the issue?

Yes: suppressing client publication in the shared event owner preserves the immediate terminal required by managed-worker settlement and avoids moving execution custody.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Duplicate lifecycle terminals confuse stopped-run clients, but the reported defect has a bounded blast radius.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Captured dev-Gateway observations exercise the changed abort and event-publication owners through chat.abort: final-head Stops produce one cancelled end with the caller's reason, and interrupt-mode replacement turns complete. Focused regressions supplement that live evidence. No stored-data model changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Captured dev-Gateway observations exercise the changed abort and event-publication owners through chat.abort: final-head Stops produce one cancelled end with the caller's reason, and interrupt-mode replacement turns complete. Focused regressions supplement that live evidence. No stored-data model changes require migration proof.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta, preserving the distinction between PR changes and base-branch drift. The supplied test merge is stale and was not used to infer removal of current-main behavior. (d94665302512)
  • Abort terminal reservation: The abort handler reserves publication before synchronous cancellation callbacks, then emits the immediate cancellation terminal with the caller's original stop reason. (src/gateway/chat-abort.ts:533, d94665302512)
  • Publication and settlement remain separate: Per-registration state survives captured routing. Lifecycle publication admission suppresses later client events, while dispatch still notifies internal observers. Gateway finalization gates chat finals and session notifications without skipping persistence and cleanup. (src/infra/agent-events.ts:526, d94665302512)
  • Focused regression coverage: Read the routing, projection, and ACP completion tests. They cover synchronous abort errors, retained sequences, registration replacement, retryable errors, hidden subscribers, duplicate finals, and late session reopening; transcript and cancellation assertions remain in the ACP case. (src/gateway/server-chat.lifecycle-publication.test.ts:41, d94665302512)
  • Recorded final-head real behavior: The captured PR body records a dev Gateway with OpenAI-backed agents: the original built-in path reproduced duplicate terminals twice; the branch produced one cancelled end and no later lifecycle activity. The final-head recheck records three Stops and successful interrupt-mode replacement turns. Reported focused validation includes 278 passing cases and one platform skip. These are contributor-recorded observations; this read-only review did not execute tests. (d94665302512)
  • Accepted approach and prior blockers: The captured body records approval to retain immediate abort terminals. The discussion at fix(gateway): stopping a turn publishes two terminal lifecycle events for the same run #165483 (comment) explains why moving terminal ownership broke managed-worker settlement. The current diff retains that publisher and does not introduce the earlier custody change. (d94665302512)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (5 earlier review cycles)
  • reviewed 2026-10-05T09:36:51.302Z sha 45c99b9 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T09:45:00.381Z sha 45c99b9 :: needs changes before merge. :: [P2] Update private-completion fixtures for execution-owned terminals
  • reviewed 2026-10-05T10:18:05.717Z sha 8100dca :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T10:50:02.695Z sha 8100dca :: blocked before merge. :: [P1] [P1] Preserve a terminal publisher for cancelled managed workers | [P1] [P1] Retain chat.send custody until execution actually settles
  • reviewed 2026-10-06T07:39:10.399Z sha 50bc8d4 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added 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: 🐚 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. labels Oct 5, 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 Oct 5, 2026
@steipete
steipete marked this pull request as draft October 5, 2026 10:35
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Holding this for maintainer review instead of landing autonomously.

Exact-head CI on 8100dca89f and follow-up investigation showed that the early abort terminal this PR removes is a real dependency elsewhere, not just stale test fixtures:

  • src/worker/worker.chat-abort.test.ts: eight managed-worker chat.abort settlement cases (queued preview true/false across none, claim, credential, run-owner, lifecycle, and before/after durable-ACK fences) now time out at 120 s. Remote worker abort settlement waits for a lifecycle terminal that chat.abort no longer publishes once execution has started.
  • A chat.send custody path also needed a production change to keep cancellation and drain working when the terminal comes only from the execution owner (local patch prepared, not pushed).

Removing the duplicate terminal is still the right goal (live repro in the description: end, then model, model, error for one aborted run), but the contract needs a decision: either (a) keep the abort handler's terminal and suppress the execution owner's late lifecycle events for an already-terminal run, or (b) move every consumer, including managed-worker settlement, to the execution-owned terminal. Option (a) is smaller and leaves worker settlement untouched.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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: 🐚 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. labels Oct 5, 2026
Keep immediate abort terminals and normalize their cancellation outcome. Retain per-run publication state through captured routing, and decide publication in dispatch order while preserving late execution facts for settlement and cleanup listeners.

Cover synchronous abort cleanup and reentrant terminal publication. Preserve managed-worker abort settlement, retryable model fallbacks, timeout precedence, and terminal persistence.
The Control UI and agent.wait consumers distinguish an RPC stop (rpc) from other cancellations; keep the abort handler's existing stop reason instead of normalizing it to aborted.
@steipete
steipete force-pushed the codex/stab-abort-lifecycle branch from 8100dca to 50bc8d4 Compare October 6, 2026 07:33
@steipete
steipete marked this pull request as ready for review October 6, 2026 07:33
@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
Preserve event sequences through context retirement and reserve the caller's cancellation terminal before synchronous abort callbacks. Share one publication decision across agent, chat, progress, and session projections while retaining internal persistence and execution settlement.

Complete the wrapper runtime source inventory and align ACP explicit-stop coverage with one lifecycle terminal and truthful transcript ownership. Keep visible partial-save warnings in their existing owner.
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L and removed size: M labels Oct 6, 2026
@steipete
steipete merged commit a81b9cd into main Oct 6, 2026
245 of 253 checks passed
@steipete
steipete deleted the codex/stab-abort-lifecycle branch October 6, 2026 10:13
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
… for the same run (openclaw#165483)

* fix(gateway): suppress lifecycle publication after run termination

Keep immediate abort terminals and normalize their cancellation outcome. Retain per-run publication state through captured routing, and decide publication in dispatch order while preserving late execution facts for settlement and cleanup listeners.

Cover synchronous abort cleanup and reentrant terminal publication. Preserve managed-worker abort settlement, retryable model fallbacks, timeout precedence, and terminal persistence.

* fix(gateway): keep the caller's stop reason on chat abort terminals

The Control UI and agent.wait consumers distinguish an RPC stop (rpc) from other cancellations; keep the abort handler's existing stop reason instead of normalizing it to aborted.

* fix(gateway): reserve abort terminals across lifecycle projections

Preserve event sequences through context retirement and reserve the caller's cancellation terminal before synchronous abort callbacks. Share one publication decision across agent, chat, progress, and session projections while retaining internal persistence and execution settlement.

Complete the wrapper runtime source inventory and align ACP explicit-stop coverage with one lifecycle terminal and truthful transcript ownership. Keep visible partial-save warnings in their existing owner.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime 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. scripts Repository scripts 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.

1 participant