Skip to content

fix(gateway): keep node host-stats checkpoint deadline on the monotonic clock - #184716

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/node-host-stats-checkpoint-deadline-monotonic-239
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/node-host-stats-checkpoint-deadline-monotonic-239

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

When a node reports host telemetry (CPU/memory) to the Gateway, NodeHostStatsCheckpoints throttles disk persistence to one write every 5 minutes per node. That deadline lived on the wall clock: the timer delay was Math.max(0, deadline - Date.now()) and the callback re-read Date.now() to decide whether the budget had elapsed. A clock correction therefore moved the budget: a backward jump slipped the checkpoint by the jump size, and a forward jump fired it early.

  • Problem: system-clock corrections slip or pre-fire host-telemetry checkpoint persistence, with no error surfaced.
  • Solution: pair every received sample's persisted wall-clock receipt with the monotonic clock while the two are still in sync (record), snapshot that deadline with the sample being written, and promote it once the write succeeds. Both the setTimeout delay and the fire-time check then run on performance.now(), and later schedules reuse the stored deadline instead of re-reading the wall clock.
  • What changed: src/gateway/node-registry.host-stats.ts (NodeHostStatsCheckpoints and its private checkpoint type) plus three cases folded into the existing host stats checkpoints suite in src/gateway/node-registry-pairing.test.ts.
  • What did NOT change: updatedAtMs remains a persisted wall-clock epoch (compared across restarts/processes), and the public API (record / forget / close) is untouched.

Why This Change Was Made

updatedAtMs is a persisted epoch written by updateHostStats (params.observedAtMs ?? Date.now()) and stored through persistHostStats, so its seed cannot become performance.now() without breaking the cross-restart contract. The fix keeps the epoch as the source of truth and derives a parallel monotonic deadline (savedAtMonotonicMs) at the receipt boundary, like src/infra/update-doctor-deadline.ts.

Deriving it once is what makes the budget stable. A live node publishes telemetry every 60s, so deriving on each schedule() would re-read the corrected wall clock on the next report and move an armed deadline again; a setTimeout firing a millisecond early would do the same through the re-arm path. The timer also writes a buffered sample, so converting at write time would fold a clock step since that sample's receipt into the following budget — hence the receipt-time capture and the per-write snapshot. NodeHostStatsCheckpoints is the only owner that arms the timer, so the fix lives there: no new parser, policy branch, configuration surface, or persisted state.

User Impact

Gateway operators get reliable node host-telemetry persistence: after a clock correction in either direction, CPU/memory stats still land in the store inside the 5-minute window anchored to the saved receipt instead of slipping or firing early.

Evidence

Runtime capture through the shipped entry points: startGatewayServer(), a node-role GatewayClient over loopback, the node.event / node.host.stats frame, and device.pair.list for the persisted node surface. Each row below is the same script with the checkpoint owner's wall clock stepped once while telemetry keeps arriving; the step is owner-scoped because this capture runs the Gateway and its clients in one process.

Signal origin/main (before) head f1cdec (after)
Backward step (-30 s): timer delay after the later report 329761 ms (budget + 30 s) 299889 ms (same deadline)
Backward step: durable sample when the deadline passes still 512 (slipped) 300 (latest, on time)
Forward step (+30 s): delay after the later report 269921 ms (budget - 30 s) 299809 ms (same deadline)
Forward step: 30 s before the deadline 300 (fired early) 512 (still waiting)
Forward step: at the deadline 300 300 (on time)

Raw terminal output (backward step, current head / origin/main)

[proof] first sample persisted: memoryFreeBytes=512 updatedAtMs=1793031594197
[timer] checkpoint setTimeout delay=299898ms
[clock] checkpoint owner wall clock stepped by -30000ms
[timer] checkpoint setTimeout delay=299889ms
[proof] at the deadline: memoryFreeBytes=300 updatedAtMs=1793031594307 (first saved updatedAtMs=1793031594197)
PASS: checkpoint persisted on the armed monotonic deadline despite the wall-clock step
[timer] checkpoint setTimeout delay=299767ms
[clock] checkpoint owner wall clock stepped by -30000ms
[timer] checkpoint setTimeout delay=329761ms
[proof] at the deadline: memoryFreeBytes=512 updatedAtMs=1793027633985 (first saved updatedAtMs=1793027633985)
[proof] after the grace window: memoryFreeBytes=300 updatedAtMs=1793027634223
FAIL: checkpoint slipped past the deadline by the wall-clock step (persisted late)

Raw terminal output (forward step, current head / origin/main)

[clock] checkpoint owner wall clock stepped by 30000ms
[timer] checkpoint setTimeout delay=299809ms
[proof] 30000ms before the deadline: memoryFreeBytes=512 updatedAtMs=1793032821880
[proof] at the deadline: memoryFreeBytes=300 updatedAtMs=1793032822070
PASS: checkpoint waited for the armed monotonic deadline despite the forward clock step
[clock] checkpoint owner wall clock stepped by 30000ms
[timer] checkpoint setTimeout delay=269921ms
[proof] 30000ms before the deadline: memoryFreeBytes=300 updatedAtMs=1793033214990
FAIL: checkpoint fired early after the forward clock step

Regression (folded into the existing host stats checkpoints suite)

Tree Quiet Keeps reporting Buffered write Result
origin/main ✗ ✗ ✗ 3 failed
f5085d8 (earlier revision) ✓ ✗ ✗ failed
663e15c (earlier revision) ✓ ✓ ✗ failed
head ✓ ✓ ✓ 112 passed

All three assert that nothing persists before the armed deadline and that the next checkpoint stays anchored to its receipt.

Scope: all five node-registry test files pass (112 tests); oxfmt/oxlint clean; no lockfile changes; no open PR touches this file.

@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 gateway Gateway runtime size: XS 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. 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 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR schedules node telemetry checkpoints using retained monotonic deadlines while preserving persisted wall-clock timestamps.

Example: The Gateway clock moves backward by 30 seconds while a node continues reporting memory statistics.

  • Before: The checkpoint delay grows to about 330 seconds, leaving memoryFreeBytes at 512 past the intended deadline.
  • After: The deadline remains about 300 seconds, and the latest memoryFreeBytes value of 300 persists on time.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused repair with shipped-entry-point before/after evidence, distinct regression cases, and no actionable correctness or security findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Contributor terminal output exercises the checkpoint owner through a real loopback Gateway and node client, showing on-time durable reads after backward and forward clock steps on f1cdec; source inspection also verifies a no-migration case because added deadlines remain process-local and persisted sample fields and epoch timestamps are unchanged.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: System-clock corrections silently change when node CPU and memory statistics reach durable storage.
Reason: The change restores the existing five-minute scheduling contract without adding configuration, public APIs, or another persistence owner.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current-main checkpoint scheduling bug, addresses the earlier findings, and has no actionable review findings; the CI gate remains pending.

Priority: P2
Reviewed head: f1cdec461672bbe10d2bcf5c61c2ebe6a037a4e8

Before merge

None.

Findings

None.

Agent review details

How this fits together

Node telemetry enters the Gateway through node.host.stats events; NodeRegistry updates live views immediately and checkpoints samples through the existing pairing writer for durable device listings.

flowchart LR
  A[Node telemetry] --> B[Gateway event handler]
  B --> C[NodeRegistry]
  C --> D[Live catalog and broadcasts]
  C --> E[Monotonic checkpoints]
  E --> F[Pairing worker]
  F --> G[Durable device listings]
Loading

Technical review

Best possible solution:

Retain receipt-time monotonic deadlines in the existing checkpoint owner and merge this focused fix after the normal CI gate passes.

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

Current-main source establishes the clock-sensitive path, and contributor-supplied Gateway traces demonstrate both clock directions; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch is the smallest complete repair using the existing owner: capture deadlines at receipt, associate them with the written sample, and retain them across rescheduling.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9969b7cc1025.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main retains the defect: The fetched main implementation derives both timer delay and callback eligibility from Date.now(), allowing clock corrections to move checkpoint timing. (src/gateway/node-registry.host-stats.ts:111, 9969b7cc1025)
  • Introduced change and earlier findings: The pinned introduced diff captures each sample's deadline at receipt, snapshots it before persistence awaits, and promotes it only after a successful write; subsequent schedules and callback checks reuse that monotonic deadline, resolving both earlier findings. (src/gateway/node-registry.host-stats.ts:63, f1cdec461672)
  • Distinct regression coverage: Added cases cover quiet nodes, heartbeat-driven rescheduling, and the next deadline after a buffered sample is written; the body reports all three failing on the base and passing on the reviewed head. (src/gateway/node-registry-pairing.test.ts:172, f1cdec461672)
  • Supplied runtime proof: The PR body supplies before/after terminal traces through startGatewayServer, a loopback node-role GatewayClient, node.host.stats events, and device.pair.list; backward and forward 30-second clock steps preserve the intended deadline on this head. (f1cdec461672)
  • Original checkpoint contract: Merged perf(nodes): checkpoint host telemetry in the Gateway #184099 introduced the checkpoint owner and its saved-receipt deadline, preserving immediate live views and existing pairing authority; this PR retains that design while correcting its clock domain. (src/gateway/node-registry.host-stats.ts:17, 7b8221094b0b)
  • Merge and CI state: GitHub reports this head mergeable, with openclaw/ci-gate pending; dependency and security-sensitive review statuses are successful, and remaining lint, type, and test jobs are queued or running. (f1cdec461672)

PR surface

Source +33, Tests +68. Total +101 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 40 7 +33
Tests 1 68 0 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 108 7 +101

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: Clock corrections can delay or prematurely trigger durable host telemetry checkpoints, with limited impact on operational statistics.
  • 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 (3 earlier review cycles)
  • reviewed 2026-10-26T14:45:48.491Z sha f5085d8b1cd8fe2b5cf37f5e2473020da82a8b50 :: needs real behavior proof before merge. :: [P2] Retain the monotonic deadline across heartbeat rescheduling
  • reviewed 2026-10-26T15:45:56.409Z sha 663e15c7f5ff878489a4f8c1e6ab16a7cccdd3fa :: needs changes before merge. :: [P2] Capture the monotonic deadline when each sample is received
  • reviewed 2026-10-26T16:33:04.418Z sha f1cdec4 :: needs maintainer review before merge. :: none

Reviewed October 26, 2026, 1:03 PM ET / 17:03 UTC (Revision 4).

@SunnyShu0925
SunnyShu0925 force-pushed the fix/node-host-stats-checkpoint-deadline-monotonic-239 branch from f5085d8 to 3887047 Compare October 26, 2026 15:32
@SunnyShu0925
SunnyShu0925 force-pushed the fix/node-host-stats-checkpoint-deadline-monotonic-239 branch from 3887047 to 663e15c Compare October 26, 2026 15:35
@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
…ic clock

NodeHostStatsCheckpoints throttles host-telemetry persistence to one write per
node every five minutes, and that deadline was read from the wall clock both when
arming the timer and again in the callback. A backward system-clock correction
therefore left the checkpoint slipping by the size of the correction.

Pair each received sample's persisted receipt with the monotonic clock while the
two are still in sync (record), snapshot that deadline with the sample being
written, and promote it once the write succeeds. The timer delay, the fire-time
check, and every later schedule reuse the stored deadline instead of re-reading
the wall clock.

Capturing at receipt (rather than at write time) matters because the timer writes
a buffered sample: converting when that write completes would fold a clock step
that happened since the sample was received into the following budget. Later
schedules must also not re-derive the deadline, or a report arriving after a jump
(the normal 60s telemetry cadence) or a timer firing a millisecond early would
push an armed deadline out.

updatedAtMs stays a persisted wall-clock epoch; the monotonic deadline is
in-memory only and the public API (record / forget / close) is unchanged.

Regression coverage folds three cases into the existing host stats checkpoints
suite: a backward jump with the node going quiet, with telemetry still arriving,
and a write that follows the jump, each asserting nothing persists before the
armed deadline and the next checkpoint stays anchored to its receipt.
@SunnyShu0925
SunnyShu0925 force-pushed the fix/node-host-stats-checkpoint-deadline-monotonic-239 branch from 663e15c to f1cdec4 Compare October 26, 2026 16:26
@SunnyShu0925

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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. 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
@SunnyShu0925

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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 28, 2026
@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

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: S 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