Skip to content

fix(cli): keep the gateway suspend wait window on the monotonic clock - #184576

Closed
mikasa0818 wants to merge 1 commit into
openclaw:mainfrom
mikasa0818:fix/problem-gateway-suspend-monotonic-wait
Closed

mikasa0818 wants to merge 1 commit into
openclaw:mainfrom
mikasa0818:fix/problem-gateway-suspend-monotonic-wait

Conversation

@mikasa0818

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: openclaw gateway suspend --wait N keeps issuing gateway.suspend.prepare calls far past the operator-advertised wait window when the system wall clock steps backward — the window deadline is seeded and compared on the wall clock while the poll sleeps run on monotonic timers.

User Impact

User impact: an operator's --wait N window now always ends after N seconds of real elapsed time, regardless of NTP corrections or VM/laptop resume. The CLI never issues a prepare that could suspend the Gateway after the operator's advertised window, and the bounded Timed out waiting for the Gateway to become idle outcome is reported in real time instead of hanging on a wall-clock-inflated loop.

Why This Change Was Made

runGatewaySuspend seeds deadlineMs = Date.now() + waitMs, guards each attempt with Date.now() >= deadlineMs, and computes remainingMs = deadlineMs - Date.now(), while the poll sleeps through node:timers/promises on the monotonic clock. A backward wall-clock step stretches the window by the step, so the loop keeps issuing real prepare calls for N + step.

The window now lives on performance.now() — seed, per-attempt guard, and remaining computation — which is monotonic and unaffected by wall-clock adjustments. This continues the cross-clock-domain series (#174151, #181335, and the merged fleet: #155846, #182180, #182778, #182859, #183742); the suspend wait window is an unclaimed CLI site in the same family.

The committed regression runs on real timers with a short 200ms window (the window sleeps through node:timers/promises, which fake timers cannot replace) and only the wall-clock reading rewound; the fixed tree stops preparing within the real window while a rewound wall clock keeps every maxAttempts attempt running. The existing suite's mockClock now advances a mocked performance.now reading alongside Date.now, preserving its original assertions.

No suspend protocol, lease, or resume semantics change; behavior on a clock that never steps is identical.

Evidence

Pre-fix RED — stock main (d18177d60f9), regression test only: every prepare reports busy with a 150ms retry hint, the window is 200ms, and the wall clock is frozen 10 minutes behind. Stock main runs every maxAttempts attempt:

$ node scripts/run-vitest.mjs run src/cli/gateway-cli/suspend-cli.monotonic.test.ts
 × ends the wait window at its monotonic deadline when the wall clock rewinds
   → expected 5 to be less than or equal to 3

Post-fix GREEN — the same scenario stops preparing within the real window, and both suites pass:

$ node scripts/run-vitest.mjs run src/cli/gateway-cli/suspend-cli.monotonic.test.ts src/cli/gateway-cli/suspend-cli.test.ts
      Tests  9 passed (9)

Real runtime proof (real Gateway WebSocket transport, in-process wall-clock rewind)

A real local WebSocket gateway fixture speaks the real Gateway wire protocol (server connect.challenge → client connect → hello-ok → gateway.suspend.prepare responses). The production callGatewayFromCliWithTransport runs its full client stack — event-loop readiness, device identity bootstrap, challenge connect — and every prepare answers busy with a 500ms retry hint. Only Date.now is rewound in-process; performance.now() reports all real elapsed times. The window is a real 30-second --wait. (Captured in a standalone Node process so no vitest worker keeps the event loop busy; the client bootstrap takes ~19s before the first prepare.)

TRACE[suspend] t=32ms    real gateway WebSocket fixture listening on ws://127.0.0.1:<port>
TRACE[suspend] t=18516ms wall clock rewound by -600000ms (in-process Date.now injection) after the first real prepare
TRACE[suspend] t=18517ms RPC gateway.suspend.prepare -> {status:"busy", retryAfterMs:500} (prepare #1)
TRACE[suspend] t=19037ms RPC gateway.suspend.prepare -> ... (prepare #2)
TRACE[suspend] t=28363ms RPC gateway.suspend.prepare -> ... (prepare #20)
PROOF[suspend] variant=fixed wait=30000ms wall_rewind=-600000ms -> state=completed prepares=24 exit=1 settled_by_cap=true cap_elapsed_real_ms=30422

TRACE[suspend] t=18984ms wall clock rewound by -600000ms (in-process Date.now injection) after the first real prepare
TRACE[suspend] t=23649ms RPC gateway.suspend.prepare -> ... (prepare #10)
PROOF[suspend] variant=old wait=30000ms wall_rewind=-600000ms -> state=still-waiting-at-cap prepares=81 exit=1 settled_by_cap=false cap_elapsed_real_ms=60683

Stock main is still issuing real prepare calls at the 60-second cap (81 prepares, past the whole 30-second window — it would continue for the length of the rewind); with this PR the window ends at 30.4s of real time after 24 real prepares and reports the bounded busy outcome.

Behavior matrix (prepare always busy, retryAfterMs: 500, --wait 30, wall clock rewound 10min at prepare #1):

clock during window          => window ends             => result
normal (no step)             => after 30s               => bounded busy report
wall rewind 10min (pre-fix)  => still preparing at 60s  => unbounded by the step
wall rewind 10min (post-fix) => after 30s               => bounded busy report

Also verified on the changed tree: pnpm format:check and the changed-file lint/typecheck lanes from pnpm check:changed (the pnpm/corepack-shelling lanes fail on this Windows contributor box for the environmental reasons documented on #182778/#182859/#183742, unrelated to this diff). CI runs those lanes authoritatively.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 cli CLI command changes size: S labels Oct 26, 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Measures the Gateway suspend polling window with performance.now() instead of Date.now().

Example: Run openclaw gateway suspend --wait 30 while the Gateway stays busy and the wall clock moves backward 10 minutes.

  • Before: The CLI continues sending prepare requests beyond the 30-second polling window.
  • After: The CLI stops retrying when the monotonic polling deadline expires.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The production repair is focused and supported by real-transport evidence, but the committed regression still fails on fixture recursion rather than the original defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The supplied standalone-process trace exercises the suspend polling owner through the production Gateway RPC client and a real WebSocket transport, injecting a backward wall-clock step and recording bounded completion after the fix versus continued prepares before it.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A backward wall-clock adjustment lets suspend polling continue beyond the operator's requested wait window.
Reason: The change restores the documented bounded polling contract through the existing owner without adding configuration or changing suspension policy.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR fixes a current clock-domain bug, but the previously reported recursive Date.now mock remains in the regression test.

Priority: P2
Reviewed head: 17c1b64872b5ccf6e15ea9c53744b42378ba6dc6

Before merge

  • Return a captured wall-clock value from the Date.now mock (P2) - The earlier finding remains: rewound is initially false, so this replacement calls Date.now(), which invokes the replacement recursively. Running the regression against the base therefore overflows the stack during deadline initialization before any prepare, while the fixed implementation can pass because it avoids Date.now. Capture the initial numeric wall-clock value before installing the spy, return it until the rewind, and verify that the base fails on excess prepares and the head passes.

Findings

  • [P2] Return a captured wall-clock value from the Date.now mock — src/cli/gateway-cli/suspend-cli.monotonic.test.ts:36-38

Tests

  • Missing end-to-end proof: The committed regression still lacks valid base-red evidence for clock rewind because its base execution recurses during deadline initialization.
Agent review details

How this fits together

The suspend CLI converts an operator's wait duration into a polling deadline, sends Gateway prepare RPCs, and reports either a suspension lease or a busy outcome.

flowchart LR
  A[Operator command] --> B[Suspend CLI]
  C[Monotonic clock] --> B
  B --> D[Gateway RPC client]
  D --> E[Gateway prepare response]
  E --> B
  B --> F[Lease or busy outcome]
Loading

Technical review

Best possible solution:

Keep the three monotonic clock substitutions and repair the regression fixture to fail on excess prepares on the base.

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

Current-main source shows the wall-clock deadline paired with elapsed-time sleeps, and the supplied real-WebSocket trace demonstrates continued prepares after a backward clock step; no target code was executed during this review.

Is this the best way to solve the issue?

Changing all three deadline reads in the existing polling owner is the smallest complete production repair and preserves lease timestamps, request identity, and protocol behavior.

Full review comments:

  • [P2] Return a captured wall-clock value from the Date.now mock — src/cli/gateway-cli/suspend-cli.monotonic.test.ts:36-38
    The earlier finding remains: rewound is initially false, so this replacement calls Date.now(), which invokes the replacement recursively. Running the regression against the base therefore overflows the stack during deadline initialization before any prepare, while the fixed implementation can pass because it avoids Date.now. Capture the initial numeric wall-clock value before installing the spy, return it until the rewind, and verify that the base fails on excess prepares and the head passes.
    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 4ca8912994b3.

Provenance checked

  • Suspend deadline and retry admission keeps the original intent (61ab6a8: The original feature added bounded polling and an explicit guard against issuing another prepare after the requested deadline; feat(gateway): make suspend/resume operator-usable end to end #122100 documents that intent.)
  • Direct clock ownership keeps the original intent (8b680f3: refactor: remove unused CLI and infrastructure arguments #178163 removed test-only dependency arguments in favor of canonical clock and timer owners, with no intended user-visible change.)
  • Existing suspend tests keeps the original intent (95dff1e: The supplied provenance records removal of redundant test layers while retaining distinct lifecycle and error-path assertions; advancing the new clock in the retained fixture preserves those assertions.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • On an isolated base checkout with the corrected regression only: node scripts/run-vitest.mjs run src/cli/gateway-cli/suspend-cli.monotonic.test.ts; confirm excess prepares cause the failure rather than recursion.
  • On the repaired head: node scripts/run-vitest.mjs run src/cli/gateway-cli/suspend-cli.monotonic.test.ts src/cli/gateway-cli/suspend-cli.test.ts
  • pnpm exec oxfmt --check src/cli/gateway-cli/suspend-cli.monotonic.test.ts
  • pnpm exec oxlint src/cli/gateway-cli/suspend-cli.monotonic.test.ts
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 61ab6a8 adds src/cli/gateway-cli/suspend-cli.ts:86 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 61ab6a8f9d15; files: src/cli/gateway-cli/suspend-cli.ts)

PR surface

Source +3, Tests +68. Total +71 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 6 3 +3
Tests 2 68 0 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 74 3 +71

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock adjustments can extend an operator's suspend polling window and allow later prepare requests, with limited impact on this advanced CLI workflow.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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-26T11:52:24.572Z sha 8bddfd91b87b5246ef79897994cad0e29fb72332 :: needs changes before merge. :: [P2] Use a complete OutputRuntimeEnv in the regression | [P3] Drive the regression with the existing mocked sleep and clocks
  • reviewed 2026-10-26T12:47:33.677Z sha 10323c37e079c340f637b91730e2d62245dac5f1 :: needs changes before merge. :: [P2] Return a captured wall-clock value from the Date.now mock

Reviewed October 26, 2026, 8:59 AM ET / 12:59 UTC (Revision 3).

@mikasa0818
mikasa0818 force-pushed the fix/problem-gateway-suspend-monotonic-wait branch from 8bddfd9 to 10323c3 Compare October 26, 2026 12:42
@mikasa0818

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 26, 2026
@mikasa0818
mikasa0818 force-pushed the fix/problem-gateway-suspend-monotonic-wait branch from 10323c3 to 17c1b64 Compare October 26, 2026 12:55
@mikasa0818

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 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. 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 26, 2026
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]>
@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Thanks @mikasa0818. This is now fixed at the root in #186484 (bf10fbe): process-local deadlines and budgets go through one monotonic clock owner, src/shared/monotonic-time.ts (bundled extensions use performance.now()). Your commit from this PR is kept in that merge and you're credited as co-author, so I'm closing this one as covered. For new deadline code, please use that owner rather than a per-site change.

@obviyus obviyus closed this Oct 28, 2026
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

cli CLI command changes P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants