Skip to content

fix(infra): wire session-delivery drain recovery guard onto the shared SQLite recovery_state column - #88885

Closed
Feelw00 wants to merge 1 commit into
openclaw:mainfrom
Feelw00:fix/session-delivery-drain-recovery-state
Closed

Feelw00 wants to merge 1 commit into
openclaw:mainfrom
Feelw00:fix/session-delivery-drain-recovery-state

Conversation

@Feelw00

@Feelw00 Feelw00 commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: The session-delivery recovery queue blind-replays an unacked agent turn after a crash. drainQueuedEntry (src/infra/session-delivery-queue-recovery.ts) runs await deliver(entry) then ackSessionDelivery. If the agent turn re-runs (dispatchAssembledChannelTurn, which can send via the message tool) but the process dies before the ack, the entry stays pending and the next recovery re-delivers it.
  • Why it matters: The same restart-continuation agentTurn runs twice (non-idempotent LLM/tool side effects) and its reply is sent twice. Restart continuations are, by definition, on the crash/restart path.
  • What changed: Wire the shared SQLite recovery_state column (#88665 already added it) into the session drain, at the turn-execution boundary. The deliver seam (server-restart-sentinel.ts) reports onSendAttemptStart right before the agent turn runs, and onSendDeferred if that attempt is merely deferred because the session is busy. drainQueuedEntry persists the marker on onSendAttemptStart and refuses a recovered marked entry (fail-safe move to failed/). On a thrown deliver, a turn that began running is refused even if it threw after sending; a pre-send / busy-deferred / no-op failure stays retryable.
  • What did NOT change: No adapter contract, no channel adapter, no new config / permission / secret / network surface. The recovery_state column itself already exists (#88665). Genuine pre-send failures still retry (at-least-once preserved); the no-op deliver paths (systemEvent / changed-session / no-route) never mark and stay retryable.

Change Type

Bug fix (reliability / crash recovery).

Scope

src/infra/ (session-delivery queue recovery + storage) and src/gateway/server-restart-sentinel.ts (the deliver seam reports the send boundary). No owner-gated paths touched.

Linked Issue

Closes #88015

Root Cause

The session-delivery queue is at-least-once: drainQueuedEntry delivers then acks. There was no durable marker recording that a delivery's turn had begun, so recovery could not distinguish "never ran" from "ran but not yet acked." The parallel outbound queue already guards exactly this with a recovery_state marker and refuses a blind replay on recovery without adapter reconciliation. #88665 moved both queues onto a shared SQLite backing carrying a recovery_state column, but the session-delivery drain neither set nor read it.

Regression Test Plan

Four tests in src/infra/session-delivery-queue.recovery.test.ts (profile: infra), RED before / GREEN after:

  1. does not re-deliver a session entry whose delivery succeeded but ack was interrupted by a crash — the turn runs (signals onSendAttemptStart); the ack throws once; a second recovery pass must not replay it.
  2. refuses to replay an entry recovered while still carrying the send marker — durable send_attempt_started on a pending entry (the cross-restart scenario); recovery refuses (no deliver, moved to failed/).
  3. refuses to replay a turn that sent before throwing (sent-before-error) — the turn signals onSendAttemptStart then throws; recovery must not treat it as pre-send and replay it.
  4. retries a pre-send failure that never started the turn — deliver throws before onSendAttemptStart; the entry stays pending and retryable with no marker (at-least-once preserved).

These exercise the SQLite-backed queue and require Node 24+ (node:sqlite StatementSync.columns), matching the repo CI test lane.

Security Impact

None. No new permission, secret, or network call; no change to data scope or the adapter surface. The only behavioral change is fail-safe refusal of a blind replay on recovery.

Repro + Verification

  • Environment: macOS (darwin arm64), Node 24.x, OpenClaw built from this branch; isolated OPENCLAW_HOME / OPENCLAW_STATE_DIR.
  • Steps: enqueue an agentTurn session delivery, let the turn run (mark) without acking (crash-before-ack), then run recoverPendingSessionDeliveries again.
  • Expected (fixed): delivered once; the recovered marker forces a fail-safe move to failed/.
  • Actual (before fix): delivered twice (turn re-run + reply re-sent).

Evidence

Regression tests RED before / GREEN after (see Regression Test Plan). Local gates on this branch: pnpm build exit 0, typecheck clean, pnpm check exit 0; target tests session-delivery-queue.recovery + .storage + server-restart-sentinel pass on Node 24. The Real behavior proof below measures deliver() invocation count across a crash-before-ack + restart sequence on the SQLite-backed queue.

Human Verification

Compared the rewritten recovery flow against the outbound-queue sibling (src/infra/outbound/delivery-queue-recovery.ts) to confirm the marker/refuse contract matches; confirmed the busy continuation path (which produces a busy-retry response, no durable work) clears the marker so it stays retryable; traced the production caller (recoverPendingSessionDeliveries ← server-restart-sentinel.ts, deliverQueuedSessionDelivery → dispatchAssembledChannelTurn) to place the onSendAttemptStart boundary at the actual turn execution.

Review Conversations

New PR — earlier internal review flagged that clearing the marker on every thrown deliver would let a sent-before-error turn replay; this revision moves the marker to the turn-execution boundary so a turn that began running is refused while genuine pre-send failures stay retryable.

Compatibility / Migration

Backward compatible, no migration. The recovery_state column already exists in the shared delivery-queue schema (#88665); pre-change entries read back with no marker and follow the normal path. A single marker state (send_attempt_started) is used.

Risks and Mitigations

  • Fail-safe over the crash window (intentional tradeoff): a crash in the narrow window after the turn starts running but before the ack moves the entry to failed/ rather than replaying it. This favors no-duplicate over at-least-once for that window — the same product choice the outbound queue makes when it has no reconcile capability. Pre-send failures, busy-deferred attempts, and no-op deliver paths are unaffected (they stay retryable). Mitigation / follow-up: a precise adapter-side reconcileUnknownSend (as the outbound queue has) would let recovery confirm actual send status and replay safely; that is a larger, multi-adapter change kept out of this one-thing-per-PR fix.

Real behavior proof

  • Behavior or issue addressed: Without this patch, the session-delivery recovery queue blind-replays an unacked agent turn after a crash. drainQueuedEntry (session-delivery-queue-recovery.ts) runs await deliver(entry) then ackSessionDelivery. If the process is killed after deliver succeeds (the agent turn re-runs via dispatchAssembledChannelTurn and the platform reply is sent) but before ack, the entry stays pending. The next recovery re-delivers it unconditionally, re-running the turn and re-sending the reply. refactor: move delivery queues to SQLite #88665 moved the delivery queues onto a shared SQLite backing (delivery-queue-sqlite.ts) that already carries a recovery_state column, but the session-delivery drain does not set or read it; the parallel outbound queue (outbound/delivery-queue-recovery.ts) does, reconciling actual send status before replay and refusing blind replay when it cannot confirm. With this patch the session drain wires the existing recovery_state column so it refuses blind replay of an already-sent turn, matching the outbound queue.
  • Real environment tested: macOS (darwin arm64), Node 24.x (node:sqlite StatementSync.columns), OpenClaw built from this branch. Isolated OPENCLAW_HOME + explicit OPENCLAW_STATE_DIR via the real-behavior-proof harness env isolation; the session-delivery queue now lives in the shared state SQLite DB. No external dependencies (no OAuth/LLM/channel calls) - the deliver callback only counts invocations. Production touched: none. The crash is modelled deterministically as deliver-success-then-ack-skip followed by a real recoverPendingSessionDeliveries restart pass (same production recovery code path); a real process SIGKILL/restart strengthens this in the post-sol run.
  • Exact steps or command run after this patch:
$ node_modules/.bin/tsx <probe>.mts          (worktree-relative, isolated state dir, Node 24)
  probe: enqueueSessionDelivery(agentTurn) ->
         PASS 1 deliver(entry) success, SKIP ack   (crash-before-ack model) ->
         PASS 2 recoverPendingSessionDeliveries()   (restart, real recovery path) ->
         count deliver() invocations on the same entry
  • Evidence after fix:

Live Node.js measurement of deliver() invocation count for one unacked agentTurn entry across a crash-before-ack then restart-recovery sequence (SQLite-backed session queue):

[Build A] without this patch (base sha):
  pendingAfterEnqueue=1 pendingAfterCrash=1 recoveryStateAfterCrash=field-absent
  deliverCount=2  recovered=1 pendingAfterRecover=0
  -> same entry delivered twice (blind replay): turn re-run + reply re-sent.

[Build B] with this patch (head sha):
  pendingAfterEnqueue=1 pendingAfterCrash=1 recoveryStateAfterCrash=send_attempt_started
  deliverCount=1  recovered=0 pendingAfterRecover=0
  -> recovery sees the persisted recovery_state and refuses blind replay: delivered once.
  • Observed result after fix: With the patch, deliver() is invoked 1x for the unacked agentTurn (vs 2x without the patch). Wiring the existing shared recovery_state column into the session drain lets it refuse blind replay of an already-sent turn, matching the outbound queue's reconciliation guarantee.
  • What was not tested: Real adapter-side reconcile round-trip (post-sol fix scope; this proof measures replay suppression via the persisted recovery_state). Real OS-level SIGKILL between deliver and ack (modelled here as ack-skip + restart pass; post-sol uses a real forked process restart). Platform-side message dedup inside dispatchAssembledChannelTurn (turn/kernel path out of scope).

AI-assisted: drafted with Claude Code (claude-opus-4-8); fully tested (build + typecheck + Node 24 target tests + real-behavior-proof). Author reviewed and understands the change.

@clawsweeper

clawsweeper Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed June 29, 2026, 6:02 PM ET / 22:02 UTC.

Summary
The PR wires a session-delivery recovery marker into SQLite-backed restart-continuation delivery so recovered already-started agent turns are not blindly replayed after a crash.

PR surface: Source +138, Tests +187. Total +325 across 4 files.

Reproducibility: yes. Source inspection and the supplied terminal proof give a high-confidence path: enqueue an agentTurn, let delivery succeed without completing ackSessionDelivery, then run recovery again and observe current main replay the pending entry.

Review metrics: 1 noteworthy metric.

  • Persistent recovery marker: 1 added session marker state. The PR changes persisted session-delivery recovery semantics, so upgrade behavior and replay/refusal tradeoffs matter before merge.

Stored data model
Persistent data-model change detected: serialized state: src/infra/session-delivery-queue-recovery.ts, serialized state: src/infra/session-delivery-queue-storage.ts, serialized state: src/infra/session-delivery-queue.recovery.test.ts, unknown-data-model-change: src/infra/session-delivery-queue-recovery.ts, unknown-data-model-change: src/infra/session-delivery-queue-storage.ts, unknown-data-model-change: src/infra/session-delivery-queue.recovery.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #88015
Summary: This PR is the active candidate fix for the canonical session-delivery blind-replay issue; related restart-continuation retry and outbound reconciliation work overlaps the area but does not own this bug.

Members:

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

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Move the marker to the afterRecord boundary and add the record/pre-dispatch retry regression.
  • Refresh the branch against current main because GitHub reports a dirty merge state.
  • Get maintainer acceptance for the intentional fail-safe recovery tradeoff.

Risk before merge

  • [P1] The marker currently flips before inbound recording and dispatch setup complete, so a record/pre-dispatch failure can move a retryable continuation to failed without any reply being sent.
  • [P1] Even after the marker-boundary repair, the PR intentionally changes the ambiguous crash window from at-least-once replay to fail-safe refusal; maintainers need to accept that delivery tradeoff.
  • [P1] GitHub reports this PR as dirty/unmergeable against the current base, so the branch needs refresh before merge review can complete.

Maintainer options:

  1. Move Marker After Record (recommended)
    Move the send-attempt marker into dispatchAssembledChannelTurn's afterRecord boundary and add a regression proving record/pre-dispatch failures stay retryable with no marker.
  2. Accept Fail-Safe Semantics
    After the boundary fix, maintainers can intentionally accept that ambiguous crash-window turns move to failed instead of blindly replaying non-idempotent work.
  3. Pause For Reconciliation Design
    If at-least-once behavior must be preserved for ambiguous session deliveries, pause this PR and design adapter-side session-delivery reconciliation instead.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Move the session-delivery send-attempt marker to dispatchAssembledChannelTurn's afterRecord boundary after inbound recording succeeds and before dispatch starts, ensure sendAttempted only becomes true after the marker write succeeds, and add regression coverage for a record/pre-dispatch failure that remains pending with no recoveryState marker.

Next step before merge

  • [P2] A narrow automated repair can move the marker to afterRecord and add the missing regression; maintainer acceptance of fail-safe semantics remains separate.

Security
Cleared: The diff changes infra recovery code and tests only, with no new dependency, workflow, secret, permission, package, or network execution surface found.

Review findings

  • [P2] Move the marker after inbound recording — src/gateway/server-restart-sentinel.ts:326
Review details

Best possible solution:

Use the existing afterRecord boundary after inbound recording succeeds and before dispatch starts, add a regression for record/pre-dispatch failure, then have maintainers explicitly accept fail-safe refusal or pause for adapter reconciliation design.

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

Yes. Source inspection and the supplied terminal proof give a high-confidence path: enqueue an agentTurn, let delivery succeed without completing ackSessionDelivery, then run recovery again and observe current main replay the pending entry.

Is this the best way to solve the issue?

No, not yet. Reusing the shared SQLite recovery_state column is the right bounded direction, but this patch sets the marker before the kernel’s inbound-recording boundary, so the marker must move to afterRecord before the solution is the best fix.

Full review comments:

  • [P2] Move the marker after inbound recording — src/gateway/server-restart-sentinel.ts:326
    This hook runs before dispatchAssembledChannelTurn, but that function still records inbound session before dispatch begins. If recording or pre-dispatch setup throws, sendAttempted is already true and recovery moves the entry to failed even though no reply could have been sent; wire this through the existing afterRecord seam and cover that retryable failure.
    Confidence: 0.87

Overall correctness: patch is incorrect
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 843ad143647e.

Label changes

Label justifications:

  • P2: This is a normal-priority reliability fix for a narrow crash/restart duplicate-turn path with a focused implementation blocker left.
  • merge-risk: 🚨 session-state: The PR changes how persisted session-delivery recovery state controls whether a restarted agent turn is retried or moved to failed.
  • merge-risk: 🚨 message-delivery: The PR changes message-delivery recovery semantics by suppressing blind replay to avoid duplicate platform replies in the crash window.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body includes after-fix terminal proof from an isolated Node 24 checkout showing delivery count drops from 2 to 1 across crash-before-ack recovery on the SQLite-backed queue.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix terminal proof from an isolated Node 24 checkout showing delivery count drops from 2 to 1 across crash-before-ack recovery on the SQLite-backed queue.
Evidence reviewed

PR surface:

Source +138, Tests +187. Total +325 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 142 4 +138
Tests 1 187 0 +187
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 329 4 +325

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/infra/session-delivery-queue.recovery.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-restart-sentinel.test.ts.
  • [P1] node scripts/run-vitest.mjs src/channels/turn/kernel.test.ts.
  • [P1] git diff --check.

What I checked:

  • Root and scoped policy read: Read root AGENTS.md fully plus scoped gateway and outbound guides; the root session-state/message-delivery and best-fix review guidance applies to this PR. (AGENTS.md:1, 843ad143647e)
  • Current main still has deliver-then-ack session recovery: Current main drains by awaiting deliver(entry) and then ackSessionDelivery, with no session-level recovery marker before replaying a pending entry. (src/infra/session-delivery-queue-recovery.ts:103, 843ad143647e)
  • Current main storage lacks a typed session marker: QueuedSessionDelivery on current main contains retry metadata but no typed recoveryState field owned by the session wrapper. (src/infra/session-delivery-queue-storage.ts:59, 843ad143647e)
  • Shared SQLite backing can persist recovery_state: The shared delivery_queue_entries row already inflates and persists recoveryState, so the remaining issue is the session queue’s use of that column. (src/infra/delivery-queue-sqlite.ts:31, 843ad143647e)
  • PR marker placement is before dispatchAssembledChannelTurn: The PR inserts onSendAttemptStart immediately before dispatchAssembledChannelTurn, which is still before the kernel records inbound session and starts dispatch. (src/gateway/server-restart-sentinel.ts:326, a8e7e8c7075b)
  • Kernel already exposes the narrower afterRecord boundary: runPreparedChannelTurn records inbound session, emits record completion, then runs afterRecord before dispatch start; existing tests assert afterRecord is skipped when recording fails. (src/channels/turn/kernel.ts:546, 843ad143647e)

Likely related people:

  • FullerStackDev: Authored the April restart-continuation/session-delivery commits that introduced the central queue path now being repaired. (role: introduced behavior; confidence: high; commits: 0ac81d41b613, 22615506333f, 03addfe9ba59; files: src/gateway/server-restart-sentinel.ts, src/infra/session-delivery-queue-recovery.ts, src/infra/session-delivery-queue-storage.ts)
  • steipete: Authored merged PR 88665, which moved delivery queues to SQLite and added the shared recovery_state backing this PR uses. (role: recent storage refactor contributor; confidence: high; commits: 1af4c035e4bc; files: src/infra/delivery-queue-sqlite.ts, src/infra/session-delivery-queue-storage.ts)
  • joshavant: Authored recent restart-sentinel internal-continuation work in the gateway file that owns the delivery seam. (role: recent adjacent contributor; confidence: medium; commits: 584fa3215c19; files: src/gateway/server-restart-sentinel.ts)
  • byungskers: Reviewed this PR’s fail-closed direction and requested retryable marker-clearing coverage that shaped the current patch. (role: reviewer; confidence: medium; files: src/infra/session-delivery-queue-recovery.ts, src/infra/session-delivery-queue.recovery.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-06-21T08:22:44.941Z sha a8e7e8c :: needs changes before merge. :: [P2] Move the marker to the post-record boundary

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 1, 2026
@byungskers

Copy link
Copy Markdown

This fail-closed direction makes sense to me for the duplicate-send risk. I do think one extra regression would strengthen it: a case where deliver() throws before returning, and recovery confirms the marker was cleared so the entry stays retryable on the next pass. The new tests cover the post-deliver/ack-interrupted path and the durable recovered-marker path, but not the intended pre-send retry path that now depends on clearSessionDeliveryRecoveryState().

@Feelw00
Feelw00 force-pushed the fix/session-delivery-drain-recovery-state branch from ce765f0 to 501944c Compare June 1, 2026 04:48
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M and removed size: S proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Jun 1, 2026
@Feelw00

Feelw00 commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed the [P1] marker-clearing finding in 501944c50a.

[P1] Keep the send marker when delivery may have thrown after sending — fixed. The marker is no longer set up front and cleared on every thrown deliver. Instead the deliver seam (deliverQueuedSessionDelivery in server-restart-sentinel.ts) reports the send boundary to recovery: it calls onSendAttemptStart right before dispatchAssembledChannelTurn (the agent turn that can send via the message tool), and onSendDeferred only if that attempt is busy-deferred (the busy turn produces a busy-retry response, no durable work). drainQueuedEntry persists the marker on onSendAttemptStart and refuses — fail-safe moveToFailed — a recovered marked entry, or a thrown deliver whose turn began running. So a turn that sent before throwing is no longer cleared and replayed. A genuine pre-send failure, a busy-deferred attempt, or a no-op deliver path (systemEvent / changed-session / no-route) never marks and stays retryable, preserving at-least-once. Added regression coverage for a turn that sends before throwing and for a pre-send failure that stays retryable.

[P1] At-most-once tradeoff for the crash window — agreed, and intentional. It is documented under Risks and Mitigations and is now scoped to the narrow window after the turn starts but before ack; pre-send / busy / no-op cases stay retryable. A precise adapter-side reconcileUnknownSend (as the outbound queue has) is noted as a larger, multi-adapter follow-up rather than part of this one-thing-per-PR fix.

On the two red checks (check:architecture deprecated-JSDoc guard on src/channels/message/types.ts:408, and prompt:snapshots:check): both are in files this PR does not touch and reproduce on current main. This diff is the three src/infra/session-delivery-queue-* files plus the server-restart-sentinel.ts seam.

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@Feelw00
Feelw00 force-pushed the fix/session-delivery-drain-recovery-state branch from 501944c to 4a7a072 Compare June 1, 2026 04:56
@Feelw00

Feelw00 commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @byungskers — added in 4a7a072873. Two regressions now cover the retryable-on-throw paths: retries a pre-send failure that never started the turn (marker never set) and clears the send marker and stays retryable when the attempt is busy-deferred (the clearSessionDeliveryRecoveryState() path you pointed at).

Note: since your review the clearing was moved out of the generic thrown-deliver catch (which would have replayed a sent-before-error turn) — the marker is now set at the turn-execution boundary, cleared only on a busy-deferred attempt, and a turn that began running is refused.

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 1, 2026
…its turn has run

The session-delivery recovery path drainQueuedEntry
(src/infra/session-delivery-queue-recovery.ts) delivers an entry then acks it
(at-least-once). If the agent turn re-runs (dispatchAssembledChannelTurn, which can
send via the message tool) but the process dies before ack, the entry stays pending
and the next recovery blind-replays it: the same turn runs twice (non-idempotent
LLM/tool side effects) and its reply is sent twice.

openclaw#88665 moved both delivery queues onto a shared SQLite backing with a recovery_state
column; the parallel outbound queue uses it to refuse a blind replay without adapter
reconciliation, but the session-delivery drain neither set nor read it.

Wire recovery_state into the session drain at the turn-execution boundary so the
refuse decision is precise:
- The deliver seam (server-restart-sentinel.ts) reports onSendAttemptStart right
  before the agent turn runs, and onSendDeferred if that attempt was merely deferred
  because the session was busy (the busy turn produces a busy-retry response, no
  durable work). The no-op deliver paths (systemEvent / changed-session / no-route)
  never run the turn and report neither.
- drainQueuedEntry persists the send marker on onSendAttemptStart (and clears it on
  onSendDeferred). A recovered entry still carrying the marker is refused (fail-safe
  moveToFailed). On a thrown deliver, a turn that began running (sendAttempted) is
  refused even if it threw after sending, while a pre-send / busy-deferred / no-op
  failure stays retryable (at-least-once preserved for genuine pre-send failures).

This matches the outbound queue's no-reconcile contract and addresses the
sent-before-error case (a turn that sends then throws is no longer cleared and
replayed). Tradeoff: a crash in the narrow window after the turn starts but before
ack moves the entry to failed/ rather than replaying it (fail-safe over at-least-once),
the same product choice the outbound queue makes without a reconcile capability.

Adds regression tests: crash-before-ack, recovered-marker refuse, sent-before-error
throw refuse, and pre-send failure stays retryable.

AI-assisted: drafted with claude code (claude-opus-4-8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Feelw00
Feelw00 force-pushed the fix/session-delivery-drain-recovery-state branch from 4a7a072 to a8e7e8c Compare June 19, 2026 05:48
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 19, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 🛠️ actively grinding The PR author has acted after the latest ClawSweeper review and work remains. 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. status: 🛠️ actively grinding The PR author has acted after the latest ClawSweeper review and work remains. labels Jun 19, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 20, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: session-delivery recovery blind-replays an unacked agent turn after a crash (duplicate turn re-run + duplicate reply)

2 participants