Skip to content

fix(media-understanding): keep provider operation deadline on the monotonic clock - #186134

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/provider-operation-deadline-monotonic-104
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/provider-operation-deadline-monotonic-104

Conversation

@SunnyShu0925

Copy link
Copy Markdown
Contributor

What Problem This Solves

Provider video-generation deadlines were computed on the wall clock (Date.now()), so a host clock jump (NTP correction, VM pause/resume, manual time change) corrupted the remaining-time budget and could abort perfectly healthy provider requests before their timeout, or silently stretch the timeout for unhealthy ones. This is the canonical owner of the provider-operation deadline, so the fix lands once and heals 30+ providers (byteplus, fal, google, minimax, openai, openrouter, pixverse, runway, together, xai, zai, ...).

  • Problem: deadlineAtMs was seeded with a wall-clock timestamp and the remaining budget was recomputed with Date.now(). When the wall clock jumps forward, remaining = deadlineAtMs - Date.now() goes negative and a healthy request is aborted immediately; when it jumps backward, remaining is inflated and real timeouts are stretched.
  • Solution: seed deadlineAtMs with performance.now() + resolvedTimeoutMs and compute the remaining budget with performance.now(), keeping the whole deadline on the monotonic clock.
  • What changed: in src/media-understanding/shared.ts, createProviderOperationDeadline now seeds the deadline on the monotonic clock, and both consumers of the deadline (resolveProviderOperationTimeoutMs and waitProviderOperationPollInterval) read the remaining budget from the same monotonic clock. The resolveDateTimestampMs / resolveExpiresAtMsFromDurationMs wall-clock imports are no longer used there and were dropped.
  • What did NOT change: the deadline payload shape (deadlineAtMs, label, timeoutMs), the timeout-resolution policy (resolveTimerTimeoutMs, Math.max(1, Math.min(defaultTimeoutMs, remaining))), the thrown timeout error, and every downstream provider request helper that consumes the resolved timeoutMs. No provider signature or wire behavior changed.

Why This Change Was Made

The canonical ProviderOperationDeadline mixed two clock domains: it was seeded on the wall clock but consumed downstream by buildTimeoutAbortSignal's setTimeout, which runs on the monotonic clock. Crossing clock domains makes the deadline non-monotonic under wall-clock jumps. The minimal, complete fix is to express both the seed and every remaining-budget read on the monotonic clock, which is the same clock the abort signal actually uses. A pure arithmetic difference of two monotonic reads is inherently immune to wall-clock drift.

  • Best fix: yes. Fixing the canonical owner means every provider shares the corrected behavior without per-provider changes.
  • Alternative: switch the deadline to a resolved absolute monotonic deadline per provider — rejected as it multiplies call sites and leaves the same underlying non-monotonic seed in the shared path.
  • Risk: deadlineAtMs values are no longer wall-clock timestamps. Nothing in the repo serializes or diagnoses them as such; all call sites only subtract to derive a remaining budget. A temporary debug log that prints the raw value would now show a small monotonic counter instead of an epoch, which is expected.

User Impact

Users running media-understanding providers no longer see healthy generation/download requests fail early (or hang too long) whenever the host clock is corrected or a VM is paused and resumed. Deadlines now behave identically regardless of wall-clock jumps, so provider timeouts reflect real elapsed time only.

Evidence

Live runtime proof (drives the shipped production function under a simulated wall-clock jump; pre-fix model uses the wall clock, post-fix uses the monotonic clock, same 60s budget):

$ node --import tsx .../BUG-104-...-evidence/proof.mjs
deadline seed  pre-fix (wall-clock epoch): 1793119296061
deadline seed  post-fix (monotonic):       61910.856693
remaining @now pre-fix : 59998
remaining @now post-fix: 59998.316386

wall-clock jump +120s (NTP correction / VM pause):
  pre-fix  remaining = -60002 => ABORTS a healthy request (bug)
  post-fix remaining = 59998.103593 (immune: monotonic clock ignores the wall-clock jump)

Regression test (RED → GREEN) — a new case "keeps the deadline on the monotonic clock across wall-clock jumps" drives a wall-clock jump forward/backward and asserts the remaining budget is unaffected. Against the pre-fix source it fails, against the fixed source it passes:

$ npx vitest run src/media-understanding/shared.test.ts -t "across wall-clock jumps"   # pre-fix
 × provider operation deadlines > keeps the deadline on the monotonic clock across wall-clock jumps
   → expected 120000 to be 60000
 Test Files  1 failed (1)

$ npx vitest run src/media-understanding/shared.test.ts   # post-fix
 Test Files  1 passed (1)
      Tests  29 passed (29)

The pre-fix failure (expected 120000 to be 60000) is the bug: after the forward wall-clock jump the remaining budget goes negative and the resolver returns the default timeout instead of the healthy remaining 60000ms.

Open PR collision check: searched open PR topics for this deadline/clock pattern and scanned changed-file lists of open PRs touching src/media-understanding/; no open PR modifies this file or the same fix region. (Related, distinct wall-clock fixes already merged: #169908, #165889.)

…otonic clock

Seed and consume the provider-operation deadline with performance.now()
instead of the wall clock, so a host clock jump (NTP correction, VM
pause/resume) no longer corrupts the remaining-time budget. This is the
canonical owner of the deadline, so it heals all 30+ media-understanding
providers at once. Keeps the deadline payload, timeout policy, and
downstream provider helpers unchanged.
@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.

@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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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 real behavior proof before merge.

What this changes

This PR measures shared provider-operation deadlines with performance.now() instead of Date.now().

Example: A provider operation has a 60000 ms budget when the host clock advances by 120000 ms.

  • Before: The remaining budget becomes negative and the next shared timeout check throws.
  • After: The shared timeout check retains the budget based on elapsed monotonic time.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The shared arithmetic repair is focused, but a definite bundled-provider regression blocks merge and the supplied proof stops at helper behavior.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: Host clock corrections can make media-provider operations expire early or exceed their intended timeout.
Reason: The timing repair has clear value, but changing the public deadline field's clock domain needs an SDK owner decision and a complete consumer cutover.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: the clock-skew bug remains on main, but the proposed cutover makes ordinary fal video generation fail before its first status request.

Priority: P2
Reviewed head: 05262bfd30f3cb2177ff84ec975f9c99aa672805
Owner decision: Required. See Decision needed.

Decision needed

  • Question: May the exported ProviderOperationDeadline.deadlineAtMs field change from epoch milliseconds to process-relative monotonic milliseconds?
  • Recommendation: Preserve the existing public clock contract: Have the SDK owner select a compatible way to retain epoch-facing values while shared operations measure elapsed time monotonically.
  • Why: The field and constructor are public SDK exports, and fal demonstrates direct reliance on the previous clock domain; no owner approval or public-consumer compatibility assessment is recorded.

Before merge

  • Add real behavior proof - The supplied terminal excerpt demonstrates helper-level deadline arithmetic, and the reported unit tests exercise fake clocks; neither shows a provider operation using the real transport through submission, polling, and completion after the change. Add a redacted trace of that scenario, including fal, with clock jumps; redact 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.
  • [P1] Migrate fal before changing the deadline's clock domain (P1) - The new seed is relative to process uptime, but extensions/fal/video-generation-provider.ts:315 still computes deadline.deadlineAtMs - Date.now(). After a normal successful queue submission, generateVideo creates this deadline and immediately calls that calculation at lines 432–436. For example, performance.now() = 2000 and a 1200000 ms budget produce 1202000, which becomes negative when an epoch timestamp is subtracted. Every ordinary fal video request then throws "fal video generation did not finish in time (last status: unknown)" before its first status GET, potentially leaving the submitted provider job running. Migrate fal to the shared remaining-budget resolver in this cutover and update its existing consumer tests.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] [P1] Migrate fal before changing the deadline's clock domain — src/media-understanding/shared.ts:128

Tests

  • Missing end-to-end proof: Provide a redacted production-path trace of provider submission, polling, and completion under forward/backward wall-clock jumps, including fal with the repaired clock contract.
Agent review details

How this fits together

The shared provider HTTP layer converts operation budgets into request timeouts and polling waits, and exports its deadline helpers through the Plugin SDK.

flowchart TD
  A[Media generation request] --> B[Provider plugin]
  B --> C[Shared operation deadline]
  C --> D[Shared timeout resolver]
  C --> E[Fal queue budget calculation]
  D --> F[Provider HTTP transport]
  E --> F
  F --> G[Generated media result]
Loading

Technical review

Best possible solution:

Keep one shared monotonic budget owner, migrate fal to its resolver, and settle the exported deadline field's compatibility contract.

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

Source establishes both the current-main clock-skew failure and the introduced fal failure; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Monotonic elapsed-time accounting addresses the cause, but this patch is incomplete because a direct deadline consumer remains on the epoch clock.

Full review comments:

  • [P1] [P1] Migrate fal before changing the deadline's clock domain — src/media-understanding/shared.ts:128
    The new seed is relative to process uptime, but extensions/fal/video-generation-provider.ts:315 still computes deadline.deadlineAtMs - Date.now(). After a normal successful queue submission, generateVideo creates this deadline and immediately calls that calculation at lines 432–436. For example, performance.now() = 2000 and a 1200000 ms budget produce 1202000, which becomes negative when an epoch timestamp is subtracted. Every ordinary fal video request then throws "fal video generation did not finish in time (last status: unknown)" before its first status GET, potentially leaving the submitted provider job running. Migrate fal to the shared remaining-budget resolver in this cutover and update its existing consumer tests.
    Confidence: 1

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 24e16034180f.

Provenance checked

  • Shared deadline creation and consumption changes intended behavior with a stated reason (a88c6f0: Bound live video generation smoke with one operation deadline shared across request and poll budgets.)
  • Date-range normalization and its regression changes intended behavior with a stated reason (06e0fd3: Keep epoch deadlines within the representable Date range while retaining timer-safe timeout bounds.)
  • Lazy remaining budgets across response reads keeps the original intent (40793e6: Prevent polling, error-body reads, and generated-media downloads from resetting an operation's total budget.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The introduced patch changes the deadline seed and both shared budget reads to performance.now(); it does not migrate the fal consumer. (src/media-understanding/shared.ts:128, 05262bfd30f3)
  • Reachable fal regression: Fal creates the shared deadline after submitting a video job, then immediately calls resolveFalQueueRemainingMs, which subtracts Date.now() from deadlineAtMs and throws before requesting status. (extensions/fal/video-generation-provider.ts:315, 05262bfd30f3)
  • Current main still uses epoch deadlines: The fetched main revision still seeds an epoch deadline and subtracts Date.now() in the shared resolver; the central clock-skew problem remains. (src/media-understanding/shared.ts:151, 24e16034180f)
  • Public SDK contract: provider-http exports both createProviderOperationDeadline and the structural ProviderOperationDeadline type, so changing the numeric field's clock domain reaches plugin consumers. (src/plugin-sdk/provider-http.ts:75, 05262bfd30f3)
  • Deadline provenance: The behavior appears to date to the bounded live-video smoke change, which introduced epoch-based shared deadlines; subsequent changes added timer-safe and Date-range bounds. (src/media-understanding/shared.ts:128, a88c6f0fe713)
  • Supplied proof and discussion: The body supplies helper-level clock arithmetic and reported red/green unit results; both discussion comments are bot status updates and add no provider-operation trace or owner approval. (05262bfd30f3)

Likely related people:

  • Peter Steinberger: Raw commit a88c6f0 adds src/media-understanding/shared.ts:62 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a88c6f0fe713; files: src/media-understanding/shared.ts)
  • Vincent Koc: Raw commit dfe99e9 adds src/media-understanding/shared.ts:95 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: dfe99e9cd79d; files: src/media-understanding/shared.ts)

PR surface

Source -4, Tests +9. Total +5 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 9 -4
Tests 1 20 11 +9
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 25 20 +5

Labels

Label changes:

  • add P2: Clock corrections can corrupt long-running media budgets, but the report establishes no widespread urgent production incident.
  • add merge-risk: 🚨 compatibility: The patch changes the meaning of a public SDK field and leaves a bundled consumer subtracting an epoch timestamp from a monotonic value.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: Clock corrections can corrupt long-running media budgets, but the report establishes no widespread urgent production incident.
  • merge-risk: 🚨 compatibility: The patch changes the meaning of a public SDK field and leaves a bundled consumer subtracting an epoch timestamp from a monotonic value.
  • 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.

Reviewed October 27, 2026, 1:06 PM ET / 17:06 UTC.

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

Closing: this change has been absorbed into maintainer PR #186484 (monotonic deadlines cutover). My original commit is preserved there with credit. Thanks!

obviyus added a commit that referenced this pull request Oct 28, 2026
fix: measure deadlines and budgets on one monotonic clock owner

Many deadline, budget and timeout calculations used Date.now(), so a wall-clock step (NTP correction, VM resume, manual change) made them expire early or run long. Contributors had been fixing these one call site at a time. Core now has one owner, src/shared/monotonic-time.ts, for process-local deadlines and elapsed time, replacing the supervisor-local helper and the per-site variants. Bundled extensions use performance.now() directly. Wall-clock values stay where they are persisted, shown to users or exchanged between processes: the public provider deadline stays epoch-valued, with monotonic enforcement kept privately, and the plugin SDK facade is unchanged.

This absorbs the per-site fixes from @SunnyShu0925 (#186039, #186134, #186412, #184716, #184613) and @mikasa0818 (#184576, #184525, #182064), whose original commits are kept. Update, Doctor, Windows-only and security-held sites are listed under "Not fixed here" in the PR.

Evidence: built CLI suspend wait, browser Gateway CDP waits, Discord READY wait and node host-stats checkpoint, each with Date.now stepped inside the process only. On main each misbehaved under the clock step (early expiry or a stretched wait); with this change each matched the no-step control. Media generation's guard blocks local fixtures, so that family relies on the shared owner's regression. Production 479 changed lines, tests net 0.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: mikasa0818 <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
…86484)

fix: measure deadlines and budgets on one monotonic clock owner

Many deadline, budget and timeout calculations used Date.now(), so a wall-clock step (NTP correction, VM resume, manual change) made them expire early or run long. Contributors had been fixing these one call site at a time. Core now has one owner, src/shared/monotonic-time.ts, for process-local deadlines and elapsed time, replacing the supervisor-local helper and the per-site variants. Bundled extensions use performance.now() directly. Wall-clock values stay where they are persisted, shown to users or exchanged between processes: the public provider deadline stays epoch-valued, with monotonic enforcement kept privately, and the plugin SDK facade is unchanged.

This absorbs the per-site fixes from @SunnyShu0925 (openclaw#186039, openclaw#186134, openclaw#186412, openclaw#184716, openclaw#184613) and @mikasa0818 (openclaw#184576, openclaw#184525, openclaw#182064), whose original commits are kept. Update, Doctor, Windows-only and security-held sites are listed under "Not fixed here" in the PR.

Evidence: built CLI suspend wait, browser Gateway CDP waits, Discord READY wait and node host-stats checkpoint, each with Date.now stepped inside the process only. On main each misbehaved under the clock step (early expiry or a stretched wait); with this change each matched the no-step control. Media generation's guard blocks local fixtures, so that family relies on the shared owner's regression. Production 479 changed lines, tests net 0.

Co-authored-by: SunnyShu <0668000539@local>
Co-authored-by: mikasa0818 <[email protected]>
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

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS 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