Skip to content

fix(gateway): prevent restart replay after final delivery - #121908

Merged
obviyus merged 1 commit into
mainfrom
reland/restart-replay-custody
Aug 11, 2026
Merged

obviyus merged 1 commit into
mainfrom
reland/restart-replay-custody

Conversation

@obviyus

@obviyus obviyus commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Re-lands #121507 (reverted in #121491, commit 0d4e9f3): a Gateway restart between preparing a final reply and confirming its delivery could replay a final the recipient already received. This PR records per-delivery custody for pending finals so restart recovery replays only proven-unsent finals and fails closed (visible interruption, no blind replay) on ambiguous evidence.

Why This Change Was Made

The original merge broke main (5 CI jobs) and was reverted. Root causes, fixed here:

  1. Pending-final deliveries never reached terminal state. The design intended the reply dispatcher to own direct-send custody, but that state machine was never implemented — markers stayed prepared forever after successful, failed, or suppressed dispatch. The dispatcher now claims custody before provider I/O (prepared→queued; a terminal or replaced marker cancels the send instead of duplicating it), settles delivered on success, restores prepared on proven no-send failures, and fails closed to unknown on ambiguous ones. Suppression is recorded before cancellation observers run.
  2. The original PR reverted main's provider-owned custody contract. It consumed onPlatformSendDispatch in core and stripped it from channel send params; main (via the re-landed seam) passes it through so transports claim custody immediately before wire I/O. This re-land keeps main's contract; markDeliveryPlatformSendDispatched's unknown_after_send preserve-guard (landed post-revert) stays authoritative, fixing the partial-send custody regression from the first attempt.
  3. Four Discord/Telegram harness type errors against the provider-owned delivery contract, fixed with the same wrap the original PR used in bot.test-helpers.ts but missed at four sites.

Custody transitions accept ["prepared", "queued"] where the durable queue or turn lifecycle may run after a dispatcher claim, so each boundary keeps exactly one authoritative writer.

User Impact

After a Gateway restart mid-reply, users no longer receive the same final answer twice. If delivery evidence is ambiguous, recovery shows a visible interruption instead of silently replaying. No configuration changes.

Evidence

  • All five originally failing CI jobs reproduced and fixed locally (see PR checks for the exact-head run):
    • check-test-types: green, including the four harness errors from the revert rationale.
    • dispatch-from-config.reply-dispatch.test.ts (10 failures): green, with the original write-count expectations intact.
    • before-deliver.test.ts (5 custody failures): green — dispatcher custody state machine implemented.
    • deliver.queue-integration.test.ts (2 unknown_after_send failures): green under main's preserve-guard.
    • heartbeat-runner.ack-token-heartbeat-acks.test.ts: green — provider-owned callback pass-through preserved.
  • Grouped run over src/auto-reply/reply, src/infra/outbound, src/channels/turn, src/agents/main-session-recovery, extensions/telegram, extensions/discord: green.
  • pnpm tsgo:core, pnpm check:test-types, pnpm plugin-sdk:api:gen + surface check: green.

Production LOC +978/−473 (net +505, the custody state machine and fail-closed recovery paths); tests +1719/−361.

@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@obviyus
obviyus marked this pull request as ready for review August 11, 2026 06:47
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: telegram Channel integration: telegram commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 11, 2026
@obviyus
obviyus force-pushed the reland/restart-replay-custody branch from e6776cf to 931c3ec Compare August 11, 2026 06:53
@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Aug 11, 2026
@clawsweeper

clawsweeper Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 11, 2026, 3:01 AM ET / 07:01 UTC.

ClawSweeper review

What this changes

The PR records durable per-delivery ownership for final replies across Gateway recovery, queues, and Telegram/Discord sends so restart recovery does not replay an already accepted final.

Regression provenance

Possible regression — probable (reviewed change; known regression link). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open: current main has a source-proven restart replay window, and the PR targets the correct custody boundary. Its high-risk persisted-state and channel-delivery changes still need exact-head CI diagnosis and maintainer review before landing.

Priority: P1
Reviewed head: 931c3eca62402d16506b941732016175f40d5298

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The source-proven bug and intended owner boundary are strong, but the large exact-head re-land remains uncertain until its failed and pending validation complete.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository state identifies the author as a member, so the external-contributor proof gate does not apply; nevertheless, no usable exact-head restart artifact was supplied.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository state identifies the author as a member, so the external-contributor proof gate does not apply; nevertheless, no usable exact-head restart artifact was supplied.
Evidence reviewed 7 items Current marker lacks delivery custody: Current main persists a replayable final with text, intent, context, and timestamp but no per-delivery state.
Current recovery blindly replays: Every replayable pending final is resumed with its pending delivery text, including when transcript loading fails.
Current cleanup is post-send: Pending-final cleanup runs after routed or queued delivery settlement, leaving a crash window after platform acceptance.
Findings None None.
Security None None.

How this fits together

An agent final is marked recoverable before delivery, then routed through a channel or outbound queue to the recipient platform. Restart recovery reads that session state to decide whether to retry or stop the interrupted run.

flowchart LR
  A[Agent final reply] --> B[Pending final marker]
  B --> C[Reply dispatcher]
  C --> D[Channel or outbound queue]
  D --> E[Platform send]
  E --> F[Durable delivery settlement]
  B --> G[Restart recovery]
  F --> G
  G --> H[Retry or visible interruption]
Loading

Before merge

  • Resolve merge risk (P1) - The re-land changes persisted pending-final state and recipient-visible send timing across direct and queued paths; its exact-head CI still has one failed compact shard and many unfinished checks.
  • Resolve merge risk (P1) - The supplied diff adds an SDK-facing outbound context field and regenerates the plugin SDK baseline, so third-party channel compatibility needs the intended contract confirmed.
  • Resolve merge risk (P1) - No exact-head restart fault trace is attached; the prior PR's Telegram proof is useful background but does not demonstrate this reworked branch.
  • Complete next step (P2) - This maintainer-owned, protected-label re-land changes delivery and persisted recovery state; it needs human review of exact-head validation rather than an automated repair lane.
Agent review details

Security

None.

PR surface

Source +525, Tests +1338, Generated 0. Total +1863 across 77 files.

View PR surface stats
Area Files Added Removed Net
Source 59 1008 483 +525
Tests 17 1452 114 +1338
Docs 0 0 0 0
Config 0 0 0 0
Generated 1 237 237 0
Other 0 0 0 0
Total 77 2697 834 +1863

Review metrics

Metric Value Why it matters
Production vs test delta production +978/-473 (net +505); tests +1719/-361 (net +1358) This is substantial production growth for a bug repair and needs the ownership-boundary proof claimed in the PR body.
Persisted delivery-state surface 1 pending-final record extended with per-delivery state Recovery behavior for existing session state changes, so upgrade and identity-less-marker behavior must be validated.
Plugin SDK contract surface 1 outbound poll context callback added The generated SDK baseline changes alongside a public channel outbound context type.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/sessions.test.ts, serialized state: src/config/sessions/store-entry-shape.ts, serialized state: src/config/sessions/types.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #121908
Summary: This PR is the current re-land of the restart-final-replay repair after the earlier implementation was reverted.

Members:

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

Merge-risk options

Maintainer options:

  1. Finish exact-head custody proof (recommended)
    Diagnose the failed shard, complete exact-head CI, and provide a restart fault-injection trace covering accepted, proven-unsent, and ambiguous final deliveries before merge.

Technical review

Best possible solution:

Keep one canonical per-delivery custody record, transition it before platform I/O, and prove on the exact head that accepted finals are never replayed while proven-unsent finals remain retryable.

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

Yes, from current source: persist a replayable final, let the platform accept it before settlement returns, then restart; recovery unconditionally resubmits that marker.

Is this the best way to solve the issue?

Yes in approach: a durable fact at the send boundary is the only way to close the crash window; a cleanup-only change remains too late. Full exact-head branch inspection was limited by unavailable promisor blobs and GitHub DNS.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2ae316e2f33d.

Labels

Label changes:

  • add P1: Current main can replay a final after a Gateway restart when the platform accepted it before pending-final cleanup.
  • add merge-risk: 🚨 compatibility: It changes an SDK-facing outbound context and the handling of older pending-final records.
  • add merge-risk: 🚨 message-delivery: The PR changes the durable ownership transition immediately before recipient-visible Telegram and Discord sends.
  • add merge-risk: 🚨 session-state: It extends persisted pending-final session records and alters restart-recovery decisions.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository state identifies the author as a member, so the external-contributor proof gate does not apply; nevertheless, no usable exact-head restart artifact was supplied.

Label justifications:

  • P1: Current main can replay a final after a Gateway restart when the platform accepted it before pending-final cleanup.
  • merge-risk: 🚨 message-delivery: The PR changes the durable ownership transition immediately before recipient-visible Telegram and Discord sends.
  • merge-risk: 🚨 session-state: It extends persisted pending-final session records and alters restart-recovery decisions.
  • merge-risk: 🚨 compatibility: It changes an SDK-facing outbound context and the handling of older pending-final records.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository state identifies the author as a member, so the external-contributor proof gate does not apply; nevertheless, no usable exact-head restart artifact was supplied.

Evidence

What I checked:

Likely related people:

  • obviyus: Authored the related merged delivery-custody implementation and the current re-land. (role: prior implementation author and current re-land author; confidence: high; commits: 1f75018600a0, 931c3eca6240; files: src/agents/main-session-recovery/main-session-restart-recovery-store.ts, src/infra/outbound/delivery-completion.ts)
  • Paul Campbell: Current recovery replay and pending-final settlement lines blame to the available main-history boundary commit. (role: current-main area contributor; confidence: medium; commits: 6bd83561ad50; files: src/agents/main-session-recovery/main-session-restart-recovery-store.ts, src/auto-reply/reply/dispatch-from-config.pending-final.ts)
  • Peter Steinberger: Recent current-main history includes session and reply-delivery changes adjacent to the affected paths. (role: recent adjacent contributor; confidence: low; commits: 27be68d2d13a, 5f562e65f684; files: src/agents/pending-final-delivery-marker.ts, src/auto-reply/reply/agent-runner-result-complete.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Diagnose the failing exact-head compact shard and complete the required check set.
  • Add a redacted restart fault trace showing one accepted final, zero replayed final, and the ambiguous-delivery interruption path.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

@obviyus
obviyus force-pushed the reland/restart-replay-custody branch 4 times, most recently from 825f8d8 to e16a790 Compare August 11, 2026 07:22
Record channel delivery custody before recipient-visible sends so restart recovery cannot duplicate accepted finals.

Ambiguous legacy markers now fail closed with a visible interruption instead of blind replay.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus
obviyus force-pushed the reland/restart-replay-custody branch from e16a790 to f9bbdec Compare August 11, 2026 07:27
@obviyus
obviyus merged commit 210aca6 into main Aug 11, 2026
119 checks passed
@obviyus
obviyus deleted the reland/restart-replay-custody branch August 11, 2026 07:40
@obviyus

obviyus commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

Landed via 210aca6 with all five originally failing jobs green on the exact head.

Final-head proof (f9bbdec84c5):

  • ClawSweeper local review: patch correct, 0 findings, security cleared.
  • Exact-head openclaw/ci-gate: success.
  • Live Telegram E2E (real QA user, mock provider): one turn sent, exactly one final reply observed (OPENCLAW_E2E_OK, botApiMessageId 836, 2.9s), zero edits/deletions/duplicate sends. Recorded event stream, gateway log, and provider request log retained.

obviyus added a commit that referenced this pull request Aug 11, 2026
…ptions

#121908 (210aca6) added the onPlatformSendDispatch options bag to
final draft-stream updates and updated draft-failures-progress.test.ts,
but missed 19 sibling assertion sites across 6 dispatch test files.
Those files do not currently execute in any CI lane, so main's local
dispatch suite has been red since. Two remaining failures
(context-recovery session-target prefix, draft-failures-progress
preview shape) predate #121908 and are tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 12, 2026
…21908)

Re-lands the reverted openclaw#121507 on the current custody contracts. The reply dispatcher now owns direct-send pending-final custody: claim before provider I/O, terminal settlement for delivered/suppressed/failed outcomes, proven no-send stays replayable, ambiguous evidence fails closed — so Gateway restarts can no longer duplicate an already-accepted final reply.

Proof: ClawSweeper local review clean, exact-head ci-gate green, live Telegram E2E (one turn, one final, no duplicates).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 12, 2026
…ptions

openclaw#121908 (d5a4097) added the onPlatformSendDispatch options bag to
final draft-stream updates and updated draft-failures-progress.test.ts,
but missed 19 sibling assertion sites across 6 dispatch test files.
Those files do not currently execute in any CI lane, so main's local
dispatch suite has been red since. Two remaining failures
(context-recovery session-target prefix, draft-failures-progress
preview shape) predate openclaw#121908 and are tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: discord Channel integration: discord channel: telegram Channel integration: telegram commands Command implementations docs Improvements or additions to documentation maintainer Maintainer-authored PR 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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.

1 participant