Skip to content

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

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

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

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 27, 2026 •

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).

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: no open PR touches schtasks-state-probe.ts / schtasks.settlement.test.ts (searched open PR topics settlement/schtasks/monotonic clock and changed-file lists).

Per review: added a real-Windows proof (forward + backward clock steps, before/after table) and fixed the new regression test's floating-promise lint by returning the withMockedPlatform promise from the test callback (CI check-lint-core-2).

@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 gateway Gateway runtime 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: 🧂 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 maintainer review before merge.

What this changes

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

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

  • Before: The PowerShell settlement allowance collapses to 1 ms and stop reports unverified.
  • After: The settlement allowance follows elapsed time and the stop can complete normally.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal owner-level repair supported by shipped-command Windows evidence, focused regression coverage, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor's updated evidence exercises the shipped Windows stop command against a real installed Scheduled Task Gateway with forward and backward Date.now injection, including post-fix successful completion and pre-fix refusal; this resolves the previous request for lifecycle-command proof.
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 wait too long or refuse confirmation when the system clock changes during task settlement.
Reason: Elapsed-time budgets should survive wall-clock corrections, and this fix preserves the established lifecycle behavior with no new product surface.

Merge readiness

✅ Ready for maintainer review

This PR is a focused, useful fix for a current Windows settlement bug, with no actionable code findings.

Priority: P2
Reviewed head: e804ccc7dcd02e06de364addfbbe86863fe09d2a

Before merge

None.

Findings

None.

Agent review details

How this fits together

Windows Gateway lifecycle commands capture the scheduled task's run identity, stop the owned process, and probe Task Scheduler until settlement, replacement, or timeout is established.

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

Technical review

Best possible solution:

Merge the focused clock replacement while preserving the existing settlement and ownership contracts.

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

Current-main source establishes the mixed-clock budget, and the contributor supplies pre-fix Windows CLI refusal plus red-to-green timeout regressions; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Replacing every clock read in the existing closure is the smallest complete fix: it keeps deadline arithmetic in one clock domain without adding state, configuration, or another owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock corrections can distort Windows stop and restart settlement budgets, with a bounded platform-specific 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-27T06:48:17.565Z sha 5308a067493b29792a0b270ccec83a484242abf7 :: needs real behavior proof before merge. :: [P3] Return the asynchronous regression promise to Vitest
  • reviewed 2026-10-27T07:49:45.707Z sha e804ccc :: needs real behavior proof before merge. :: none

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

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)
@SunnyShu0925
SunnyShu0925 force-pushed the fix/schtasks-state-probe-settlement-monotonic branch from 5308a06 to e804ccc Compare October 27, 2026 07:38
@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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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

🦞👀
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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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
@clawsweeper clawsweeper Bot added 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. labels Oct 27, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor 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: 👀 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