Skip to content

fix(subagents): keep the subagent spawn reconcile budget on the monotonic clock - #186412

Closed
SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/subagent-spawn-gateway-reconcile-deadline-monotonic-110
Closed

SunnyShu0925 wants to merge 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/subagent-spawn-gateway-reconcile-deadline-monotonic-110

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The subagent spawn reconciliation deadline was measured on the wall clock (Date.now()), so a host clock jump (NTP correction, VM pause/resume, manual time change) corrupted the retry budget and could wrongly kill a healthy reconciliation, or silently stretch the Gateway timeout for an unhealthy one.

  • Problem: reconcileSubagentAgentDispatch in src/agents/subagents/spawn/subagent-spawn-gateway.ts seeded deadline = Date.now() + SUBAGENT_AGENT_RECONCILE_TIMEOUT_MS (6_400ms) and recomputed the remaining budget with Date.now(). That value feeds two monotonic consumers: the Gateway RPC timeout (callGateway timeoutMs) and the inter-iteration delay (node:timers/promises setTimeout). A forward wall-clock jump between two iterations drives remainingMs = deadline - Date.now() below zero and the loop rethrows the original unavailable error, killing a reconciliation that would otherwise recover; a backward jump stretches the timeout and the delay past the intended budget.
  • Solution: measure the budget on performance.now(), the clock both consumers already run on. A difference of two monotonic reads is immune to wall-clock drift.
  • What changed: the three reads inside reconcileSubagentAgentDispatch — deadline seed, remainingMs, and the delay upper bound — switched from Date.now() to performance.now(). The constants (800 / 6_400), the retry/throw policy, the dispatched request shape, and transport-error handling are unchanged; no wire behavior changed. deadline stays a pure in-process closure value (never serialized or reported across processes), so nothing observes it as an epoch.

User Impact

A subagent spawn no longer fails spuriously when the host clock is corrected or a VM is resumed during the 6.4s reconciliation window, and the Gateway RPC retries and inter-iteration delays reflect real elapsed time only.

Evidence

Regression (RED → GREEN) — the existing reconciles ambiguous dispatch (terminal=…) case in src/agents/subagents/spawn/subagent-spawn.test.ts now steps Date.now() forward 10s on the pending replay, and still requires the admitted run plus the 800ms per-call Gateway RPC cap. It reuses that case's single 800ms interval wait, so no new sleep is added, and the suite's test-line total stays flat (net delta: 0; the ratchet reports "Tree is over the ceiling; this change does not add test lines").

$ OPENCLAW_VITEST_RUNTIME=node node scripts/test-projects.mts --maxWorkers=1 \
    src/agents/subagents/spawn/subagent-spawn.test.ts                  # fixed source
 Tests  33 passed (33)

# same file, subagent-spawn-gateway.ts restored to the base revision
 × |infra| src/agents/subagents/spawn/subagent-spawn.test.ts > spawnSubagentDirect seam flow > reconciles ambiguous dispatch (terminal=false)
   → AssertionError: expected { status: 'error', …(3) } to match object { status: 'accepted', …(2) }
 Tests  1 failed | 32 passed (33)

Real Gateway transport trace — isolated Gateway (startGatewayServer: token auth, loopback, fake OpenAI-compatible provider) driven by the production callNativeSubagentGateway over a real WebSocket. The first agent RPC gets a 60ms client timeout, so the run is created but the reply arrives after the client gives up; Date.now() is then stepped forward 10s while that same call is reconciling. Base revision:

[proof] trial ambiguous dispatch timeoutMs=60
[proof] +139ms wall clock stepped +10000ms
[proof] +221ms rejected gateway timeout after 60ms

Same harness on the fixed source:

[proof] trial ambiguous dispatch timeoutMs=60
[proof] +137ms wall clock stepped +10000ms
[proof] +1148ms reconciled status=in_flight runId=reconcile-proof-target-60-441174-1-3
Same script, same Gateway, same +10s wall step Base revision Fixed revision
Reconcile result rethrew gateway timeout after 60ms at +221ms returned the admitted run at +1148ms
Gateway run after the step healthy run abandoned status=in_flight, runId=reconcile-proof-target-60-441174-1-3
Inter-iteration delay collapsed to zero by the step full 800ms interval
Remaining budget at the next read negative, so the loop aborted about 5.4s left, so the replay ran
Unit regression (reconciles ambiguous dispatch) 1 failed, 32 passed 33 passed

The step is the only difference between the runs: on the base revision it zeroes the delay and then drives remainingMs negative, so the loop rethrows the original timeout and abandons a healthy run; on the fixed revision the interval and the budget come from performance.now(), so the replay of the same idempotency key returns the already-admitted run (single run — a second launch would have produced another run id).

Checks: oxlint clean, oxfmt clean on both changed files, test-line ratchet reports no growth. Open PR collision check: no open PR touches src/agents/subagents/spawn/subagent-spawn-gateway.ts, and origin/main still uses Date.now() at all three sites.

@clawsweeper

clawsweeper Bot commented Oct 28, 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 agents Agent runtime and tooling size: XS labels Oct 28, 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 28, 2026
@clawsweeper

clawsweeper Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Measures the subagent spawn reconciliation deadline with performance.now() so wall-clock changes cannot distort its retry budget.

Example: The host clock jumps forward 10 seconds while a pending subagent launch is being reconciled.

  • Before: The 6.4-second budget appears exhausted, and the parent reports an error despite the healthy child run.
  • After: Reconciliation retains its elapsed-time budget and returns the admitted child run.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused, correct repair with real transport recovery evidence and a reported red/green regression; current-head CI is still completing.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Contributor-supplied terminal output exercises production callNativeSubagentGateway against an isolated token-authenticated Gateway over a real WebSocket with a fake provider, injected timeout, and forward clock step; the base rejects while the fixed source reconciles the admitted in_flight run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A clock correction can make the parent report a failed spawn while its child is healthy, or prolong recovery beyond the intended budget.
Reason: The patch restores the existing bounded-recovery contract with three clock substitutions and a focused regression.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current reconciliation-budget bug with a focused change; the prior findings are resolved, and no introduced defect was found.

Priority: P2
Reviewed head: b8c61561f77576a50b70bd412164ff9c79ca3455

Before merge

None.

Findings

None.

Agent review details

How this fits together

Native and ACP subagent launches share a Gateway dispatch owner that reconciles ambiguous transport failures using the original idempotency key and returns settled acceptance or an error.

flowchart TD
  A[Native or ACP spawn] --> B[Shared Gateway dispatch]
  B --> C[Gateway agent RPC]
  C --> D[Ambiguous transport failure]
  D --> E[Monotonic reconciliation budget]
  E --> C
  C --> F[Accepted run or terminal error]
Loading

Technical review

Best possible solution:

Use the monotonic clock for every read of the existing in-process reconciliation budget, as this PR does.

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

Current-main source exposes the failure directly, and the contributor supplies matching base-failing regression output and a real-WebSocket before/after trace; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete fix: keep elapsed-time accounting in the existing shared reconciliation owner without adding state, abstractions, or policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared ambiguous-dispatch reconciliation keeps the original intent (bcb5403: Recover accepted child runs after acknowledgement loss using bounded same-key replay, while rejecting provisional and terminal results.)
  • Existing ambiguous-dispatch test keeps the original intent (43fbf45: Consolidate duplicated test setup and overlapping assertions while retaining owner-boundary coverage.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b6a2e5b adds src/agents/subagents/spawn/subagent-spawn-gateway.ts:156 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b6a2e5b4eff7; files: src/agents/subagents/spawn/subagent-spawn-gateway.ts)

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 7 3 +4
Tests 1 15 15 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 22 18 +4

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Clock changes during the short out-of-process reconciliation window can produce false spawn failures or stretch recovery, with limited blast radius.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-28T01:10:27.009Z sha d3dd3da7ab846543b5be837488eaf99d17585c06 :: needs real behavior proof before merge. :: [P3] Keep the regression within the test-line ratchet | [P3] Drive the reconciliation wait with controlled timers

Reviewed October 27, 2026, 10:53 PM ET / October 28, 2026, 02:53 UTC (Revision 2).

…onic clock

reconcileSubagentAgentDispatch anchored its reconciliation deadline and the
remaining-budget reads to Date.now() (wall clock), then fed the result into
two monotonic consumers: the Gateway RPC timeout (callGateway timeoutMs) and
the inter-iteration delay (node:timers/promises setTimeout). A wall-clock step
(NTP sync) landing between two loop iterations distorts remainingMs: a forward
step shrinks it below zero and prematurely kills a healthy reconciliation,
while a backward step stretches the Gateway timeout and the delay well past the
intended budget.

The deadline is a pure in-process closure variable (never serialized, persisted,
or reported across processes), so it is safe to anchor to performance.now(). All
three reads now use the monotonic clock, keeping the budget stable across wall
steps.

The regression folds into the existing ambiguous-dispatch reconcile case: its
pending replay steps Date.now() forward 10s and the case still requires the
admitted run plus the 800ms per-call Gateway RPC cap, so the suite keeps its
real 800ms interval wait and adds no test lines.
@SunnyShu0925
SunnyShu0925 force-pushed the fix/subagent-spawn-gateway-reconcile-deadline-monotonic-110 branch from d3dd3da to b8c6156 Compare October 28, 2026 02:46
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressing the three before-merge items from the last review on the same head:

  1. Real Gateway transport proof — added an isolated Gateway (startGatewayServer, token auth, loopback, fake OpenAI-compatible provider) driven by the production callNativeSubagentGateway over a real WebSocket. The first agent RPC gets a 60ms client timeout so the run is created while the reply is still pending, then Date.now() steps forward 10s during that call. Base revision rethrows gateway timeout after 60ms at +221ms; fixed revision returns the same-key admitted run (status=in_flight) at +1148ms. Raw terminal output is inline in the PR body.
  2. Test-line ratchet — removed the standalone test file and folded the wall-clock step into the existing reconciles ambiguous dispatch (terminal=…) case, which already covers both the pending replay and the terminal rejection. check:test-lines-ratchet now reports net delta: 0 ("Tree is over the ceiling; this change does not add test lines").
  3. Controlled timers — the case fakes only Date (vi.useFakeTimers({ toFake: ["Date"] }) + vi.setSystemTime) and restores timers in afterEach; it reuses that case's single real 800ms interval wait, so the suite adds no new sleep.

The production change is unchanged from the reviewed head: the three budget reads in reconcileSubagentAgentDispatch move from Date.now() to performance.now(), with no new clock abstraction, no constant or policy change, and no wire-visible behavior difference.

@clawsweeper

clawsweeper Bot commented Oct 28, 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. 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: 🧂 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. labels 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

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

1 participant