Skip to content

fix(agents): don't fail media completion when wake deadline expires with pending handoff - #152114

Closed
synthalorian wants to merge 2 commits into
openclaw:mainfrom
synthalorian:fix/issue-151964
Closed

synthalorian wants to merge 2 commits into
openclaw:mainfrom
synthalorian:fix/issue-151964

Conversation

@synthalorian

@synthalorian synthalorian commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

When a media generation completion is accepted into the durable session-delivery queue behind the requester's own active run, the handoff is already owned by that queue and drains when the run ends. The caller-side retry loop still threw at the 120s handoff deadline, and the scheduler recorded a blocked delivery failure plus a false "completion wake failed after successful generation" log. The queued handoff was not actually lost, but the task looked failed. Marking the turn successful at that deadline would also be wrong: queue custody is not delivery.

Why This Change Was Made

wakeMediaGenerationTaskCompletion now reports queueOwned only when the delivery disposition is session_queued, and includes the durable queueEntryId. Until the deadline, admission retries are unchanged. If that deadline expires while the handoff is still pending:

  • a queue-owned receipt is not failed and not completed as success
  • later observation reads that same receipt instead of enqueueing again, so the handoff is not rewritten or dropped
  • delivery finalizes the operation as success
  • a permanent queue failure still records the blocked terminal result
  • any other pending handoff (refused admission, transient read, unconfirmed settling) still fails closed, so retention and failure recording stay intact

User Impact

image_generate / video_generate / music_generate no longer record a false delivery failure when the requester's own turn still holds a queue-owned completion past 120s. The generated media stays queued for delivery. The turn is not marked successful unless the media actually lands, and a later permanent delivery failure is still recorded as blocked.

Evidence

Head 533a6ef485e373f8f9c3d54dfa88da50a0709bef.

Real scheduler run (src/agents/tools/media-generate-background-shared.queue-deadline.test.ts):

{"proof":"pending handoff past wake deadline","operationStatus":"running","endedAt":null,"terminalOutcome":null,"wakeFailures":0,"wakeCalls":63}
{"proof":"handoff delivered after the deadline","operationStatus":"succeeded","terminalOutcome":null,"wakeFailures":0}
{"proof":"media never landed at the wake deadline","operationStatus":"running","endedAt":null,"terminalOutcome":null,"wakeFailures":0}
{"proof":"permanent handoff failure after the deadline","operationStatus":"succeeded","terminalOutcome":"blocked","wakeFailures":2}

 Test Files  2 passed (2)
      Tests  29 passed (29)

Real durable-queue admission (src/gateway/server-restart-sentinel.media-binding.test.ts, 12 passed) now requires queueOwned: true and the same queueEntryId as the pending queue row. Unconfirmed pending handoffs still stop at the deadline with a blocked result (stops pending handoff retries at the completion deadline).

Fixes #151964

@clawsweeper

clawsweeper Bot commented Sep 18, 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 agents Agent runtime and tooling size: S labels Sep 18, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 18, 2026
@clawsweeper

clawsweeper Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR carries durable queue receipts through media completion and keeps confirmed queued handoffs pending beyond the 120-second wake deadline.

Example: An image finishes generating while its requester remains active for more than 120 seconds.

  • Before: The completion deadline records a blocked result even though the queue still owns delivery.
  • After: The operation remains running while the scheduler observes the queued handoff.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction is useful, but two P1 lifecycle defects remain and the supplied proof bypasses the changed receipt-observation path; no persisted format or schema changes require migration.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Successfully generated media can appear blocked while its completion waits behind the requesting turn.
Reason: The central bug is established, but the linked issue also requires the requester to escape its circular wait and observe actionable completion state.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: it addresses a current upstream media-completion bug, but both previously reported P1 findings remain unresolved.

Priority: P1
Reviewed head: 5666c9aa2b5d7785dd20819c58ae10844da99799

Before merge

  • Add real behavior proof - The supplied terminal traces come from fake-timer scheduler tests with mocked wake outcomes and no receipt IDs; the Gateway binding harness mocks final dispatch. Neither exercises the new post-deadline receipt observer through a real Gateway. Supply redacted logs or terminal output showing requester release, actual delivery, and permanent queue failure, removing IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Read terminal queue status instead of treating absent pending rows as pending (P1) - After a confirmed handoff passes 120 seconds, the scheduler switches to this reader. loadPendingSessionDelivery invokes sessionDelivery.load, whose worker query filters status to pending. Normal successful finalization writes completed, and permanent failure writes failed, so either finalized receipt returns null here and is classified as pending indefinitely unless a poll happens to catch the intermediate settlement marker. The operation never reaches success or blocked retention and keeps polling despite terminal delivery. Add a typed queue-owner read that distinguishes pending, completed, failed, and missing receipts. This previously reported finding remains unresolved.
  • Release the cron requester wait when the queue accepts custody (P1) - For an isolated cron turn that starts background media and then finishes its model response, attempt-stream-settle still calls waitForCompletionRequiredAsyncTasks, which waits for terminal media-operation status. This loop now keeps that operation running beyond the deadline, while server-restart-sentinel-agent-delivery defers its completion until the same requester admission ends. Removing the bounded failure therefore leaves the cron turn waiting until its own timeout, or indefinitely with no deadline. Publish confirmed custody to the existing operation/wait owner and let it release the requester without marking media delivery successful. This previously reported finding remains unresolved.

Findings

  • [P1] Read terminal queue status instead of treating absent pending rows as pending — src/agents/tools/media-generate-background-completion.ts:132-134
  • [P1] Release the cron requester wait when the queue accepts custody — src/agents/tools/media-generate-background-shared.ts:155-164

Tests

  • Missing end-to-end proof: Show a real Gateway retaining one receipt beyond 120 seconds, releasing the cron requester, delivering the attachment, and settling completed and permanently failed receipts; the new receipt-observation regression is not demonstrated against the base.
Agent review details

How this fits together

Background image, music, and video generation hands results to the durable session-delivery queue, which resumes the requesting session and records delivery settlement.

flowchart TD
  A[Requester turn] --> B[Media generation]
  B --> C[Completion scheduler]
  C --> D[Durable session queue]
  D --> E[Requester continuation]
  E --> F[Media delivery]
  D --> G[Receipt observation]
  G --> C
Loading

Technical review

Best possible solution:

Let confirmed queue custody release the requester wait and obtain terminal delivery status from the queue owner without declaring delivery early.

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

The official-release report and current-main deadline path establish the original failure; source inspection establishes both patch defects, without executing target code.

Is this the best way to solve the issue?

Distinguishing durable custody from delivery is appropriate, but the repair must reach both terminal receipt reads and the requester wait owner.

Full review comments:

  • [P1] Read terminal queue status instead of treating absent pending rows as pending — src/agents/tools/media-generate-background-completion.ts:132-134
    After a confirmed handoff passes 120 seconds, the scheduler switches to this reader. loadPendingSessionDelivery invokes sessionDelivery.load, whose worker query filters status to pending. Normal successful finalization writes completed, and permanent failure writes failed, so either finalized receipt returns null here and is classified as pending indefinitely unless a poll happens to catch the intermediate settlement marker. The operation never reaches success or blocked retention and keeps polling despite terminal delivery. Add a typed queue-owner read that distinguishes pending, completed, failed, and missing receipts. This previously reported finding remains unresolved.
    Confidence: 0.99
  • [P1] Release the cron requester wait when the queue accepts custody — src/agents/tools/media-generate-background-shared.ts:155-164
    For an isolated cron turn that starts background media and then finishes its model response, attempt-stream-settle still calls waitForCompletionRequiredAsyncTasks, which waits for terminal media-operation status. This loop now keeps that operation running beyond the deadline, while server-restart-sentinel-agent-delivery defers its completion until the same requester admission ends. Removing the bounded failure therefore leaves the cron turn waiting until its own timeout, or indefinitely with no deadline. Publish confirmed custody to the existing operation/wait owner and let it release the requester without marking media delivery successful. This previously reported finding remains unresolved.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Completion wake deadline changes intended behavior with a stated reason (cab8040: The bounded retry preserved exact cron continuation context while waiting for delivery; subsequent timeout refactoring retained its semantics.)
  • Durable media completion custody keeps the original intent (fix(agents): wake owning session after generated-media direct delivery #108024: Media completion enters the durable session queue and settles only from terminal delivery evidence, avoiding orphaned continuations and duplicate attachments.)
  • Blocked media reference retention keeps the original intent (1f654d4: Generated attachment references remain recoverable when final handoff is permanently blocked; later Tasks removal moved recovery to existing session owners.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/tools/media-generate-background-shared.queue-deadline.test.ts src/agents/tools/media-generate-background-shared.test.ts src/agents/tools/media-generate-background-retention.test.ts --maxWorkers=1
  • pnpm test src/agents/embedded-agent-runner/run/attempt.async-tasks.test.ts --maxWorkers=1
  • pnpm test src/gateway/server-restart-sentinel.media-binding.test.ts src/infra/session-delivery-queue.storage.test.ts src/infra/session-delivery-queue.recovery.test.ts --maxWorkers=1
  • pnpm check:changed
  • git diff --check

What I checked:

Likely related people:

  • Peter Lee: Raw commit cab8040 adds src/agents/tools/media-generate-background-shared.ts:176 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cab8040b1436; files: src/agents/tools/media-generate-background-shared.ts)
  • Peter Steinberger: Raw commit ab4d26a adds src/agents/tools/media-generate-background-shared.ts:148 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ab4d26a77b18; files: src/agents/tools/media-generate-background-shared.ts)

PR surface

Source +93, Tests +156. Total +249 across 6 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 104 11 +93
Tests 2 166 10 +156
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 270 21 +249

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #151964
Summary: The canonical issue tracks requester-held completion delivery and false deadline failure; two open candidates attempt its repair.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The reported failure disrupts real autonomous media-generation workflows, and the patch can prolong requester waits indefinitely.
  • merge-risk: 🚨 session-state: Completed or failed queue delivery can leave the media operation running, and cron requester settlement remains coupled to delivery that requires requester release.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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 (3 earlier review cycles)
  • reviewed 2026-10-10T21:53:45.580Z sha 6373bda51bb7a4903602f5cbdd3a82e23ea5e56a :: needs real behavior proof before merge. :: [P2] Keep queued completion observable until delivery actually settles
  • reviewed 2026-10-13T04:45:57.561Z sha 533a6ef485e373f8f9c3d54dfa88da50a0709bef :: needs real behavior proof before merge. :: [P1] Read terminal queue status instead of treating absent pending rows as pending | [P1] Release the cron requester wait when the queue accepts custody
  • reviewed 2026-10-13T21:22:32.405Z sha 5666c9a :: needs real behavior proof before merge. :: [P1] Read terminal queue status instead of treating absent pending rows as pending | [P1] Release the cron requester wait when the queue accepts custody

Reviewed October 13, 2026, 5:49 PM ET / 21:49 UTC (Revision 4).

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 25, 2026
@synthalorian

Copy link
Copy Markdown
Contributor Author

Live behavior proof — deadline expiry with a pending handoff completes deferred, not failed

Environment: worktree pinned to PR head 5039bdbeb31 (verified with git rev-parse HEAD), upstream/main at b27c79ba156.

Without the fix (upstream media-generate-background-shared.ts + this PR's test)

Simulated requester-busy completion: the wake keeps returning pending (the handoff sits in the durable session-delivery queue behind the requester's active run) until the handoff deadline expires:

FAIL  agents-tools  .../media-generate-background-shared.test.ts
  > completes deferred-pending when the handoff deadline expires with a pending wake outcome
AssertionError: expected "vi.fn()" to be called with arguments: [ ObjectContaining{…} ]

-   ObjectContaining {
-     "terminalResult": undefined,
+   { … (upstream records a blocked/failure terminal instead)

Upstream's generic deadline error flows into the failure path: completeTaskRun receives a blocked terminal result and onWakeFailure fires with "completion wake failed after successful generation" — a false delivery-failure terminal, recorded even though the durable queue still owns the handoff and will drain it when the requester's run ends (the issue's lost-completion report).

With the fix (exact PR head)

 ✓  agents-tools  .../media-generate-background-shared.test.ts
    > completes deferred-pending when the handoff deadline expires with a pending wake outcome

Test Files  1 passed (1)
     Tests  1 passed | 26 skipped (27)

The distinguishable MediaGenerationCompletionHandoffPendingTimeoutError routes to the deferred path: completeTaskRun is called with terminalResult: undefined (no false failure recorded) and onWakeFailure is never called — with an info log noting the handoff is queued behind the requester's active run and completes when that run ends.

What this proof does and does not cover: this demonstrates the terminal-recording contract at the exact seam the issue reported (deadline expiry while pending). The remaining end-to-end leg — a live gateway showing the durable queue actually draining on requester-run end — is the e2e leg of the proof plan; the durable-drain behavior itself is pre-existing upstream machinery this PR does not modify.

Suite state on the PR head: 27/27 green, including the companion contract that generic handoff failures still record failures (does not direct-deliver generated media after a generic handoff failure).

@synthalorian

Copy link
Copy Markdown
Contributor Author

Follow-up: deferral now gated on positive queue ownership

Pushed 9133c57c448 after CI's media-generate-background-retention shard exposed a real hole in the first revision — thank you, upstream retention tests.

The hole: the first revision treated every deadline-expired pending wake outcome as "the durable queue owns the handoff." But pending covers three dispositions — session_queued (queue positively accepted), retryable (transient, e.g. admission refused), and completion_handoff_pending (unconfirmed settling). Deferring on the latter two would have skipped blocked-completion retention and failure recording for media nothing durable owned — a silent loss, exactly the concern behind the merge-risk flags.

The fix: the wake outcome now carries queueOwned, set only when the delivery disposition is session_queued. The deadline path defers exclusively on queueOwned === true; any other pending handoff fails closed with upstream's original generic error, so retention and failure recording run unchanged:

if (outcome.queueOwned === true) {
  throw new MediaGenerationCompletionHandoffPendingTimeoutError();  // deferred, no false failure
}
throw new Error("media completion did not settle before the handoff deadline");  // fail closed

Verified locally (2 files, 39/39 green):

  • media-generate-background-shared.test.ts (27/27) — the deferred-pending regression test (its mock now returns queueOwned: true, matching the issue's requester-busy shape)
  • media-generate-background-retention.test.ts (12/12) — upstream's retention contract: refused-admission pending now correctly produces a blocked terminal, transcript retention fires, and onWakeFailure records the genuine failure

The net behavior matrix:

Deadline reached with… Before this PR This PR
session_queued pending (the issue's requester-busy case) false delivery-failure terminal deferred, no failure recorded
retryable / refused admission blocked terminal + retention + failure recorded unchanged (blocked + retention + failure)
requester read transiently failing blocked terminal + failure recorded unchanged

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Sep 30, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper recorded closeout evidence for this proposed close.

  • Action: close remains subject to final live verification.
  • Close reason: lowest-signal PR over the author's open-PR budget.
    Review evidence: durable ClawSweeper review.

@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. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Oct 10, 2026
@synthalorian

Copy link
Copy Markdown
Contributor Author

Live proof — queued handoff stays pending past the wake deadline

Head f52fbbd930550d00fd8493471ad08ed751ede8f3 on current upstream/main (799b7a347c5).

The real completion scheduler was run with a pending handoff held through the 120s wake deadline:

{"proof":"pending handoff past wake deadline","operationStatus":"running","endedAt":null,"terminalOutcome":null,"wakeFailures":0,"wakeCalls":63}
{"proof":"handoff delivered after the deadline","operationStatus":"succeeded","terminalOutcome":null,"wakeFailures":0}

At the deadline the operation was still running, with no endedAt, no terminal outcome, and no wake failure. It became succeeded only after the handoff actually delivered.

When the media never lands, the same deadline does not mark success. After a later permanent failure the terminal outcome is blocked:

{"proof":"media never landed at the wake deadline","operationStatus":"running","endedAt":null,"terminalOutcome":null,"wakeFailures":0}
{"proof":"permanent handoff failure after the deadline","operationStatus":"succeeded","terminalOutcome":"blocked","wakeFailures":2}

src/gateway/server-restart-sentinel.media-binding.test.ts: 12 passed. Successful queue admission returns { status: "pending", queueOwned: true, queueEntryId } equal to the durable row id, so the receipt is kept.

src/agents/tools/media-generate-background-shared.test.ts plus the new deadline file: 29 passed. Unconfirmed pending handoffs still fail closed at the deadline.

@synthalorian

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@synthalorian

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

A session_queued completion is already owned by the durable delivery
queue. The 120s caller deadline was recording a blocked failure even
though that handoff was still pending. Keep the receipt until delivery
or a permanent queue failure, and do not mark the turn successful when
the media never lands. Unconfirmed pending handoffs still fail closed.

Fixes openclaw#151964
The assertion-safety ratchet rejects a new unchecked cast. The failed
delivery tombstone stores failedAt outside the live payload type.
@synthalorian

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

Thank you for this fix. The same problem (#151964) was resolved on main by #172637 (ff9985c). It keeps queued media completions alive past the 120 s handoff, releases the requesting lane, and gives the model explicit "end this turn" guidance from action=status, with regressions for image, music and video. Since main already carries an equivalent fix, I'm closing this as superseded. Your analysis and repro helped confirm the shape of the fix.

@steipete steipete closed this Oct 15, 2026
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: 🚨 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

2 participants