Skip to content

fix(process): use monotonic clock for process-tree kill grace deadline - #174151

Merged
obviyus merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/exec-process-tree-kill-grace-deadline-wall-clock-098
Oct 18, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
SunnyShu0925:fix/exec-process-tree-kill-grace-deadline-wall-clock-098

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: when the wall clock steps back (NTP correction, VM or laptop resume) while OpenClaw is tearing down a command's process group, a child that ignores SIGTERM survives for the size of the step instead of the 300 ms kill grace.

createCommandTerminationController (graceful SIGTERM, then group SIGKILL) and waitForCommandProcessGroupExit (the post-SIGKILL exit confirmation) seeded and checked their deadlines with Date.now(), but wait on monotonic setTimeout/sleep. A backward step of N ms pushes the deadline out by N ms.

Fix

Seed, compare and consume both deadlines with performance.now(), the clock the timers use. Same-process deadlines only; nothing crosses a process boundary.

Thanks to @SunnyShu0925 for finding and fixing this.

User Impact

Commands that OpenClaw runs with process-tree ownership (for example a repository's .openclaw/worktree-setup.sh, git, npm and update commands) are force-stopped on time after a timeout or cancel, even if the wall clock steps back during teardown. Before the fix, a stuck child stayed alive, and the caller (for example sessions.create) stayed blocked, for the size of the step.

Evidence

End to end, both trees built with pnpm build (Node 24, Docker with an init process): a real Gateway; the operator calls sessions.create with worktree: true on a git repository whose .openclaw/worktree-setup.sh starts a descendant that traps SIGTERM and keeps running. The setup hits its 120 s timeout and the runner tears down the process group. When the descendant gets SIGTERM, it asks a preload in the Gateway process to step Date.now() by -60 s (only that process; the system clock is not changed). Time is measured from the descendant's SIGTERM to its death.

Run SIGTERM to death of the stuck child sessions.create returned after
main, no step (control) 303 ms 125.7 s
main, -60 s step 60348 ms 185.3 s
this PR, no step (control) 334 ms 124.5 s
this PR, -60 s step 347 ms 130.2 s

All runs return worktree setup failed (timed out after 120 seconds; signal SIGTERM). After merging current main, the -60 s step on the merged head: 394 ms, sessions.create returned after 123.9 s.

Regression test (exec-termination.test.ts): rewinds the wall clock by 60 s during the kill grace and again during the exit confirmation. On main no SIGKILL is sent after the grace; with only the confirmation site reverted, settlement stays pending past the confirmation window. Both pass on this PR. oxfmt and oxlint are clean on the changed files.

Line delta against the merge base: production +5/-5; tests +23/-3. The separate waitForCommandProcessGroupExit test was folded into the one termination test, which now covers both deadlines.

Merge danger

Two-way door: in-process deadline arithmetic only; no persisted state, config, protocol or schema change, and a revert fully undoes it. Blast radius: POSIX commands run with process-tree ownership (worktree setup, git, npm, update and plugin commands); Windows taskkill paths are unchanged.

@clawsweeper

clawsweeper Bot commented Oct 16, 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. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Use monotonic time for process-group termination grace and post-kill exit-confirmation deadlines.

Example: The wall clock rewinds by 60 seconds while a worktree setup descendant ignores SIGTERM.

  • Before: The supplied Gateway run took 60348 ms to terminate the descendant.
  • After: The patched run terminated it in 347 ms.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused repair with supplied end-to-end evidence and meaningful regression coverage; broad CI remains pending.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Node 24 Docker Gateway run exercises sessions.create worktree setup, timeout-driven process-group teardown, a SIGTERM-resistant descendant, and a process-local wall-clock rewind, with baseline controls and prompt descendant death after the fix; regression evidence separately covers exit-confirmation expiry.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Timed-out or canceled commands can remain blocked beyond their cleanup allowance after a backward wall-clock correction.
Reason: The change restores the existing bounded-cleanup contract while preserving its established budgets and ownership.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it fixes a concrete current-main cleanup delay with a focused change, relevant regression coverage, and supplied Gateway evidence; no actionable defect was found.

Priority: P2
Reviewed head: 32f3cd681e47e1cbea069bdebc63da85f7f257af

Before merge

None.

Findings

None.

Agent review details

How this fits together

Command runners delegate process-tree shutdown to the termination controller, which sends signals and uses the shared exit observer to return confirmed cleanup or uncertainty.

flowchart TD
  A[Gateway worktree setup] --> B[Command runner]
  B --> C[Termination controller]
  C --> D[Owned process group]
  C --> E[Shared exit observer]
  E --> D
  E --> F[Cleanup result]
Loading

Technical review

Best possible solution:

Retain the existing cleanup owners and budgets while measuring both elapsed-time deadlines with performance.now().

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

Both current-main deadline calculations explain the failure, and the supplied real Gateway comparison demonstrates it; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch fixes elapsed-time accounting at both existing owners without adding machinery or changing cleanup policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Graceful process-group termination deadline keeps the original intent (220578b: Retain process cleanup independently of command completion and force termination after cooperative grace.)
  • Shared post-kill exit confirmation keeps the original intent (69197e7: Give post-SIGKILL teardown a dedicated 10-second confirmation allowance across all cleanup consumers.)
  • Existing termination and buffered-command timing fixtures keeps the original intent (chore(process): make descendant termination proof deterministic #131876: Separate real subprocess readiness from controlled host deadlines; later consolidation retained final-probe and process-identity cases.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 69197e7 adds src/process/exec-spawn.ts:37 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 69197e789eb1; files: src/process/exec-spawn.ts)

PR surface

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

View PR surface stats
Area Files Added Removed Net
Source 2 5 5 0
Tests 2 23 3 +20
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 28 8 +20

Review metrics

Metric Value Why it matters
Production versus regression changes Production +5/-5; tests +23/-3 Production growth is zero; test growth protects both clock-rewind failures and aligns existing timing fixtures.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Clock corrections can delay command cancellation and cleanup, but the demonstrated trigger has limited scope and does not establish a widespread urgent regression.
  • 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 (5 earlier review cycles)
  • reviewed 2026-10-16T11:30:32.161Z sha 4b89884f63b32bdf4fe7b121e8af9d728e117ae8 :: needs real behavior proof before merge. :: [P2] Advance performance in the buffered-command timing fixture
  • reviewed 2026-10-16T12:18:16.158Z sha e4fa5c8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-16T12:35:40.491Z sha e4fa5c8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-18T20:44:28.332Z sha b7c9751 :: needs changes before merge. :: none
  • reviewed 2026-10-18T21:11:33.657Z sha 22f7275 :: needs maintainer review before merge. :: none

Reviewed October 18, 2026, 5:26 PM ET / 21:26 UTC (Revision 6).

Ref: BUG-098-process-tree-kill-grace-deadline-wall-clock (local finding)
@SunnyShu0925
SunnyShu0925 force-pushed the fix/exec-process-tree-kill-grace-deadline-wall-clock-098 branch from 4b89884 to e4fa5c8 Compare October 16, 2026 12:08
@clawsweeper

clawsweeper Bot commented Oct 16, 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 16, 2026
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review.

@clawsweeper

clawsweeper Bot commented Oct 16, 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. 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 16, 2026
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 18, 2026
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 18, 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@obviyus
obviyus merged commit 19c6d8f into openclaw:main Oct 18, 2026
133 of 136 checks passed
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

Landed in 19c6d8f. Thanks @SunnyShu0925 for the fix, and for sharing it with the community.

Maintainer follow-up: merged current main and folded the tests into one case that rewinds the clock during both the kill grace and the exit confirmation. Your production change is unchanged and proven end to end through a real worktree setup teardown against main.

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@obviyus Thanks too~

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
openclaw#174151)

Command process-group teardown now keeps its kill-grace and exit-confirmation deadlines on the monotonic clock. A backward wall-clock step during teardown (NTP correction, VM or laptop resume) no longer keeps a child that ignores SIGTERM alive for the length of the step before SIGKILL.

Proof: isolated Gateway in secretless Docker, `sessions.create` with `worktree: true` on a git repo whose setup script starts a descendant that traps SIGTERM, with a -60 s `Date.now` step inside the Gateway during teardown. On main 8ac7518 the stuck child dies 60.3 s after SIGTERM and `sessions.create` returns 60 s late; the candidate kills it after about 0.35 s, matching the no-step control. Live gate passed with openai/gpt-5-mini.

Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
steipete pushed a commit that referenced this pull request Oct 23, 2026
…e deadline (#181335)

## What Problem This Solves

When a worker/sandbox environment exits, `reapOrphanedProcesses` clears its orphaned process tree. A child that ignores `SIGTERM` is escalated to `SIGKILL` after a 5-second grace window — but that window is measured on the wall clock. If the wall clock steps backward during teardown (NTP correction, VM or laptop resume), the escalation is delayed by the length of the step, so the stuck child stays alive for `5s + step` instead of `5s`. This change keeps the reap grace deadline on the monotonic clock.

- **Problem**: `waitForExit` seeds and compares its 5s grace deadline with `Date.now()` (wall clock), while `sleepWithAbort` consumes the remaining budget through `setTimeout` (monotonic). A backward wall-clock step during teardown inflates the grace window, delaying the `SIGKILL` escalation of a child that ignores `SIGTERM`; a forward step escalates early.
- **Solution**: use `performance.now()` for the deadline seed, the exit-condition comparison, and the remaining-budget calculation. `performance.now()` is monotonic and unaffected by wall-clock adjustments.
- **What changed**: `src/process/orphaned-process.ts` — the `waitForExit` grace deadline now lives entirely on the monotonic clock (3 lines). `src/process/orphaned-process.test.ts` — a regression test that rewinds the wall clock mid-teardown and asserts the `SIGKILL` escalation stays bounded at 5s.
- **What did NOT change**: no parser, policy branch, or configuration surface; no behavior change on a normal clock. The `sleepWithAbort` consumer is untouched — `resolveSleepDelayMs` already floors internally, so no `Math.floor` is needed here.

## Why This Change Was Made

`reapOrphanedProcesses` is the canonical owner of the orphaned-process-tree reap grace deadline, so the fix lives there rather than at call sites. This is the same cross-clock-domain pattern already fixed for command process-group teardown in #174151 (`exec-spawn.ts` / `exec-termination.ts`); `orphaned-process.ts` `waitForExit` is the sibling site in the same module that was left on the wall clock. Node 16+ exposes a global `performance`, so no import is required.

## User Impact

Environment exit and resource reclamation are no longer delayed or spuriously accelerated by wall-clock adjustments. An orphaned child that ignores `SIGTERM` is always force-killed after a bounded 5s monotonic grace window, regardless of NTP corrections or machine resume.

## Evidence

**Pre-fix RED** — source reverted to `Date.now()`, regression test kept: the 60s wall rewind inflates the grace window, tree never reaped in 5s monotonic, test times out at 120s.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 × keeps SIGKILL escalation bounded when the wall clock rewinds  120079ms  (timed out 120000ms)
 Test Files  1 failed | Tests  1 failed | 21 passed (22)
```

**Post-fix GREEN** — with `performance.now()`, same test completes in 56ms, suite 22/22.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 ✓ keeps SIGKILL escalation bounded when the wall clock rewinds  56ms
 Test Files  1 passed | Tests  22 passed (22)
```

**Behavior matrix** (wall rewound 60s during teardown, child ignores `SIGTERM`):

```text
clock during teardown      => SIGKILL escalation      => result
normal (no step)            => after 5s grace          => bounded
wall rewind 60s (pre-fix)   => after 5s + 60s (hangs)  => delayed by step
wall rewind 60s (post-fix)  => after 5s grace          => bounded
```

**Regression test** uses #174151's two-clock separation: `vi.setSystemTime(Date.now() - 60_000)` rewinds only wall clock; `performance.now()` keeps advancing on the fake-timer clock.

**macOS real-behavior proof (single continuous capture)** — GHA `macos-14` arm64, through the shipped `recoverManagedLlamaServer` (`extensions/llama-cpp`) entry: real managed llama-server asset at its pinned install path (root PPID=1), TERM-resistant descendant, real native inspection + real `process.kill`. 60s wall-clock rollback injected at the remaining-budget read (CI pins clock via NTP; monotonic clock + transport stay real). Full run: [oc-macos-proof run 39908934594](https://github.com/SunnyShu0925/oc-macos-proof/actions/runs/39908934594).

```console
===== CASE: FIXED (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[FIXED] before recovery: 4964  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=4964 port=19321
[FIXED] recoverManagedLlamaServer returned elapsed_monotonic=5634ms root_alive_after=false
VERDICT[FIXED] wall_jump=-60000ms elapsed_monotonic=5634ms reaped_root=4964 root_alive_after=false
PROOF PASS: FIXED escalated to SIGKILL in ~5s monotonic under wall-clock rollback

===== CASE: OLD (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[OLD] before recovery: 5509  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=5509 port=19321
[OLD] recoverManagedLlamaServer returned elapsed_monotonic=65290ms root_alive_after=false
VERDICT[OLD] wall_jump=-60000ms elapsed_monotonic=65290ms reaped_root=5509 root_alive_after=false
PROOF EXPECTED-OLD: OLD delayed SIGKILL by ~|rollback| (bug reproduced on real tree)
```

| variant | deadline clock | SIGKILL escalation (rollback −60s) |
|---|---|---|
| OLD (pre-fix) | `Date.now()` | **65.29s** = 5s grace + 60s rollback |
| FIXED (this PR) | `performance.now()` | **5.63s** = bounded grace |

Real managed-service recovery on a real macOS orphan tree, matching already-landed sibling #174151.

**Open PR collision check**: no open/merged PR touches `orphaned-process.ts` clock domain; sibling #174151 landed for `exec-spawn.ts`/`exec-termination.ts`, no overlap.

Co-authored-by: SunnyShu <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
…e deadline (openclaw#181335)

## What Problem This Solves

When a worker/sandbox environment exits, `reapOrphanedProcesses` clears its orphaned process tree. A child that ignores `SIGTERM` is escalated to `SIGKILL` after a 5-second grace window — but that window is measured on the wall clock. If the wall clock steps backward during teardown (NTP correction, VM or laptop resume), the escalation is delayed by the length of the step, so the stuck child stays alive for `5s + step` instead of `5s`. This change keeps the reap grace deadline on the monotonic clock.

- **Problem**: `waitForExit` seeds and compares its 5s grace deadline with `Date.now()` (wall clock), while `sleepWithAbort` consumes the remaining budget through `setTimeout` (monotonic). A backward wall-clock step during teardown inflates the grace window, delaying the `SIGKILL` escalation of a child that ignores `SIGTERM`; a forward step escalates early.
- **Solution**: use `performance.now()` for the deadline seed, the exit-condition comparison, and the remaining-budget calculation. `performance.now()` is monotonic and unaffected by wall-clock adjustments.
- **What changed**: `src/process/orphaned-process.ts` — the `waitForExit` grace deadline now lives entirely on the monotonic clock (3 lines). `src/process/orphaned-process.test.ts` — a regression test that rewinds the wall clock mid-teardown and asserts the `SIGKILL` escalation stays bounded at 5s.
- **What did NOT change**: no parser, policy branch, or configuration surface; no behavior change on a normal clock. The `sleepWithAbort` consumer is untouched — `resolveSleepDelayMs` already floors internally, so no `Math.floor` is needed here.

## Why This Change Was Made

`reapOrphanedProcesses` is the canonical owner of the orphaned-process-tree reap grace deadline, so the fix lives there rather than at call sites. This is the same cross-clock-domain pattern already fixed for command process-group teardown in openclaw#174151 (`exec-spawn.ts` / `exec-termination.ts`); `orphaned-process.ts` `waitForExit` is the sibling site in the same module that was left on the wall clock. Node 16+ exposes a global `performance`, so no import is required.

## User Impact

Environment exit and resource reclamation are no longer delayed or spuriously accelerated by wall-clock adjustments. An orphaned child that ignores `SIGTERM` is always force-killed after a bounded 5s monotonic grace window, regardless of NTP corrections or machine resume.

## Evidence

**Pre-fix RED** — source reverted to `Date.now()`, regression test kept: the 60s wall rewind inflates the grace window, tree never reaped in 5s monotonic, test times out at 120s.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 × keeps SIGKILL escalation bounded when the wall clock rewinds  120079ms  (timed out 120000ms)
 Test Files  1 failed | Tests  1 failed | 21 passed (22)
```

**Post-fix GREEN** — with `performance.now()`, same test completes in 56ms, suite 22/22.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 ✓ keeps SIGKILL escalation bounded when the wall clock rewinds  56ms
 Test Files  1 passed | Tests  22 passed (22)
```

**Behavior matrix** (wall rewound 60s during teardown, child ignores `SIGTERM`):

```text
clock during teardown      => SIGKILL escalation      => result
normal (no step)            => after 5s grace          => bounded
wall rewind 60s (pre-fix)   => after 5s + 60s (hangs)  => delayed by step
wall rewind 60s (post-fix)  => after 5s grace          => bounded
```

**Regression test** uses openclaw#174151's two-clock separation: `vi.setSystemTime(Date.now() - 60_000)` rewinds only wall clock; `performance.now()` keeps advancing on the fake-timer clock.

**macOS real-behavior proof (single continuous capture)** — GHA `macos-14` arm64, through the shipped `recoverManagedLlamaServer` (`extensions/llama-cpp`) entry: real managed llama-server asset at its pinned install path (root PPID=1), TERM-resistant descendant, real native inspection + real `process.kill`. 60s wall-clock rollback injected at the remaining-budget read (CI pins clock via NTP; monotonic clock + transport stay real). Full run: [oc-macos-proof run 39908934594](https://github.com/SunnyShu0925/oc-macos-proof/actions/runs/39908934594).

```console
===== CASE: FIXED (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[FIXED] before recovery: 4964  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=4964 port=19321
[FIXED] recoverManagedLlamaServer returned elapsed_monotonic=5634ms root_alive_after=false
VERDICT[FIXED] wall_jump=-60000ms elapsed_monotonic=5634ms reaped_root=4964 root_alive_after=false
PROOF PASS: FIXED escalated to SIGKILL in ~5s monotonic under wall-clock rollback

===== CASE: OLD (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[OLD] before recovery: 5509  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=5509 port=19321
[OLD] recoverManagedLlamaServer returned elapsed_monotonic=65290ms root_alive_after=false
VERDICT[OLD] wall_jump=-60000ms elapsed_monotonic=65290ms reaped_root=5509 root_alive_after=false
PROOF EXPECTED-OLD: OLD delayed SIGKILL by ~|rollback| (bug reproduced on real tree)
```

| variant | deadline clock | SIGKILL escalation (rollback −60s) |
|---|---|---|
| OLD (pre-fix) | `Date.now()` | **65.29s** = 5s grace + 60s rollback |
| FIXED (this PR) | `performance.now()` | **5.63s** = bounded grace |

Real managed-service recovery on a real macOS orphan tree, matching already-landed sibling openclaw#174151.

**Open PR collision check**: no open/merged PR touches `orphaned-process.ts` clock domain; sibling openclaw#174151 landed for `exec-spawn.ts`/`exec-termination.ts`, no overlap.

Co-authored-by: SunnyShu <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 28, 2026
…e deadline (#181335)

## What Problem This Solves

When a worker/sandbox environment exits, `reapOrphanedProcesses` clears its orphaned process tree. A child that ignores `SIGTERM` is escalated to `SIGKILL` after a 5-second grace window — but that window is measured on the wall clock. If the wall clock steps backward during teardown (NTP correction, VM or laptop resume), the escalation is delayed by the length of the step, so the stuck child stays alive for `5s + step` instead of `5s`. This change keeps the reap grace deadline on the monotonic clock.

- **Problem**: `waitForExit` seeds and compares its 5s grace deadline with `Date.now()` (wall clock), while `sleepWithAbort` consumes the remaining budget through `setTimeout` (monotonic). A backward wall-clock step during teardown inflates the grace window, delaying the `SIGKILL` escalation of a child that ignores `SIGTERM`; a forward step escalates early.
- **Solution**: use `performance.now()` for the deadline seed, the exit-condition comparison, and the remaining-budget calculation. `performance.now()` is monotonic and unaffected by wall-clock adjustments.
- **What changed**: `src/process/orphaned-process.ts` — the `waitForExit` grace deadline now lives entirely on the monotonic clock (3 lines). `src/process/orphaned-process.test.ts` — a regression test that rewinds the wall clock mid-teardown and asserts the `SIGKILL` escalation stays bounded at 5s.
- **What did NOT change**: no parser, policy branch, or configuration surface; no behavior change on a normal clock. The `sleepWithAbort` consumer is untouched — `resolveSleepDelayMs` already floors internally, so no `Math.floor` is needed here.

## Why This Change Was Made

`reapOrphanedProcesses` is the canonical owner of the orphaned-process-tree reap grace deadline, so the fix lives there rather than at call sites. This is the same cross-clock-domain pattern already fixed for command process-group teardown in #174151 (`exec-spawn.ts` / `exec-termination.ts`); `orphaned-process.ts` `waitForExit` is the sibling site in the same module that was left on the wall clock. Node 16+ exposes a global `performance`, so no import is required.

## User Impact

Environment exit and resource reclamation are no longer delayed or spuriously accelerated by wall-clock adjustments. An orphaned child that ignores `SIGTERM` is always force-killed after a bounded 5s monotonic grace window, regardless of NTP corrections or machine resume.

## Evidence

**Pre-fix RED** — source reverted to `Date.now()`, regression test kept: the 60s wall rewind inflates the grace window, tree never reaped in 5s monotonic, test times out at 120s.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 × keeps SIGKILL escalation bounded when the wall clock rewinds  120079ms  (timed out 120000ms)
 Test Files  1 failed | Tests  1 failed | 21 passed (22)
```

**Post-fix GREEN** — with `performance.now()`, same test completes in 56ms, suite 22/22.

```console
$ npx vitest run src/process/orphaned-process.test.ts
 ✓ keeps SIGKILL escalation bounded when the wall clock rewinds  56ms
 Test Files  1 passed | Tests  22 passed (22)
```

**Behavior matrix** (wall rewound 60s during teardown, child ignores `SIGTERM`):

```text
clock during teardown      => SIGKILL escalation      => result
normal (no step)            => after 5s grace          => bounded
wall rewind 60s (pre-fix)   => after 5s + 60s (hangs)  => delayed by step
wall rewind 60s (post-fix)  => after 5s grace          => bounded
```

**Regression test** uses #174151's two-clock separation: `vi.setSystemTime(Date.now() - 60_000)` rewinds only wall clock; `performance.now()` keeps advancing on the fake-timer clock.

**macOS real-behavior proof (single continuous capture)** — GHA `macos-14` arm64, through the shipped `recoverManagedLlamaServer` (`extensions/llama-cpp`) entry: real managed llama-server asset at its pinned install path (root PPID=1), TERM-resistant descendant, real native inspection + real `process.kill`. 60s wall-clock rollback injected at the remaining-budget read (CI pins clock via NTP; monotonic clock + transport stay real). Full run: [oc-macos-proof run 39908934594](https://github.com/SunnyShu0925/oc-macos-proof/actions/runs/39908934594).

```console
===== CASE: FIXED (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[FIXED] before recovery: 4964  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=4964 port=19321
[FIXED] recoverManagedLlamaServer returned elapsed_monotonic=5634ms root_alive_after=false
VERDICT[FIXED] wall_jump=-60000ms elapsed_monotonic=5634ms reaped_root=4964 root_alive_after=false
PROOF PASS: FIXED escalated to SIGKILL in ~5s monotonic under wall-clock rollback

===== CASE: OLD (wall jump -60000ms) =====
[DIAG] platform=darwin arch=arm64 state_dir=/tmp/llama-state
[DIAG] findManagedLlamaServerAsset(command) => llama-b10809-bin-macos-arm64.tar.gz
[OLD] before recovery: 5509  1 /tmp/llama-state/tools/llama.cpp/b10809/darwin-arm64/llama-server
[llama-cpp] reaping orphaned managed llama-server: pid=5509 port=19321
[OLD] recoverManagedLlamaServer returned elapsed_monotonic=65290ms root_alive_after=false
VERDICT[OLD] wall_jump=-60000ms elapsed_monotonic=65290ms reaped_root=5509 root_alive_after=false
PROOF EXPECTED-OLD: OLD delayed SIGKILL by ~|rollback| (bug reproduced on real tree)
```

| variant | deadline clock | SIGKILL escalation (rollback −60s) |
|---|---|---|
| OLD (pre-fix) | `Date.now()` | **65.29s** = 5s grace + 60s rollback |
| FIXED (this PR) | `performance.now()` | **5.63s** = bounded grace |

Real managed-service recovery on a real macOS orphan tree, matching already-landed sibling #174151.

**Open PR collision check**: no open/merged PR touches `orphaned-process.ts` clock domain; sibling #174151 landed for `exec-spawn.ts`/`exec-termination.ts`, no overlap.

Co-authored-by: SunnyShu <[email protected]>

(cherry picked from commit f9a17a7)

Co-authored-by: RomneyDa <[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: 🐚 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.

2 participants