Skip to content

fix(daemon): use monotonic clock for scheduled task settlement deadline - #199640

Closed
shuisadev wants to merge 1 commit into
openclaw:mainfrom
shuisadev:resub/schtasks-state-probe-settlement-monotonic
Closed

shuisadev wants to merge 1 commit into
openclaw:mainfrom
shuisadev:resub/schtasks-state-probe-settlement-monotonic

Conversation

@shuisadev

Copy link
Copy Markdown
Contributor

What Problem This Solves

On Windows, stopping or updating the Gateway can hang or bail out early when the system clock is adjusted: the scheduled-task settlement probe computes its deadline and remaining budget from Date.now() (wall clock) while the PowerShell probe's spawnSync timeout and the poll sleep are monotonic timers. A clock jump forward shrinks the probe timeout (a 280s budget collapsed to 50s, or 1ms past a 330s roll), killing PowerShell before settlement can be observed; a clock jump backward keeps the wall-clock deadline from ever elapsing, so the loop never exits. The fix uses a monotonic clock (performance.now()) for the deadline and remaining budget, matching the sibling isScheduledTaskDefinitionAbsent in the same file.

  • Problem: prepareScheduledTaskSettlement seeds its deadline and reads the remaining budget from the wall clock (Date.now()), while the consuming spawnSync timeout and sleep poll are monotonic timers — a cross-clock-domain budget.
  • Solution: compute deadline, remaining, and the exit comparisons with performance.now() so the budget lives entirely on the monotonic clock.
  • What changed: all six Date.now() usages inside prepareScheduledTaskSettlement in src/daemon/schtasks-state-probe.ts became performance.now(), plus a new regression test and an update to the existing settlement test's clock mock.
  • What did NOT change: the caller contract (stopScheduledTask / restartScheduledTask), the settlement result shape, and the default timeout constants all remain unchanged.

Why This Change Was Made

prepareScheduledTaskSettlement is the only cross-clock-domain spot left in this file: its sibling isScheduledTaskDefinitionAbsent already computes remainingTimeout() and expired() from performance.now(), and the file's other deadline helpers use performance.now() too. The settlement deadline is a purely process-internal closure variable — never serialized, persisted, or compared across processes — so a full switch to the monotonic clock is safe and keeps the budget aligned with the monotonic timers that consume it. No new parser, policy branch, or configuration surface is introduced. The existing schtasks.settlement.test.ts clock mock was moved from Date.now() to performance.now() while preserving the test's intent (settlement exhausts the full stop budget without a false restart).

  • Best fix: keep the budget and its consumers on one clock domain. performance.now() is exactly the clock the surrounding spawnSync timeout and poll sleep already use, so the deadline can no longer be skewed by a wall-clock step.
  • Alternative(s): (a) clamp the wall-clock delta to a maximum step — rejected because it still mixes clock domains and cannot recover a lost budget; (b) pass an injected clock through the caller contract — rejected because it widens a public signature for a purely internal deadline; (c) leave the deadline in wall-clock and shorten the probe timeout — rejected because it trades a hang for a false settlement unavailable.
  • Risk: performance.now() is monotonic per process, so a deadline seeded before a process restart is not portable — not a concern here because the deadline is a local closure variable read only within one call. Node's performance.now() resolution on Windows is millisecond-class, matching the previous Date.now() granularity, so the sub-second comparisons keep their behavior. Boundary left unchanged: the default timeout constants and the stop/restart caller contract.

User Impact

Windows Gateway stop/update no longer stalls or fails spuriously when the system clock is adjusted (NTP resync, manual set, DST), because the settlement deadline is no longer skewed by wall-clock jumps. The settlement still waits the full configured stop budget before declaring the task unavailable, and still refuses a restart only when settlement genuinely cannot be confirmed.

Evidence

Real shipped command, real runner (before/after): a windows-latest runner installs a real Scheduled-Task Gateway (openclaw gateway install), then runs the actual shipped openclaw gateway stop --force while a preload steps the wall clock (Date.now(); performance.now() stays monotonic) between the settlement deadline seed and budget read — exactly the NTP/manual-set/DST incident. Both builds drive the real schtasks.exe/PowerShell subprocess; the only difference is the clock source of the settlement deadline (Date.now() pre-fix vs performance.now() post-fix):

wall-clock jump pre-fix (Date.now deadline) post-fix (performance.now deadline)
+280s (forward, in-roll) openclaw gateway stop ok (50s budget) ok (full 60s budget)
+380s (forward, past roll) stop FAILS (1ms budget → settlement unavailable → unverified) ok (full 60s budget, inert)
-280s (backward) ok (inflated budget, over-waits) ok (inert)

Proof artifact + workflow: SunnyShu0925/oc-winproof run #40486854535.

Raw CLI output (inline, current head e804ccc7dcd) — verbatim, redacted to service/port only (no IPs, keys, endpoints):

$ # post-fix (performance.now deadline): clock +280s between deadline seed and budget read
$ openclaw gateway stop --force --json
stop exit=0 elapsed=6.4801074s
{ "action": "stop", "ok": true, "result": "stopped",
  "service": { "label": "Scheduled Task", "loaded": true, "loadedText": "registered" } }
[proof-inject] settlement Date.now reads stepped: 5   # wall clock jumped, deadline monotonic -> inert
VERDICT[post-fix-forward]: STOPPED bounded completion in 6.4801074s

$ # pre-fix (Date.now deadline): same command, clock +380s (past the 330s roll) collapses remaining to 1ms
$ openclaw gateway stop --force --json
stop exit=1 elapsed=4.443505s
{ "action": "stop", "ok": false,
  "error": "Gateway stop failed: Error: Task settlement unavailable; stop unverified.",
  "hints": ["Run openclaw gateway status --deep to inspect the service, then retry."] }
VERDICT[pre-fix-forward-380]: STOP_REFUSED exit=1

Under the same wall-clock jump the pre-fix build fails the very openclaw gateway stop that succeeds on the post-fix build: the collapsed 1ms budget times out the real PowerShell probe, settlement reports unavailable, and terminate() refuses to confirm the stop. The backward jump is equally inert post-fix (stop exit=0 elapsed=5.41s).

Unit regression (forward wall-clock skew), pre-fix RED / post-fix GREEN:

$ vitest run src/daemon/schtasks-state-probe.test.ts   # pre-fix (reverted to Date.now)
AssertionError: expected 50000 to be 60000   (280000 ms)
AssertionError: expected 1 to be 60000        (380000 ms)
$ vitest run src/daemon/schtasks-state-probe.test.ts   # post-fix (monotonic)
Test Files  1 passed (1)
     Tests  18 passed (18)
$ vitest run src/daemon/schtasks.settlement.test.ts
Test Files  1 passed (1)
     Tests  37 passed (37)

Full daemon shard: 118 files / 1943 tests passed.

Beyond the clock budget, the settlement state machine and its JSON parsing are not re-tested here: they are covered by the existing 37-test settlement suite (unchanged apart from its clock-mock alignment).

Open PR collision check: searched open PR topics settlement/schtasks/monotonic clock and changed-file lists — no open PR touches src/daemon/schtasks-state-probe.ts or src/daemon/schtasks.settlement.test.ts. The long-lived draft #138344 also edits src/daemon/schtasks-state-probe.ts, but its scope is scheduled-task definition listing, not the settlement deadline clock source.

This replaces a previously closed PR carrying the identical commit (same fix, same proof); the branch is unchanged apart from being pushed from a different fork.

prepareScheduledTaskSettlement computed its deadline and remaining budget
with Date.now() (wall clock) while the consuming probe's spawnSync timeout
and sleep poll are monotonic timers. A wall-clock jump forward shrank the
probe timeout (a 280s budget became 50s, or 1ms past a 330s roll), killing
PowerShell prematurely; a backward roll could keep the deadline loop from
exiting. Align with the sibling isScheduledTaskDefinitionAbsent, which
already uses performance.now() for the same budget. Update the settlement
test's clock mock to drive performance.now(), which now owns the deadline.

Ref: BUG-149-schtasks-state-probe-settlement-deadline-wall-clock (local finding)
@clawsweeper

clawsweeper Bot commented Nov 15, 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 gateway Gateway runtime size: XS labels Nov 15, 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: 🦞 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR measures Scheduled Task settlement deadlines with performance.now() so wall-clock adjustments cannot distort the waiting budget.

Example: The wall clock advances 380 seconds during openclaw gateway stop --force --json.

  • Before: The settlement probe allowance collapses to 1 ms, and stop can report settlement unavailable.
  • After: The probe allowance follows elapsed time, allowing settlement to be observed normally.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal owner-level repair with shipped-command evidence, focused regression coverage, and no actionable findings; workflow approval remains a separate landing gate.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor supplies Windows shipped-CLI stop output against a real installed Scheduled Task Gateway, with successful post-fix completion under injected clock skew and pre-fix settlement refusal; inspected workflow and preload sources support that 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: Windows Gateway stop or restart can refuse confirmation or wait too long when the system clock changes during task settlement.
Reason: Elapsed-time budgets should survive wall-clock corrections, and the patch preserves existing lifecycle policy and defaults.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR fixes a current Windows settlement deadline bug with a minimal change and no actionable code findings. Its required CI workflows await approval.

Priority: P2
Reviewed head: e804ccc7dcd02e06de364addfbbe86863fe09d2a

Before merge

Findings

None.

Agent review details

How this fits together

Windows Gateway lifecycle commands capture the Scheduled Task run identity, stop the owned processes, and consume settlement observations before confirming stop or attempting restart.

flowchart TD
  A[Gateway stop or restart] --> B[Capture task run identity]
  B --> C[Stop owned Gateway processes]
  C --> D[Monotonic settlement budget]
  D --> E[PowerShell Task Scheduler query]
  E --> F[Settled replaced or unavailable]
Loading

Technical review

Best possible solution:

Keep all settlement deadline arithmetic on performance.now() within the existing lifecycle owner.

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

Current-main source establishes the mixed-clock budget, and supplied Windows CLI output demonstrates pre-fix refusal under forward clock skew; no target code was executed during this review.

Is this the best way to solve the issue?

Replacing every clock read in the existing closure is the smallest complete fix, preserving settlement outcomes without introducing another owner, configuration, or persisted state.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Scheduled Task settlement deadline keeps the original intent (5232aba: Wait for the captured task run to settle while preserving replacement processes and reporting unavailable inspection honestly.)
  • Settlement exhaustion fixture keeps the original intent (808458d: Consolidate fixtures while retaining distinct settlement timeout, recovery, and refusal contracts.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5232aba adds src/daemon/schtasks-state-probe.ts:286 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5232aba0030e; files: src/daemon/schtasks-state-probe.ts)
  • RoboClaw: Raw commit 47a9e77 adds src/daemon/schtasks-state-probe.ts:30 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 47a9e77007f7; files: src/daemon/schtasks-state-probe.ts)

PR surface

Source 0, Tests +35. Total +35 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 6 0
Tests 2 36 1 +35
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 42 7 +35

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: canonical
Canonical: #199640
Summary: This PR carries the identical unmerged repair from the earlier closed submission.

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:

  • P2: Wall-clock corrections can distort Windows Gateway stop and restart settlement budgets, with a platform-specific blast radius.
  • 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.

Reviewed November 15, 2026, 10:12 AM ET / 15:12 UTC.

@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

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: XS 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.

2 participants