Repository navigation
fix: finish reply recording before resetting sessions - #181105
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. What this changesThis 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherAuto-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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +38, Tests +248. Total +286 across 7 files. Added test files: 1. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReviewed October 22, 2026, 10:02 PM ET / October 23, 2026, 02:02 UTC (Revision 3). |
|
@clawsweeper re-review Exact final head: |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review The exact head remains 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. |
|
🦞👀 Re-review progress:
|
|
Merge-ready (on behalf of Sally). Reviewed |
|
Merged via squash.
|
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
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]>
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.
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
SqliteSessionMutationConflictErrorwhile 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.
sessions.resetis observed waiting in the existing lifecycle owner before HTTP 200 is released. Baseline delivery succeeds with one durable reply, but reset failsSqliteSessionMutationConflictError. The final build completes both RPCs with one physical send and one durable reply before the reset boundary; new-contextchat.historyexcludes it. Baseline receipt, final receipt.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.dist/build-info.jsonbind both runs to the exact final commit.chat.history, preserves every prior canonical event JSON/compressed byte, and delivers/persists a new CLI reply. 117.26s passing receipt.git diff --checkpassed.The baseline executable is
2975dedca83e94d3530fdb339077bfe040d1b560; its auto-reply, sessions, and Gateway sources match task basea8ead196291935d24c44a4f40b67397d88c70256. 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.