Skip to content

fix(outbound): prevent remote gateway duplicate sends - #128202

Merged
obviyus merged 1 commit into
mainfrom
t3code/remote-gateway-queued-send
Aug 23, 2026
Merged

obviyus merged 1 commit into
mainfrom
t3code/remote-gateway-queued-send

Conversation

@obviyus

@obviyus obviyus commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Follow-up to #124310 (issue #124279). That fix dead-letters caller-owned proven-not-sent durable rows so the model's resend is the only retry. It only applies when the gateway can see that the caller is an agent run (runtimeAgentId). In remote Gateway mode (gateway.mode: "remote" or a gatewayUrl/gatewayToken override) the agent runtime deliberately mints no runtime identity, so the gateway keeps the row replay-eligible and returns the error to the model — two retry owners, one duplicate send.

Approach

Queue stays the single retry owner; the model is told so.

  • deliver-queue-execute.ts: the executor already decides which rows stay replay-eligible. When a proven-not-sent failure keeps the row, it marks the thrown OutboundDeliveryError with recoveryOwnedRetry.
  • gateway/server-methods/send.ts: message.action maps that marker to additive UNAVAILABLE details { code: "OUTBOUND_DELIVERY_QUEUED" } (new closed-union member in @openclaw/gateway-protocol; Swift/Kotlin regenerated). No trust-boundary or method change.
  • message-tool-execution.ts: the message tool turns that error into a non-throwing result — status: "delivery_queued", delivered: false, "not delivered … the gateway queued it and will retry automatically. Do not resend it." — and keeps the autogenerated idempotency-key mapping, so a model that resends the same content anyway hits the gateway's cached result for that key instead of creating a second durable send.

Unstructured UNAVAILABLE errors still throw; in-process and identity-bearing RPC paths are unchanged (#124310 still dead-letters those rows).

Validation

  • git diff --check, node scripts/check-changed.mjs, pnpm protocol:check, pnpm check:test-types: green.
  • Focused vitest (src/infra/outbound, src/gateway/server-methods/send.test.ts, src/agents/tools/message-tool-execution.test.ts, src/agents/tools/message-tool.test.ts, packages/gateway-protocol): 78 files / 1267 tests pass.
  • New tests: executor marks proven-not-sent failures; message.action emits the details code only for queue-owned retries; message tool returns the queued result, reuses the idempotency key on an identical resend, and still throws for unstructured unavailability; protocol schema accepts the new details member.

Telegram E2E (real Telegram, remote-gateway path, fault injection)

$telegram-e2e-userbot outbound-duplicate-send recipe, remote variant: the SUT runs from the checkout with OPENCLAW_GATEWAY_URL/OPENCLAW_GATEWAY_TOKEN set, so the in-process agent's message tool resolves the loopback gateway as a remote target and mints no runtime identity (the exact gap). A controllable Bot API proxy closes its data listener before the first send (ECONNREFUSED, proven-not-sent) and reopens before the model's next turn. The mock model honors a delivery_queued tool result like a real model would (no resend); otherwise it retries with a _RETRY marker. DM to the SUT bot, recorded by the QA user account via TDLib.

build first tool output model turn 2 recipient-visible SUT texts
origin/main @ 93c36f5 (includes #124310) OutboundDeliveryError: Network request for 'sendMessage' failed! (raw error) resends …_RETRY OPENCLAW_E2E_DUPSEND_PROBE_RETRY, then OPENCLAW_E2E_DUPSEND_PROBE replayed by Outbound delivery retry: drained delivery … → duplicate
this PR @ 664776d {"status":"delivery_queued","delivered":false,"message":"Message not delivered: … The gateway queued it and will retry automatically. Do not resend it."} DUPSEND_QUEUED_ACK (no resend) exactly one OPENCLAW_E2E_DUPSEND_PROBE, delivered by the drain after the proxy came back → single send

Fixed-run gateway log: ⇄ res ✗ message.action 5462ms errorCode=UNAVAILABLE … for the first call, then Outbound delivery retry: drained delivery 12c6cf0a-… on telegram; proxy transitions up → down (20.8s) → up (26.4s). Affected-run proxy log shows four sendMessage calls (draft, _RETRY, DUPSEND_TURN_DONE, replayed probe); fixed-run shows three (draft, ack, one probe).

Notes

  • message-tool-execution.ts sits at the 700-line lint cap; two single-use helpers were collapsed (normalizeOptionalString(value)?.replace(...), inline Set literal) to make room. Behavior unchanged.

@clawsweeper

clawsweeper Bot commented Aug 23, 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 app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Aug 23, 2026
Follow-up to #124310 for #124279. When the agent runtime talks to a remote
Gateway it mints no runtime identity, so the gateway keeps a proven-not-sent
durable row replayable and also returns the error to the model, which resends.

- executor marks proven-not-sent OutboundDeliveryError as recoveryOwnedRetry
- message.action maps that marker to additive UNAVAILABLE details
  { code: "OUTBOUND_DELIVERY_QUEUED" }
- message tool returns a non-throwing "not delivered, queued, do not resend"
  result and keeps the autogenerated idempotency key mapping so a resend of
  the same content hits the gateway's cached result instead of a second send
@obviyus
obviyus force-pushed the t3code/remote-gateway-queued-send branch from 664776d to 42884c4 Compare August 23, 2026 12:06
@obviyus
obviyus merged commit 500c9b4 into main Aug 23, 2026
224 of 226 checks passed
@obviyus
obviyus deleted the t3code/remote-gateway-queued-send branch August 23, 2026 12:14
@clawsweeper clawsweeper Bot added mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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 23, 2026
@clawsweeper

clawsweeper Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 23, 2026, 8:14 AM ET / 12:14 UTC.

ClawSweeper review

What this changes

Adds a queued-delivery Gateway error so remote message-tool sends tell the model not to resend while the durable queue retries.

Merge readiness

⛔ Blocked by patch quality or review findings - 8 items remain

Keep open. The PR’s process-local idempotency cache does not prevent a second durable queue row after Gateway restart, expiry, or eviction, so duplicates can still drain; its queued-result parser also accepts the marker on non-UNAVAILABLE errors.

Priority: P1
Reviewed head: 42884c4161cd0619338c921e097bced326af1c8c

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The intended retry-owner design is sound, but the current patch leaves a cache-loss duplicate path and an overbroad error projection.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: This maintainer-authored PR is exempt from the contributor proof gate, but its stated Telegram scenario does not cover Gateway restart or cache eviction and should be refreshed on the final head.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the contributor proof gate, but its stated Telegram scenario does not cover Gateway restart or cache eviction and should be refreshed on the final head.
Evidence reviewed 6 items Process-local cache: Gateway idempotency state is an in-memory Map and is pruned after five minutes or when it exceeds 1,000 entries.
Durable ownership contract: Queue reuse is keyed by deliveryIntentId; without it, admission creates a fresh durable delivery.
Remote Telegram producer: The gateway-owned Telegram action forwards deliveryRetryOwner but no stable delivery intent to its durable sender.
Findings 2 actionable findings [P1] Persist the resend identity with the queue
[P2] Require the matching Gateway error code
Security None None.

How this fits together

The message tool calls a remote Gateway, which sends through a durable outbound queue. The queue’s retry state and the tool result must agree so one failed send has exactly one retry owner.

flowchart LR
  A[Agent message tool] --> B[Remote Gateway]
  B --> C[Gateway idempotency cache]
  B --> D[Durable outbound queue]
  D --> E{Proven not sent}
  E --> F[Queued-delivery result]
  F --> G[Model avoids resend]
  D --> H[Recovery drain and channel send]
Loading

Before merge

  • Persist the resend identity with the queue (P1) - The queued failure is reused only while context.dedupe survives. After restart, five-minute expiry, or eviction, the same request reaches the Telegram durable sender without a deliveryIntentId, creating a second recoverable row; both rows can drain. Derive and pass a scoped stable intent from the trusted request key, then cover cache loss before retry.
  • Require the matching Gateway error code (P2) - The new helper converts any GatewayClientRequestError with this detail into “do not resend.” The server emits that detail only on UNAVAILABLE; require that code too so a malformed or future rejection cannot falsely report queued delivery and hide an unsent message.
  • Resolve merge risk (P1) - The PR adds 48 net production lines for a new protocol/result path; no existing typed result represents durable queued delivery, so the added boundary is justified only if the durable identity repair is completed.
  • Resolve merge risk (P1) - The Telegram fault-injection evidence in the PR body names an earlier head, not the reviewed commit; refresh it after the repair.
  • Complete next step (P2) - The repair direction is concrete, but this maintainer-labelled message-delivery change needs owner review and exact-head fault evidence before merge.
  • Improve patch quality - Persist the queue intent and prove a retry after Gateway restart or dedupe expiry produces one provider send.
  • Improve patch quality - Require UNAVAILABLE with the queued detail and add the negative-code regression case.
  • Improve patch quality - Refresh the redacted remote-Gateway Telegram proof at the final head.

Findings

  • [P1] Persist the resend identity with the queue — src/gateway/server-methods/send.ts:842-849
  • [P2] Require the matching Gateway error code — src/infra/outbound/message-action-execution.ts:221-223
Agent review details

Security

None.

PR surface

Source +48, Tests +139, Other +18. Total +205 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 9 67 19 +48
Tests 4 164 25 +139
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 18 0 +18
Total 14 249 44 +205

Review metrics

Metric Value Why it matters
Production versus test delta production +67/-19; tests +164/-25; generated protocol +18/-0 The bug fix grows a cross-boundary delivery contract; the new durable behavior needs boundary proof beyond the local cache mock.

Merge-risk options

Maintainer options:

  1. Persist retry deduplication (recommended)
    Carry a stable scoped delivery intent from the trusted message-action idempotency key to the durable queue, add restart or expiry coverage, and restrict the queued-result parser to UNAVAILABLE.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Persist a scoped delivery intent from the trusted message-action idempotency key through the durable queue, add cache-loss coverage, and require UNAVAILABLE for the queued result.

Technical review

Best possible solution:

Derive a route-scoped durable delivery intent from the trusted Gateway idempotency request, reuse it at queue admission after cache loss, and accept the queued marker only with the matching UNAVAILABLE contract.

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

Yes. Current source shows that Gateway cache loss removes the only reused-key record while the durable queue receives no delivery intent, making the duplicate path source-reproducible.

Is this the best way to solve the issue?

No. The queue, not a short-lived Gateway cache, must own duplicate prevention across restart and eviction; the structured result also needs the full error-code predicate.

Full review comments:

  • [P1] Persist the resend identity with the queue — src/gateway/server-methods/send.ts:842-849
    The queued failure is reused only while context.dedupe survives. After restart, five-minute expiry, or eviction, the same request reaches the Telegram durable sender without a deliveryIntentId, creating a second recoverable row; both rows can drain. Derive and pass a scoped stable intent from the trusted request key, then cover cache loss before retry.
    Confidence: 0.96
  • [P2] Require the matching Gateway error code — src/infra/outbound/message-action-execution.ts:221-223
    The new helper converts any GatewayClientRequestError with this detail into “do not resend.” The server emits that detail only on UNAVAILABLE; require that code too so a malformed or future rejection cannot falsely report queued delivery and hide an unsent message.
    Confidence: 0.93

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found but not applied because it conflicted with ClawSweeper's review contract.

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

Labels

Label changes:

  • add P1: After normal Gateway cache loss, the same model retry can create two durable rows that later send duplicate messages.
  • add merge-risk: 🚨 message-delivery: This PR changes whether repeated remote requests collapse or become separate durable channel sends.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the contributor proof gate, but its stated Telegram scenario does not cover Gateway restart or cache eviction and should be refreshed on the final head.
  • add mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The intended fix is recipient-visible: recovery should result in one Telegram message rather than duplicates.

Label justifications:

  • P1: After normal Gateway cache loss, the same model retry can create two durable rows that later send duplicate messages.
  • merge-risk: 🚨 message-delivery: This PR changes whether repeated remote requests collapse or become separate durable channel sends.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the contributor proof gate, but its stated Telegram scenario does not cover Gateway restart or cache eviction and should be refreshed on the final head.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The intended fix is recipient-visible: recovery should result in one Telegram message rather than duplicates.

Evidence

What I checked:

Likely related people:

  • synthalorian: Authored merged predecessor fix(outbound): prevent duplicate sends from proven-not-sent message-tool failures #124310, which established the retry-owner invariant and documented remote Gateway mode as remaining work. (role: introduced adjacent retry-ownership behavior; confidence: high; commits: 5e1a28bb5664; files: src/infra/outbound/deliver-queue-execute.ts, src/gateway/server-methods/send.ts)
  • obviyus: Authored the reviewed remote-Gateway follow-up and is credited on the predecessor commit. (role: current follow-up author and adjacent contributor; confidence: high; commits: 42884c4161cd, 5e1a28bb5664; files: src/infra/outbound/deliver-queue-execute.ts, src/agents/tools/message-tool-execution.ts)
  • Peter Steinberger: Recent main history includes a gateway delivery reliability repair in the same area. (role: recent adjacent gateway-delivery contributor; confidence: medium; commits: 7700a3b3e331; files: src/gateway/server-methods/send.ts)

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 24, 2026
When the agent runtime talks to a remote Gateway (gateway.mode "remote" or a
gatewayUrl/gatewayToken override), the message tool withholds the runtime
identity, so a proven-not-sent outbound failure kept its durable retry row
and also surfaced as an error the model would answer by resending — a
duplicate once the queue replayed the row.

- deliver-queue-execute: mark the thrown error recoveryOwnedRetry when the
  proven-not-sent row stays replay-eligible (one retry owner per row)
- message.action: additive UNAVAILABLE detail code OUTBOUND_DELIVERY_QUEUED
- message tool: project that error into a non-throwing delivery_queued
  result ("queued, will retry automatically, do not resend") and keep the
  autogenerated idempotency-key mapping so an identical resend collapses

Validated with unit tests and a real-Telegram remote-gateway E2E
(affected on main: duplicate; fixed: single send, delivery_queued).

Closes openclaw#124279

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 app: web-ui App: web-ui gateway Gateway runtime maintainer Maintainer-authored PR mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M 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.

1 participant