Skip to content

fix(agents): keep runtime auth deadline budget in the monotonic domain - #190976

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/runtime-auth-deadline-wall-clock-budget-280
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/runtime-auth-deadline-wall-clock-budget-280

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

When the host clock is corrected backward (NTP resync) between the moment the startup auth budget is seeded and the moment the remaining budget is read, the embedded-agent-runner stretched that budget. The seed and the read both used Date.now(), while the budget is consumed by a relative setTimeout. This change seeds the startup budget in the monotonic domain so a backward step can no longer extend it.

  • Problem: createRuntimeAuthDeadline seeded its startup deadline with Date.now() + timeoutMs and read the remaining budget as deadline.deadlineAtMs - Date.now(). A backward jump between those two reads inflated remainingMs, so the startup auth exchange received far more than its configured timeoutMs.
  • Solution: seed the startup deadline with monotonicNow() (frozen at creation) and read each source in its own clock domain — the startup path subtracts monotonicNow(), the upstream path keeps subtracting Date.now().
  • What changed: src/agents/runtime-auth-refresh.ts (seed + per-source read) and a new src/agents/runtime-auth-refresh.test.ts covering both paths.

Why This Change Was Made

Only the startup deadline is moved into the monotonic domain. It is the budget this helper owns: seed and read both live inside createRuntimeAuthDeadline, so freezing it at creation removes the seed→read jump entirely. The upstream getDeadline() source is a different owner's value — a wall-clock epoch by contract — and this helper does not reseed it. Reading it against Date.now() is therefore arithmetically unchanged, and a backward correction still stretches that one source. That is an existing upstream limitation, named here rather than claimed as fixed. The two sources are told apart by reference equality (deadline === startupDeadline).

  • Best fix: yes for the startup budget — remove the mixed-clock seed at its single owner.
  • Alternative rejected: a boundary conversion (monotonicNow() + Math.max(0, deadlineAtMs - Date.now()) for both sources) cancels its own two monotonicNow() reads, so it leaves the startup seed→read stretch exactly as it was while implying protection it does not provide.
  • Risk: the same-family wall-clock pattern in attempt-async-tasks.ts and attempt-stream-settle.ts and the upstream deadline epoch are untouched; they are separate follow-ups, not regressions introduced here.

User Impact

An embedded-agent run no longer waits longer than its configured startup auth budget when the host clock steps backward during a provider authentication exchange. A stalled exchange aborts at timeoutMs instead of holding the run slot for the inflated budget.

Evidence

1. Real stalled exchange through the shipped runner

A real openclaw agent --local run against microsoft-foundry with apiKey: "__entra_id_dynamic__" performs the provider's real prepareRuntimeAuthV2 exchange, with az replaced by a local script that accepts the call and then never answers (a stalled authentication service). agents.defaults.timeoutSeconds is 8. A preload shim reads each deadline seed on the real clock and rewinds Date.now() by 20s on every later read — a backward NTP step.

$ CLOCK_REWIND_MS=20000 openclaw agent --local -m "hi"
[clock-probe] seed observed via performance.now; rewinding Date.now by 20000ms from here
[diagnostic] lane task error: lane=main durationMs=-11828 error="microsoft-foundry runtime auth exchange timed out at the run deadline (7997ms). Check the provider's authentication service and retry the run." errorName=AbortError taskKind=turn sessionKey=agent:main:main runId=<redacted> modelFallbackCandidate=true
[clock-probe] exit=1 armed=true rewoundDateNowReads=95

durationMs=-11828 is the rewind itself: the run measures its own duration with the Date.now() the shim moved back, so 20s − 8.17s ≈ 11.8s. The stalled exchange still aborted at its 7997ms budget.

2. Same code, pre-fix vs post-fix budget

The real createRuntimeAuthDeadline driven through the real withTimeout/setTimeout consumer, with the same shim and a 5000ms budget:

                        pre-fix (origin/main)        post-fix (this branch)
budget fed to setTimeout    38000ms (5s + 30s step)     7999.8ms (unchanged)

Pre-fix source: deadlineAtMs: Date.now() + timeoutMs then deadlineAtMs - Date.now(); the 30s backward step lands entirely inside that difference. Post-fix the seed and the read are the same monotonic clock, so the step is invisible.

3. Behavior matrix (budget captured from setTimeout, 5000ms budget, clock rewound 30s)

scenario                                   => pre-fix        => post-fix
startup deadline (getDeadline() undefined) => 35000ms        => 5000ms
upstream wall-clock queue deadline         => 35000ms        => 35000ms

The second row is the documented upstream limitation: its test pins the bounded-budget contract only, not clock-jump immunity.

4. Unit regression

$ node scripts/run-vitest.mjs src/agents/runtime-auth-refresh.test.ts --run
# pre-fix source, test kept:  expected 35000 to be less than or equal to 5000  (1 failed | 1 passed)
# post-fix:                   Test Files 1 passed (1), Tests 2 passed (2)

auth-controller.test.ts (the caller's suite) passes 39/39.

Collision check: no open PR touches src/agents/runtime-auth-refresh.ts or embedded-agent-runner/run/auth-controller.ts; origin/main still carries the wall-clock seed bug.

@clawsweeper

clawsweeper Bot commented Nov 2, 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.

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: 11b2c8ef5752880434f8ed3662775fdf147b567f

These sensitive security changes were made:

  • src/agents/runtime-auth-refresh.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@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: 🧂 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 Nov 2, 2026
@clawsweeper

clawsweeper Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR measures the startup authentication deadline with a monotonic clock while preserving upstream epoch deadlines.

Example: A 5-second startup authentication budget encounters a 30-second backward wall-clock correction.

  • Before: The remaining timeout can grow to 35 seconds.
  • After: The startup timeout remains within its 5-second budget.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused contract repair with supplied shipped-entry-point proof, supporting regression coverage, and no identified introduced defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied terminal trace exercises the changed startup deadline through openclaw agent --local, the real microsoft-foundry runtime-auth exchange, and a deliberately hung az process while Date.now() rewinds by 20 seconds; the exchange aborts at its approximately 8-second budget, addressing the prior review's requested scenario.
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 leave a stalled startup authentication exchange occupying the run longer than its configured timeout.
Reason: This restores the existing startup-budget contract without adding settings, public APIs, storage, or another policy owner.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR fixes a current startup authentication timeout defect, resolves the prior scope concern, and introduces no identified correctness defect.

Priority: P2
Reviewed head: 11b2c8ef5752880434f8ed3662775fdf147b567f

Before merge

  • Await maintainer action - A maintainer must review and approve the security-sensitive change at head 11b2c8e using the enforced approval command.

Findings

None.

Agent review details

How this fits together

The embedded runner's auth controller supplies credential lookup and token exchange operations to the deadline helper, which returns their result or aborts authentication when the shared budget expires.

flowchart TD
  A[Embedded agent runner] --> B[Auth controller]
  B --> C[Runtime auth deadline]
  D[Monotonic startup budget] --> C
  E[Upstream epoch deadline] --> C
  C --> F[Credential lookup and exchange]
  F --> G[Result or authentication abort]
Loading

Technical review

Best possible solution:

Retain the focused monotonic startup-budget repair in the existing deadline owner without changing the upstream epoch contract.

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

Current-main source directly shows the seed-to-read wall-clock rollback failure, supported by the contributor's baseline regression output; this read-only review ran no target code.

Is this the best way to solve the issue?

The change repairs elapsed-time accounting at its existing owner, reuses the shared monotonic clock, and preserves unlimited deadlines, cancellation, and upstream deadline semantics.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Startup authentication budget keeps the original intent (7bd53ff: Bound stalled credential lookup and runtime token exchange with one shared startup budget, then consume the execution owner's published deadline.)
  • Deadline and auth-controller ownership keeps the original intent (bae3b0b: Remove redundant forwarding machinery while retaining deadline, cancellation, account-authority, and error behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • RoboClaw: Raw commit 7bd53ff adds src/agents/runtime-auth-refresh.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7bd53ff28f69; files: src/agents/runtime-auth-refresh.ts)

PR surface

Source +13, Tests +66. Total +79 across 2 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 15 2 +13
Tests 1 66 0 +66
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 81 2 +79

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Backward clock corrections can extend stalled startup authentication beyond the configured budget, with limited scope and no established urgent release impact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • 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 (1 earlier review cycle)
  • reviewed 2026-11-02T08:38:50.684Z sha 05744d1217e340f447f8d741e93b4db05c95866d :: needs real behavior proof before merge. :: [P3] Limit the clock-jump guarantee to the startup deadline

Reviewed November 2, 2026, 4:55 AM ET / 09:55 UTC (Revision 2).

startupDeadline was seeded from Date.now() and the remaining budget read
from Date.now() at each withTimeout call. A backward host clock (NTP
correction) between seed and read stretched remainingMs, letting the auth
exchange overrun its run deadline budget. Seed the own deadline with
monotonicNow() and convert an upstream wall-clock command-queue deadline
to the monotonic domain at the boundary (cf. run-wait.ts).
@SunnyShu0925
SunnyShu0925 force-pushed the fix/runtime-auth-deadline-wall-clock-budget-280 branch from 05744d1 to 11b2c8e Compare November 2, 2026 09:49
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Refreshed for the current head. Changes since the last review:

  • Dropped the boundary-conversion claim and the deadlineAtMs intermediate; each deadline source is now read in its own clock domain, and the upstream wall-clock source is named as an existing limitation instead of being implied fixed.
  • Added real behavior proof: a stalled prepareRuntimeAuthV2 exchange (foundry + a hung az) through the shipped runner aborts at its 7997ms budget with Date.now() rewound 20s, plus a pre-fix/post-fix setTimeout budget comparison (38000ms → 7999.8ms).
  • Body corrected: behavior matrix upstream row now reads 35000ms → 35000ms (unchanged), and the "what was not tested" section is replaced by the executed proof.

@clawsweeper

clawsweeper Bot commented Nov 2, 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: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 2, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 8, 2026
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the work here. We're closing this along with the other open PRs that apply the same change one call site at a time. This series moves individual deadlines to the monotonic clock one at a time; the shared owner is src/shared/monotonic-time.ts, and remaining call sites should be handled together. Please open one issue (or one PR at the shared owner) that covers the whole pattern, with a reproduction of real user-visible harm, instead of separate per-site PRs. Further per-site variants of this pattern will be closed.

@obviyus obviyus closed this Nov 16, 2026
obviyus added a commit that referenced this pull request Nov 16, 2026
fix: keep five local elapsed-time waits on the monotonic clock

Five local waits measured elapsed time with the wall clock, so a clock step (NTP correction, sleep/wake, manual change) ended them early or let them overrun: the exec-approval follow-up wait, the runtime auth deadline, the managed update handoff response wait, and two Windows scheduled-task waits (process exit and settlement). They now use `src/shared/monotonic-time.ts`, passing `monotonicNow` to `scheduleAbsoluteDeadline` where it's used. Epoch values that cross process, RPC or persistence boundaries stay epochs, RPC timeouts stay integers, upstream epoch auth deadlines are untouched, and the handoff `closed` command keeps its helper-owned settlement. No new text.

Evidence: full-build CLI with the process-local Date.now stepped by a preload in that process only, main twice and this change twice, plus unstepped controls. Exec-approval follow-up: main ends after about 60 s; this change waits the real ~360 s, the same as unstepped. Runtime auth: a forward step makes main expire after ~367 ms of a ~9.3 s allowance and a backward step makes it overrun to ~12.4 s; this change keeps the allowance and aborts on time. The Windows scheduled-task sites have unit-level proof with a stepped clock, and the handoff wait has source-level proof through a real child pipe. 75 consumer and 55 daemon tests pass; full build and packed smoke pass. CI red is inherited from main (receipt: #199951 (comment)). Receipts: #199951 (comment).

Supersedes the closed per-site PRs #181942, #187439, #190976, #195457, #199640 and #199665.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…199951)

fix: keep five local elapsed-time waits on the monotonic clock

Five local waits measured elapsed time with the wall clock, so a clock step (NTP correction, sleep/wake, manual change) ended them early or let them overrun: the exec-approval follow-up wait, the runtime auth deadline, the managed update handoff response wait, and two Windows scheduled-task waits (process exit and settlement). They now use `src/shared/monotonic-time.ts`, passing `monotonicNow` to `scheduleAbsoluteDeadline` where it's used. Epoch values that cross process, RPC or persistence boundaries stay epochs, RPC timeouts stay integers, upstream epoch auth deadlines are untouched, and the handoff `closed` command keeps its helper-owned settlement. No new text.

Evidence: full-build CLI with the process-local Date.now stepped by a preload in that process only, main twice and this change twice, plus unstepped controls. Exec-approval follow-up: main ends after about 60 s; this change waits the real ~360 s, the same as unstepped. Runtime auth: a forward step makes main expire after ~367 ms of a ~9.3 s allowance and a backward step makes it overrun to ~12.4 s; this change keeps the allowance and aborts on time. The Windows scheduled-task sites have unit-level proof with a stepped clock, and the handoff wait has source-level proof through a real child pipe. 75 consumer and 55 daemon tests pass; full build and packed smoke pass. CI red is inherited from main (receipt: openclaw#199951 (comment)). Receipts: openclaw#199951 (comment).

Supersedes the closed per-site PRs openclaw#181942, openclaw#187439, openclaw#190976, openclaw#195457, openclaw#199640 and openclaw#199665.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawtributors PR from a clawtributor 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. security-review-required security-sensitive-changed size: S status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants