Skip to content

fix(media): measure the completion handoff deadline on the monotonic clock - #185704

Merged
obviyus merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/media-generation-handoff-retry-deadline-monotonic
Oct 27, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
SunnyShu0925:fix/media-generation-handoff-retry-deadline-monotonic

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A cron-triggered image generation finishes, the cron continuation is not ready yet, and the handoff keeps retrying against a 120 second budget that is measured on the wall clock while the wait between retries runs on the monotonic timer. When the host clock is corrected mid-handoff, the budget moves: a backward correction leaves the handoff retrying past 120s, a forward correction fails a healthy handoff with media completion did not settle before the handoff deadline and the finished media is retained as blocked.

  • Problem: wakeMediaGenerationTaskCompletionWithRetry seeds the deadline with Date.now() and computes remainingMs from Date.now(), while sleepWithAbort waits on a libuv monotonic timer, so the two clocks disagree after any wall-clock correction.
  • Solution: seed and measure the same 120s budget with performance.now(), the clock the retry wait already uses.
  • What changed: src/agents/tools/media-generate-background-shared.ts (deadline seed and remaining calculation), its focused test (the deadline test now covers clock rollback, no jump, and clock jump forward), and the consumer test in src/agents/tools/media-generate-background-retention.test.ts that used to drive the old deadline with a synthetic Date.now() jump.
  • What did NOT change: retry count, backoff schedule, the queueOwnsCompletion rule (once the queue owns delivery the deadline no longer bounds observation), the error text, and the wall-clock fields that report task timestamps.

Why This Change Was Made

Both sides of the handoff budget now read the monotonic clock, which is the only clock the retry wait obeys. This matches the deadline loops already shipped in this repository, such as src/agents/tools/agents-wait-tool.ts, which seeds with performance.now() + timeoutMs, compares with performance.now() >= deadline, and sleeps Math.max(0, deadline - performance.now()).

The deadline is a local closure value: it is never serialized, persisted, or read from another process, so there is no dual-clock contract to preserve and no reason to keep a wall-clock copy. sleepWithAbort already floors and clamps the delay inside resolveSleepDelayMs, so the fractional performance.now() value needs no Math.floor at the call site.

  • Best fix: yes. Aligning the clock domain removes the failure by construction instead of adding tolerance or another timeout.
  • Alternative: a monotonic deadline plus a separate wall-clock deadline would only be needed if the budget crossed a process boundary; it does not.
  • Risk: the 120s end state has not been observed on a host that receives a real NTP correction during a cron run; the wall-clock jump is injected while the timers stay real.

User Impact

  • A host clock correction no longer shortens or extends the media completion handoff budget, so cron-triggered image, music, and video results are no longer marked blocked only because the clock moved.
  • A stalled cron continuation still stops after 120 seconds of real elapsed time even if the clock was moved backward.

Evidence

Before/after comparison, same scenarios, only the deadline clock source changed (Date.now() → performance.now()):

Scenario Before (Date.now() deadline) After (performance.now() deadline)
Real process, clock jumps +121s 300ms into the handoff (6s window) Handoff declared failed after 755ms; 3 wake attempts; media retained as blocked No failure; 6 wake attempts; handoff still pending at 6s
Real process, clock rolls back -130s (130s window) Still retrying at 130s (10s past the 120s budget); 68 wake attempts Settles at 120007ms, the 120s monotonic mark; 65 wake attempts
Focused test, clock rollback (-60_000ms) fail — handoff still pending at the 120_000ms mark pass
Focused test, no clock change (0ms) pass (control) pass (control)
Focused test, clock jump forward (+60_000ms) fail — handoff already settled before 119_999ms pass
Consumer test retains references in the live requester (6 variants) current variant never settles (hits the 90s test timeout) 6 passed, current takes 35.8s (~39s on the base revision)

Fixed code, real process (node --import tsx/esm) directly calling the exported scheduleMediaGenerationTaskCompletion with a real lifecycle and real monotonic timers, with a wall-clock jump injected 300ms after the handoff started:

--- PRE-FIX (base revision: Date.now) ---
wall clock jump applied at 300 ms after schedule: +121000 ms
observed window: 6000 ms
handoff wake attempts: 3
handoff failures: [{"elapsedMs":755,"message":"Image generation completion wake failed after successful generation"},{"elapsedMs":5491,"message":"Image generation blocked completion retention failed"}]
detached crashes: none
verdict: handoff budget consumed by the wall clock jump (deadline fired early)

--- POST-FIX (performance.now) ---
wall clock jump applied at 300 ms after schedule: +121000 ms
observed window: 6000 ms
handoff wake attempts: 6
handoff failures: none
detached crashes: none
verdict: still pending at observation end

Clock rollback on real elapsed time (130s window, -130s jump). Before the fix the handoff is still retrying 10s past its 120s budget; after the fix it settles on the 120s monotonic mark:

PRE-FIX  (-130000 ms jump, 130s window): wake attempts 68, handoff failures: none, verdict: still pending at observation end
POST-FIX (-130000 ms jump, 130s window): wake attempts 65, handoff failures: [{"elapsedMs":120007,"message":"Image generation completion wake failed after successful generation"}], verdict: settled at 120007 ms

Pre-fix output, test kept and source reverted, 2 failed | 1 passed:

FAIL ... wall clock jumps -60000 ms: AssertionError: expected 'pending' to be 'settled'
FAIL ... wall clock jumps 60000 ms: AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 ✓   ... wall clock jumps 0 ms

Post-fix, 3 passed; full file 29 passed (27 before the change, because the single deadline test became three parameterized cases).

Consumer test src/agents/tools/media-generate-background-retention.test.ts, retains references in the live requester (6 variants): 6 passed with the fix, while the same updated test on the base revision does not settle at all and hits the 90s test timeout.

Open PR collision check: scanned the full changed-file list of the 358 open PRs created since media-generate-background-shared.ts exists, plus the newest 500 open PRs of any age; no open PR touches media-generate-background-shared.ts or its test. The only open PR touching media generation files, #184640, changes media-generate-background-completion.ts and media-generate-background-retention.test.ts for a different symptom (showing retained images after a blocked delivery) and does not modify the handoff deadline.

What was not tested: no real host NTP correction was performed; the wall-clock jump is injected at process level while the monotonic clock and the timers are real. The cron continuation is held pending by the harness rather than by a genuinely stalled cron run. The 120s end state was observed for 130s, not across a full generation lifecycle on a clock-corrected host.

Additional shipped Gateway Evidence

#185704 (comment)

Built Gateway image generation, main twice/candidate twice, plus no-step controls: with a +180s process-local wall-clock step during transient unconfirmed storage refusal, main falsely expires after 19–64ms and delivers no image. Candidate retries and delivers one image in both runs, matching the controls. No system clock change or real credentials.

The remaining Gateway exhaustion fixture now advances the monotonic clock. Focused Linux validation: 64/64 tests passed; the previous timeout case passed in 736ms, with queued-delivery cases passing. Oxfmt passed. Production delta against merge base: +2/-2 (net 0); tests +58/-23 (net +35), including +14 lines of consumer clock cutover. Simplification pass retained the two substitutions at the existing deadline owner and distinct clock/retention/consumer regressions; no new runtime abstraction or state.

The subsequent exact-head review identified the queued deadline control as another Date-only fixture. It now crosses the mocked monotonic deadline while preserving queue custody assertions. Gateway consumer rerun: 15/15 passed (including all three queued outcomes), with Oxfmt passing. No production behavior changed after the built-Gateway proof.

…clock

The media generation completion handoff retried a pending cron continuation
against a 120s budget seeded with Date.now(), while the sleep between retries
runs on a libuv monotonic timer. A wall-clock correction therefore moved the
budget: a backward jump let a pending handoff retry past 120s, and a forward
jump failed a healthy handoff early because the remaining budget went negative.

Seed and measure the deadline with performance.now(), the clock the retry sleep
already uses, matching the other deadline loops in the repository. The deadline
is a process-local closure value, so no dual-clock contract is needed.

The retention test that drove the old deadline with a synthetic Date.now() jump
now advances performance.now() instead.
@clawsweeper

clawsweeper Bot commented Oct 27, 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 Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Measure the media completion handoff budget with the monotonic clock and update affected deadline tests.

Example: The wall clock advances 180 seconds while generated-image completion encounters a temporary storage refusal.

  • Before: The handoff expires prematurely and the requester receives no image.
  • After: The handoff retries within its elapsed-time budget and delivers the image after storage recovers.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Minimal complete repair with shipped-entry-point before/after proof, meaningful clock and custody coverage, and no remaining findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): obviyus supplies isolated Node 24 Linux built-Gateway evidence through session creation, image_generate, real completion refusal and recovery, and requester chat.history: main prematurely blocks after a forward wall-clock step, while both candidate runs deliver one image like the controls; later commits change only fixtures, and contributor output additionally covers rollback exhaustion.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A host clock correction can prevent finished media from reaching its requester or prolong a stalled completion handoff.
Reason: This restores the designed two-minute unconfirmed-handoff budget while preserving accepted queue ownership and existing user settings.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current-main mixed-clock deadline bug with a minimal production change; both prior review findings are resolved and no actionable defects remain.

Priority: P2
Reviewed head: 4a3b59dfa8a2fcb6c5c703c29ff466145f774456

Before merge

None.

Findings

None.

Agent review details

How this fits together

Background image, music, and video generation pass completed results to the completion lifecycle, which retries unconfirmed handoffs and observes accepted queue work until delivery settles.

flowchart TD
A[Media generation] --> B[Completion scheduler]
B --> C[Monotonic handoff budget]
C --> D[Completion wake]
D --> E[Durable delivery queue]
E --> F[Original requester]
C --> G[Blocked result retention]
Loading

Technical review

Best possible solution:

Keep the two monotonic clock substitutions and the updated regression fixtures at their existing owners.

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

Current-main source establishes the mixed-clock failure, supported by the supplied before/after built-Gateway comparison; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Using performance.now for both deadline calculations restores the existing elapsed-time contract without adding another timer, state owner, or compatibility path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Completion handoff deadline changes intended behavior with a stated reason (cab8040: Bound retries while the exact cron continuation remains unavailable without losing its original runtime context.)
  • Durable queue custody keeps the original intent (ff9985c: Avoid false delivery failures after queue admission while the original requester remains busy.)
  • Existing consumer regression fixtures keeps the original intent (test(ui,gateway,agents): remove low-value tests (batch d231) #175743: Consolidate repeated fixture setup while retaining distinct lifecycle and recovery contracts.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Patrick Erichsen: Raw commit ff9985c adds src/agents/tools/media-generate-background-shared.ts:159 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ff9985c61bd6; 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 0, Tests +35. Total +35 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 2 0
Tests 3 58 23 +35
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 60 25 +35

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, 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:

  • P2: Clock corrections can prematurely block generated-media delivery or extend stalled handoff retries, with a limited trigger and blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (2 earlier review cycles)
  • reviewed 2026-10-27T09:16:22.391Z sha 3822121 :: needs real behavior proof before merge. :: [P2] Update the Gateway deadline fixture for the monotonic clock
  • reviewed 2026-10-27T10:45:07.308Z sha 393ccf3 :: needs changes before merge. :: [P3] Advance the monotonic clock in the queued deadline control

Reviewed October 27, 2026, 7:10 AM ET / 11:10 UTC (Revision 3).

@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Built Gateway media-completion handoff proof

Compared main 50a1bd5e246262b947a86336da1c770680486124 with contributor candidate 38221213503a9707dbc954838d190df6af86c9e6 in isolated Node 24.22.1 Linux Docker builds.

The shipped Gateway RPC path creates a session and invokes image_generate; a deterministic local provider returns a PNG. Completion queue/transcript writes are temporarily refused for 2.5 seconds. On the first real refusal, an in-process preload steps Date.now forward 180 seconds; monotonic clocks and timers are untouched. No system-clock change or real provider credentials.

Run Clock step Result in requester chat.history Completion reentry after generation
Main 1 +180 s No image; premature blocked handoff None
Main 2 +180 s No image; premature blocked handoff None
Main control None One generated image 7.331 s
Candidate 1 +180 s One generated image 7.249 s
Candidate 2 +180 s One generated image 6.821 s
Candidate control None One generated image 7.026 s

Both main runs log media completion did not settle before the handoff deadline, 64 ms / 19 ms after the first refusal—not after the intended two-minute budget. Both candidate runs retain retry custody, recover when storage becomes available, and deliver the image to the original requester, like the no-step controls. Timing uses clocks outside the shifted process. The fixture induces a transient storage failure; it does not replace the scheduler or completion handoff implementation.

A queued-owner control confirmed that a refusal after durable queue admission does not falsely expire either version, consistent with the existing exemption.

The remaining Gateway fixture now advances its mocked monotonic clock when deliberately exhausting the deadline, keeping all blocked-retention assertions. Focused Linux checks passed: Gateway consumer 15/15, retention 20/20, shared lifecycle 29/29 (64 total). The former exhaustion timeout completed in 736 ms; queued-delivery cases passed too. Changed-file Oxfmt check passed.

This proof covers forward-clock correction through the built image-generation path; the contributor's regression matrix retains backward/zero/forward clock coverage. No broader native-channel claim is made.

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 27, 2026
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 27, 2026
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 27, 2026
@obviyus
obviyus merged commit 308ce18 into openclaw:main Oct 27, 2026
137 of 139 checks passed
@obviyus

obviyus commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Landed in 308ce18. Thanks @SunnyShu0925. Media completion handoff now ignores wall-clock jumps.

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@obviyus Thanks!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…clock (openclaw#185704)

fix(media): measure the completion handoff deadline on the monotonic clock

The media generation completion handoff measured its retry deadline with the wall clock, so a forward clock step made it give up almost at once and the generated image was never delivered. The deadline now uses monotonic time.

Evidence: shipped image_generate through a built Gateway producing a real PNG, with completion queue and transcript writes refused at first and Date.now stepped forward 180 seconds inside the process only. On main the handoff expired 64 ms and 19 ms after the first refusal and no image was delivered (twice); with this change the retries recovered and one image was delivered about 7 seconds after generation (twice), matching the no-step runs on both refs. Details: openclaw#185704 (comment). Production +2/-2.

Thanks @SunnyShu0925.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 28, 2026
…clock (#185704)

fix(media): measure the completion handoff deadline on the monotonic clock

The media generation completion handoff measured its retry deadline with the wall clock, so a forward clock step made it give up almost at once and the generated image was never delivered. The deadline now uses monotonic time.

Evidence: shipped image_generate through a built Gateway producing a real PNG, with completion queue and transcript writes refused at first and Date.now stepped forward 180 seconds inside the process only. On main the handoff expired 64 ms and 19 ms after the first refusal and no image was delivered (twice); with this change the retries recovered and one image was delivered about 7 seconds after generation (twice), matching the no-step runs on both refs. Details: #185704 (comment). Production +2/-2.

Thanks @SunnyShu0925.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 308ce18)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 9cd8dd324952857419dc9773ceccb55b96f53509)
RomneyDa added a commit that referenced this pull request Oct 28, 2026
…clock (#185704)

fix(media): measure the completion handoff deadline on the monotonic clock

The media generation completion handoff measured its retry deadline with the wall clock, so a forward clock step made it give up almost at once and the generated image was never delivered. The deadline now uses monotonic time.

Evidence: shipped image_generate through a built Gateway producing a real PNG, with completion queue and transcript writes refused at first and Date.now stepped forward 180 seconds inside the process only. On main the handoff expired 64 ms and 19 ms after the first refusal and no image was delivered (twice); with this change the retries recovered and one image was delivered about 7 seconds after generation (twice), matching the no-step runs on both refs. Details: #185704 (comment). Production +2/-2.

Thanks @SunnyShu0925.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: Ayaan Zaidi <[email protected]>

Beta.5 baseline adaptation: Retain the native beta.5 owners, fixtures and public contracts; add focused regression controls and bounded fixture extraction; apply checkout formatting.

(cherry picked from commit 308ce18)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 208c310ba770240a22835251fb2edb597d403f33)
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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