Skip to content

fix: finish reply recording before resetting sessions - #181105

Merged
roboclaw-bot merged 3 commits into
openclaw:mainfrom
jason-allen-oneal:fix/issue-134498
Oct 23, 2026
Merged

roboclaw-bot merged 3 commits into
openclaw:mainfrom
jason-allen-oneal:fix/issue-134498

Conversation

@jason-allen-oneal

@jason-allen-oneal jason-allen-oneal commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Related: #134498

What Problem This Solves

A canonical session reset can fail after the transport has already accepted a reply. Delivery becoming idle releases lifecycle custody before the transcript mirror and cleanup finish, allowing SqliteSessionMutationConflictError while the accepted reply is being recorded.

User Impact

Session reset waits for the existing recording and cleanup owner. The accepted reply remains durable before the reset boundary and is excluded from the new context. Transcript writer fences and delivery authorization remain unchanged; no new schema, retention policy, or configuration is introduced.

The reported CLI-backed reset/rebind paths and accepted-reply crash boundary have now been exercised on this exact head. Unfinished CLI work is canceled before stale delivery; supported deletion/recreation changes the physical session ID; accepted CLI/model replies already have canonical records before the HTTP acknowledgment. The patch repairs the demonstrated reset/settlement conflict within those existing owners. No new historical append destination or transactional outbox is introduced.

Why This Change Was Made

Registered dispatcher settlement tasks remain joinable until they finish, run once through their existing owner, and participate in the existing lifecycle after-clear barrier. Source-owned events retain their operation until transport settlement before clearing it. No duplicate send or competing persistence owner is added.

Affected low-level test callers now finish the same outer dispatcher settlement lifecycle that the production facade owns. Intermediate producer/transport assertions remain intact.

Evidence

Exact final head: a7f5cc2f35fb2e0254207492149d52d3923c0cbc.

Immutable execution proof, raw logs, receipts, scripts, model/build identity, and SHA256 manifest.

  • Baseline RED → final GREEN through the shipped Gateway: a real loopback HTTP receiver accepts the reply and holds HTTP 200; real sessions.reset is observed waiting in the existing lifecycle owner before HTTP 200 is released. Baseline delivery succeeds with one durable reply, but reset fails SqliteSessionMutationConflictError. The final build completes both RPCs with one physical send and one durable reply before the reset boundary; new-context chat.history excludes it. Baseline receipt, final receipt.
  • Actual agent and model: a separate final-head run removes the synthetic reply resolver and uses the default agent path with existing local Ollama qwen3:0.6b, no cloud fallback. Actual inference produces all three replies; physical HTTP delivery, durable assistant-row recording, reset, and progress after retained-state restart pass. Model receipt, model Gateway log, model identity.
  • Both final lanes stop and restart the built Gateway with retained isolated state, verify prior history and every retained transcript event byte, and repeat the held-receipt/reset overlap afterward. Both Gateway processes exit 0. Build: 148.01s; deterministic runtime: 63.89s; model runtime: 97.11s. Executable hashes and dist/build-info.json bind both runs to the exact final commit.
  • Reported CLI reset/rebind and abrupt crash: the documented CLI backend launches a real Node subprocess that calls local Ollama and holds stdout before finalization. Through the actual originating-channel adapter (direct dispatcher deliberately throws), reset and delete/recreate suppress stale output; recreated physical session IDs differ. A real CLI reply accepted by HTTP has one canonical assistant row while HTTP200 is withheld. After actual Gateway SIGKILL, the fresh Gateway reads that reply through chat.history, preserves every prior canonical event JSON/compressed byte, and delivers/persists a new CLI reply. 117.26s passing receipt.
  • Accepted delivery plus actual replacement: with the default agent/model and originating-channel transport, delete first returns the existing retryable UNAVAILABLE while transport is active, preserving storage. After settlement, delete/recreate changes the physical session ID; the accepted reply remains durable and is excluded from the new context. The same sequence passes after retained-state restart. Receipt. The first fixture's structured-error assertion failure is retained and explained in the proof bundle.
  • Affected consumers: 45/45 passed on the final head across owner settlement, tool-authored transcripts, pending-final dispatch, and pending-final delivery (log, 80.83s). Initial raw-fixture hangs and the intermediate 15-pass/2-timeout result are retained. Completing the fixture's missing settlement lifecycle fixes them; the owner suite also passed 17/17 under a stricter 15s diagnostic bound. No assertions were weakened or timeouts increased.
  • Final-head CI passed, with no failed or pending PR checks at publication (snapshot). Committed real HTTP/SQLite/controller regression covers the reset overlap; dispatcher regression covers concurrent settlement and joinability. Targeted type-aware lint, formatting, and git diff --check passed.
  • Independent Codex autoreview was scoped-clean P0–P2 for the production change. The subsequent test-only migration received its own review; its one failure-cleanup finding was fixed and the final review is scoped-clean (reports and exact test-only delta). Final-head native runs were rebuilt/replayed after that commit; prior-head proof remains separately labeled.

The baseline executable is 2975dedca83e94d3530fdb339077bfe040d1b560; its auto-reply, sessions, and Gateway sources match task base a8ead196291935d24c44a4f40b67397d88c70256. The deterministic baseline and candidate use the same driver bytes. The real-model run is a separate sibling-path proof. All state and prompts are synthetic. Supported physical session replacement and abrupt process death at the accepted CLI reply boundary are proved; real Discord delivery, OOM, raw-database rebinding and arbitrary new outbox/destination policies are not claimed.

@clawsweeper

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

@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR keeps reply recording and cleanup joinable until session lifecycle custody can safely release.

Example: A receiver accepts “ACCEPTED-REPLY-reset-ONLY” while sessions.reset waits for delivery to finish.

  • Before: The reply is recorded, but reset fails with SqliteSessionMutationConflictError.
  • After: Recording finishes before reset commits, with one send and the old reply excluded from the new context.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused existing-owner repair with meaningful regressions, inspected shipped-Gateway evidence, successful exact-head CI, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): Inspected immutable artifacts bind built Gateway runs to the exact head: held real HTTP delivery reproduces baseline reset failure and candidate success; actual agent/model and CLI lanes cover reset, physical replacement, retained-state restart, and SIGKILL after acceptance with canonical records preserved.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Resetting a session while an accepted reply finishes recording can fail with a session mutation conflict.
Reason: The reproduced reset defect is repaired through existing owners; broader historical recording-recovery concerns remain separately linked without being claimed as resolved.

Merge readiness

✅ Ready for maintainer review

This PR fixes a demonstrated session-reset conflict through the existing settlement owner; no actionable findings remain, and exact-head execution evidence and CI support merging.

Priority: P1
Reviewed head: a7f5cc2f35fb2e0254207492149d52d3923c0cbc

Before merge

None.

Findings

None.

Agent review details

How this fits together

Auto-reply dispatch connects agent or command output to transport delivery, transcript recording, and session lifecycle settlement.

flowchart TD
  A[Agent or command reply] --> B[Reply dispatcher]
  B --> C[Transport delivery]
  C --> D[Dispatcher settlement tasks]
  D --> E[Transcript recording and cleanup]
  E --> F[Session lifecycle release]
  F --> G[Session reset]
Loading

Technical review

Best possible solution:

Merge the focused settlement-ordering repair while retaining existing writer fences, transport authority, and the related issue’s separate recovery discussion.

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

Supplied Gateway execution reproduces the baseline reset conflict, and current-main source retains the responsible idle-only release; this review ran no target code.

Is this the best way to solve the issue?

The patch repairs lifecycle custody at its existing owner and preserves operation clearing before settlement, addressing the demonstrated conflict without restoring the earlier queue deadlock.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 87aada17522b.

Provenance checked

  • Dispatcher settlement ownership keeps the original intent (b381559: Move transcript mirroring out of active reply completion to prevent a queued same-session delivery deadlock while retaining one cleanup owner.)
  • Sequential settlement and error preservation keeps the original intent (b5d8778: Run registered settlement tasks sequentially despite delivery or cleanup failure and preserve the original error.)
  • Source-owned event completion keeps the original intent (753a7a5: Retain the originating operation through delivery so reset or replacement cannot redirect delayed event work.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ivan Z: Raw commit b381559 adds src/auto-reply/dispatch-dispatcher.ts:11 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b38155918447; files: src/auto-reply/dispatch-dispatcher.ts)

PR surface

Source +38, Tests +248. Total +286 across 7 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 49 11 +38
Tests 4 261 13 +248
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 310 24 +286

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Canonical reset can fail during accepted reply recording, disrupting an active session workflow.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-23T00:38:12.621Z sha 8c111e3 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-23T01:17:09.001Z sha a7f5cc2 :: needs maintainer review before merge. :: none

Reviewed October 22, 2026, 10:02 PM ET / October 23, 2026, 02:02 UTC (Revision 3).

@jason-allen-oneal

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Exact final head: a7f5cc2f35fb2e0254207492149d52d3923c0cbc. The body now links immutable shipped-Gateway baseline RED/final GREEN receipts, real-agent/local-model delivery-reset-restart evidence, final-head 45/45 affected consumer results, and successful final-head CI. Prior raw-fixture failures and their reviewed test-only repair remain disclosed. The original arbitrary replacement/crash recovery scope remains open.

@clawsweeper

clawsweeper Bot commented Oct 23, 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The exact head remains a7f5cc2f35fb2e0254207492149d52d3923c0cbc. New immutable execution evidence addresses the previously unverified replacement/crash paths: proof matrix and raw artifacts.

A real registered CLI backend invokes the existing local model and holds stdout before finalization. Actual originating-channel delivery is exercised (the direct dispatcher deliberately throws). Both reset and supported delete/recreate suppress stale CLI output, with physical session IDs asserted different. Accepted-originating-channel model delivery plus delete/recreate also passes before and after restart, retaining the old canonical reply and excluding it from new-context history.

At the accepted CLI reply boundary, read-only SQLite proves the canonical assistant row exists while HTTP200 is withheld. Actual Gateway SIGKILL occurs before acknowledgment; a fresh Gateway reads the accepted reply, preserves every retained canonical event JSON/compressed byte, and successfully delivers/persists a new CLI reply. The final combined execution passes in117.26s. These are actual replacement and crash runs, not a reinterpretation of the partial-scope finding.

The PR body now distinguishes the reset-ordering repair from existing durable-before-send behavior established by these runs. No new historical append authority, outbox policy, raw-database rebinding or arbitrary storage-failure claim is made. The failed first replacement fixture and its structured-error correction remain published. Final-head CI remains green, with0 failed/pending checks at the new snapshot. Please assess the remaining linked-issue scope against this concrete matrix; any remaining blocker should identify the uncovered supported path or invariant.

@clawsweeper

clawsweeper Bot commented Oct 23, 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 23, 2026
@sallyom sallyom self-assigned this Oct 23, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merge-ready (on behalf of Sally). Reviewed a7f5cc2f35fb2e0254207492149d52d3923c0cbc: no compatibility issues or breaking changes found. Existing SDK/API contracts and writer fences are preserved; passing exact-head CI, regression evidence, and a fresh independent review support landing.

@roboclaw-bot
roboclaw-bot merged commit 3ac1e62 into openclaw:main Oct 23, 2026
191 of 192 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via squash.

gloss-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 23, 2026
Conflicts:
- queue/recent-message-ids.ts was folded into queue/enqueue.ts upstream
  (openclaw#181498). Its recent-source release now goes through
  releaseBeforeTurnAdoptionRetry there, so a cancelled queued turn also
  forgets its recent message id, as on this branch.
- dispatch-from-config.prepare-context.ts imports: keep
  releaseBeforeTurnAdoptionRetry; waitForReplyDispatcherIdle is no longer
  used after upstream's openclaw#181105.

Semantic: upstream dropped createTwitchIngress's pollIntervalMs option
(openclaw#180700), so the aged-cancelled Twitch test stops passing it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PiKbtQbHKKfq82arnmwBYp
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
Keep reply lifecycle custody until registered transcript recording and cleanup tasks settle, preventing session-reset conflicts after accepted delivery. Preserve post-clear delivery ordering, existing SDK/API contracts, and transcript writer fences.

Co-authored-by: sallyom <[email protected]>
amittell added a commit to amittell/openclaw that referenced this pull request Nov 11, 2026
Branch-native equivalent of upstream openclaw#195612 (head
272d4c6, issue openclaw#194303). Upstream's fix
holds the Stop message's own session-controller source through
trackSessionControllerSourceWork, which comes from openclaw#175837
(36e277d), and waits with waitForReplyDispatcherSettlement from
openclaw#181105 (3ac1e62). Neither is on this branch. Drop this commit when a
release that carries upstream's fix is carried.

The defect on this branch: a fast /stop records its command exchange
(command-input, command-reply) in a dispatcher settled task, after its
reply is delivered and after dispatchReplyFromConfig has returned. The
fast path claims no reply operation, so nothing fences the next turn.
A turn admitted after the Stop, whether a new message or the queued
follow-up whose drain was in flight when Stop cleaned up the queue, can
therefore persist its user row first. The Stop's rows then land in that
turn's replay window, and replay admission refuses it with "Persisted
user turn changed before replay admission".

The fix fences successor admission from the moment a stop request is
recognized until the Stop's exchange is recorded:
- abort.ts: tryFastAbortFromMessage takes an onAbortRequest hook. It
  runs once for a stop request, before Stop selects anything to cancel
  (as upstream).
- dispatch-from-config.prepare-operation.ts: the hook registers the hold
  for the session the exchange is recorded in. After the Stop is handled,
  a dispatcher settled task registered after the transcript mirror's own
  task releases it. Settled tasks run in order, so the release follows
  the mirror, and it also follows a failed delivery. A message that is
  not a handled stop releases at once.
- reply-run-registry.state.ts: holdReplyRunSuccessorAdmissionForCommandExchange
  keeps the hold per session key, bounded by waitForReplyBarrierSettlement
  with the dispatcher's follow-up admission timeout policy, the same bound
  an ordinary reply's delivery barrier uses.
  isReplyRunSuccessorAdmissionBlocked also reports the hold.
- reply-run-registry.registry.ts: waitForReplyRunSuccessorAdmission waits
  for a pending hold before the successor barrier. The registry test reset
  clears holds.
- No change to reply-turn-admission.ts. Its existing successor checks (at
  the loop head and after database admission) now cover the hold.
  Visible turns and queued follow-ups wait for it, and heartbeats skip
  with "active-run", as they do for the successor barrier.
- docs/concepts/queue.md states the hold.

Unchanged: Stop's selection and queue cleanup, command classification,
the transcript contents, the current-turn walk, replay admission and its
refresh, and ordinary messages. Only a recognized stop request
registers a hold.

Tests:
- dispatch-from-config.stop-transcript-order.test.ts (new): a real
  dispatchReplyFromConfig /stop with its delivery held, idle and with an
  active run. The next turn is admitted through admitReplyTurn, the gate
  that visible messages and queued follow-ups share, because this branch
  has no withSessionTurn. It runs in the database-worker project, because
  admission needs the agent database host.
- attempt-session-replay.stop-delivery.test.ts (new, from upstream's
  file): the same /stop, then the next turn's persisted user row, then
  replay with the Stop delivered inside the replay window, for both
  replay readers. The window is afterReplayPreparation in both cases,
  because this branch's withReplaySession does not hand out the manager.
  The fixture has settled history (settledPrefix), as a stopped
  conversation does. A control runs the same next turn with no /stop.
- attempt-session-replay.test-support.ts: upstream's admitUserTurn option.
- Both tests use isReplyRunSuccessorAdmissionBlocked to decide whether to
  release the ack before the next turn writes. That keeps them
  deterministic, where upstream's single-setImmediate probe misses the
  window on this branch: admission here takes longer than one tick.

Proof (M4, Node 26.12.1, pnpm test <file> --maxWorkers=1):
- Red-before, with abort.ts, prepare-operation.ts and the three registry
  files reverted (throwaway commit):
  dispatch-from-config.stop-transcript-order.test.ts 2 failed of 2, both
  "expected [ 'next-turn', 'command-input', ...(1) ] to deeply equal
  [ 'command-input', ...(2) ]". attempt-session-replay.stop-delivery
  2 failed | 2 passed. Both /stop cases throw "Persisted user turn changed
  before replay admission. Retry the turn." (SESSION_WORK_START_CHANGED),
  the issue's refusal, and the two no-/stop controls pass.
- Green: stop-transcript-order 2/2, stop-delivery 4/4.
- Existing tests of the touched files, all passed. They ran one revision
  earlier, which differs only by createDeferredCore's type argument and a
  test row expression:
  attempt-session-replay 46/46, attempt-session-replay-cohort 19/19,
  abort 15/15 + abort.lazy 1/1, abort.acp-boundary 3/3,
  abort.target-owner 30/30; the seven dispatch-from-config fast-abort
  files (acp-abort, binding-activity, owner-settlement, reply-dispatch,
  restart-tombstone, terminal-recovery, reply-scaffolding) 110/110;
  chat.abort-errors 13/13; the six reply-run-registry files 17/17 and
  126/126; the six reply-turn-admission files 59/59.
- Gates: check-line-cap-ratchet --base v2026.11.2 rc 0, run-oxlint on
  the 8 touched .ts files rc 0, check-test-mock-exports --base
  v2026.11.2 rc 0, tsgo:core rc 0, tsgo:test:src rc 0, and
  oxfmt --check on the 10 touched files rc 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M 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.

3 participants