Repository navigation
fix(gateway): stopping a turn publishes two terminal lifecycle events for the same run - #165483
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 4:30 AM ET / 08:30 UTC (Revision 6). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +80, Tests +281, Docs +10, Other +1. Total +372 across 11 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
|
Holding this for maintainer review instead of landing autonomously. Exact-head CI on
Removing the duplicate terminal is still the right goal (live repro in the description: |
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.
8100dca to
50bc8d4
Compare
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.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
… 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.
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
endand then, up to two seconds later,model,model, and a second terminalerror, 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,
endwithstatus: "cancelled",aborted: true, and the caller's stop reason (rpcfor Stop;restartandtimeoutkeep theirs). Nothing is published after it.chat abortedis still immediate. Execution settlement, cleanup, and managed-workerchat.abortsettlement 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
endorerrorhas 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 duplicateendcannot produce a secondchat.final, and a latestartcannot 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):2983dfcfb319chat aborted, lifecycleend,model,model,error(reproduced 2/2)chat aborted, lifecycleend{status: "cancelled", aborted: true, stopReason: "rpc"}, nothing after (3/3)chat aborted, singleendThe 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):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 coverschat.finaland session lifecycle projections (5 cases). The PR tooling's wrapper source inventory gainspackages/normalization-core/src/agent-run-terminal-outcome.ts. Inserver.chat.acp-completion.test.ts, the explicit-stop case expected an obsolete seconderrorterminal: no assistant text had reached the client before Stop, and its transcript and cancellation assertions are kept.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.waitand the Control UI background notice userpcto 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 aggregatingopenclaw/ci-gate:src/gateway/server-methods/agent.test.tsterminates withSQLite WAL sidecar identity mismatch; terminating without SQLite cleanup, then SIGKILL at 67/395 tests. All other jobs pass or are skipped;security-fastpasses. 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
253b51435c850480c702133e5e8bccdd330b90c3and the actual CI merge71f44b369632928d9b9f94845e5e9c3e525cc178fail 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-prepareadmits a real database before dispatch, whileagent.base.test-utils.tsuses filesystem-onlywithTestDircleanup. 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.