Skip to content

fix(sessions): replay a queued follow-up across an interposed command exchange - #194396

Closed
HeMiaolin wants to merge 11 commits into
openclaw:mainfrom
HeMiaolin:fix/a2a-stop-exchange-admission-194303
Closed

HeMiaolin wants to merge 11 commits into
openclaw:mainfrom
HeMiaolin:fix/a2a-stop-exchange-admission-194303

Conversation

@HeMiaolin

@HeMiaolin HeMiaolin commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A follow-up message queued while a run is active is dropped when /stop is used. The dispatcher mirrors the stop's
command exchange into the transcript, and the queued follow-up's replay admission then resolves the command row as
the current turn, refuses with Persisted user turn changed before replay admission, and the message is never answered.

Reproduced with the reporter's fixture (extensions-free, real session manager + real transcript): on main the queued
follow-up ends with 0 model calls and that error; with this change it is answered.

Why This Change Was Made

src/agents/sessions/session-manager-current-turn.ts decides which transcript entries the current-turn walk may step
over. It already treats context metadata, compaction markers and runtime/system custom messages as traversable because
they are not model-facing turns. A delivered command exchange is the same kind of row — a transcript mirror of the
dispatcher's reply — but it was not listed, so the walk stopped on it.

The fix marks rows whose idempotencyKey is command-input:* or command-reply:* as traversable. Nothing else changes:
real user turns still stop the walk, and the admission still requires the prepared user message to match exactly.

User Impact

A queued follow-up survives /stop: it is persisted once and gets answered instead of silently disappearing behind a
generic "couldn't finish this reply". Commands that are not mirrored (/new etc. still write their exchange the same
way) behave the same, and no transcript bytes change.

Evidence

Reporter's fixture, run with node scripts/test-projects.mts <file>:

case base this branch
no interposed write (control) answered answered
Workshop notice interposed (control, #181473) answered answered
/stop exchange interposed Persisted user turn changed before replay admission, 0 model calls 1 model call, FOLLOWUP_ANSWERED
  • Base: 2 failed | 4 passed (both reader modes fail on the interposed case). Fixed: 6 passed.
  • Neighbours: attempt-session-replay.test.ts 61 passed; session-manager-bounded.test.ts 28 passed;
    session-manager-async-entries.test.ts 9 passed.
  • oxlint: 0 warnings, 0 errors. The new test file carries an allocation in
    config/test-lines-allocations/stop-exchange-replay-admission.txt.

Why there is no gateway-level trace here

I built the full isolated stack and tried to drive the reported race, then stopped when the attempt could not reach
the state the report describes. What works, and what does not:

  • Works: an isolated gateway from a built worktree (gateway run --port 3099 with a --profile-isolated config,
    /health 200) plus the repo's mock model server (scripts/e2e/mock-openai-server.mjs) really does run agent turns —
    openclaw --profile … agent -m "…" returns the mock's marker.
  • Does not reach the race: openclaw agent -m "/stop" is delivered as an ordinary user message, not as a slash
    command. In my runs the long first turn reported aborted: false and stopReason: "stop", and the /stop call was
    queued and answered like any other turn. Without an actual command-path stop there is no command exchange mirrored
    into the transcript, which is precisely the precondition this fix changes.
  • Earlier notes in this PR cited process-supervisor failures for e2e; those were real, but they are not the reason this
    trace is missing. The accurate reason is the one above: the CLI agent channel does not exercise the command path.

What a reviewer can run instead, given a channel that delivers commands (the report used Telegram): queue a follow-up
during an active turn, send /stop, and confirm the queued message still reaches a model request instead of failing with
Persisted user turn changed before replay admission. The reporter's fixture in this PR covers the same predicate without
a channel: it fails on base with that error and passes with the change.

Scope

One production file (the traversal predicate), the reporter's regression test registered next to
attempt-session-replay.test.ts in test/vitest/vitest.database-worker-core-paths.mjs, and the allocation file.

AI Assistance

This PR was prepared with AI assistance from the issue report and its attached fixture; the author reviewed the change
and its evidence.

Gateway-level proof: what a CI-shaped test would need

I could not produce this here (no provider endpoint on this machine), but the pieces are in the repo:

  • test/helpers/openclaw-test-instance.ts starts a real Gateway with isolated state without Playwright
    (startGateway / port / url / cli), so the queue/stop sequence can be driven over the Gateway API.
  • scripts/e2e/mock-openai-server.mjs is an OpenAI-compatible mock with MOCK_RESPONSE_CHUNK_DELAY_MS, which keeps a turn
    running long enough to queue a follow-up and send /stop — that is the whole sequence this PR changes.
  • With those two, a *.real-gateway.e2e.test.ts can assert: first turn streaming -> second chat.send queues ->
    /stop -> the queued message receives an assistant reply (base: user row only, no reply).

The existing ui/src/e2e/*.real-gateway.e2e.test.ts suites do not run a model (they append to the transcript directly), so
there is no fixture to copy for this yet.

@clawsweeper

clawsweeper Bot commented Nov 7, 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.

@HeMiaolin
HeMiaolin marked this pull request as ready for review November 7, 2026 01:25
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Nov 7, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 7, 2026
@clawsweeper

clawsweeper Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close as superseded by #195612, which addresses the same delayed Stop failure at the producer, supplies Gateway evidence, and passes the current CI gate.

Root-cause cluster
Relationship: superseded
Canonical: #195612
Summary: The replacement owns the same delayed Stop transcript-ordering failure with production-boundary evidence.

Members:

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

Canonical path: Consolidate the delayed Stop repair in #195612, preserving command history and existing replay barriers.

So I’m closing this here and keeping the remaining discussion on #195612.

Review details

Best possible solution:

Consolidate the delayed Stop repair in #195612, preserving command history and existing replay barriers.

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

Current source and the reporter's fixture establish how a delayed command exchange displaces the persisted replay anchor; this read-only review executed no target code.

Is this the best way to solve the issue?

Repairing Stop ordering through existing source retention is more complete than broadly crossing all command exchanges during replay.

Security review:

Security review cleared: No concrete credential, authorization, dependency, or supply-chain regression was identified.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 40cdfd0 adds src/agents/sessions/session-manager-current-turn.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 40cdfd038332; files: src/agents/sessions/session-manager-current-turn.ts)

Codex review notes: model internal, reasoning medium; reviewed against 2f199387d3dc.

@HeMiaolin

Copy link
Copy Markdown
Contributor Author

Answering the intent question first, since it decides whether the change is even allowed to look like this.

What the change does and does not touch. excludeFromContext / __openclaw.contextFreeCommand are untouched: every
row this PR's predicate skips stays in the model context exactly as before, so "status exchanges remain visible" and
"ordinary commands keep their context-bearing behavior" still hold. The predicate only decides whether the current-turn
walk
may step over a row while resolving which user turn is being admitted.

Why it cannot swallow an ordinary command's turn. recordDeliveredCommandExchange is the fast path for commands the
dispatcher answers itself; ordinary context-bearing commands never write a command-input: row (they reach the agent as
a normal user message). The walk still stops at the first real user row, so a command's own turn is only reachable when it
is genuinely the tail — which is unchanged.

Why keying on the context-free marker instead would not fix the bug. The /stop fast-abort mirror builds its
metadata in src/auto-reply/reply/dispatch-from-config.prepare-operation.ts:165-172 and does not set
contextFreeCommand; /stop is not the read-only /status path (commands-status.ts:19). So the interposed /stop
rows are ordinary command rows — the reporter's fixture mirrors that by calling recordDeliveredCommandExchange without
the flag. A marker-based predicate would leave the reported failure in place.

The recovery path. The walk from the tail now steps over command-input:* / command-reply:* rows
(src/config/sessions/command-transcript.ts:147 defines those idempotency keys) and stops on the queued follow-up, whose
prepared user message then still has to match exactly before admission — the invariant that produced the original error
is intact, it just no longer fires on a transcript mirror.

c2cb56c665e3 (#192585) is about /status mid-turn reaching the transcript without conflicting with the running turn.
This PR does not change when those rows are written or how they are stored; it changes what the following turn's replay
admission considers "the current user turn", and the /status mid-turn case has no following admission while the turn is
still running.

On the remaining ask (a shipped Gateway trace): I will add one showing a queued follow-up being answered across /stop,
and update the body before asking for another review.

@HeMiaolin

Copy link
Copy Markdown
Contributor Author

Adding what I can and being explicit about what I cannot, so nobody waits on me for a trace I am not able to produce.

What I cannot produce here. A live Gateway trace needs an agent turn that is still running when the follow-up is
queued and /stop arrives, which needs a reachable model endpoint. This machine has no provider configuration
(~/.openclaw/config.json does not exist, no OPENCLAW_* provider env) and the only credential available to me is a bare
sk-… string with no base URL, so I cannot stand up a gateway that actually answers a turn. I would rather say that than
paste a trace with a stubbed model and call it behavior proof.

How to verify in about two minutes with a configured provider (any channel or the Control UI both work):

  1. openclaw gateway run against an isolated OPENCLAW_CONFIG_PATH/OPENCLAW_STATE_DIR.
  2. Send a prompt that keeps the turn busy for a while (for example: "write a 400-word summary of the attached text, then
    three more variants").
  3. While it runs, send a second message — it queues as a follow-up.
  4. Send /stop.
  5. Inspect the session: on main the queued message's user row exists once, has no assistant reply, and the turn fails
    with Persisted user turn changed before replay admission. On this branch the same sequence produces a second
    assistant reply for the queued message.

What the committed fixture does prove. attempt-session-replay.stop-exchange.test.ts is not a mock of the failing
layer: it drives the real SessionManager, the real SQLite transcript writes (recordDeliveredCommandExchange,
appendAssistantMessageToSessionTranscript) and the real replay admission (sessionManagerPrepareCurrentTurnReplay), in
both reader modes (hydrated manager and persisted-transcript reader). Only the model call is stubbed — which is the part
this bug does not touch, since the failure happens before any model request is made (the base case asserts
modelCalls === 0).

On main it fails with exactly the reported error; with the change the queued follow-up is admitted and answered. Neighbour
suites (attempt-session-replay.test.ts, session-manager-bounded.test.ts, session-manager-async-entries.test.ts) pass
unchanged.

If the maintainer would rather have the Gateway trace as a merge condition and cannot run it either, I am fine with this
PR waiting or being superseded — the fix and the fixture stay available either way.

@HeMiaolin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Answering the second item, and being explicit about the first.

Ordinary versus context-free command behavior (#192585 intent preserved).

c2cb56c665e made /status mid-turn stop cancelling the active reply: the status exchange must stay visible
without interrupting the turn, while ordinary commands keep their existing context-bearing behavior. This change does not
touch either.

  • The new predicate matches only the two keys a delivered command exchange writes:
    isCommandExchangeIdempotencyKey returns true for command-input: and command-reply: prefixes
    (src/config/sessions/command-transcript-keys.ts). Those rows are the dispatcher's mirror of the command reply.
  • Everything else is untouched. An ordinary user turn — including an ordinary command typed as a user message — has no
    such key, so traversable resolves exactly as before and its context-bearing behavior is unchanged.
  • Persistence and delivery do not change at all: the status exchange is still written and still delivered. Only turn
    navigation changes, so the replay admission no longer mistakes the mirror for the current user turn.
  • That is precisely what preserves the fix: status checks no longer cancel active replies #192585 outcome: the status reply stays visible, the running turn is not
    interrupted, and a follow-up queued before the mirror is admitted against its real user turn instead of the command row
    (the bug this PR fixes: Persisted user turn changed before replay admission).

Real behavior proof (still not producible here). Two reproducible environment limits, both unrelated to this change:

  • Gateway e2e cannot run in this container: the built runtime is available, but e2e tests fail in the process supervisor
    with service child cleanup identity lost: native owner closed without kernel descendant extinction (reproduced with
    test/gateway-restart-lane.e2e.test.ts).
  • Isolated-gateway RPC auth does not resolve: gateway.auth.mode: "none" still answers token_missing, and a token the
    gateway accepts answers token_mismatch, although src/gateway/auth.ts returns ok for mode: "none".

To capture the trace elsewhere: start a Gateway with the mock provider (scripts/e2e/mock-openai-server.mjs), queue a
follow-up during an active turn, send /stop, and confirm the queued message still reaches a model request instead of
failing with Persisted user turn changed before replay admission.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Nov 10, 2026
@clawsweeper clawsweeper Bot removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 10, 2026
@HeMiaolin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Corrected the proof-gap explanation in the body: my earlier note blamed e2e process-supervisor failures, which was not the
real reason this trace is missing.

I did build the stack and drive it: an isolated gateway from a built worktree plus the repo's mock model server returns
real agent turns (openclaw --profile … agent -m "…" → the mock's marker). The blocker is narrower and more honest than
"e2e cannot run": openclaw agent -m "/stop" is delivered as an ordinary user message, not a slash command, so no
command exchange is mirrored into the transcript. In my runs the long first turn ended with aborted: false and
stopReason: "stop", and the /stop call was queued and answered like a normal turn — the race precondition never
existed.

That also means I cannot claim a gateway trace for this fix. What stands is the predicate-level proof in the PR's fixture,
which fails on base with Persisted user turn changed before replay admission and passes with the change, plus the
explanation of the Ordinary-versus-context-free behaviour answered earlier. If a maintainer wants the channel-level
trace, it needs a channel that delivers commands (the report used Telegram), where the same steps reproduce it.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 10, 2026
@HeMiaolin
HeMiaolin force-pushed the fix/a2a-stop-exchange-admission-194303 branch from acd1279 to ba38416 Compare November 11, 2026 02:01
@HeMiaolin

Copy link
Copy Markdown
Contributor Author

Closing this myself rather than leaving it open indefinitely.

State of the change: the fix is complete and green (the predicate is covered by a regression test that fails on the base
with Persisted user turn changed before replay admission and passes with the change), but the review asked for a
Gateway/CLI trace of the queued-follow-up + /stop flow, and I established that I cannot produce one here:
openclaw agent -m "/stop" is delivered as an ordinary message rather than a slash command, so the command-exchange
precondition never occurs on this path. There is no real model credential in this environment either.

Since a proof I cannot produce would otherwise keep the PR parked forever, the honest outcome is to close it and leave the
analysis behind:

  • what it changes: the replay admission predicate treats a command-only exchange as traversable instead of failing the
    queued turn; the leaf module and the session-manager predicate are the only production edits.
  • how to reproduce the reported symptom without a channel: the reporter's fixture in this PR's test file fails on base with
    Persisted user turn changed before replay admission.
  • how to get the trace, for anyone with a channel that delivers commands (the report used Telegram): queue a follow-up
    during an active turn, send /stop, and confirm the queued message still reaches a model request.

If a maintainer wants the change, the branch and its tests are intact and can be reopened on request.

@HeMiaolin

Copy link
Copy Markdown
Contributor Author

Closing: fix verified at the predicate boundary, but the requested Gateway/channel trace is not producible in this environment (see comment above). Reopenable as-is.

@HeMiaolin HeMiaolin closed this Nov 11, 2026
@HeMiaolin
HeMiaolin deleted the fix/a2a-stop-exchange-admission-194303 branch November 11, 2026 23:00
obviyus added a commit that referenced this pull request Nov 18, 2026
…Stop reply is delivered late (#195612)

Root cause: src/auto-reply/reply/dispatch-from-config.prepare-operation.ts:217 (on main 1680f54) the fast-abort path lets Stop cancel and release its own message source at once, while a direct Stop reply records its `/stop` exchange only later, at dispatcher settlement after delivery. A turn accepted while that reply is still being sent persists its user row first, so the Stop exchange lands after it and the follow-up can fail replay admission ("Persisted user turn changed before replay admission") and go unanswered.

Fixes #194303

Thanks @amittell for the report, the root-cause analysis and this fix. Thanks @arcabotai for #195358, which reported the same unanswered follow-up; this PR fixes the Stop path at the producer instead of relaxing replay admission.

## What Problem This Solves

Fixes: a message sent right after `/stop` is recorded ahead of the Stop exchange in session history, and can go unanswered, when the Stop reply reaches the channel late.

## User Impact

User impact: after `/stop`, the next message waits until the Stop reply is delivered and recorded, then runs and is answered once, with the Stop exchange first in history. Input already waiting when Stop arrived is still cancelled, as before.

## Why This Change Was Made

Once a stop request is recognized, before Stop selects anything, dispatch retains the Stop message's own source until the Stop reply settles (dispatcher settlement, bounded by the existing follow-up admission barrier timeout). The mailbox does not select past a source with unsettled work, so the next turn starts after the Stop rows. If the abort resolver throws or the message is not handled as a stop, the retention is released immediately.

Unchanged: what Stop cancels, command classification, the command history format, and replay admission (a command row written before a turn still refuses a stale replay). #194336, #194396 and #195358 instead make command exchanges traversable for replay admission, which reverses the `c2cb56c665e` boundary; this PR touches neither replay predicate.

Maintainer edits on top of @amittell's commits: merged current main, rewrote the retention without re-indenting the fast-abort branch (`.catch`/`.finally` instead of `try/finally`), and kept one red-on-base regression (dispatch order) in place of the two test files and the test-lines allocation.

## Evidence

Observed proof lines (base and head): #195612 (comment)

- Regression `dispatch-from-config.command-transcript.test.ts` > "records a late-delivered /stop before the next turn's row" (active run false/true): main 1680f54 fails 2/2 with `expected [ 'next-turn', 'command-input', …(1) ] to deeply equal [ 'command-input', …(2) ]`; this head passes 4/4.
- Real Gateway (`ocx src --node`) with the Telegram plugin, a local Bot API that holds the Stop reply, and a local chat-completions model: on main the follow-up's user row and answer are written before `/stop` / `Agent was aborted.`; here the Stop exchange is recorded first, then the follow-up row and one answer. `/stop` alone behaves the same on both.
- Replay admission still refuses a genuinely out-of-order replay: `attempt-session-replay-cohort.test.ts` (including `completed-after-preparation`), the steering replay test and `abort.test.ts` pass, 48/48.

## Merge danger

Two-way door: no stored data, config or contract change; a revert restores the old ordering. Blast radius: channels that send `/stop` as a message; a hung Stop delivery delays the next turn by at most the existing follow-up admission barrier timeout.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…Stop reply is delivered late (openclaw#195612)

Root cause: src/auto-reply/reply/dispatch-from-config.prepare-operation.ts:217 (on main 5cd28bd) the fast-abort path lets Stop cancel and release its own message source at once, while a direct Stop reply records its `/stop` exchange only later, at dispatcher settlement after delivery. A turn accepted while that reply is still being sent persists its user row first, so the Stop exchange lands after it and the follow-up can fail replay admission ("Persisted user turn changed before replay admission") and go unanswered.

Fixes openclaw#194303

Thanks @amittell for the report, the root-cause analysis and this fix. Thanks @arcabotai for openclaw#195358, which reported the same unanswered follow-up; this PR fixes the Stop path at the producer instead of relaxing replay admission.

## What Problem This Solves

Fixes: a message sent right after `/stop` is recorded ahead of the Stop exchange in session history, and can go unanswered, when the Stop reply reaches the channel late.

## User Impact

User impact: after `/stop`, the next message waits until the Stop reply is delivered and recorded, then runs and is answered once, with the Stop exchange first in history. Input already waiting when Stop arrived is still cancelled, as before.

## Why This Change Was Made

Once a stop request is recognized, before Stop selects anything, dispatch retains the Stop message's own source until the Stop reply settles (dispatcher settlement, bounded by the existing follow-up admission barrier timeout). The mailbox does not select past a source with unsettled work, so the next turn starts after the Stop rows. If the abort resolver throws or the message is not handled as a stop, the retention is released immediately.

Unchanged: what Stop cancels, command classification, the command history format, and replay admission (a command row written before a turn still refuses a stale replay). openclaw#194336, openclaw#194396 and openclaw#195358 instead make command exchanges traversable for replay admission, which reverses the `1bcf6c36036` boundary; this PR touches neither replay predicate.

Maintainer edits on top of @amittell's commits: merged current main, rewrote the retention without re-indenting the fast-abort branch (`.catch`/`.finally` instead of `try/finally`), and kept one red-on-base regression (dispatch order) in place of the two test files and the test-lines allocation.

## Evidence

Observed proof lines (base and head): openclaw#195612 (comment)

- Regression `dispatch-from-config.command-transcript.test.ts` > "records a late-delivered /stop before the next turn's row" (active run false/true): main 5cd28bd fails 2/2 with `expected [ 'next-turn', 'command-input', …(1) ] to deeply equal [ 'command-input', …(2) ]`; this head passes 4/4.
- Real Gateway (`ocx src --node`) with the Telegram plugin, a local Bot API that holds the Stop reply, and a local chat-completions model: on main the follow-up's user row and answer are written before `/stop` / `Agent was aborted.`; here the Stop exchange is recorded first, then the follow-up row and one answer. `/stop` alone behaves the same on both.
- Replay admission still refuses a genuinely out-of-order replay: `attempt-session-replay-cohort.test.ts` (including `completed-after-preparation`), the steering replay test and `abort.test.ts` pass, 48/48.

## Merge danger

Two-way door: no stored data, config or contract change; a revert restores the old ordering. Blast radius: channels that send `/stop` as a message; a hung Stop delivery delays the next turn by at most the existing follow-up admission barrier timeout.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…Stop reply is delivered late (#195612)

Root cause: src/auto-reply/reply/dispatch-from-config.prepare-operation.ts:217 (on main 1680f54) the fast-abort path lets Stop cancel and release its own message source at once, while a direct Stop reply records its `/stop` exchange only later, at dispatcher settlement after delivery. A turn accepted while that reply is still being sent persists its user row first, so the Stop exchange lands after it and the follow-up can fail replay admission ("Persisted user turn changed before replay admission") and go unanswered.

Fixes #194303

Thanks @amittell for the report, the root-cause analysis and this fix. Thanks @arcabotai for #195358, which reported the same unanswered follow-up; this PR fixes the Stop path at the producer instead of relaxing replay admission.

## What Problem This Solves

Fixes: a message sent right after `/stop` is recorded ahead of the Stop exchange in session history, and can go unanswered, when the Stop reply reaches the channel late.

## User Impact

User impact: after `/stop`, the next message waits until the Stop reply is delivered and recorded, then runs and is answered once, with the Stop exchange first in history. Input already waiting when Stop arrived is still cancelled, as before.

## Why This Change Was Made

Once a stop request is recognized, before Stop selects anything, dispatch retains the Stop message's own source until the Stop reply settles (dispatcher settlement, bounded by the existing follow-up admission barrier timeout). The mailbox does not select past a source with unsettled work, so the next turn starts after the Stop rows. If the abort resolver throws or the message is not handled as a stop, the retention is released immediately.

Unchanged: what Stop cancels, command classification, the command history format, and replay admission (a command row written before a turn still refuses a stale replay). #194336, #194396 and #195358 instead make command exchanges traversable for replay admission, which reverses the `c2cb56c665e` boundary; this PR touches neither replay predicate.

Maintainer edits on top of @amittell's commits: merged current main, rewrote the retention without re-indenting the fast-abort branch (`.catch`/`.finally` instead of `try/finally`), and kept one red-on-base regression (dispatch order) in place of the two test files and the test-lines allocation.

## Evidence

Observed proof lines (base and head): #195612 (comment)

- Regression `dispatch-from-config.command-transcript.test.ts` > "records a late-delivered /stop before the next turn's row" (active run false/true): main 1680f54 fails 2/2 with `expected [ 'next-turn', 'command-input', …(1) ] to deeply equal [ 'command-input', …(2) ]`; this head passes 4/4.
- Real Gateway (`ocx src --node`) with the Telegram plugin, a local Bot API that holds the Stop reply, and a local chat-completions model: on main the follow-up's user row and answer are written before `/stop` / `Agent was aborted.`; here the Stop exchange is recorded first, then the follow-up row and one answer. `/stop` alone behaves the same on both.
- Replay admission still refuses a genuinely out-of-order replay: `attempt-session-replay-cohort.test.ts` (including `completed-after-preparation`), the steering replay test and `abort.test.ts` pass, 48/48.

## Merge danger

Two-way door: no stored data, config or contract change; a revert restores the old ordering. Blast radius: channels that send `/stop` as a message; a hung Stop delivery delays the next turn by at most the existing follow-up admission barrier timeout.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit b42a8ff)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
…Stop reply is delivered late (openclaw#195612)

Root cause: src/auto-reply/reply/dispatch-from-config.prepare-operation.ts:217 (on main 1680f54) the fast-abort path lets Stop cancel and release its own message source at once, while a direct Stop reply records its `/stop` exchange only later, at dispatcher settlement after delivery. A turn accepted while that reply is still being sent persists its user row first, so the Stop exchange lands after it and the follow-up can fail replay admission ("Persisted user turn changed before replay admission") and go unanswered.

Fixes openclaw#194303

Thanks @amittell for the report, the root-cause analysis and this fix. Thanks @arcabotai for openclaw#195358, which reported the same unanswered follow-up; this PR fixes the Stop path at the producer instead of relaxing replay admission.

## What Problem This Solves

Fixes: a message sent right after `/stop` is recorded ahead of the Stop exchange in session history, and can go unanswered, when the Stop reply reaches the channel late.

## User Impact

User impact: after `/stop`, the next message waits until the Stop reply is delivered and recorded, then runs and is answered once, with the Stop exchange first in history. Input already waiting when Stop arrived is still cancelled, as before.

## Why This Change Was Made

Once a stop request is recognized, before Stop selects anything, dispatch retains the Stop message's own source until the Stop reply settles (dispatcher settlement, bounded by the existing follow-up admission barrier timeout). The mailbox does not select past a source with unsettled work, so the next turn starts after the Stop rows. If the abort resolver throws or the message is not handled as a stop, the retention is released immediately.

Unchanged: what Stop cancels, command classification, the command history format, and replay admission (a command row written before a turn still refuses a stale replay). openclaw#194336, openclaw#194396 and openclaw#195358 instead make command exchanges traversable for replay admission, which reverses the `c2cb56c665e` boundary; this PR touches neither replay predicate.

Maintainer edits on top of @amittell's commits: merged current main, rewrote the retention without re-indenting the fast-abort branch (`.catch`/`.finally` instead of `try/finally`), and kept one red-on-base regression (dispatch order) in place of the two test files and the test-lines allocation.

## Evidence

Observed proof lines (base and head): openclaw#195612 (comment)

- Regression `dispatch-from-config.command-transcript.test.ts` > "records a late-delivered /stop before the next turn's row" (active run false/true): main 1680f54 fails 2/2 with `expected [ 'next-turn', 'command-input', …(1) ] to deeply equal [ 'command-input', …(2) ]`; this head passes 4/4.
- Real Gateway (`ocx src --node`) with the Telegram plugin, a local Bot API that holds the Stop reply, and a local chat-completions model: on main the follow-up's user row and answer are written before `/stop` / `Agent was aborted.`; here the Stop exchange is recorded first, then the follow-up row and one answer. `/stop` alone behaves the same on both.
- Replay admission still refuses a genuinely out-of-order replay: `attempt-session-replay-cohort.test.ts` (including `completed-after-preparation`), the steering replay test and `abort.test.ts` pass, 48/48.

## Merge danger

Two-way door: no stored data, config or contract change; a revert restores the old ordering. Blast radius: channels that send `/stop` as a message; a hung Stop delivery delays the next turn by at most the existing follow-up admission barrier timeout.

Co-authored-by: Ayaan Zaidi <[email protected]>

Release adaptation: Add callback to existing abort parameter type; defer Stop transcript through existing dispatcher lifecycle barrier.

(cherry picked from commit b42a8ff)

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant