Skip to content

fix: prevent duplicate generated images after queued send failures - #155804

Draft
valkyriweb wants to merge 1 commit into
openclaw:mainfrom
valkyriweb:fix/generated-media-retry-custody
Draft

valkyriweb wants to merge 1 commit into
openclaw:mainfrom
valkyriweb:fix/generated-media-retry-custody

Conversation

@valkyriweb

@valkyriweb valkyriweb commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Related: #151964

Draft / incomplete (closeout update): ClawSweeper found a verified missing projection in buildRestartRecoveryTerminalDeliveryEvidence; the resumed test bypasses that production builder. CI also found TS2322 in the new test plus two runtime-suite failures needing triage. The earlier local review and bounded passing tests do not establish restart-path correctness or merge readiness. See the closeout handoff comment for the repair sequence, CI links, and pending maintainer policy decision. This head must not be merged or deployed.

What Problem This Solves

Fixes duplicate generated-image sends when a failed automatic delivery is still queued for outbound recovery, but the generated-media completion job starts another send.

User Impact

A transient transport failure no longer makes the completion job replay media that the outbound queue already owns. Outbound recovery keeps its existing retry behavior.

This is a fail-closed duplicate-prevention fix: the parent completion job is dead-lettered with an explicit custody diagnostic, not marked delivered. It does not reconcile eventual outbound success back into the media task, retrofit terminal evidence recorded before this patch, or fix the underlying WhatsApp listener error. No configuration or database migration is required.

Why This Change Was Made

The outbound error already records retained queue custody, but agent delivery status discarded it. The session queue then interpreted missing delivery evidence as permission to advance the agent attempt, producing a fresh outbound send alongside the original recovery job.

Preserve the existing custody fact through the agent result and restart-recovery evidence, then prevent the parent from rearming. This keeps the outbound queue as the sole retry owner without bypassing its write-ahead queue or inventing another receipt store.

This is separate from #154064, which addresses media-producer timeouts while waiting for the session queue. The status projection moves into the existing delivery-result module solely to meet the repository's over-cap file-growth rule; the existing large test files remain unchanged.

Evidence

  • Observed incident: one generated image, an initial no-listener/no-dispatch error, successful outbound recovery, and repeated sends from newly rearmed completion attempts. No private transcript, recipient identifiers, or media are included.
  • Before the fix: two producer custody assertions and four fresh/resumed consumer regressions failed. The consumer reported missing media and rearmed despite retained outbound custody.
  • After the fix: delivery.custody.test.ts 4/4 passed (124.7 s wall; 74.8 s Vitest duration); server-restart-sentinel-agent-delivery.test.ts 5/5 passed (179.0 s wall, 366 ms total test bodies). These use real agent delivery/result and session-delivery entry points with mocked transport/queue writes, including persisted restart-evidence normalization. Held, released, absent, partial-failure, resumed, and ordinary no-custody retry cases are covered.
  • Existing delivery.test.ts: 64/64 passed after moving the status projection (59.4 s wall; 42.3 s Vitest duration).
  • Focused files were run with pnpm exec vitest run <file> --maxWorkers=1 (gateway files additionally select test/vitest/vitest.gateway.config.ts). Large wall times were dominated by local transform/import work, not added timers or polling.
  • Changed-file oxlint, oxfmt, line-cap ratchet, max-lines ratchet, assertion-safety ratchet, and git diff --check: passed. Independent read-only autoreview: no actionable findings.

Validation gaps: The broader gateway file run (pnpm test src/gateway/server-restart-sentinel.test.ts --maxWorkers=1, before relocating the new tests) had 99 passes, one restart-notice continuation assertion failure, and seven ENOENT failures after its temporary namespace disappeared (520.9 s wall). The unchanged continuation test passed alone afterward; that does not establish the full-run failure is fixed. No unrelated fixture changes are included. pnpm tsgo:core exceeded 600 seconds without diagnostics and was stopped; full build/check/test were not completed. CI results and CI timing remain pending. No production restart, rollout, or live-channel test was performed; these tests do not establish transport-wide exactly-once delivery.

@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M labels Sep 22, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The branch carries outbound queue custody into agent delivery results and saved recovery evidence, then dead-letters generated-media completion jobs instead of starting another send while outbound recovery owns the retry.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The ownership direction is useful, but production restart coverage is incomplete and the supplied evidence remains mocked.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Merge readiness

⛔ Blocked before merge - 8 items remain

This remains useful work distinct from the related session-queue timeout fix. Both prior findings remain unresolved at the pinned head, and no merged replacement establishes that the outbound-custody problem is solved.

Priority: P1
Reviewed head: 1b19f2d20b428b1d1f37e2be1b015626daf376ef
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should held outbound custody permanently dead-letter the generated-media parent as an interim containment fix, or should parent settlement follow the outbound owner's eventual outcome?
  • Recommendation: Accept bounded duplicate containment: Accept permanent parent dead-lettering with a clear custody diagnostic while outbound recovery retains its existing retry behavior.
  • Why: Both avoid a competing send, but only reconciliation can reflect eventual success in the parent; neither the discussion nor repository notes record acceptance of the proposed permanent-failure tradeoff.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: the changed delivery and recovery owners are exercised with mocked outbound transport and queue writes, and resumed cases bypass the production builder. Supply redacted after-fix terminal output or logs showing outbound recovery sends once and the parent does not resend through the real persisted restart path. Independently prove legacy and new evidence compatibility; no full application or paid provider run is required. Redact private IPs, credentials, phone numbers, and endpoints. Update the PR body to trigger re-review; if needed, ask a maintainer to comment @clawsweeper re-review.
  • Preserve custody in the production terminal-evidence builder (P1) - The new recovery guard depends on deliveryStatus.queueCustody, but this production projection still omits it. post-run.ts calls this builder before saving terminal evidence, so a held outbound retry becomes ordinary missing-media evidence after restart and can rearm another send. Preserve exact held custody here and route the resumed regression through this builder; passing a fabricated result directly to cleanup bypasses the failure.
  • Type the resumed fixture against the evidence contract (P2) - The separately declared mutable result widens its status and custody literals to string, making this assignment incompatible with RestartRecoveryTerminalDeliveryEvidenceResult. The captured CI reports TS2322 at this exact line. Use the real input contract and production builder to produce the terminal fixture rather than casting around the mismatch.
  • Resolve merge risk - Held custody permanently dead-letters the parent even when outbound recovery later succeeds; that observable settlement tradeoff needs explicit maintainer acceptance or a reconciliation design.
  • Resolve merge risk - Existing-state compatibility remains unproven: the resumed test performs in-memory normalization, without a real persisted-state reopen covering legacy evidence and new held-custody evidence.
  • Complete next step - Repair the retained findings, resolve current merge conflicts, and obtain an explicit choice on permanent parent dead-lettering versus outbound-outcome reconciliation.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Preserve custody in the production terminal-evidence builder — src/agents/agent-command-restart-recovery.ts:218-227
  • [P2] Type the resumed fixture against the evidence contract — src/gateway/server-restart-sentinel-agent-delivery.test.ts:76
Agent review details

How this fits together

Generated-media completion jobs run through the requesting session and send their results through the durable outbound queue. Delivery evidence determines whether the completion job settles, retries, or stops after a failure.

flowchart TD
  A[Generated media completion] --> B[Requesting session turn]
  B --> C[Durable outbound queue]
  C --> D[Channel transport]
  C --> E[Delivery evidence]
  E --> F{Outbound custody held}
  F -->|Yes| G[Stop parent retry]
  F -->|No| B
Loading

Technical review

Best possible solution:

Keep outbound recovery as the sole send-retry owner, preserve custody through production persistence, and give the parent an explicitly approved outcome that does not misrepresent delivery.

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

Yes, source establishes a focused path: a failed generated-media send retains outbound custody, but saved terminal projection discards it before restart recovery evaluates whether to rearm. No runtime reproduction was executed in this read-only review.

Is this the best way to solve the issue?

Unclear overall: extending the existing custody owner is appropriate, but the production persistence path is incomplete and permanent parent failure needs an explicit settlement-policy choice.

Full review comments:

  • [P1] Preserve custody in the production terminal-evidence builder — src/agents/agent-command-restart-recovery.ts:218-227
    The new recovery guard depends on deliveryStatus.queueCustody, but this production projection still omits it. post-run.ts calls this builder before saving terminal evidence, so a held outbound retry becomes ordinary missing-media evidence after restart and can rearm another send. Preserve exact held custody here and route the resumed regression through this builder; passing a fabricated result directly to cleanup bypasses the failure.
    Confidence: 0.99
  • [P2] Type the resumed fixture against the evidence contract — src/gateway/server-restart-sentinel-agent-delivery.test.ts:76
    The separately declared mutable result widens its status and custody literals to string, making this assignment incompatible with RestartRecoveryTerminalDeliveryEvidenceResult. The captured CI reports TS2322 at this exact line. Use the real input contract and production builder to produce the terminal fixture rather than casting around the mismatch.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 800fce298ba8.

Merge-risk options

Maintainer options:

  1. Complete the custody path and compatibility proof (recommended)
    Repair the terminal projection and typed regression, then prove fresh and persisted recovery leaves exactly one outbound retry owner.
  2. Accept permanent parent failure explicitly
    Record acceptance that outbound success will not reconcile the dead-lettered parent, while retaining the independent code and proof requirements.

Security

None.

Evidence

What I checked:

  • Pinned introduction: Reviewed the complete eight-file introduction from the verified merge base to original PR head. Base-only changes were not attributed to this PR; no verified test-merge result is available. (1b19f2d20b42)
  • Production evidence projection still drops custody: The terminal-evidence builder reconstructs delivery status without queueCustody. The production post-run callback invokes this builder after delivery, so the newly added saved-evidence normalizer cannot recover the discarded fact. (src/agents/agent-command-restart-recovery.ts:218, 1b19f2d20b42)
  • Resumed regression bypasses the production builder: The test passes its fabricated result directly to buildRestartRecoveryClaimCleanupPatch. Its mutable status, queueCustody, and payload-outcome literals widen to string; the contributor's captured CI handoff reports TS2322 at the same assignment. (src/gateway/server-restart-sentinel-agent-delivery.test.ts:76, 1b19f2d20b42)
  • Existing outbound custody owner: createQueuedDeliveryOwner projects held or released custody from the existing outbound owner. The PR consumes that recorded retry fact; it does not change principal authorization, transport access, or the allowed recipient. The prior authority-chain marker therefore does not apply under the narrowed trigger. (src/infra/outbound/deliver-queue-state.ts:79, 1b19f2d20b42)
  • Current main still lacks the central propagation: Current main's delivery-status type and durable-send projection omit queueCustody. Its generated-media evaluator still rearms missing-media results without the introduced held-custody guard. (src/agents/command/delivery-result.ts:14, 800fce298ba8)
  • Contributor proof and disposition: The captured body and fix: prevent duplicate generated images after queued send failures #155804 (comment) explicitly acknowledge the missing production projection, mocked transport and queue writes, missing persisted-state proof, and absence of a production restart or live-channel run. The proposed permanent parent failure without eventual-success reconciliation has no recorded maintainer acceptance. (1b19f2d20b42)

PR surface

Source +24, Tests +264. Total +288 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 6 83 59 +24
Tests 2 264 0 +264
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 347 59 +288

Review metrics

Metric Value Why it matters
Net code growth production +24 lines; tests +264 lines Production growth implements custody propagation and suppression, while the resumed coverage currently bypasses the production projection.
Stored evidence extension 1 optional custody field added The field changes recovery decisions after restart and needs existing-state compatibility evidence.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The reported transport failure can produce repeated generated-image sends through competing retry owners.
  • merge-risk: 🚨 message-delivery: The incomplete restart projection leaves duplicate-send prevention ineffective after recovery.
  • merge-risk: 🚨 session-state: The parent becomes permanently failed even when its outbound delivery later succeeds.
  • merge-risk: 🚨 compatibility: Saved recovery evidence gains a decision-bearing field without verified legacy and candidate-state reopen proof.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Repair both retained findings and make the resumed regression enter through the production terminal builder.
  • Provide real queue/transport fault recovery and persisted-state reopen evidence for legacy and held-custody records.
  • Record the maintainer's chosen parent-settlement policy.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-22T15:54:15.450Z sha 1b19f2d :: needs real behavior proof before merge. :: [P1] Preserve custody in the production terminal-evidence builder
  • reviewed 2026-09-22T16:27:39.367Z sha 1b19f2d :: needs real behavior proof before merge. :: [P1] Preserve custody in the production terminal-evidence builder | [P2] Type the resumed fixture against the terminal-evidence contract
  • reviewed September 27, 2026, 10:37 AM ET / 14:37 UTC (Revision 3) sha unknown :: needs real behavior proof before merge. :: [P1] Preserve custody in the production terminal-evidence builder | [P2] Type the resumed fixture against the evidence contract
  • reviewed September 27, 2026, 10:37 AM ET / 14:37 UTC (Revision 4) sha unknown :: needs real behavior proof before merge. :: [P1] Preserve custody in the production terminal-evidence builder | [P2] Type the resumed fixture against the evidence contract

Reviewed October 7, 2026, 6:55 AM ET / 10:55 UTC (Revision 5).

@valkyriweb
valkyriweb marked this pull request as draft September 22, 2026 16:17
@valkyriweb

Copy link
Copy Markdown
Contributor Author

Closeout handoff — draft / not merge-ready

Branch + commit: valkyriweb/openclaw-upstream:fix/generated-media-retry-custody @ 1b19f2d20b428b1d1f37e2be1b015626daf376ef (pushed; all eight changed files preserved).

Issue / PR: this PR; related #151964 and #154064.

Why incomplete: I verified ClawSweeper's P1 finding in src/agents/agent-command-restart-recovery.ts:218–227: buildRestartRecoveryTerminalDeliveryEvidence() reconstructs delivery status without queueCustody. The resumed regression bypasses that production builder, so its passing result does not prove the real restart path is repaired. The earlier independent review missed this. The PR is now draft; please do not merge this head.

Next action: preserve exact held custody in that production builder and first route the resumed regression through it to establish a failing test. Then add a real persisted-state round trip (both legacy records without custody and new held-custody records), demonstrate recovery ownership without a second parent send in an isolated test/candidate, repair the test type error below, and rerun affected suites plus independent review. Explicit maintainer acceptance of parent dead-lettering without eventual-success reconciliation remains required. Do not restart, roll, or mutate production to gather proof.

Verification state: 4 new producer tests, 5 consumer tests, and 64 existing delivery tests passed locally; these are bounded mocked-boundary proofs, not production-path or transport-wide exactly-once proof. Local targeted lint/format/ratchets passed. Full local typecheck timed out, and the broader gateway failures remain disclosed in the body. CI now reports:

  • Regression / blocker: check-test-types: server-restart-sentinel-agent-delivery.test.ts(76,13): TS2322; the fabricated result widens deliveryStatus.status to string rather than the allowed union. Type the fixture against the real evidence contract rather than casting around this.
  • Blocker, cause untriaged: checks-node-compact-large-13: gateway retained-request-root/auth-refresh/chat assertions (expected 1 to be 0, expected 3 to be 2). Do not label these pre-existing without baseline evidence.
  • Blocker, cause untriaged: checks-node-changed-extensions-bundle-44: Slack monitor.history-policy.test.ts unhandled EnvironmentTeardownError: Closing rpc while "onUserConsoleLog" was pending, alongside fetch/auth errors. Needs fixture/infra triage, not an assumed flake.

Support needed: maintainer policy decision before merge; no production approval requested. Work is preserved for follow-up, not complete or merge-ready. Yield misuse remains out of scope.

This branch has not been deployed

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

Labels

agents Agent runtime and tooling 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. 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. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant