Skip to content

fix(infra): use monotonic clock for managed service handoff deadline - #199665

Closed
shuisadev wants to merge 1 commit into
openclaw:mainfrom
shuisadev:resub/managed-service-handoff-control-deadline-monotonic
Closed

shuisadev wants to merge 1 commit into
openclaw:mainfrom
shuisadev:resub/managed-service-handoff-control-deadline-monotonic

Conversation

@shuisadev

Copy link
Copy Markdown
Contributor

What Problem This Solves

During a managed service update the parent process waits for the helper's handoff response under an absolute deadline. That deadline was seeded and read with the wall clock (Date.now()), so a host clock correction during the handoff skewed the remaining budget: a rewind inflated it and let a wedged handoff hang far past its configured timeout, while a forward jump shrank it and could terminate a healthy handoff early. The deadline now runs on the monotonic clock.

  • Problem: scheduleAbsoluteDeadline(Date.now() + timeoutMs, cb) computed the remaining budget on the wall clock; a 90 s rewind turned a 5 s handoff budget into ~95 s of waiting.
  • Solution: seed and read the deadline with performance.now() and pass that clock explicitly to scheduleAbsoluteDeadline.
  • What changed: src/infra/update-managed-service-handoff-control.ts — the waitForHandoffResponse deadline arm only; plus a rewind regression folded into the existing handoff readiness-timeout case.
  • What did NOT change: the handoff line reader, exit/error/input-close settlement, and child-process kill logic are untouched.

Why This Change Was Made

The handoff deadline is purely in-process: it is not serialized, persisted, or reported to the UI, so a full switch to the monotonic clock is safe and needs no dual-clock-domain conversion. This is the same canonical pattern already merged for the update-operation deadline (scheduleAbsoluteDeadline with an explicit monotonic now), keeping the deadline utilities consistent. Risk is low: performance is a Node global and only the deadline arm changed.

  • Best fix: align the deadline with the monotonic clock that scheduleAbsoluteDeadline already consumes. performance.now() is monotonic per process, unaffected by NTP steps or manual clock changes, and matches the clock domain of the update-operation deadline.
  • 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 after a rewind; (b) inject an abstract clock through the caller — rejected because it widens a public signature for a purely internal deadline; (c) shorten the handoff timeout to compensate — rejected because it trades a hang for a false timeout under healthy conditions.
  • Risk: performance.now() is a Node global available since Node 16; the handoff runtime is a sealed subprocess that does not re-read the clock after launch. Boundary left unchanged: the handoff line reader, exit/error settlement, and child-process kill logic.

User Impact

Operators running a managed service update no longer risk a stuck or prematurely cancelled handoff when the host clock is corrected (NTP step, manual change, VM restore). The handoff deadline tracks real elapsed time and fires at the configured budget.

Evidence

All evidence below is for reviewed head a921354150a843d908ffbeca4f9a2f9e710072fb.

Case Before (pre-fix) After (post-fix)
90 s wall-clock rewind during handoff budget inflated to ~95 s; handoff hangs budget stays 8 s; handoff terminated at 12.5 s
Forward clock jump during handoff budget shrunk; healthy handoff terminated early budget unaffected; handoff completes normally

Shipped command:

node dist/index.js update.run --use-managed-service systemd

The real detached managed-handoff-runtime helper was used. Full run logs in the GHA links below.

1. Completed managed update across the published-driver/candidate boundary. The repository's own published-driver-update cell (scripts/e2e/published-driver-update-docker.sh, the same cell CI runs for update changes) upgraded the published 2026.10.8 driver to the package built from this head. Candidate build: commit a921354150a8, built 2026-10-28T05:49:28Z. The cell relabels the branch manifest's 2026.10.7 to the driver version so the future-version guard exercises an upgrade rather than a downgrade.

update: exit=0 durationMs=403636
status=ok phase=finished
serviceRunning=true versionMatch=true readyz=true coreReady=true settled=true
admission owner=candidate checks: config=warn database-schema=ok node-runtime=ok plugin-availability=ok
summary: phase=finished readyz=200 runningVersion=2026.10.8

Operator state survived the update (identical durable session row before and after):

durable-before sessionId=c7044560-a175-4d23-bab4-c3eb8cd4584b text=published-driver-durable-5ff70041-42f2-442d-865e-e34e182db80a
durable-after  sessionId=c7044560-a175-4d23-bab4-c3eb8cd4584b text=published-driver-durable-5ff70041-42f2-442d-865e-e34e182db80a
after-ready    {"ready":true,"coreReady":true,"failing":[]}

2. Committed regression: green on head, red on base. Same test, only src/infra/update-managed-service-handoff-control.ts reverted to its parent:

# head a921354
✓ rejects readiness timeout after a wall-clock rewind and cleans up the sensitive handoff (5016ms)
# base source (Date.now() deadline)
× rejects readiness timeout after a wall-clock rewind and cleans up the sensitive handoff
  Error: Test timed out in 120000ms.   # the rewound budget never expires, so the helper wait never settles
VERDICT=PASS head-green base-red

3. Handoff deadline under a real 90 s rewind. Isolated systemd-managed install; shipped update.run Gateway RPC with the real detached managed-handoff-runtime helper; readiness line held 12 s and a -90 s wall-clock step applied the moment the deadline timer arms:

run driver deadline armed handoff settlement
published 2026.10.8 wall clock T+8.5 s for 8 s readiness accepted T+22.7 s (6.2 s late)
this head monotonic T+8.5 s for 8 s terminated T+12.5 s (0.4 s late)
[run 1] wall_clock_stepped byMs=-90000 trigger=handoff-deadline-armed budgetArgMs=7999
[run 1] helper_readiness_released delayMs=12000
[run 1] managed-service update handoff durationMs=-87080
[run 2] wall_clock_stepped byMs=-90000 trigger=handoff-deadline-armed budgetArgMs=7999.96
[run 2] update.run managed-service handoff failed error=managed update handoff did not signal readiness within 8 seconds
[run 2] update.run reason=managed-service-handoff-failed rpcDurationMs=12541

Runs: managed-update cell, regression red/green.

Open PR collision check: searched open PR topics handoff deadline/monotonic clock/managed-service-handoff-control and changed-file lists — no open PR touches src/infra/update-managed-service-handoff-control.ts.

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.

Workstation note: this host's systemd 239 libsystemd lacks sd_bus_set_method_call_timeout, so the published driver cannot inspect a local managed unit here; the completed upgrade therefore ran in CI's own cell (Ubuntu 24.04, systemd 257) with the same script CI uses.

scheduleAbsoluteDeadline defaulted to Date.now(), so a wall-clock rewind
inflated the remaining budget and let a healthy handoff hang past its
configured timeout. Seed and read the deadline with performance.now().

Ref: BUG-164 (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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug 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: needs maintainer review before merge.

What this changes

This PR makes managed-service handoff response deadlines use elapsed time unaffected by wall-clock changes.

Example: The wall clock rewinds 90 seconds during a 30-second helper-readiness wait.

  • Before: The deadline recheck can extend the wait to roughly 120 seconds.
  • After: The helper still times out after approximately 30 seconds of elapsed time.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-level repair with shipped-entry-point evidence, a base-red/head-green regression, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Reviewed-head inline logs exercise update.run through an isolated managed Gateway and the real detached helper under delayed readiness and a 90-second rewind, showing timeout rejection; published-driver upgrade output also shows successful readiness and preserved session data.
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 clock rewind can leave an operator waiting beyond the managed-service handoff timeout.
Reason: The patch restores the existing elapsed-time budget without changing timeout ceilings, configuration, persisted state, or lifecycle ownership.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: current main retains the clock-dependent handoff timeout, and this focused repair has no actionable correctness or security findings.

Priority: P2
Reviewed head: a921354150a843d908ffbeca4f9a2f9e710072fb

Before merge

None.

Findings

None.

Agent review details

How this fits together

The update parent launches a detached helper and waits for readiness or control responses; the deadline scheduler invokes existing rejection and cleanup when the response budget expires.

flowchart LR
  A[Update request] --> B[Managed handoff owner]
  B --> C[Detached helper]
  C --> D[Response waiter]
  E[Monotonic deadline] --> D
  D --> F[Response or timeout cleanup]
Loading

Technical review

Best possible solution:

Keep the existing handoff owner and scheduler, using one monotonic clock for deadline creation and expiry checks.

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

Current-main source establishes the rewind failure through the scheduler's wall-clock recheck, and supplied production traces demonstrate it; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is the smallest complete repair: both clock reads change together, existing settlement and cleanup remain intact, and the existing regression gains the distinct rewind case without new machinery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 55fec79d1ec5.

Provenance checked

  • Handoff response deadline keeps the original intent (9b3f350: The foreground-update repair centralized response settlement while retaining the detached updater's activation and finalization budgets.)
  • Readiness-timeout cleanup regression keeps the original intent (a1e75e0: Startup verification rejects missing readiness, terminates the helper, and removes sensitive handoff artifacts; later lifecycle changes retained this contract.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +4, Tests 0. Total +4 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 10 6 +4
Tests 1 5 5 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 15 11 +4

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: #199665
Summary: This PR carries the identical head from the closed, unmerged predecessor.

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: Clock corrections can extend a managed-update handoff beyond its configured budget; the repair has a limited lifecycle scope.
  • 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.

Reviewed November 15, 2026, 11:12 AM ET / 16: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

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