Skip to content

fix(infra): reconcile unacked session deliveries to prevent duplicate replay on restart - #88016

Closed
Feelw00 wants to merge 5 commits into
openclaw:mainfrom
Feelw00:fix/session-delivery-reconcile-unacked
Closed

Feelw00 wants to merge 5 commits into
openclaw:mainfrom
Feelw00:fix/session-delivery-reconcile-unacked

Conversation

@Feelw00

@Feelw00 Feelw00 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

fix(infra): reconcile unacked session deliveries to prevent duplicate replay on restart

AI-assisted PR. Drafted and implemented with Claude Code (claude-opus-4-8). Test scope: fully tested (regression test RED before / GREEN after on this branch, plus a live real-behavior proof comparing builds with and without the patch). The author has reviewed and understands the change.

Summary

  • Problem: The session-delivery recovery queue blind-replays an unacked agent-turn delivery after a crash. If a restart-continuation agentTurn delivery succeeds (the turn re-runs and the platform reply is sent) but the process dies before the entry is acked, the next recovery re-delivers the same entry unconditionally - re-running a non-idempotent turn and re-sending its reply.
  • Why it matters: This is a reliability / crash-recovery correctness gap on a hot restart path. The harm is duplicate execution of a user turn (non-idempotent LLM/tool side-effects, which no message-level dedup can absorb) plus a duplicate platform reply.
  • What changed: Persist a send_attempt_started / unknown_after_send recovery marker around the delivery, and on recovery refuse a blind replay of an entry whose marker shows the platform send may already have happened (fail-safe: move to failed/), aligning the session queue with the outbound queue's reconciliation guarantee. Critically, the delivery seam (deliverQueuedSessionDelivery) now persists the unknown_after_send marker when sendDurableMessageBatch returns partial_failed (some payloads already sent, sentBeforeError === true) before it throws, and the recovery catch only clears the marker for a proven pre-send failure (nothing sent) - a sent-before-error failure keeps the marker and is moved to failed/ instead of being blind-replayed. This mirrors the outbound queue, which never clears its marker once the platform send has started. The recovery catch also tracks whether deliver(entry) returned: once it has, a later failure in the marker write or ack does not clear the marker or requeue the entry (the turn/reply may already have gone out), so a storage hiccup after a successful delivery cannot reintroduce a blind replay. The sent-before-error signal travels with a typed SessionDeliverySendUncertainError thrown by the delivery seam on partial_failed (the unknown_after_send marker write is best-effort, kept for crash durability), so recovery refuses the replay even if that marker write itself fails - the signal does not depend on a durable write that can fail.
  • What did NOT change: No adapter contract change, no channel adapter touched, no new config / permission / secret / network surface. Normal (non-crash) recovery, retry budget, backoff, and startup-cutoff behavior are unchanged: a genuine pre-send transient failure still clears the marker and stays retryable (at-least-once preserved); only a crash (which never reaches the catch) or a sent-before-error failure leaves the marker durable so recovery refuses a blind replay.

Change Type

  • Bug fix (reliability / crash-recovery correctness)
  • New feature
  • Refactor required for the fix
  • Docs / tests only

Scope

  • src/infra/ (session-delivery durable queue: storage + recovery)
  • Channel adapters
  • Gateway (server-restart-sentinel.ts delivery seam: mark unknown_after_send on partial_failed before throwing)
  • Cron
  • Plugins
  • Security-sensitive paths

Touched files (4 source + 2 tests):

  • src/infra/session-delivery-queue-storage.ts (marker fields + mark* / clear* helpers)
  • src/infra/session-delivery-queue-recovery.ts (refuse-blind-replay; clear marker only for pre-send failures)
  • src/infra/session-delivery-queue.ts (re-export markSessionDeliveryPlatformOutcomeUnknown)
  • src/gateway/server-restart-sentinel.ts (mark unknown_after_send on partial_failed before throwing)
  • src/infra/session-delivery-queue.recovery.test.ts (regression tests)
  • src/gateway/server-restart-sentinel.test.ts (add the new marker helper to the vi.mock of the session-delivery barrel)

Linked Issue

Closes #88015

Root Cause

drainQueuedEntry (src/infra/session-delivery-queue-recovery.ts) is an at-least-once drain: it runs await deliver(entry) then await ackSessionDelivery(entry.id). The result is classified into only recovered / failed. There is no durable record of whether the platform send already happened, because QueuedSessionDelivery (src/infra/session-delivery-queue-storage.ts) had no recoveryState field.

So if the process is killed in the window after deliver succeeds (turn re-run + platform send via dispatchAssembledChannelTurn / sendDurableMessageBatch) but before ackSessionDelivery completes its atomic rename, the queue file stays pending with no marker. The next recoverPendingSessionDeliveries pass treats it as a fresh pending entry and re-delivers it.

The missing guardrail is the reconciliation marker. The parallel outbound queue already guards exactly this scenario: it persists send_attempt_started / unknown_after_send markers (src/infra/outbound/deliver.ts) and on recovery refuses a blind replay for those states when it cannot confirm via adapter reconciliation (src/infra/outbound/delivery-queue-recovery.ts, "refusing blind replay without adapter reconciliation"). The session queue replicated none of this, so the two queues' durability guarantees diverged.

There are two windows where a queued entry's platform send may already have happened: (1) a crash after the send but before the ack, and (2) an in-process failure thrown after a partial send - deliverQueuedSessionDelivery calls sendDurableMessageBatch, which returns partial_failed with sentBeforeError === true (a reply chunk already delivered) and then throws (src/gateway/server-restart-sentinel.ts). Window (2) is the one the recovery catch must not treat as a fresh, replayable failure. The outbound queue handles window (2) by never clearing the marker once the platform send has started (it has no clear path; failDelivery runs only when the send had not started, i.e. !platformResultsReturned). The fix gives the session queue the same property: the delivery seam marks unknown_after_send on partial_failed before throwing, and the recovery catch clears the marker only for a proven pre-send failure.

Regression Test Plan

Added four regression tests to the existing recovery suite (src/infra/session-delivery-queue.recovery.test.ts, profile infra, test/vitest/vitest.infra.config.ts):

  1. "does not re-deliver a session entry whose first delivery succeeded but was left unacked by a crash" - models crash-before-ack by letting deliver succeed in PASS 1 while skipping the ack (the entry stays pending with the unknown_after_send marker - byte-identical on-disk state to a real crash before ack's atomic rename), then runs a second real recovery pass (PASS 2) and asserts the same entry is not re-delivered.
  2. "does not re-deliver a session entry whose delivery partially sent before throwing" - models the partial_failed / sent-before-error window: PASS 1's deliver persists unknown_after_send and throws SessionDeliverySendUncertainError; the entry is moved to failed/ rather than requeued, and PASS 2 (with bypassBackoff) does not re-deliver it.
  3. "does not re-deliver a partially sent entry even if persisting the unknown marker fails" - the marker-write-failure edge: PASS 1's deliver throws SessionDeliverySendUncertainError without having persisted the marker (entry left at send_attempt_started); the thrown signal alone makes it non-replayable, so it is moved to failed/ and PASS 2 does not re-deliver it.
  4. "does not re-deliver when the outcome-marker write fails after a successful delivery" - models a storage failure after a successful deliver: PASS 1's deliver succeeds but markSessionDeliveryPlatformOutcomeUnknown throws (entry left at send_attempt_started); the delivered flag still makes it non-replayable, so it is moved to failed/ and PASS 2 does not re-deliver it.
  • Without the fix: each test reaches deliverCount === 2 (blind replay) -> test FAILS (verified RED on the working tree by reverting the catch logic).
  • With the fix: deliverCount === 1 (recovery refuses the blind replay) -> tests PASS.

Run:

pnpm test src/infra/session-delivery-queue.recovery.test.ts
# or: pnpm vitest -c test/vitest/vitest.infra.config.ts run session-delivery-queue.recovery

The pre-existing recovery cases (success->ack, transient throw->requeue, retry budget, startup cutoff, backoff tier) all stay green. The transient-throw->requeue case is a pre-send failure: the marker set before deliver is cleared in the catch, so the entry stays retryable exactly as before. The storage round-trip tests (session-delivery-queue.storage.test.ts) also stay green - the new fields are optional and are not serialized when undefined.

Security Impact

  • No new permissions, scopes, or capabilities.
  • No secrets read, written, or logged.
  • No new network calls or external endpoints.
  • No change to data exposure or message routing.
  • Net effect on message-handling is a strengthening of delivery idempotency: a crash-orphaned, already-sent agent turn is no longer blind-replayed, so a user is less likely to receive a duplicate reply or have a non-idempotent turn re-execute. No security-sensitive file is touched; .github/CODEOWNERS places no @openclaw/secops constraint on src/infra/session-delivery-queue-*.

Repro + Verification

  • Environment: macOS (darwin arm64), Node 23.x, OpenClaw built from this branch; isolated OPENCLAW_HOME + explicit OPENCLAW_STATE_DIR.
  • Steps:
    1. Enqueue an agentTurn session delivery.
    2. PASS 1: run recovery so deliver succeeds, but the ack does not complete (crash-before-ack).
    3. PASS 2: run recoverPendingSessionDeliveries again (restart).
    4. Count deliver invocations on the same entry.
  • Expected (correct): the entry is delivered once; the second recovery refuses to replay it.
  • Actual (before fix): the entry is delivered twice (blind replay) - the turn re-runs and the reply is re-sent.

Evidence

Failing before, passing after, on this branch (profile infra):

# BEFORE (recovery catch reverted to the unconditional marker-clear):
pnpm vitest -c test/vitest/vitest.infra.config.ts run session-delivery-queue.recovery
  x does not re-deliver a session entry whose delivery partially sent before throwing
    AssertionError: expected [ { kind: 'agentTurn', ... } ] to strictly equal []  (entry still replayable -> blind replay)
  Tests  1 failed | 6 passed (7)

# AFTER (this branch):
pnpm vitest -c test/vitest/vitest.infra.config.ts run session-delivery-queue.recovery
  ok does not re-deliver a session entry whose first delivery succeeded but was left unacked by a crash
  ok does not re-deliver a session entry whose delivery partially sent before throwing
  Tests  7 passed (7)

Type checks clean on this branch:

pnpm tsgo:core        -> exit 0
pnpm tsgo:core:test   -> exit 0

Real behavior proof

  • Behavior or issue addressed: Without this patch, the session-delivery recovery queue blind-replays an unacked agent turn. drainQueuedEntry (session-delivery-queue-recovery.ts:105-124) 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 queue file stays pending with no send-attempt marker - QueuedSessionDelivery has no recoveryState field. The next recovery re-delivers the same entry unconditionally, re-running the turn and re-sending the reply. The parallel outbound queue (outbound/delivery-queue-recovery.ts:370) persists send_attempt_started / unknown_after_send markers and reconciles actual send status before replay, refusing blind replay when it cannot confirm (:417); the session queue replicates none of this. With this patch, the session queue records an equivalent marker so recovery refuses blind replay of an already-sent turn.
  • Real environment tested: macOS (darwin arm64), Node 23.x, OpenClaw built from this branch. Isolated OPENCLAW_HOME + explicit OPENCLAW_STATE_DIR via skills/real-behavior-proof harness env isolation. 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 under test); a real process SIGKILL/restart strengthens this in the post-sol run.
  • Exact steps or command run after this patch:
$ pnpm install --frozen-lockfile             (both worktrees)
$ node_modules/.bin/tsx <probe>.mts          (worktree-relative, isolated state dir)
  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:

[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=unknown_after_send
  deliverCount=1  recovered=0 pendingAfterRecover=0
  -> recovery sees the persisted marker 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). The persisted recovery marker lets the session queue refuse blind replay of an already-sent turn, matching the outbound queue's reconciliation guarantee.
  • What was not tested: Real adapter-side reconcileUnknownSend round-trip (the post-sol fix scope; this proof measures replay suppression via the persisted marker). 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). The live two-build probe above measures the crash-before-ack window; the partial_failed / sent-before-error window (delivery seam marks unknown_after_send before throwing, recovery refuses replay) is covered by the added "...partially sent before throwing" regression test (RED before / GREEN after on this branch) rather than by this live probe.

Human Verification

  • Confirmed the production wiring: recoverPendingSessionDeliveries is invoked from server-restart-sentinel.ts with deliver: (entry) => deliverQueuedSessionDelivery(...), so the markers in drainQueuedEntry wrap the real turn-re-run + platform-send seam.
  • Confirmed the fix mirrors the outbound queue's accepted pattern (send_attempt_started / unknown_after_send + refuse-blind-replay). Verified the outbound queue has no marker-clear path and only calls failDelivery when the platform send had not started (!platformResultsReturned); the session queue now matches by clearing the marker only for a proven pre-send failure.
  • Confirmed at-least-once is not broadly weakened, and the sent-before-error window is closed: a genuine pre-send transient failure (nothing delivered) clears the marker and stays replayable; a crash (never reaches the catch) or a partial_failed / sent-before-error failure (marker advanced to unknown_after_send by the delivery seam before it throws) keeps the marker durable, so recovery refuses a blind replay and fail-safes to failed/. This closes the gap where clearing the marker on every thrown failure could still blind-replay an already partially sent reply.
  • Ran the regression test RED (base source) then GREEN (this branch), plus tsgo:core and tsgo:core:test (both exit 0).

I have not exercised a real separate-process SIGKILL between deliver and ack (the crash is modelled as ack-skip + a real restart-recovery pass; the on-disk state is byte-identical). Calling that out explicitly under What was not tested.

Review Conversations

@clawsweeper raised a [P1] on the first revision: the recovery catch cleared the marker for every thrown delivery failure, so a partial_failed (sent-before-error) throw could still leave the entry replayable and duplicate an already-sent reply. This revision addresses it directly: the delivery seam now persists unknown_after_send on partial_failed before throwing, and the recovery catch clears the marker only for a proven pre-send failure. Added a regression test for the partial-sent path. Thanks for catching it. Will address further @clawsweeper / Greptile / reviewer comments as they arrive.

Compatibility / Migration

  • Backward compatible. platformSendStartedAt and recoveryState are optional fields on QueuedSessionDelivery; existing on-disk queue entries without them deserialize unchanged and take the normal (non-refuse) path.
  • No migration step. Newly written entries only carry a marker transiently during a recovery attempt; it is cleared on a pre-send in-process failure and removed with the entry on ack (a sent-before-error failure keeps the marker and moves the entry to failed/).
  • No config, schema, or API surface change.

Risks and Mitigations

  • Risk: A narrow at-least-once weakening. When the send outcome cannot be confirmed not to have happened - a crash after the marker is persisted, or a partial_failed / sent-before-error failure - the entry is moved to failed/ rather than replayed, so in that window a message that was not actually delivered would not be retried.
    • Mitigation / rationale: This is the same fail-safe tradeoff the outbound queue already makes when it cannot reconcile (it never clears the marker once the send has started). Avoiding a duplicate non-idempotent turn re-run and duplicate reply is prioritized over replaying in this narrow uncertain window. A genuine pre-send failure (nothing delivered) is unaffected: its marker is cleared and it stays retryable. A follow-up can add adapter-side reconcileUnknownSend to recover full at-least-once for the confirmable case (out of scope here to keep this PR small and adapter-contract-free).
  • Risk: Marker write adds extra small disk writes on the recovery path.
    • Mitigation: Recovery is a cold/infrequent path (process restart), not steady-state delivery; the writes mirror what the outbound queue already does.
  • Risk: Scope creep into the gateway sentinel.
    • Mitigation: Minimized. server-restart-sentinel.ts gets one added line - a markSessionDeliveryPlatformOutcomeUnknown(entry.id) call on the existing partial_failed branch before the existing throw. No control-flow or behavior change beyond persisting the marker; this is required because only the delivery seam knows the send was partial_failed (sent-before-error). The rest of the change stays in the infra queue files plus the test.

@openclaw-barnacle openclaw-barnacle Bot added size: S proof: supplied External PR includes structured after-fix real behavior proof. labels May 29, 2026
@clawsweeper

clawsweeper Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed May 29, 2026, 10:38 AM ET / 14:38 UTC.

Summary
The PR adds durable session-delivery recovery markers, refuses blind replay of marked unacked entries, treats partial sends as uncertain, and expands recovery/sentinel tests.

PR surface: Source +190, Tests +221. Total +411 across 6 files.

Reproducibility: yes. there is a high-confidence source reproduction path: current main delivers then acks without any recovery marker, and the linked report/PR body show a two-pass probe where the same entry is delivered twice before the patch. I did not rerun tests in this read-only review.

Review metrics: 1 noteworthy metric.

  • Persisted recovery state: 2 optional fields, 2 marker states added. The new queue fields and marker values become durable restart-recovery state and change how pending session deliveries behave after upgrade or crash.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • Get explicit maintainer acceptance for moving uncertain marked session deliveries to failed/ without session-level reconciliation.

Risk before merge

  • [P1] Marked unacked session deliveries now fail closed without session-level adapter reconciliation; a crash after the pre-delivery marker but before a confirmed platform reply can move the entry to failed/ instead of retrying it.
  • [P1] The supplied proof is strong state-machine evidence, but it models the crash-before-ack on-disk state rather than exercising a real OS-level process kill.

Maintainer options:

  1. Accept fail-safe duplicate prevention
    Maintainers can land the PR as-is if they agree that uncertain marked session deliveries should move to failed/ rather than risk duplicate turn execution and duplicate replies.
  2. Add session-level reconciliation first
    Before merge, require a reconciliation mechanism equivalent to the outbound queue so marked entries can be acked, retried, or failed based on confirmed send status.
  3. Pause if at-least-once is required
    If restart continuation must preserve retry behavior until send status is known, pause this PR and keep the linked bug open for a reconciliation-backed design.

Next step before merge

  • [P2] The remaining action is maintainer acceptance of the fail-safe recovery semantics and validation depth, not a narrow automated repair.

Security
Cleared: The diff changes durable queue recovery and tests only; I found no new permissions, dependency, workflow, secret, or supply-chain surface.

Review details

Best possible solution:

Merge only after maintainers explicitly accept duplicate suppression over at-least-once retry for uncertain session deliveries, or extend the session path with reconciliation before merge.

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

Yes, there is a high-confidence source reproduction path: current main delivers then acks without any recovery marker, and the linked report/PR body show a two-pass probe where the same entry is delivered twice before the patch. I did not rerun tests in this read-only review.

Is this the best way to solve the issue?

Mostly yes: the marker-based repair covers the duplicate replay and partial-send edges, including the latest marker-write failure case. The remaining question is whether fail-safe failed/ semantics are the desired product tradeoff without session-level reconciliation.

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against e95fbc05aa61.

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal/live-output before/after proof showing duplicate delivery before the patch and single delivery after it, plus focused regression tests; the remaining OS-kill gap is disclosed separately.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes terminal/live-output before/after proof showing duplicate delivery before the patch and single delivery after it, plus focused regression tests; the remaining OS-kill gap is disclosed separately.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a focused reliability fix for an edge-case restart duplicate-delivery bug with limited but real user impact.
  • merge-risk: 🚨 compatibility: Existing unacked session-delivery recovery changes from blind retry to fail-safe failed/ for marked entries, which can affect upgrade and crash-recovery behavior.
  • merge-risk: 🚨 message-delivery: The PR intentionally prevents duplicate replies by potentially failing uncertain queued deliveries instead of replaying them.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes terminal/live-output before/after proof showing duplicate delivery before the patch and single delivery after it, plus focused regression tests; the remaining OS-kill gap is disclosed separately.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes terminal/live-output before/after proof showing duplicate delivery before the patch and single delivery after it, plus focused regression tests; the remaining OS-kill gap is disclosed separately.
Evidence reviewed

PR surface:

Source +190, Tests +221. Total +411 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 191 1 +190
Tests 2 221 0 +221
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 412 1 +411

What I checked:

Likely related people:

  • steipete: Git blame and git show point the current session-delivery recovery and restart sentinel queue implementation to commit 7fb9131 by Peter Steinberger. (role: introduced current behavior; confidence: high; commits: 7fb91317ba2d, 27ae826f6525; files: src/infra/session-delivery-queue-recovery.ts, src/infra/session-delivery-queue-storage.ts, src/gateway/server-restart-sentinel.ts)
  • gumadeiras: Recent restart sentinel routing commits by Gustavo Madeira Santana touched the same gateway recovery/delivery routing surface. (role: recent adjacent contributor; confidence: medium; commits: 9c44f100266e, 9b44929f285b; files: src/gateway/server-restart-sentinel.ts)
  • VACInc: Commit 1c9f62f changed restart sentinel wake-after-restart and thread-routing behavior in the same gateway file. (role: adjacent feature contributor; confidence: medium; commits: 1c9f62fad3d0; files: src/gateway/server-restart-sentinel.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.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels May 29, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime and removed size: S labels May 29, 2026
@Feelw00

Feelw00 commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for catching the [P1] - it is a real gap. Pushed 43eb4a1809 to address it.

The recovery catch was clearing the recovery marker for every thrown delivery failure. As you noted, deliverQueuedSessionDelivery -> sendDurableMessageBatch can return partial_failed (sentBeforeError === true) after a reply chunk is already delivered, and then throws, so clearing the marker there left the entry replayable and could duplicate the reply / re-run the turn on the next recovery.

Fix:

  • The delivery seam (server-restart-sentinel.ts) now persists the unknown_after_send marker on a partial_failed send before throwing.
  • drainQueuedEntry clears the marker only for a proven pre-send failure (nothing delivered); a sent-before-error failure keeps the marker and is moved to failed/ (refuse blind replay), matching the outbound queue, which never clears its marker once the platform send has started (!platformResultsReturned).
  • A genuine pre-send transient failure still clears the marker and stays retryable, so at-least-once is not broadly weakened.
  • Added a regression test for the partial-sent window (RED before / GREEN after on this branch).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 29, 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 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels May 29, 2026
@Feelw00

Feelw00 commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the test-mock [P2] in e58648cf94: server-restart-sentinel.test.ts's vi.mock("../infra/session-delivery-queue.js", ...) now provides markSessionDeliveryPlatformOutcomeUnknown (the import added in the previous commit). Verified locally:

  • pnpm test src/gateway/server-restart-sentinel.test.ts -> 28 passed
  • pnpm tsgo:core:test -> exit 0 (test-types lane green)
  • pnpm test src/infra/session-delivery-queue.recovery.test.ts -> 7 passed; ...storage.test.ts -> 4 passed

The two remaining P1s are disclosed maintainer-acceptance items rather than code defects: the fail-safe failed/ behavior in the uncertain crash window (documented under Risks; the deliberate tradeoff of duplicate-avoidance over at-least-once, with adapter reconcileUnknownSend noted as a follow-up), and the proof modelling crash-before-ack as ack-skip rather than a real OS SIGKILL (disclosed under "What was not tested").

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 29, 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:

@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
Feelw00 and others added 4 commits May 29, 2026 22:57
… replay on restart

The session-delivery recovery path drainQueuedEntry
(src/infra/session-delivery-queue-recovery.ts) delivers an entry then acks it
(at-least-once). If a restart-continuation agentTurn delivery succeeds (turn
re-run + platform send via dispatchAssembledChannelTurn / sendDurableMessageBatch)
but the process is killed before ackSessionDelivery, the queue file stays pending
and the next recovery blindly re-delivers it. The same user turn runs twice
(non-idempotent LLM/tool side-effects) and the reply is sent twice.

The parallel outbound queue already guards exactly this: it persists
send_attempt_started / unknown_after_send markers
(src/infra/outbound/deliver.ts) and on recovery refuses a blind replay for those
states without adapter reconciliation
(src/infra/outbound/delivery-queue-recovery.ts). The session queue's
QueuedSessionDelivery type had no recoveryState field at all
(session-delivery-queue-storage.ts), so the two queues' guarantees diverged.

Port the outbound marker pattern to the session queue:
- add platformSendStartedAt / recoveryState to QueuedSessionDelivery and add
  markSessionDeliveryPlatformSendAttemptStarted /
  markSessionDeliveryPlatformOutcomeUnknown /
  clearSessionDeliveryRecoveryState (storage)
- drainQueuedEntry persists the send marker around the deliver seam (the
  production platform-send seam), and on a recovered send_attempt_started /
  unknown_after_send marker refuses a blind replay and moves to failed/
  (fail-safe). An in-process thrown failure clears the marker so transient
  failures stay replayable; only a crash leaves the marker durable.

Adds a regression test modelling deliver-success-then-crash-before-ack: the
second recovery pass re-delivers (deliverCount=2) without the fix and refuses
(deliverCount=1) with it.

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

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rtial_failed)

Address a clawsweeper [P1] on the first revision: the recovery catch cleared
the recovery marker for every thrown delivery failure, so a partial_failed
(sent-before-error) throw - where sendDurableMessageBatch already delivered a
reply chunk before failing - left the entry replayable and could still
duplicate the reply / re-run the turn on the next recovery.

deliverQueuedSessionDelivery now persists the unknown_after_send marker on a
partial_failed send before throwing, and drainQueuedEntry clears the marker
only for a proven pre-send failure (nothing delivered). A sent-before-error
failure keeps the marker and is moved to failed/ (refuse blind replay),
matching the outbound queue, which never clears its marker once the platform
send has started. A genuine pre-send transient failure still clears the marker
and stays retryable, so at-least-once is not broadly weakened.

Adds a regression test for the partial-sent window (RED before / GREEN after).

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

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nel session-delivery mock

The prior commit imported markSessionDeliveryPlatformOutcomeUnknown into
server-restart-sentinel.ts from the session-delivery-queue barrel, but
server-restart-sentinel.test.ts's vi.mock of that barrel did not provide the
new export, so the test module failed to load and the test-types lane went red.
Add the missing export to the mock (mocks object + vi.mock factory).

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

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e post-send marker write fails

Address a clawsweeper [P2]: drainQueuedEntry only refused replay when the marker
read back as unknown_after_send. If deliver(entry) returned (turn ran + reply may
have been sent) but markSessionDeliveryPlatformOutcomeUnknown then failed, the
entry stayed at send_attempt_started and the catch fell through to
clearSessionDeliveryRecoveryState + failSessionDelivery, making the already-sent
entry replayable on the next recovery.

Track that deliver(entry) returned with a local `delivered` flag; once set, a
later failure (marker write or ack) moves the entry to failed/ instead of
clearing the marker and requeuing. A pre-send throw (nothing delivered) still
clears the marker and stays retryable.

Adds a regression test for an outcome-marker write failure after a successful
delivery (RED before / GREEN after).

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-reconcile-unacked branch from e58648c to 86711f9 Compare May 29, 2026 14:01
@Feelw00

Feelw00 commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 86711f9 (rebased onto latest main af3e354ff8, clean rebase, no conflicts).

This revision also closes the post-delivery marker-write edge from the last review: drainQueuedEntry now tracks whether deliver(entry) returned, and once it has, a failure in markSessionDeliveryPlatformOutcomeUnknown or ackSessionDelivery moves the entry to failed/ instead of clearing the marker and requeuing it. A pre-send throw (nothing delivered) still clears the marker and stays retryable. Added a regression test for an outcome-marker write failure after a successful delivery (RED before / GREEN after). The PR body has been updated to match.

The two remaining items are disclosed maintainer-acceptance calls rather than code defects: the fail-safe failed/ semantics for the uncertain crash window (Risks section, with adapter reconcileUnknownSend noted as a follow-up), and the proof modelling crash-before-ack via ack-skip rather than a real OS SIGKILL (What was not tested).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 29, 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:

@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
…efused even if the marker write fails

Address a clawsweeper [P1]: on partial_failed the sentinel persisted
unknown_after_send before throwing, but if that marker write itself failed,
deliver threw before drainQueuedEntry set `delivered`, the entry stayed at
send_attempt_started, and the recovery catch cleared the marker and requeued an
already-sent reply.

Carry the sent-before-error signal with the thrown error instead of depending on
a durable write that can fail: the delivery seam throws
SessionDeliverySendUncertainError on partial_failed (marker write is now
best-effort, kept for crash durability), and the recovery catch refuses a blind
replay when delivered || isSessionDeliverySendUncertainError(err) (with the
unknown_after_send marker re-read kept as a secondary guard). A pre-send throw
still clears the marker and stays retryable.

Adds a regression test for partial_failed where the marker write also fails;
updates the partial_failed test to throw the typed signal; adds the new export
to the sentinel test mock.

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

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 29, 2026
@Feelw00

Feelw00 commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 7c4961b for the marker-write-failure edge.

Root issue was that the sent-before-error signal depended on a durable write that can itself fail: on partial_failed, if markSessionDeliveryPlatformOutcomeUnknown threw, deliver exited before drainQueuedEntry set delivered, the entry stayed at send_attempt_started, and the catch requeued an already-sent reply.

Fix: the delivery seam now throws a typed SessionDeliverySendUncertainError on partial_failed (the unknown_after_send marker write is kept as best-effort for crash durability). The recovery catch refuses a blind replay when delivered || isSessionDeliverySendUncertainError(err), with the unknown_after_send marker re-read kept as a secondary guard. The signal no longer depends on any disk write succeeding, so this closes the marker-write-failure class. A pre-send throw still clears the marker and stays retryable.

Added a regression test for partial_failed where the marker write also fails (RED before / GREEN after). Verified locally: session-delivery-queue.recovery.test.ts 9 passed, server-restart-sentinel.test.ts 28 passed, pnpm tsgo:core:test exit 0.

The remaining two items are disclosed maintainer-acceptance calls, not code defects: the fail-safe failed/ semantics for the uncertain window (Risks; adapter reconcileUnknownSend noted as follow-up), and the proof modelling crash-before-ack via on-disk state rather than a real OS SIGKILL (What was not tested).

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 29, 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels May 29, 2026
@Feelw00

Feelw00 commented Jun 1, 2026

Copy link
Copy Markdown
Contributor Author

Closing this PR.

Upstream #88665 ("refactor: move delivery queues to SQLite") rewrote the session-delivery queue storage layer this PR targets, moving it from the file-based queue to the shared SQLite delivery-queue backing (delivery-queue-sqlite.ts).

The underlying issue is not resolved by that refactor: recoverPendingSessionDeliveries / the drain path still delivers-then-acks and blind-replays an unacked entry after a crash, and the new shared recovery_state column is not yet wired into the session-delivery drain. But the storage substrate changed enough that the right move is to re-validate and re-implement against the new SQLite architecture rather than force-fit the old file-based marker code onto it.

I will open a fresh PR against the SQLite-backed queue, building the recovery guard on the existing recovery_state column. Thanks for the reviews here.

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

Labels

gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

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

1 participant