Skip to content

fix(gateway): prevent duplicate final replay after restart - #121507

Merged
obviyus merged 1 commit into
mainfrom
fix/telegram-restart-duplicate
Aug 10, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/telegram-restart-duplicate

Conversation

@obviyus

@obviyus obviyus commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Context: #96242

What Problem This Solves

A final reply could be delivered twice when the gateway stopped after the channel accepted it but before later session cleanup removed its replay marker.

Root Cause and Fix

Delivery custody had divergent owners. Reply dispatch could mark a final as admitted before a durable queue row existed; direct channel adapters could cross platform I/O before core recorded ambiguity; restart recovery then had to infer whether the reply was sent.

Pending-final delivery now records one serialized logical identity. One boundary owns each transition:

  • durable queue publication moves prepared to queued; the durable executor records the batch terminal result
  • the shared channel send lifecycle runs adapter preflight, publishes the durable row, records custody, then invokes the adapter
  • core-managed direct delivery records custody after preparation/hooks and immediately before adapter delivery
  • provider-owned late-routing delivery receives one required internal callback for the first recipient-visible/finalizing request
  • immediate or deferred finalization refines the exact identity to delivered or suppressed
  • restart recovery reads that serialized fact and exact queue owner; it does not reconstruct success from cleanup

The shared durable lifecycle consumes the callback once and removes it from the adapter context, so channel leaf/chunk paths cannot repeat custody writes. Generic reply-dispatcher transitions and three caller-specific completion derivations were deleted.

Identity-less markers from older builds cannot prove whether the platform accepted the final. Restart uses the visible interruption path instead of replaying it; no fabricated identity, duplicate sender, cache, schema, sidecar, or config was added.

Product Contract

Accepted final replies are delivered at most once across restart. Proven pre-send work remains retryable. Ambiguous or partial delivery fails closed with one visible interruption notice; OpenClaw does not rerun the previous model/tool request.

Local Proof

Exact head f1fb7130227:

  • focused channel/durable boundary group: 195/195
  • targeted Oxfmt/Oxlint: clean
  • tsgo:core, tsgo:test:src, tsgo:extensions:test: clean
  • Plugin SDK API baseline and surface checks: clean
  • exact-head local review: patch correct; zero findings, security concerns, maintainer decisions, and next steps

A broader earlier ownership-boundary group covered shared send/queue/lifecycle, Telegram draft/native/durable, and Discord durable/component paths: 285/285. A local mock-gateway restart trace also proved one accepted final, one provider request, and zero recovery model dispatch; a seeded shipped identity-less marker produced one visible interruption and zero replay/model dispatch.

Discord

Command shape (broker secrets omitted):

E2E_DISCORD_PROVIDER_API=openai-completions E2E_DISCORD_CONFIG_PATCH='{"streaming":{"mode":"partial"}}' run-mock-sut-e2e --text 'OPENCLAW_E2E_DRAFTPROOF please run the check and answer' --expect OPENCLAW_E2E_DRAFTPROOF --expect-edit --expect-delete

The real Discord recorder observed the progress/tool draft, its final edit, the persistent final, then draft cleanup.

{"status":"pass","head":"f1fb7130227","discord":{"messages":2,"edits":1,"deletions":1,"timeline":[{"elapsedMs":1535,"kind":"message","textLen":60},{"elapsedMs":7554,"kind":"edit","textLen":23},{"elapsedMs":7971,"kind":"message","textLen":23},{"elapsedMs":8272,"kind":"delete"}],"expectedFinal":"OPENCLAW_E2E_DRAFTPROOF"}}

Telegram

The real-user Telegram doctor check passed. An external inspector paused the exact candidate after Telegram accepted the final and before pending-final cleanup, then sent SIGKILL; the same config and state restarted while the recorder stayed active. The user saw exactly one final and no duplicate, edit, or deletion. The provider received one request, restart issued zero recovery model dispatches, and the gateway reached ready twice.

{"status":"pass","head":"f1fb7130227","telegram":{"sutFinals":1,"duplicates":0,"edits":0,"deletions":0,"providerRequests":1,"recoveryModelDispatches":0,"gatewayReadyEvents":2}}

Diff

  • production: +992 / -499 (net +493) — one serialized delivery-ownership boundary across restart, queue, direct delivery, preview adoption, and deferred finalization
  • tests/support: +1,191 / -203 (net +988) — crash ordering, queue races, command batches, media ownership, transformations, direct delivery, preview adoption, and restart controls
  • generated: +1,466 / -1,466 (net 0) — Plugin SDK API baseline hashes

Maintainer Decision

Accepted: identity-less pending-final markers fail closed with one visible interruption instead of blind replay. Historic state cannot prove whether a channel already accepted the final; at-most-once delivery takes priority over silently duplicating it. This is the named shipped-state bridge. No fabricated identity, migration sender, or compatibility replay path is permitted. Blind replay can duplicate recipient-visible effects and model/tool side effects.

Decision owner: Ayaan Zaidi — APPROVED. For shipped pending-final markers without delivery identities, fail closed with the existing visible interruption. Do not fabricate identities or blind replay; either can duplicate recipient-visible output and re-run model/tool side effects.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling labels Aug 10, 2026
@obviyus
obviyus marked this pull request as ready for review August 10, 2026 08:09
@openclaw-barnacle openclaw-barnacle Bot added size: XL maintainer Maintainer-authored PR labels Aug 10, 2026
@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch from fffe8f3 to 8af9ffd Compare August 10, 2026 08:28
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Aug 10, 2026
@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch from 8af9ffd to 4e26e2b Compare August 10, 2026 08:38
@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: 🦪 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. labels Aug 10, 2026
@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 10, 2026, 6:54 AM ET / 10:54 UTC.

ClawSweeper review

What this changes

The PR records per-final-delivery state across direct and queued channel sends so restart recovery can avoid replaying an already accepted reply.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep open. The source change addresses the prior legacy-marker replay path, but its fail-closed upgrade behavior for existing identity-less session markers needs maintainer confirmation before merge.

Priority: P1
Reviewed head: 1224fe4a77383a016e6f5922e494767a7d29a501
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The repair has meaningful boundary and fault-oriented coverage, with merge readiness blocked by a maintainer policy choice and branch conflict rather than a discrete patch defect.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: This maintainer-authored PR is not subject to the external-contributor proof gate; its body nevertheless reports real fault-injection evidence on an earlier head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is not subject to the external-contributor proof gate; its body nevertheless reports real fault-injection evidence on an earlier head.
Evidence reviewed 4 items Current-main replay behavior: Current main resumes any replayable pending-final marker, including markers without a delivery identity.
Legacy-marker repair: The PR treats missing or empty delivery identities as ambiguous and routes recovery to the visible interruption path rather than replaying the final.
Boundary regression coverage: The updated recovery test covers missing and empty legacy delivery identities, asserts no resumed gateway dispatch, and expects the interruption notice.
Findings None None.
Security None None.

How this fits together

Channel turns create agent reply payloads and send them through direct adapters or the durable outbound queue. Persisted session state is later used by restart recovery to retry, complete, or interrupt a final delivery.

flowchart LR
  A[Inbound channel turn] --> B[Agent final payload]
  B --> C[Persisted delivery identity]
  C --> D{Direct or queued delivery}
  D --> E[Channel platform request]
  E --> F[Delivery state settlement]
  F --> G[Restart recovery]
  G --> H[Retry, complete, or interruption]
Loading

Decision needed

Question Recommendation
Should identity-less pending-final markers from existing installs fail closed with an interruption notice rather than preserve the former automatic replay behavior? Prefer at-most-once delivery: Keep the fail-closed interruption path for legacy markers so an accepted final is never blindly replayed after restart.

Why: This intentionally changes upgrade behavior to prevent duplicate user-visible replies at the cost of not automatically recovering an ambiguous final; source inspection cannot choose that product tradeoff.

Before merge

  • Resolve merge risk (P1) - Existing persisted markers without delivery identities will no longer replay; they produce an interruption notice instead, so maintainers must explicitly accept the at-most-once versus possible missing-final tradeoff.
  • Resolve merge risk (P1) - Production code grows by a net 425 lines across session recovery, queueing, and channel delivery; maintainers should confirm the shared completion owner replaces rather than duplicates prior lifecycle policy.
  • Resolve merge risk (P1) - GitHub reported the branch as conflicted at the supplied snapshot, so it needs conflict resolution and exact-head validation before merge.
  • Complete next step (P2) - The remaining action is maintainer acceptance of an upgrade-policy tradeoff plus conflict resolution, not a narrow automated code repair.
Agent review details

Security

None.

PR surface

Source +502, Tests +979, Generated 0. Total +1481 across 74 files.

View PR surface stats
Area Files Added Removed Net
Source 57 1006 504 +502
Tests 16 1177 198 +979
Docs 0 0 0 0
Config 0 0 0 0
Generated 1 80 80 0
Other 0 0 0 0
Total 74 2263 782 +1481

Review metrics

Metric Value Why it matters
Production versus test LOC production +896/-471 (net +425); tests +1,133/-192 (net +941); generated 0 net The positive production expansion is material for a bug fix and needs owner confirmation that it consolidates delivery custody across the affected paths.

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.

Merge-risk options

Maintainer options:

  1. Confirm the legacy-state policy (recommended)
    Approve the fail-closed interruption behavior for identity-less markers, then resolve conflicts and rerun exact-head recovery and delivery validation.
  2. Retain automatic legacy replay
    Choose the former retry behavior only if duplicate accepted finals are acceptable for upgraded sessions.

Technical review

Best possible solution:

Adopt one canonical delivery-owner state machine, retain the legacy fail-closed interruption, resolve the branch conflict, and revalidate the resulting head across restart recovery plus direct and queued delivery.

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

Yes, from source: current main replays replayable markers without an identity, while the PR's focused recovery test covers that same legacy state and prevents the replay.

Is this the best way to solve the issue?

Unclear pending product direction: recording delivery custody at the send owner is the right architectural layer, but maintainers must approve the fail-closed behavior for older persisted markers.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is not subject to the external-contributor proof gate; its body nevertheless reports real fault-injection evidence on an earlier head.
  • remove rating: 🧂 unranked krab: 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:

  • P1: A restart can duplicate a user-visible final reply in a live channel workflow.
  • merge-risk: 🚨 compatibility: The pending-final session format and behavior of markers written by older builds change.
  • merge-risk: 🚨 message-delivery: The new state machine decides whether a final is retried, suppressed, or replaced by an interruption notice.
  • merge-risk: 🚨 session-state: Restart recovery now depends on serialized delivery identities and terminal states.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is not subject to the external-contributor proof gate; its body nevertheless reports real fault-injection evidence on an earlier head.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Current-main history and blame identify this contributor on the restart-recovery owner module. (role: recent area contributor; confidence: medium; commits: b54fafa2724b; files: src/agents/main-session-restart-recovery-store.ts)

Rank-up moves

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

  • Confirm the legacy-marker fail-closed policy.
  • Resolve the branch conflict and rerun focused exact-head recovery and delivery validation.

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-10T08:46:48.118Z sha 4e26e2bbc5b1c974881a039f918dc6ea8993683d :: found issues before merge. :: [P1] Fail closed legacy pending-final markers
  • reviewed 2026-08-10T09:49:24.897Z sha 9fe5320a08624f3e499f6ca1107855f97b57cb9f :: found issues before merge. :: [P1] Fail closed legacy pending-final markers

@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch from 4e26e2b to a710ab3 Compare August 10, 2026 09:41
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord channel: telegram Channel integration: telegram labels Aug 10, 2026
@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch from a710ab3 to 9fe5320 Compare August 10, 2026 09:43
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 10, 2026
@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch 6 times, most recently from 14c6b7b to 1224fe4 Compare August 10, 2026 10:47
@clawsweeper clawsweeper Bot 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 Aug 10, 2026
@clawsweeper clawsweeper Bot added 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. labels Aug 10, 2026
@obviyus
obviyus force-pushed the fix/telegram-restart-duplicate branch from 1224fe4 to f1fb713 Compare August 10, 2026 11:02
@obviyus
obviyus merged commit 1f75018 into main Aug 10, 2026
133 of 140 checks passed
@obviyus
obviyus deleted the fix/telegram-restart-duplicate branch August 10, 2026 11:12
@steipete

Copy link
Copy Markdown
Contributor

Reverted commit 1f75018 in #121491 because main CI runs 31382622463 and 31383087703 fail five substantive jobs: check-test-types, checks-node-compact-large-2, checks-node-compact-small-7, checks-node-compact-small-9, and checks-node-compact-small-11.

The two state-machine regressions are:

  • pending-final deliveries remain prepared after successful, failed, or suppressed final dispatch instead of reaching their expected terminal state;
  • partial-send queue custody regresses from unknown_after_send to send_attempt_started, losing the durable post-send ambiguity marker.

The same runs also report four Discord/Telegram harness type errors against the new provider-owned delivery custody contract. Please re-land the restart-replay repair once the cross-lane delivery suites and test-type gate are green together.

obviyus added a commit that referenced this pull request Aug 11, 2026
Re-lands the reverted #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
…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]>
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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

2 participants