Skip to content

fix(gateway): derive the darwin stop budget from the launchd job - #157007

Merged
Patrick-Erichsen merged 42 commits into
openclaw:mainfrom
etzelm:fix/launchd-stop-budget
Sep 29, 2026
Merged

Patrick-Erichsen merged 42 commits into
openclaw:mainfrom
etzelm:fix/launchd-stop-budget

Conversation

@etzelm

@etzelm etzelm commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #156968

What Problem This Solves

On darwin the Gateway's stop deadline is derived from restart ownership rather than from the supervisor that enforces it. A host running with OPENCLAW_SUPERVISOR_MODE=external resolves drain=315000ms and reports source=Gateway stop policy=330000ms, whatever launchd actually enforces, because detectGatewayRespawnSupervisor short-circuits to "external" before any platform detection and resolveGatewayShutdownBudget consumes that ownership answer for timing.

OPENCLAW_SUPERVISOR_MODE=external is documented supported configuration. docs/cli/gateway/restart-and-supervision.md:144 instructs operators to set it when another process manager owns the lifecycle, with a worked command at :154. Any darwin operator following that page reaches this budget.

User Impact

A macOS Gateway now plans its drain against the deadline its own launchd job enforces instead of a platform-neutral constant, and it does so per stop rather than once at startup. The stop budget is the time until the supervisor may kill the process; drain is the first portion spent waiting for active work to finish, before reserved cleanup and exit time.

Every job keeps a positive drain. The two fixed allowances that fund cleanup and process exit were sized against the 315 second platform-neutral drain, and against a short ExitTimeOut they consumed it entirely. The exit margin is now capped at a quarter of the job's deadline, and the reserve yields only as far as keeping a 5000 ms drain requires, so a short deadline keeps a usable drain instead of spending its whole budget on overhead.

On the installed LaunchAgent template's 20 second deadline the drain becomes 5000 ms with a 15000 ms shutdown deadline, rather than a planned 315000 ms the supervisor would cut short. That is the same nominal 5000 ms drain and 10000 ms reserve the current code already allocates at that deadline, so the installed template's split does not change beyond the cost of reading the deadline, measured here as a 13 ms debit that moves from the reserve to the drain, and tracking that cost one-for-one for as long as it stays within 5 seconds; what changes is that the Gateway now plans against 15000 ms instead of 315000 ms. Deadlines below 20 seconds gain drain and give up some reserve: the current code drains nothing at all at 15 seconds and below, and 4000 ms at 19 seconds.

When the job cannot be inspected at all, the Gateway keeps the stop policy it already had and warns with the target and reason. A failed inspection establishes nothing about who is stopping the job, so it is not allowed to shorten a drain that no launchd deadline was bounding.

Why This Change Was Made

Upstream already named this principle and implemented it for Linux only. src/cli/gateway-cli/run-loop-shutdown-budget.ts:19-20 at base reads:

// Restart ownership may be external while systemd still enforces the stop deadline.
const systemdStop = process.platform === "linux" ? await readSystemdStopTimeout() : null;

The comment states the rule and the next expression gates it to one platform. run-loop-shutdown-budget.test.ts:29 states it again as a describe title, "Gateway stop deadline independent of restart ownership", with platform: "linux" stubbed at :16 and no case overriding it. PR #151142 introduced that gate. This is its darwin half.

detectRespawnSupervisor already answers correctly on darwin, and upstream already asserts the two resolvers disagree at src/infra/supervisor-markers.test.ts:137-145. The information needed to fix this was already in the tree.

Why the deadline is read per stop, not at startup

ExitTimeOut bounds a stop that launchd is running and nothing else. An externally delivered SIGTERM never starts that clock, and the job outlives the deadline untouched. There is no enforcing deadline to read before a stop is under way, so reading one at startup would spend a launchctl print only to adopt a deadline that does not govern the stop the Gateway will actually get.

The job's own state is what separates the two. launchd reports the job as SIGTERMed from the moment it begins its own stop, and keeps reporting running while the process handles a signal some other sender delivered. Measured on macOS 27 against a job carrying ExitTimeOut 47:

Stop delivery job state Deadline enforced?
launchctl bootout SIGTERMed yes, killed at the 47 second mark
launchctl kickstart -k SIGTERMed yes, last terminating signal = Killed: 9
plain kill -TERM running no, still alive at 85 seconds

Anything unrecognised counts as not stopping, so an unfamiliar state leaves the Gateway on the budget it already had rather than shortening a drain launchd was never going to interrupt.

Why a short job deadline no longer spends its whole budget on overhead

GATEWAY_SHUTDOWN_RESERVE_MS (10000) and GATEWAY_SUPERVISOR_EXIT_MARGIN_MS (5000) were sized against the 315 second platform-neutral drain, where they are rounding error. Against a job's own ExitTimeOut they are not: subtracting both fixed values from a short deadline consumed it entirely, so drain reached zero at every ExitTimeOut at or below 15 seconds. 5 seconds funded the margin alone; 15 funded margin plus reserve.

The exit margin is now capped at a quarter of the job's deadline. The reserve keeps its full 10000 ms wherever the budget can fund it, and yields only as far as preserving a 5000 ms drain requires:

const drainFloorMs = Math.min(5_000, Math.floor(budgetMs * 0.5));
return Math.min(10_000, budgetMs - drainFloorMs);

The 5000 ms figure is not chosen freely. It is the drain the installed 20 second LaunchAgent template already yields today, once main subtracts its fixed 5000 ms margin and 10000 ms reserve. Funding the full reserve beside it needs 15000 ms of shutdown budget, which is exactly what a 20 second deadline resolves to. Four properties follow.

  1. No deadline at or above the template loses any reserve. For any shutdown budget of 15000 ms or more the reserve is the untouched 10000 ms and the drain is identical to main's, so nothing that works today is re-timed.
  2. The total spend still ends one margin before launchd's deadline: timeoutMs + margin == ExitTimeOut exactly.
  3. Drain is positive for every positive deadline, and both reserve and drain are monotone in the deadline, so no job is worse off than a shorter one. The resolution cost is debited as before.
  4. The drain never shrinks against main at any deadline. It is equal at 20 seconds and longer and strictly larger below.

This is not a fixed minimum drain. A fixed minimum spent regardless of the deadline gets SIGKILLed mid-drain on short jobs. This floor only ever redistributes budget that launchd is already granting, never extends past it, and yields to the deadline first: at a 5 second job the floor is min(5000, floor(3726/2)), which is 1863 ms, not 5000 ms.

A related reporting bug is fixed in the same expression. The shutdown log computed its drain figure by subtracting the unscaled reserve constant rather than the reserve actually held back, so on any short budget it understated drain by the difference. It now reports the margin and drain actually spent.

Why the launcher case needs its own ceiling

The installed service can keep a launcher parent while the serving Gateway runs as its child, so launchctl print reports the launcher's pid. Two things follow, and only taking both is safe.

First, a bare pid === process.pid test rejects the job that actually enforces the deadline, and the Gateway silently falls back in exactly the layout where an operator's ExitTimeOut was supposed to apply.

Second, accepting that job at face value is worse than rejecting it. On a forwarded stop signal the launcher re-sends SIGTERM to its child, force-kills it one grace later, and exits one grace after that. A reader that adopted a 55 second job deadline in that layout would plan drain=40000ms shutdown=50000ms and then be killed by its own parent around 19 seconds in, truncating the drain it just promised.

The launcher does not declare that instant. Both sides derive it from one expression in gateway-shutdown-budget.mjs, the launcher to arm its escalation and the Gateway to bound its budget, so the two cannot disagree. Deriving rather than declaring is what makes this correct on upgrade: replacing files cannot change a launcher that is already running, so the first Gateway built from any change is started by the previous launcher. A value that had to be announced would be missing exactly then, which is when the mismatch is widest. A launcher that declares the timer through an environment variable was measured to resolve the identical 19000 ms cap and the identical budget, so the variable carried no information the child could not derive and it is not in this PR. The derived case is measured below.

Holding the parent slot is not evidence of that timer. An external process manager can start the Gateway from inside the same job and run no reap timer at all, and capping its deadline at OpenClaw's would cut a valid drain short. The cap is therefore gated on the respawn markers a runRespawnedChild parent stamps on its child. All three call sites are covered, not just the Node-recovery one: the two compile-cache respawns in openclaw.mjs reach the same launcher through the same function and arm the same escalation, and the packaged one can wrap a foreground gateway run on an installed service. The marker set lives beside the deadline it authorises so a new respawn path cannot silently escape the cap. A parent that set no marker still caps nothing.

A shorter job deadline applies in every layout, because launchd reaps the whole job regardless of the launcher.

launchd clamps ExitTimeOut at 60 seconds

Measured on macOS 27 against a bare /bin/sleep 600 job with no OpenClaw code involved. plutil reads back the requested value in every case; launchctl print reports what launchd will enforce:

plist ExitTimeOut 20 47 59 60 61 75 90 120 300
launchd reports 20 47 59 60 60 60 60 60 60

For positive finite values the Gateway reads the enforced value rather than the plist; on macOS 27 that caps the launchd branch at a 55000 ms shutdown budget. An explicit ExitTimeOut=0 is different: launchd defines it as infinity. The reader now keeps that job unlimited unless a marked launcher has its own finite reap timer.

The change in one sentence

The linux-gated probe becomes a platform dispatch, and a new readLaunchdStopTimeout mirrors readSystemdStopTimeout by reading the running job's effective exit timeout, accepting it only when launchd is the party stopping the job and the printed pid is this process or the launcher that spawned it, capping the launcher case at the reap timer that launcher derives from the same shared expression, and scaling the fixed reserve and exit margin so a short deadline still funds a drain.

At this revision the diff is 2025 additions and 138 deletions across 14 files: 362/-33 production and declarations, 1586/-100 tests, and 77/-5 documentation. The launchd reader is 187 lines and the shared budget module adds 69. Most remaining size is lifecycle test scaffolding: the darwin run-loop cases were split out of the existing line-capped suite.

Contract

Case Resolved source Budget
launchd stopping, exit timeout = 5 launchd <domain>/<label> exit timeout drain 1863 ms, shutdown 3726 ms, measured on an earlier arithmetic-equivalent revision
launchd stopping, exit timeout = 20 launchd <domain>/<label> exit timeout drain 5000 ms, shutdown 14987 ms, measured on an earlier arithmetic-equivalent revision
launchd stopping, exit timeout = 19 launchd <domain>/<label> exit timeout drain 5000 ms, shutdown 14238 ms, measured on an earlier arithmetic-equivalent revision
launchd stopping, exit timeout = 47 launchd <domain>/<label> exit timeout drain 31986 ms, shutdown 41986 ms, measured
launchd stopping, exit timeout = 55, pid is this process launchd <domain>/<label> exit timeout drain 40000 ms, shutdown 50000 ms
pid is the launcher, respawn marker present, enforced exit timeout = 60 ... capped at the launcher's 19000ms stop timer capped to 19000 ms, measured; that budget then splits to drain 5000 ms, measured on an earlier arithmetic-equivalent revision
pid is the launcher, respawn marker present, exit timeout = 5 launchd <domain>/<label> exit timeout 5000 ms, uncapped: launchd reaps the job first
pid is the launcher, no respawn marker, enforced exit timeout = 60 launchd <domain>/<label> exit timeout 60000 ms, uncapped, measured
pid is the launcher, respawn marker present, job is not the service launchd <domain>/<label> exit timeout uncapped: the derived policy timer outlasts any job deadline
pid is this process, respawn marker inherited launchd <domain>/<label> exit timeout uncapped: a launcher timer belongs to a parent
Job printed, state = running reader returns null unchanged stop policy, full drain kept, measured; a directly signaled launcher remains a known ambiguity
Job stopping, exit timeout = 0, no launcher timer unlimited launchd timeout ordinary Gateway policy, no native cap on requested restart drain; new regression tests
Job stopping, exit timeout = 0, marked launcher launchd unlimited, capped at launcher timer finite parent reap timer wins; new regression test
Job printed and stopping, exit timeout missing or invalid ... exit timeout unavailable; default ExitTimeOut 20000 ms, with a warning
pid is neither this process nor its launcher next domain, then unresolved unchanged stop policy, warning naming every rejected target
launchctl print fails or throws in every domain unresolved, no deadline unchanged stop policy, with a warning
darwin, not a launchd job reader returns null unchanged, nativeStopBudget false
linux unchanged systemd path unchanged

The source string names the cap only when the cap actually binds, so an operator reading the log can tell a clamped deadline from an adopted one.

The allocation across the deadline range, with main's split beside it:

Job ExitTimeOut Exit margin Shutdown deadline Reserve Active-work drain main's reserve/drain
5s 1250 ms 3750 ms 1875 ms 1875 ms 0 / 0
10s 2500 ms 7500 ms 3750 ms 3750 ms 5000 / 0
15s 3750 ms 11250 ms 6250 ms 5000 ms 10000 / 0
19s 4750 ms 14250 ms 9250 ms 5000 ms 10000 / 4000
20s (template) 5000 ms 15000 ms 10000 ms 5000 ms 10000 / 5000
25s 5000 ms 20000 ms 10000 ms 10000 ms 10000 / 10000
47s 5000 ms 42000 ms 10000 ms 32000 ms 10000 / 32000
No launchd deadline 5000 ms 325000 ms 10000 ms 315000 ms 10000 / 315000

From the 20 second template upward the split is main's split. Below it the reserve is genuinely lower than main's, for every deadline from roughly 8 seconds to 20, and that is a real reduction rather than only a reallocation of budget main was wasting. At 16 to 19 seconds main does drain positively, 4000 ms at 19 seconds, so those rows trade cleanup reserve for a longer drain. At 15 seconds and below main holds a full or near-full reserve but drains nothing at all. No shipped template or platform default lands in that range; the installed template is 20 seconds and the systemd default is 90.

In live runs the resolved budget is a few milliseconds under its nominal value, because resolving it is itself debited. At the 20 second template that puts the budget at 14987 ms rather than 15000 ms, just below the point where the full reserve fits, so the measured reserve is 9987 ms rather than 10000 ms and the drain is 5000 ms rather than 4990 ms. The reserve given up at the template is the 13 ms probe debit, and it buys back the same 13 ms of drain.

Evidence

One machine, a Mac Studio on macOS 27 with node v26.8.1, base 0ad702eda0c. Scratch LaunchAgents bootstrapped into gui/501 from a temp directory, never written to ~/Library/LaunchAgents, with a throwaway HOME and their own profile; they never contact a production Gateway, port, or profile, and every scratch label was booted out of both user/501 and gui/501 afterwards and verified absent, with launchctl list ending at zero matches.

Two scoping facts, stated once here rather than repeated per capture. The captures are at three trees: the before-and-after pair at b736529385f2, the six reserve-split captures at tree-clean fdb0608ca1a, and the seven loaded captures at 6b5583b6362 (tree d8c94bd958424416d5488ecda8b044642f3c4ecf); each tree was verified with git write-tree before building, and changes to gateway-shutdown-budget.mjs since the reserve-split captures are comment-only; its positive finite allowance arithmetic is unchanged. And the allowance arithmetic changed after the state-gate, launcher-upgrade and loaded captures were taken, so the reserve and drain fields in those three carry the earlier flat half-of-budget cap: on the same budgets the shipped code yields reserve=9969ms drain=5000ms (state gate, 14969 ms budget), reserve=9237ms drain=5000ms (launcher, 14237 ms budget) and 9987 ms of reserve at the 20 second template rather than 7488 ms. Each of those captures is cited for a source-selection, cap, or cleanup-cost result that does not depend on the split, and the positive finite split is measured on the cited revision in the reserve-split section; this revision retains that arithmetic and adds the zero-timeout guard. Because the shipped reserve at the template is strictly larger than the one the loaded captures ran against, every headroom conclusion drawn from them is conservative by 2499 ms.

Before and after, one variable, through the real service boundary

The only difference between the two builds is the darwin probe this PR adds. The control reverts it to the shape base has, which is 1 insertion, 6 deletions in one file:

   if (process.platform === "darwin" && stopping) {
-    const read = await readLaunchdStopTimeout();
-    return { ...read, inconclusive: read.stop === null && read.warning !== undefined };
+    return { stop: null, inconclusive: false };
   }

Both runs used the identical plist carrying ExitTimeOut 47, and both were stopped by launchctl bootout. The job reports that itself, sampled live while the stop was under way:

AFTER, pid 68955                    BEFORE, pid 69734
	state = SIGTERMed                   state = SIGTERMed
	exit timeout = 47                   exit timeout = 47
	pid = 68955                         pid = 69734

In both runs the printed job is the serving Gateway, not a same-named job in another domain: ps reports 68955 1 openclaw-gateway and 69734 1 openclaw-gateway, and lsof puts each pid on 127.0.0.1:18799 and [::1]:18799.

AFTER:

15:18:55.707 [gateway] shutdown budget at startup: drain=315000ms shutdown=325000ms reserve=10000ms exitMargin=5000ms; source=Gateway stop policy=330000ms
15:19:04.926 [gateway] shutdown budget at shutdown: drain=31983ms shutdown=41983ms reserve=10000ms exitMargin=5000ms; source=launchd gui/501/ai.openclaw.evidence exit timeout=47000ms
15:19:04.927 [gateway] active-work drain settled; beginning server close
15:19:04.977 [shutdown] completed cleanly in 49ms

BEFORE, same tree, darwin probe reverted:

15:20:36.595 [gateway] shutdown budget at startup:  drain=315000ms shutdown=325000ms reserve=10000ms exitMargin=5000ms; source=Gateway stop policy=330000ms
15:20:46.560 [gateway] shutdown budget at shutdown: drain=315000ms shutdown=325000ms reserve=10000ms exitMargin=5000ms; source=Gateway stop policy=330000ms
Measured at the stop BEFORE AFTER
Selected source Gateway stop policy=330000ms launchd gui/501/<label> exit timeout=47000ms
Drain 315000 ms 31983 ms
Shutdown deadline 325000 ms 41983 ms
source=launchd records in the log 0 1
Deadline launchd was actually enforcing 47000 ms 47000 ms

The BEFORE shutdown record is byte identical to its own startup record. That is the defect: the deadline the Gateway plans against is the one it resolved at startup from restart ownership, and the 47 second deadline launchd is enforcing on that very stop never reaches it.

The AFTER pair also proves the reread happens per stop rather than once at startup. Both records come from the same process in the same run.

The same 47 second configuration re-measured on the shipped arithmetic gives drain=31986ms shutdown=41986ms reserve=10000ms exitMargin=5000ms, against 31983ms above, so the long-deadline case is untouched by the scaling and the pair above still describes the shipped build:

	state = SIGTERMed
	exit timeout = 47
	pid = 45310

shutdown budget at shutdown: drain=31986ms shutdown=41986ms reserve=10000ms exitMargin=5000ms; source=launchd gui/501/ai.openclaw.probe.eto47.9c3b6e5d exit timeout=47000ms

margin = min(5000, floor(47000 * 0.25)) = 5000; min(325000, 42000) = 42000; a 14 ms debit gives 41986; reserve = min(10000, floor(41986 / 2)) = 10000; drain = 41986 - 10000 = 31986.

The reserve split, measured against main's own arithmetic

The compatibility question is about the allowance split rather than the probe, so this pair holds the probe fixed and varies only the two allowance expressions. The control restores base's arithmetic exactly, 2 insertions, 12 deletions in gateway-shutdown-budget.mjs.

Base computes both inline in src/cli/gateway-cli/run-loop-shutdown-budget.ts rather than in named functions, which is what this PR extracted. The two expressions the control restores are base's own, at :43 and :49:

Math.min(GATEWAY_SHUTDOWN_TIMEOUT_MS, stop.timeoutMs - GATEWAY_SUPERVISOR_EXIT_MARGIN_MS);
const reserveMs = Math.min(GATEWAY_SHUTDOWN_RESERVE_MS, timeoutMs);

Base already applies them to a real supervisor deadline on Linux, where readSystemdStopTimeout has been wired since #151142, so for a systemd TimeoutStopSec this is base's live behaviour, not a counterfactual. On darwin base never reaches them with a job deadline at all, which is the defect this PR fixes, so there the control answers the narrower question: what these deadlines get if the probe lands and the allowances stay fixed.

-export const resolveSupervisorExitMarginMs = (stopTimeoutMs) =>
-  Math.min(
-    GATEWAY_SUPERVISOR_EXIT_MARGIN_MS,
-    Math.floor(Math.max(0, stopTimeoutMs) * GATEWAY_SUPERVISOR_EXIT_MARGIN_SHARE),
-  );
+export const resolveSupervisorExitMarginMs = () => GATEWAY_SUPERVISOR_EXIT_MARGIN_MS;

-export const resolveShutdownReserveMs = (shutdownTimeoutMs) => {
-  const budgetMs = Math.max(0, shutdownTimeoutMs);
-  const drainFloorMs = Math.min(
-    GATEWAY_SHUTDOWN_DRAIN_FLOOR_MS,
-    Math.floor(budgetMs * GATEWAY_SHUTDOWN_DRAIN_FLOOR_SHARE),
-  );
-  return Math.min(GATEWAY_SHUTDOWN_RESERVE_MS, budgetMs - drainFloorMs);
-};
+export const resolveShutdownReserveMs = (shutdownTimeoutMs) =>
+  Math.min(GATEWAY_SHUTDOWN_RESERVE_MS, Math.max(0, shutdownTimeoutMs));

Six runs: three ExitTimeOut values against both builds, same plist generator, same launchctl bootout stop, a throwaway HOME each. All six printed state = SIGTERMed while the stop was in flight, so launchd enforced each deadline in every cell. All six exited 0, and launchctl list | grep -c ai.openclaw.cap afterwards is 0.

ExitTimeOut Build exitMargin shutdown reserve drain
20s (template) this PR 5000 ms 14987 ms 9987 ms 5000 ms
20s (template) main 5000 ms 14990 ms 10000 ms 4990 ms
19s this PR 4750 ms 14238 ms 9238 ms 5000 ms
19s main 5000 ms 13988 ms 10000 ms 3988 ms
5s this PR 1250 ms 3726 ms 1863 ms 1863 ms
5s main 5000 ms 0 ms 0 ms 0 ms

At the installed template the reserve is unchanged to within the probe debit. 9987 ms against main's 10000 ms is a 13 ms difference, and the drain gains the same 13 ms. The compatibility band at issue, cleanup between 7500 ms and 10000 ms, is therefore not opened: the only cleanup duration that finishes under main and not under this PR at the template is one lasting between 9987 ms and 10000 ms.

At 5 seconds main resolves the entire budget to zero. The two verbatim records, same deadline, same stop:

this PR  07:47:40 shutdown budget at shutdown: drain=1863ms shutdown=3726ms reserve=1863ms exitMargin=1250ms; source=launchd gui/501/ai.openclaw.cap701.cand5-8961e1 exit timeout=5000ms
main     07:56:24 shutdown budget at shutdown: drain=0ms    shutdown=0ms    reserve=0ms    exitMargin=5000ms; source=launchd gui/501/ai.openclaw.cap701.ctrl5-e8032c exit timeout=5000ms

main's fixed 5000 ms exit margin consumes a 5000 ms deadline in full, leaving no shutdown budget at all. What follows in that run is not a clean stop:

07:56:24.564 [gateway] shutdown deadline reached; abandoning unfinished cleanup and active work before stop; last observed: no active work; exiting cleanly
07:56:24.565 [gateway] wrote stability bundle: .../openclaw-stability-...-gateway.stop_shutdown_timeout.json

A healthy stop of an idle Gateway files a gateway.stop_shutdown_timeout diagnostic. The candidate build at the same deadline logs neither line. This is the case the proportional margin exists for, and it is the one a lifecycle owner would be trading away by keeping the fixed values.

The template rows differ only in the drain they announce:

this PR  07:46:38 draining active work before stop with timeout 5000ms: rootRequests=1
main     07:56:12 draining active work before stop with timeout 4990ms: rootRequests=1

Candidate arithmetic, so the numbers are checkable rather than asserted: margin = min(5000, floor(ETO * 0.25)); budget = ETO - margin less an elapsed debit; floor = min(5000, floor(budget / 2)); reserve = min(10000, budget - floor); drain = budget - reserve.

  • 20s: margin 5000, 15000 less a 13 ms debit is 14987, floor min(5000, 7493) = 5000, reserve min(10000, 9987) = 9987, drain 5000.
  • 19s: margin 4750, 14250 less 12 ms is 14238, floor 5000, reserve min(10000, 9238) = 9238, drain 5000.
  • 5s: margin 1250, 3750 less 24 ms is 3726, floor min(5000, 1863) = 1863, reserve 1863, drain 1863.

Control rows use margin = 5000 fixed and reserve = min(10000, budget): 20s gives 14990, reserve 10000, drain 4990; 19s gives 13988, reserve 10000, drain 3988; 5s gives 0, so both are 0.

The state gate, measured against the same job

Same plist at ExitTimeOut 47, stopped with a plain kill -TERM instead of launchctl:

[print at-stop]	state = running
[print at-stop]	exit timeout = 47

shutdown budget at shutdown: drain=7485ms shutdown=14969ms reserve=7484ms exitMargin=5000ms; source=launchd ExitTimeOut=20000ms

The job reports running, so the 47000 ms deadline is refused and the template value kept. This is what establishes that the 5000 ms and 47000 ms adopted above came from launchd driving the stop rather than from the plist merely existing. The reserve and drain fields here are the earlier cap, as noted in the preamble; the refusal this capture is cited for does not depend on the split.

The launcher upgrade case, measured

The layout that matters on upgrade: an already-running published launcher starting the candidate Gateway. The published launcher is the merge base's own file, extracted with git show 8dd24e6ec0a:node-runtime-recovery.mjs and confirmed byte-unchanged, so it sets no marker this branch added. It loads unmodified against the candidate tree.

The launchd job runs that published launcher, which respawns the candidate Gateway as its child. In both captures the printed job pid equals the child's ppid and not the child's own pid, so the reader is genuinely on the launcher relation, and the child's argv positionals are ["gateway","run"] at boot and again at the stop:

printed job pid child ppid child own pid relation state enforced exit timeout
marker present 57433 57433 57437 launcher SIGTERMed 60
marker absent 57482 57482 57486 launcher SIGTERMed 60

Marker present, the upgrade case, with OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS unset in the child:

shutdown budget at shutdown: drain=7119ms shutdown=14237ms reserve=7118ms exitMargin=4750ms; source=launchd gui/501/ai.openclaw.probe.caseA2.pub.8d1f4e7a exit timeout capped at the launcher's 19000ms stop timer=19000ms

The job's enforced deadline was 60000 ms and the budget resolved to 14237 ms, held down by the launcher rather than the job. margin = min(5000, floor(19000 * 0.25)) = 4750; min(325000, 19000 - 4750) = 14250; a 13 ms debit gives 14237. The cap this capture is cited for is independent of the split; the shipped split on that same 14237 ms budget is the 19 second row measured on an earlier arithmetic-equivalent revision above, 14238 / 9238 / 5000.

Marker absent, the control, same rig:

shutdown budget at shutdown: drain=44985ms shutdown=54985ms reserve=10000ms exitMargin=5000ms; source=launchd gui/501/ai.openclaw.probe.caseC2.nomark.2b9c6f3d exit timeout=60000ms

No cap clause in the source and the job's enforced 60000 ms adopted, which is the guarantee that a parent holding the job's pid without having respawned this process is never shortened by a timer it does not run.

The reserve under load, measured

Every capture above left the Gateway idle, and idle cleanup cannot establish that a smaller reserve is safe. This round drives real work through the Gateway's own /v1/chat/completions surface: N concurrent streaming agent runs, each its own session, each holding an HTTP response and gateway root work open, backed by a loopback stub provider that streams tokens indefinitely so no run can settle inside the drain.

Every loaded capture therefore spends its entire drain budget and enters cleanup with exactly the reserve left, which is the worst case the reserve has to survive. The Gateway's own counts at the stop say so:

draining active work before stop with timeout 7489ms: queueSize=64 embeddedRuns=32 sessionAdmissions=32 rootRequests=32
active-work drain timeout reached; proceeding with shutdown: queueSize=64 embeddedRuns=32 sessionAdmissions=32 rootRequests=32
Capture Allowances ExitTimeOut Live runs Reserve Drain spent Cleanup Outcome SIGTERM to gone
cand20idle proportional 20 s 0 7489 ms 7490 ms 196 ms completed cleanly 7866 ms
cand20 proportional 20 s 8 7488 ms 7490 ms 1185 ms completed, http-server[0] 8866 ms
cand20heavy proportional 20 s 32 7488 ms 7491 ms 1170 ms completed, http-server[0] 8871 ms
ctrl20 fixed 20 s 8 10000 ms 4984 ms 1217 ms completed, http-server[0] 6406 ms
cand5 proportional 5 s 8 1865 ms 1866 ms 1194 ms completed, http-server[0] 3270 ms
cand5heavy proportional 5 s 32 1870 ms 1872 ms 1164 ms completed, http-server[0] 3231 ms
ctrl5 fixed 5 s 8 10000 ms 0 ms abandoned shutdown deadline reached, stability bundle 208 ms

Cleanup is the Gateway's own [shutdown] completed in Nms measure, which starts at active-work drain settled; beginning server close. ctrl20 and ctrl5 are the same tree with one file reverted to fixed allowances, 6 insertions, 10 deletions in gateway-shutdown-budget.mjs, so the only variable between a cand row and its ctrl row is the share policy itself. Those two control rows reverted the reserve to a flat 10000 ms constant, which is why ctrl5 reports reserve 10000 ms against a zero budget; base clamps it with min(GATEWAY_SHUTDOWN_RESERVE_MS, timeoutMs) and reports reserve 0 ms there, as the newer control does. The drain is 0 ms either way, so the abandoned-cleanup result these rows establish is unaffected. The 5 second rows describe the shipped build: at or below a 10000 ms budget both the earlier and the shipped cap reduce to half the budget, and cand5 at 1865 ms is within the debit of the 1863 ms measured on an earlier arithmetic-equivalent revision.

Three results follow.

Cleanup cost tracks neither the load nor the reserve. Quadrupling concurrent runs from 8 to 32 moved it by -15 ms at 20 seconds and -30 ms at 5 seconds. Across a reserve range of 1865 ms to 10000 ms, a 5.4x spread, cleanup stayed inside 1164 ms to 1217 ms, a 53 ms spread. What it does track is the fixed HTTP_CLOSE_GRACE_MS that server-close.ts spends before forcing live connections, which the log names directly:

[shutdown] http-server[0] close exceeded 1000ms; forcing connection shutdown and waiting for close
[shutdown] completed in 1170ms with warnings: http-server[0]

That warning appears identically under both allowance policies at the same deadline, cand20 and ctrl20, so it is a property of holding live streams open across a stop rather than of the smaller reserve. With no client connections at all it disappears: cand20idle cleans up in 196 ms and completes cleanly. cand20idle is not an idle Gateway, only a Gateway with no client connections; the memory-core plugin's own dreaming cron job was mid-run, so that capture reports embeddedRuns=1 activeTasks=1 and still spends its whole 7489 ms drain. It is the connection count, not the work count, that separates 196 ms from 1185 ms.

The per-step close trace isolates it. At 32 live runs, the same single step dominates at both deadlines and costs the same at both, while every other step is sub-millisecond to tens of milliseconds:

ExitTimeOut 20, reserve 7488ms
  restart.close.websocket-server  0.1ms
  restart.close.http-server    1004.9ms
  restart.close.total          1170.0ms

ExitTimeOut 5, reserve 1870ms
  restart.close.websocket-server  0.1ms
  restart.close.http-server    1004.1ms
  restart.close.total          1164.0ms

Both were driven by launchd, sampled live while the stop was under way:

cand20heavy                         cand5heavy
	state = SIGTERMed                   state = SIGTERMed
	exit timeout = 20                   exit timeout = 5
	pid = 41260                         pid = 40863

At the installed template the reserve is 8.5x the measured loaded cleanup cost, 9987 ms against 1170 ms at 32 live runs.

At the short deadline the scaled rule finishes under load and the fixed one does not. On the same 5 second job with eight live runs the candidate drains 1866 ms, completes cleanup in 1194 ms inside its 1865 ms reserve, and is gone 3270 ms into a 5000 ms deadline.

The thinnest margin is the 5 second one: 1194 ms of cleanup inside 1865 ms, 64 % used, 671 ms of slack. Since cleanup is dominated by a fixed 1000 ms grace rather than the reserve, the crossing point is an ExitTimeOut near 3.2 seconds, where 0.375 x ExitTimeOut stops covering it. Below that the fixed policy is already at drain=0, so 3.2 seconds is the honest boundary of what is measured.

What it would take to land in the affected band

On the 20 second template the band at risk is 13 ms wide: a cleanup costing between 9987 ms and 10000 ms finished before and is cut off now. That is the probe debit, not a policy choice, and the whole residual at the template.

A wider band exists at 19 seconds and below, where the reserve is budget - 5000: 762 ms at 19 seconds, 3750 ms at 15. That range is the open decision in Gaps.

What it would take to reach even the wider band, from the close path's own constants in src/gateway/server-close.ts: the largest single grace is 5000 ms (GATEWAY_SHUTDOWN_HOOK_TIMEOUT_MS, HTTP_CLOSE_FORCE_WAIT_MS, and the MCP, LSP, embedding-provider and agent-harness closes), with ACTIVE_SESSIONS_SHUTDOWN_DRAIN_TIMEOUT_MS at 2000 ms and WEBSOCKET_CLOSE_FORCE_CONTINUE_MS at 250 ms. No single one reaches 9987 ms, so one hung closer cannot enter the template band; it takes two independent closers each running to full grace, and the total would then have to land inside a 13 ms window. Even then the close is warned and bounded, not hung, because every step has its own cap.

Part of cleanup is already reserve-aware: createServiceChildCleanupDeadline adopts the shutdown budget and escalates by min(GRACEFUL_CANCEL_TIMEOUT_MS, remaining / 2), so child cleanup compresses with a smaller reserve instead of being truncated, and runWithProcessCleanupBudget pulls the close deadline in by min(HARD_EXIT_WATCHDOG_GRACE_MS / 2, remaining / 2), so a cleanup that runs out reports failure before the hard exit timer fires.

Measured whole-path cost with 32 live runs is 1170 ms, 8.5x below the template band's floor.

The rig for the loaded captures

Same machine and isolation rules as the captures above: scratch LaunchAgents bootstrapped into gui/501 from a temp directory, a throwaway HOME, port 18799, OPENCLAW_SUPERVISOR_MODE=external, and OPENCLAW_GATEWAY_RESTART_TRACE=1 for the per-step close trace.

The load needs a model that never finishes, so the provider is a 60 line loopback HTTP server that answers /v1/chat/completions with an SSE stream emitting a token every 400 ms and no finish_reason. It is a stub because the shutdown path is model agnostic: it only has to keep runs genuinely in flight so the drain is spent rather than skipped. The Gateway confirms it is the one being used, agent model: stub/stub-slow, and the stub confirms the Gateway is really calling it, one open upstream stream per client run. No shared or production model service was contacted.

The loaded job, not the plist

launchctl print reports the deadline of the job launchd has loaded, not the value sitting in the plist. Measured on macOS 27 against a scratch /bin/sleep job in gui/501, with no OpenClaw code involved:

Step plist on disk loaded job reports
bootstrap at ExitTimeOut 20 20 20
rewrite the same plist to 47, no reload 47 20
launchctl kickstart -k, process restarted, job not reloaded 47 20
launchctl bootout then launchctl bootstrap, job reloaded 47 47

So editing a loaded job changes nothing until the job is reloaded, and reloading it restarts the Gateway anyway. The previous guidance at docs/gateway/restart-recovery.md:405-406 claimed a plist edit took effect on the next stop; it now says what is measured above, and states what reading per stop actually buys: the Gateway never plans against a deadline it cached at its own startup.

Other checks

On the contributor's earlier measured revision, pnpm check:changed --base 0ad702eda0c ran 29 lanes on a clean worktree; 28 were ok:

Lane Result
typecheck all ok in 245.75 s, and all four links ran: tsgo:core:all (including tsgo:infra), tsgo:extensions:all, tsgo:scripts, tsgo:test:root
dead export scan ok in 47.41 s, all three Knip scans at 0 entries
line-cap growth ratchet, max-lines suppression ratchet ok
core tsgo graph boundary, database-first legacy-store guard, runtime sidecar loader guard ok
coercion helper declaration guard, deprecated API usage, assertion SAFETY comment ratchet ok
19 further lanes ok
lint fails on four pre-existing whole-tree violations, detailed in Gaps

On the earlier reviewed head 3e1d4ac13aee, pnpm format:check, pnpm format:docs:check and pnpm check:docs exited 0. The later a1e509ecee8e head introduced a two-assertion formatting difference, corrected by the isolated formatter at 0cca02df4cfd; its CI is pending. pnpm check:env-var-count also reported OPENCLAW_* count 486/486 on that earlier head. This branch leaves config/env-var-count-budget.txt untouched, so no ratchet waiver is needed; the respawn marker names are kept in the root module rather than in src so reading them does not promote a previously test-only name into the counted set.

CI on prior reviewed head 3e1d4ac13aee reported no failing check: 175 success, 45 skipped, CodeQL neutral. Head a1e509ecee8e later failed formatting and unrelated tooling shards. The formatting defect is corrected at current head 0cca02df4cfd, whose exact-head CI remains mandatory. That includes check-additional-boundaries, all five check-lint-core shards and all 44 checks-node-compact-large shards.

Measured test cost

Per-suite counts are quoted because a green vitest exit proves nothing when the path matched nothing: an export missing from a re-export barrel makes a suite report Tests no tests rather than a failure, which a count check catches and an exit code does not.

Cost is measured on one host, a Mac Studio (32 cores, 512 GB) on macOS 27 with node v26.8.1. The five rows other than run-loop-shutdown-budget.test.ts were measured at tree d8c94bd958424416d5488ecda8b044642f3c4ecf with a clean worktree, and four of those files remain byte identical at this head; the launchd reader test gained two zero-timeout/direct-signal cases, and the budget test was remeasured on an earlier revision before the new zero-timeout cases. Each file runs alone through node scripts/run-vitest.mjs run <file> --no-file-parallelism, which is a single worker, after one warm-up run that is discarded. Three timed runs per file; the figure is the median. vitest is the runner's own reported Duration, wall is the whole process measured from outside it, so the difference between them is process start and teardown.

File Tests vitest wall Share in tests Base wall
src/infra/launchd-stop-timeout.test.ts new 34 passed (34) 4.31 s 5.71 s 2 % n/a
src/cli/gateway-cli/run-loop.launchd.test.ts new 4 passed (4) 5.24 s 6.63 s 95 % n/a
src/cli/gateway-cli/run-loop-shutdown-budget.test.ts +459 48 passed (48) see below see below 1 % see below
src/cli/gateway-cli/run-loop.model-acquisition.process.test.ts +16 2 passed (2) 23.70 s 25.10 s 83 % 25.21 s
src/infra/node-runtime-recovery.shutdown.test.ts +18 5 passed (5) 545 ms 1.46 s 12 % 1.55 s
src/cli/gateway-cli/run-loop.test.ts -112 6 failed, 212 passed (218) 19.19 s 20.59 s 80 % 21.47 s

Base wall is the same median measured in the merge base's own worktree at ceac53a0feaf75eb599e4c310fbd7e35923ba9cf; it is wall only, because that pass did not capture vitest's own Duration. Every materially changed file is at or below its base cost.

run-loop-shutdown-budget.test.ts gains 40 cases, and its figures are reported separately because they are not comparable with the rows above. That pass ran in the same persistent worktree used for the other five rows, checking out each commit in turn with one discarded warm-up before three timed runs per arm; the paired base figure from the same worktree and the same session is given alongside it, which makes the delta the meaningful number:

Commit Tests vitest median wall median
tip 67bc549ab05 48 passed (48) 4.41 s 5.83 s
merge base 0ad702eda0c 8 passed (8) 4.40 s 5.78 s
delta for 40 added cases +40 +0.01 s +0.05 s

Three timed runs per arm after a discarded warm-up, all six exit 0, all six report Test Files 1 passed (1), and pnpm-lock.yaml is byte identical between the two commits so one install served both arms. The added cases cost about 0.25 ms each of vitest duration; the file's cost is dominated by transforming its module graph, which both arms pay identically. The cited tip row predates the new zero-timeout regression cases and the current-main test API adaptation. Treat its wall time as historical, not current-head measurement.

Two further figures deserve their own sentence.

run-loop.launchd.test.ts at 5.24 s is marginally above the 5 s per-file target, and almost none of that is test work. The file exists only because this branch moved the darwin cases out of run-loop.test.ts, which is at 3501 counted lines against a 1000 line cap where check-line-cap-ratchet rejects any growth; the three moved cases are byte identical to their originals. Counted honestly, the split costs about 5.8 s of wall on a sequential single-worker run of the pair: run-loop.test.ts fell 21.47 s to 20.59 s when the cases left, and the new file costs 6.63 s. Almost all of that is a second process start and a second load of the run-loop module graph, not the cases: in CI the file's four cases sum to 582 ms of reported test time, and the one case this branch adds rather than moves is 134 ms of it. In CI the file does not run alone, so the process start is not paid twice there.

run-loop.model-acquisition.process.test.ts at 23.70 s is the one file over the 5 s target by a wide margin, and this branch did not make it so. It costs 25.21 s at the merge base and 25.10 s here, a 0.11 s improvement. It is an out-of-process test that spawns a real Gateway child to assert the shutdown deadline through a real process boundary, which is the contract no cheaper layer proves; this branch adds 16 lines to it.

CI seconds. The repository's node shards run a per-test reporter, not the default file-summary reporter, so there is no per-file duration line in any node shard log. Verified rather than assumed: across all 115 Run Node test shard logs in the run below, grep -E '\([0-9]+ tests?\)' returns 6 hits, all in the core-tooling lane, and zero in any checks-node-compact-* shard. config/ci-test-timings.json is keyed by group for these files, not by file: only toolingFileSeconds and repoE2eFileSeconds are per-file. So the figure CI can supply is the sum of the per-test durations the reporter did print, which excludes import, transform, setup and teardown and is therefore a lower bound, not a file duration.

Measured from CI run 36219672571, at head 6b5583b6362. Four of the six files are byte identical between that head and this one, verified per path. The launchd-reader and shutdown-budget tests have grown since that run; the latter had already grown substantially: the reporter printed 29 cases for it there, against 48 at this head, so its CI figure below was measured before those cases existed and is a lower bound on the current file for that reason as well as the reporter reason. That shard was also cancelled in that run, so 29 is itself a floor. The single-worker cost of the cases this branch adds to the file is +0.01 s, measured in the table above.

File Shard Job Sum of per-test ms Job wall
src/infra/launchd-stop-timeout.test.ts core-runtime-infra-misc checks-node-compact-large-18 112 ms 317 s
src/cli/gateway-cli/run-loop.launchd.test.ts agentic-cli checks-node-compact-small-24 582 ms 350 s
src/cli/gateway-cli/run-loop-shutdown-budget.test.ts agentic-cli checks-node-compact-small-24 69 ms 350 s
src/cli/gateway-cli/run-loop.test.ts agentic-cli checks-node-compact-small-24 37396 ms 350 s
src/cli/gateway-cli/run-loop.model-acquisition.process.test.ts agentic-cli checks-node-compact-small-24 did not execute 350 s
src/infra/node-runtime-recovery.shutdown.test.ts core-runtime-infra-network-node checks-node-compact-large-31 did not execute 465 s

Shard assignment is not inferred from output: each shard job carries its own include list in OPENCLAW_NODE_TEST_GROUPS_GZIP_BASE64, and decoding it across all 115 shard logs puts each of the six files in exactly one job's includePatterns. That is also how the two non-executing files are located.

The two "did not execute" rows are honest gaps, and they are a cancellation cascade rather than a routing problem. checks-node-compact-small-13 failed that run on test/scripts/lint-suppressions.test.ts, which cancelled roughly thirty sibling shards at 05:14:36; run-loop.model-acquisition.process.test.ts was still queued behind its shard's 408-file include list, and core-runtime-infra-network-node never launched because the 384 s agentic-agents-support-hosted-1 shard ahead of it consumed its job. Neither is routed to a macOS or release-only lane: macos-node, macos-swift and checks-windows were all skipped in that run. That upstream failure is fixed as of 256abd76af3, test/scripts/lint-suppressions.test.ts reports 4 passed (4) at this head, and CI on the earlier 3e1d4ac13aee head was green on every shard. Current-head CI is tracked separately.

The one number the CI table makes plain: run-loop.test.ts at 37.4 s of reported test time is two orders of magnitude above everything this branch adds, and it is the file the branch made smaller.

Gaps, stated plainly

  • CI at a1e509ecee8e was red. check-docs and check-lint identified an oxfmt difference in the new launchd reader test; the formatter-generated two-assertion edit is the only change at 0cca02df4cfd. Several tooling shards also failed in untouched test/scripts/** files on missing .release-harness/scripts/lib/official-external-provider-catalog.json imports. Those failures are not presented as passing or waived; inspect the new exact-head suite and current main before landing.
  • Pre-format-head focused proof and measured test cost: Secretless AWS Crabbox lease cbx_5887cb73daf3 checked out a1e509ecee8e0a16f052d2dd6d983115dc18249a, verified no instance role with the trusted bootstrap, and ran the three affected files together with --maxWorkers=1: 3 files/91 tests passed, 46.33 s wall (run). Two files were also timed individually at that head: src/infra/launchd-stop-timeout.test.ts 37/37 in 36.62 s wall, and src/cli/gateway-cli/run-loop-shutdown-budget.test.ts 50/50 in 13.10 s wall (run). Import/transform dominate those wall times. This Linux mock-boundary proof does not replace the earlier real Mac launchd captures for positive deadlines; the new zero-timeout branch has no real macOS stop capture. CI shard seconds and the final head remain separate gates.
  • Design decision for RoboClaw's delegated repair-and-land scope: accept the measured short-deadline allocation, including the smaller cleanup reserve for custom launchd and systemd jobs under 20 seconds. At 19 seconds, about 762 ms of cleanup reserve buys about one second more active-work drain; at 15 seconds the previous drain was zero, so the larger old reserve could never be reached after a drain. The installed 20-second LaunchAgent and default 90-second systemd unit keep their nominal split. The accepted residual risk is an unusually slow plugin or service close on a custom short job: it may be interrupted sooner than under the prior reserve. Captured loaded stops used about 1.2 seconds of cleanup with up to 32 live runs; this is evidence for the choice, not a guarantee for every host. This decision does not waive exact-head CI or the repository merge gates.
  • On stop deadlines of 20 seconds and above the reserve is base's, less only what reading the deadline costs. That includes the installed LaunchAgent template and systemd's 90 second default. The debit measured 13 ms at the template and lands on the reserve, which buys the drain the same 13 ms. The reserve pays it alone only while the debit is 5 seconds or less; the probe's own worst case is larger, at most three launchctl print calls of 2 seconds each, and past 5 seconds the drain floor is share-bounded too and the two converge on half the remainder. A 6 second debit therefore splits a 20 second job's 9 second budget 4500/4500 rather than retaining the old reserve. Reaching that needs launchctl to hang on all three domain probes. Both the threshold and the over-threshold split are pinned by tests, including one asserting the over-threshold case is not the old reserve less the debit.
  • The reserve is not bit-identical to base at the template, only equal within the probe debit. Resolving the budget is debited from it, so the template lands at 14987 ms rather than a nominal 15000 ms, one debit below where the full 10000 ms reserve fits. A cleanup lasting 9987 ms to 10000 ms is the one duration that finishes under base and not here, a 13 ms window against a cleanup cost measured at 1170 ms with 32 live runs. A slow probe widens the window while also shortening base's own budget.
  • Cleanup is measured under load, but only to 32 concurrent runs on one host. The seven loaded captures show cleanup cost flat across 0, 8 and 32 concurrent agent runs and dominated by a fixed 1000 ms grace, so it is not reserve-bound at these deadlines. What is not shown is a host with hundreds of live connections, or a plugin whose own close step is slow; a sidecar that blocks for seconds would spend the reserve wherever the reserve came from, and the shares only change how much of it there is. The measured crossing point for the observed cleanup cost is an ExitTimeOut near 3.2 seconds.
  • The state-gate, launcher-cap and loaded captures predate the shipped allowance arithmetic, as set out at the head of Evidence. Each is cited for a result that does not depend on the split, and the shipped split is separately measured on an earlier arithmetic-equivalent revision, but no live capture at the shipped arithmetic exists for the state = running refusal or the launcher cap; those two are pinned by unit cases and by the bare-job measurements above.
  • Historical Mac run-loop measurement: run-loop.test.ts failed 6 cases on the contributor's measuring host, at its merge base and earlier branch revision alike. Base reports 6 failed | 215 passed (221), this head 6 failed | 212 passed (218), the 3 test difference being exactly the cases moved into run-loop.launchd.test.ts, and the sorted failing case names diff empty between the two. The cause is managed update handoff returned an invalid readiness response, a managed package lifecycle path unrelated to the shutdown budget. Not claimed fixed, shown not caused; the earlier CI head passed the shard that owns the file. Run it with node scripts/run-vitest.mjs run: under bare pnpm vitest run it reports a seventh failure that is a wrong-runner artifact.
  • The whole-tree lint lane fails locally on four files this branch does not touch. At this head: Found 0 warnings and 4 errors, all eslint(max-lines), on server-kernel.test.ts (1003), channel-health-monitor.test.ts (1023), mention-inbox.ts (713) and task-registry-state.ts (702). For each, git diff origin/main HEAD -- and git diff <merge-base> HEAD -- are both empty, none is in config/max-lines-baseline.txt, and this branch touches neither them nor the lint config, runner or baseline. The set drifts with upstream. CI's own check-lint and five check-lint-core shards were green on the earlier 3e1d4ac13aee head. The later formatting failure and current-head status are called out above; the four unrelated whole-tree local violations are not asserted as passing. The branch-scoped ratchet lanes both pass.
  • The marker gate is exactly as good as the marker. A third-party wrapper holding the job's pid that does arm its own reap timer stays over-budgeted, because it sets no marker. That is inherent to keying on positive evidence rather than the parent relation: the alternative shortens the budget of every parent that runs no timer at all. Unchanged from base.
  • The launcher cap is gated on launchd's state, but the launcher's timer is not. If the recovery launcher is resident and something other than launchd signals the job pid, the launcher arms its reap timer while the printed job still reports running, so the Gateway keeps its existing budget and the launcher force-kills the drain. Unchanged from base, which resolves the identical budget in that layout, and not reachable through supported paths: a CLI restart signals the verified port listener, and openclaw gateway stop goes through launchctl bootout, making launchd the stopper. Fixing it means applying the cap from the respawn marker alone on signal-initiated stops, which is a change to when the cap applies rather than how the deadline is read, so not in this PR. The same marker-based cap would also close the case where two launchers sit between the job and the Gateway, which defeats resolveJobRelation; reaching that needs an unsupported Node version plus an operator-set NODE_COMPILE_CACHE, which no template writes.
  • The launcher's foreground branch is derived from argv in two builds. The resident launcher evaluates its own build's flag tables while the serving Gateway evaluates the candidate's, so a flag they disagree about could select different branches. The tables match today, and the harmful direction needs a token known only to the candidate that the resident plist already carried.
  • While the recovery launcher is in the path, its timer derives from the LaunchAgent template's exit timeout rather than the running job's. So raising a job's ExitTimeOut buys no extra drain in that layout, measured above as a 60000 ms job held at a 14237 ms budget. That is correct, since the parent really will force-kill at 19000 ms, but it is a ceiling operators should know about and it is now documented.
  • The reader spends up to three launchctl print calls on a darwin stop, each bounded at 2 seconds, stopping at the first job whose pid matches this process or its launcher. The systemd path already spends up to two systemctl show calls there. A miss fails fast: an absent job answers immediately, an unavailable domain answers 125.
  • launchctl print output is not a stable API. The reader depends on three fields. pid and exit timeout each occur exactly once, which is what makes the last-value-wins parseKeyValueOutput safe for them. state occurs three times, the job's own at one tab plus two nested coalition lines at two tabs, so it is read with an anchored single-tab regex instead. All three were checked against live output in the captures above.

resolveGatewayShutdownBudget derives the stop deadline from restart
ownership, so a darwin host running with OPENCLAW_SUPERVISOR_MODE=external
resolves drain=315000ms whatever launchd actually enforces.

The linux-gated systemd probe becomes a platform dispatch, and a new
readLaunchdStopTimeout mirrors readSystemdStopTimeout: it reads the running
job's effective exit timeout and accepts it only when the printed pid is
this process. run-loop.ts is untouched because the reader detects launchd
from the environment itself.

Closes openclaw#156968
@clawsweeper

clawsweeper Bot commented Sep 24, 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 docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes size: M labels Sep 24, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 8:19 PM ET / September 29, 2026, 00:19 UTC (Revision 26).

ClawSweeper review

What this changes

The branch makes the Gateway size macOS shutdown from its loaded launchd job, shares deadline calculations with its launcher, adds lifecycle coverage and guidance, and completes a frozen tooling import list.

Merge readiness

✅ Ready for maintainer review

Current main still misses the loaded launchd stop deadline. This PR has a distinct fix, real Mac stop evidence, and a recorded acceptance of its short-deadline cleanup tradeoff.

Priority: P2
Reviewed head: de0f1976220ee8acdc64365cb0755c93f1ecde94

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is coherent and supported by real Mac stop traces, with substantial but explained lifecycle test growth.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Scratch macOS LaunchAgents exercised the changed Gateway stop path before and after the fix, with observed deadline selection and loaded cleanup under short stops. The final positive-deadline arithmetic is separately measured; the newer unlimited-timeout branch has focused boundary coverage rather than a live Mac capture. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Scratch macOS LaunchAgents exercised the changed Gateway stop path before and after the fix, with observed deadline selection and loaded cleanup under short stops. The final positive-deadline arithmetic is separately measured; the newer unlimited-timeout branch has focused boundary coverage rather than a live Mac capture. No stored-data contract changes.
Evidence reviewed 6 items Current-main gap: Current main probes systemd on Linux and otherwise derives the fallback from restart ownership; it has no launchd stop reader at this path.
Introduced stop reader: The reader checks the loaded job's PID and stopping state, preserves unlimited ExitTimeOut, and bounds a marked launcher by its own timer.
Budget integration: The run loop refreshes its budget on macOS stops; the budget owner distinguishes a confirmed native deadline from an inconclusive inspection.
Findings None None.
Security None None.

How this fits together

The Gateway run loop receives stop and restart requests and allocates time for active work, cleanup, and exit. On macOS, the new reader checks the loaded launchd job before that budget controls shutdown.

flowchart LR
  A[Stop request] --> B[Gateway run loop]
  B --> C[Loaded launchd job]
  C --> D[Deadline and launcher cap]
  D --> E[Drain and cleanup budget]
  E --> F[Gateway exit]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +247, Tests +1487, Docs +72, Other +77. Total +1883 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 4 265 18 +247
Tests 8 1588 101 +1487
Docs 1 77 5 +72
Config 0 0 0 0
Generated 0 0 0 0
Other 4 97 20 +77
Total 17 2027 144 +1883

Review metrics

Metric Value Why it matters
Production versus test growth production/declarations +362/-38; tests/support +1588/-101 The new launchd reader and shared launcher deadline justify production growth; lifecycle fixtures account for most added lines.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #156968
Summary: The open issue describes this Darwin stop-budget defect; the earlier merged systemd repair addresses the analogous Linux boundary.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep deadline discovery in the Gateway shutdown owner, retain the documented short-job allocation, and land the reviewed head through the normal exact-head gates.

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

Yes. Current-main source shows the Darwin gap, and the PR supplies a real scratch LaunchAgent before/after stop trace; this review did not run current main on macOS.

Is this the best way to solve the issue?

Yes. Reading the loaded job during shutdown addresses the enforcing deadline at the existing budget owner while preserving the direct-signal fallback.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The fix addresses a bounded Gateway shutdown error on macOS without evidence of an emergency outage.
  • merge-risk: 🚨 compatibility: Custom launchd and systemd jobs under 20 seconds receive a smaller cleanup reserve, a tradeoff accepted in the delegated landing review.
  • merge-risk: 🚨 availability: Incorrect deadline selection could let a supervisor end the Gateway during drain or cleanup; the PR's Mac captures and focused tests address that path.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Scratch macOS LaunchAgents exercised the changed Gateway stop path before and after the fix, with observed deadline selection and loaded cleanup under short stops. The final positive-deadline arithmetic is separately measured; the newer unlimited-timeout branch has focused boundary coverage rather than a live Mac capture. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Scratch macOS LaunchAgents exercised the changed Gateway stop path before and after the fix, with observed deadline selection and loaded cleanup under short stops. The final positive-deadline arithmetic is separately measured; the newer unlimited-timeout branch has focused boundary coverage rather than a live Mac capture. No stored-data contract changes.

Evidence

What I checked:

  • Current-main gap: Current main probes systemd on Linux and otherwise derives the fallback from restart ownership; it has no launchd stop reader at this path. (src/cli/gateway-cli/run-loop-shutdown-budget.ts:19, 27de2f87db28)
  • Introduced stop reader: The reader checks the loaded job's PID and stopping state, preserves unlimited ExitTimeOut, and bounds a marked launcher by its own timer. (src/infra/launchd-stop-timeout.ts:103, de0f1976220e)
  • Budget integration: The run loop refreshes its budget on macOS stops; the budget owner distinguishes a confirmed native deadline from an inconclusive inspection. (src/cli/gateway-cli/run-loop-shutdown-budget.ts:67, de0f1976220e)
  • Real behavior proof: The PR body records scratch LaunchAgent before/after stops: a 47-second job changed from a 315-second drain to about 32 seconds, and loaded 5-second stops completed cleanup under concurrent streaming work. The body identifies earlier capture trees and the later arithmetic change.
  • Accepted tradeoff: The delegated landing review accepts less cleanup reserve for custom short launchd deadlines and records the measured residual risk; the PR body also explicitly covers custom systemd deadlines. This acceptance does not waive merge gates.
  • Area history: Merged main history shows repeated Gateway shutdown-budget and restart-lifecycle work by Peter Steinberger; this is routing context, not proof that any one commit caused the Darwin gap. (src/cli/gateway-cli/run-loop-shutdown-budget.ts, 27de2f87db28)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Patrick-Erichsen: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (25 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-26T17:14:46.196Z sha 67bc549 :: blocked before merge. :: [P3] Qualify the remaining full-reserve claim
  • reviewed 2026-09-26T17:53:42.190Z sha 2f5a91c :: blocked before merge. :: none
  • reviewed 2026-09-26T18:40:34.852Z sha 3e1d4ac :: blocked before merge. :: none
  • reviewed 2026-09-26T19:46:48.502Z sha 3e1d4ac :: blocked before merge. :: none
  • reviewed September 27, 2026, 6:56 AM ET / 10:56 UTC (Revision 22) sha unknown :: blocked before merge. :: none
  • reviewed 2026-09-28T22:50:54.007Z sha a1e509e :: blocked before merge. :: none
  • reviewed 2026-09-28T23:08:20.442Z sha 0cca02d :: blocked before merge. :: none
  • reviewed 2026-09-29T00:05:08.982Z sha f04d978 :: needs maintainer review before merge. :: none

The darwin reader accepted the printed job only when its pid was this
process. The installed service can keep a launcher parent while the serving
Gateway runs as its child, so the job prints the launcher's pid, the
enforcing job was rejected, and the Gateway fell back to 20 seconds in the
one layout where an operator's ExitTimeOut was meant to apply.

Accepting that job at face value would be worse than rejecting it.
node-runtime-recovery.mjs builds the launcher's own reap timer from the
compile-time LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS rather than from the job, so
on a forwarded stop it re-sends SIGTERM to its child at 18000ms and SIGKILLs
it at 19000ms. Adopting a 90 second job deadline in that layout would plan a
75000ms drain and then lose it to its own parent, which is the truncated
drain this change exists to prevent. The reader now accepts process.pid or
process.ppid and takes min(jobExitTimeout, 20000) in the launcher case,
naming the cap in the source string only when it binds. A shorter job
deadline still applies in both layouts, because launchd reaps the whole job
regardless of the launcher.

The docs claimed the deadline is read at startup and when accepting
shutdown. run-loop.ts gates the budget refresh on linux at both consumption
sites, so on darwin it is read once, at startup, and nativeStopBudget has no
shutdown-time consumer there. The page now says startup-only and drops the
sentence about a failed shutdown reread retaining the startup budget, which
described linux behaviour only.
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Sep 24, 2026
Address the two review findings on the previous revision.

The launcher parent is now identified by an explicit
OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a bare ppid
match, so an unknown parent keeps the job's full deadline instead of
being capped on a guess.

The darwin reader inspects the launchd job only while a stop is under
way, and adopts that job's deadline only when the job reports the
SIGTERMed state. An external SIGTERM keeps the platform-neutral drain,
because launchd's ExitTimeOut bounds only a stop launchd itself is
running.

The job state is read with an anchored single-tab pattern. launchctl
print emits further "state = active" lines inside the resource and
jetsam coalition blocks, and the shared key/value parser keeps the last
occurrence, so the shared parser could never observe SIGTERMed. A test
fixture reproduces the nested coalition shape.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Sep 24, 2026
…dget

`readLaunchdStopTimeout` answered a failed job inspection with the Gateway's own
330000ms stop policy wrapped in a non-null result. `resolveGatewayShutdownBudget`
classifies every non-null result as a native stop budget, so a probe that
established nothing still set `nativeStopBudget`. On an externally supervised
darwin Gateway that caps a longer requested restart drain and can arm a forced
exit against a deadline no supervisor was confirmed to be enforcing.

The reader now reports its two answers separately. `stop` carries a deadline only
while launchd is confirmed to be stopping the job; `warning` reaches the operator
either way. A failed inspection reports `stop: null` and leaves the caller on the
platform-neutral policy it had already resolved, which is the same number as
before, now classified honestly. The reader no longer imports
GATEWAY_SERVICE_STOP_TIMEOUT_MS, because choosing the Gateway's policy number was
never its job.

Tests assert the flag and the downstream restart drain in the failure case, paired
with a confirmed-deadline case so deleting the read outright cannot pass both.

Also fixes TS2532 on the job-state regex: the named group is optional under
`noUncheckedIndexedAccess`, so `.trim()` needed the optional chain.
…* count

`spawn` is hoisted once per file, so its call log survived across cases and
`toHaveBeenCalledExactlyOnceWith` could only hold for the first one. Clear it in
`beforeEach`.

CI reports `OPENCLAW_* count 488 exceeds budget 487; update
config/env-var-count-budget.txt` as a warning. The new name is the launcher's
OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration, so the count is correct and the
ratchet moves to 488 with the reason recorded in the file.
Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line.
`pnpm run format:check` then reports "All matched files use the correct format."
…s out

Activating the darwin stop-budget refresh made `run-loop.test.ts` exercise the real
`readLaunchdStopTimeout`, which spawns three `launchctl print` calls against live
subprocess I/O while the suite holds `vi.useFakeTimers()`. One case ran 120039ms
before failing and the abandoned loop leaked into later cases, for eight failures
in total. All eight clear by mocking the reader; no existing expectation was wrong.

The mock could not simply be added. `run-loop.test.ts` is 3813 lines against a 1000
line cap where `check-line-cap-ratchet` rejects any growth, and an earlier attempt
failed with `3501 -> 3510 counted lines`. Taking the remedy that ratchet names, the
darwin cases move to `run-loop.launchd.test.ts` and the original file shrinks by 82
lines. It keeps the mock too, because four of those cases are registered into it by
shared `register*` helpers whose `it.each` arrays interleave systemd and launchd
variants and cannot be split without touching those support files.

The new file adds one case the default mock would otherwise hide: a job reporting a
30000ms deadline bounds the stop at 25000ms and arms the force exit there.

`node-runtime-recovery.test.ts` asserts the replacement child's spawn env exactly,
so it gains the launcher's own OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather
than a loosened matcher. That argv is a non-foreground `doctor --fix`, so the value
is the 1s signal exit grace plus the 1s force-kill grace.
…usive

Extending the stop-budget refresh to darwin gave the retained-budget safety net a
new and wrong trigger. On a launchd-owned Gateway the startup budget is already
native, and an in-process restart signals the process without launchd running the
stop, so the job still prints `running` and the reader reports `stop: null`. The
old condition treated any null as unconfirmed, so every in-process restart of a
default macOS install logged "Retaining the startup shutdown budget of 15000ms
because the current supervisor stop timeout could not be confirmed." The timeout
was confirmed; it was confirmed not to apply.

`readNativeStopTimeout` now reports `inconclusive` alongside the deadline, and only
an inconclusive probe retains. Linux keeps its exact previous condition, an absent
unit or a warned read. The budget number was already unaffected, so this is the
message and the wasted `launchctl print` calls, not the deadline.

Two cases pin it: a confirmed not-stopping read warns nothing, and a failed
inspection still retains and still says so.

Also fixes two wording defects found in review. `unresolved()` no longer takes a
label it only ever interpolated as "the launchd job the configured label"; each
failure already names its own target. And the `readJobState` comment said `state`
appears four times in `launchctl print` output when its own next clause counts
three, which is what a live LaunchDaemon prints.
Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line.
Whitespace only, in a test file, so it cannot change runtime behaviour.
`inconclusive` keyed off the warning alone, so the defaulted-value case counted as a
failed probe. There launchd is confirmed to be stopping the job and only its
deadline had to be guessed, so a clock is genuinely running and there is nothing to
retain. Under launchd ownership that combination logged both "using 20000ms
default" and "could not be confirmed" for the same stop, the second being false.

Now only a warning with no deadline at all counts as inconclusive. A third case
pins it, asserting the defaulted read warns exactly once and about the deadline
rather than about confirmation.

Also corrects a test fixture comment that still said `launchctl print` emits `state`
four times; the arrangement it documents, and a live LaunchDaemon, both show three.
The comment said active work "had time to finish" during the reported 315 second
drain. The reporting host's log shows the opposite: that drain hit its own timeout
with five tasks still active, and the Sep 20 stop with six. The drain was being
used, which is a stronger reason for the guard, not a weaker one.
@etzelm

etzelm commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

All four items are closed by measurement. Nothing in this branch's own files changed since Revision 8's reviewed head 6b5583b6362: git diff 6b5583b6362 HEAD -- over all fourteen changed paths is empty. The head moved only because upstream main was merged, twice.

P3, measured test cost. Single-worker Duration and wall for all six new and materially changed test files, median of three timed runs after a discarded warm-up, on a clean worktree at this head, plus the base-side figure for every changed file. Every changed file is at or below its base cost. run-loop.launchd.test.ts is 5.24 s, marginally over the 5 s target, and the body counts the split honestly rather than hiding it: its four cases sum to 582 ms of reported CI test time and the rest is a second process start.

CI seconds are reported at the only granularity CI produces. The node shards run a per-test reporter and emit no per-file duration line: across all 115 shard logs in the cited run, grep -E '\([0-9]+ tests?\)' returns 6 hits, all in core-tooling, and zero in any checks-node-compact-* shard. So the table gives per-test sums with shard and job, names the two files that did not execute, and names the cancellation cascade that stopped them.

P1 and the maintainer decision, measured under load. Seven real launchd stops, every one of them spending its full drain budget, driving concurrent streaming agent runs through the Gateway's own /v1/chat/completions surface:

ExitTimeOut 20 ExitTimeOut 5
proportional, 8 live runs cleanup 1185 ms in a 7488 ms reserve cleanup 1194 ms in a 1865 ms reserve
proportional, 32 live runs cleanup 1170 ms cleanup 1164 ms
fixed allowances, 8 live runs cleanup 1217 ms in a 10000 ms reserve drain=0, cleanup abandoned, stop-timeout bundle

Cleanup cost moved 53 ms across a 5.4x change in reserve and tens of milliseconds across a 4x change in load, because it is dominated by the fixed 1000 ms HTTP_CLOSE_GRACE_MS, which the per-step trace isolates at 1004.9 ms and 1004.1 ms. The recommended option was "retain or tune the shares from the observed result": the observed result is retain. 6.3x headroom at the installed 20 second template, 1.56x at 5 seconds, and at the short deadline the policy being replaced does not merely get tighter, it abandons cleanup and files a gateway.stop_shutdown_timeout diagnostic on a healthy stop. The honest boundary is stated too: the crossing point for the measured cleanup cost is an ExitTimeOut near 3.2 seconds.

P2 is that same evidence, including the A/B. ctrl20 and ctrl5 are the same tree, same rig and same load with one file reverted to the previous revision's fixed allowances, 6 insertions, 10 deletions, so the share policy is the only variable between a cand row and its ctrl row.

Two CI notes, both upstream owned, both evidenced in the body rather than asserted:

  • lint:no-chained-type-assertions fails on src/gateway/server-chat-progress-snapshot.ts:36:24. That file and config/oxlint/boundary-guards.json are byte identical to origin/main here. It is invisible on main because a main CI run is 37 jobs and does not include check-additional-boundaries, while a pull request run is 172 and does.
  • test/scripts/lint-suppressions.test.ts was failing in both directions this morning. Measured on a clean checkout of main itself at 47a9e77007f, it failed there too, 1 failed | 3 passed (4). Upstream fixed it in 256abd76af3; this branch merged that and the file now reports 4 passed (4) here.

One further CI note. src/gateway/server-close.model-acquisition.test.ts failed one case once, in shard agentic-control-plane-runtime-server-hosted-2. That file and src/gateway/server-close.ts are byte identical to origin/main here, and this branch contributes no file to that shard. Following the repository's flake triage order, the shard was reproduced in its own file order rather than only in isolation: decoding OPENCLAW_NODE_TEST_GROUPS_GZIP_BASE64 from the failing job gives its exact three groups, and re-running that job definition at this head with OPENCLAW_VITEST_MAX_WORKERS=2 gives Test Files 117 passed (117) for that shard and rc=0 for the job. Standalone it is 6/6 clean at this head and 6/6 clean on pristine main.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

launchctl print reports the job launchd has loaded, not the plist on disk,
so editing a loaded job's ExitTimeOut changes nothing until the job is
reloaded. Measured on macOS 27 against a scratch job: the plist moves from
20 to 47 while the loaded job keeps reporting 20, and it still reports 20
after launchctl kickstart -k, which restarts the process without reloading
the job. Only bootout then bootstrap makes it report 47, and that restarts
the Gateway with it.

State what reading per stop actually buys instead: the Gateway never plans
against a deadline it cached at its own startup.
@etzelm

etzelm commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P3 is fixed, and the correction is measured rather than reasoned.

Corrected the loaded-job timeout guidance (6cc1af4a60d). You were right: the reader takes the deadline from the job launchd has loaded, so a plist edit changes nothing on its own. Measured on macOS 27 against a scratch /bin/sleep job in gui/501, no OpenClaw code involved:

Step plist on disk loaded job reports
bootstrap at ExitTimeOut 20 20 20
rewrite the same plist to 47, no reload 47 20
launchctl kickstart -k, process restarted, job not reloaded 47 20
launchctl bootout then launchctl bootstrap, job reloaded 47 47

The doc now says the value applies only after the job is reloaded, notes that a kickstart -k is not enough, and states what reading per stop does buy: the Gateway never plans against a deadline it cached at its own startup. pnpm format:check, pnpm format:docs:check and pnpm check:docs all exit 0 at this head.

On the narrowed merge risk, "a slower plugin or service close that previously finished in the extra time could now be cut off": that is exactly right, and the body now bounds it instead of waving at it. The affected band on the 20 second template is a cleanup costing between 7500 ms and 10000 ms. Reading the close path's own constants in src/gateway/server-close.ts, no single grace reaches that band, the largest being 5000 ms; entering it takes at least two independent closers each running near their own cap. One part of cleanup is already reserve-aware rather than fixed, createServiceChildCleanupDeadline, which derives its escalation from the remaining budget, so child cleanup compresses rather than truncating. Measured whole-path cost with 32 live agent runs is 1170 ms, 6.4x below the bottom of the band.

On the maintainer decision, I am not going to claim evidence can settle it. Your reasoning is correct: accepting less cleanup time for services that already exist is an upgrade tradeoff, and a contributor's captures cannot authorize it on the lifecycle owner's behalf. What I can do is make the ask exact, and the body now does: a lifecycle owner accepting that on stop deadlines under 25 seconds the post-drain reserve shrinks, in exchange for the drain those deadlines currently do not get, with the measured basis, the affected band, and the failure mode of the current policy all stated. That item stays open on purpose until an owner answers it.

One update on the CI note from my last comment, now that the runs finished: the shard containing server-close.model-acquisition.test.ts was re-run at this head in its own file order, decoded from the failing job's OPENCLAW_NODE_TEST_GROUPS_GZIP_BASE64, and passed 2 of 2 with Test Files 117 passed (117). The same shard definition also passes on pristine upstream main. Standalone the file is 6/6 clean on both trees.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

The reserve was capped at half the shutdown budget whenever the budget could
not fund it outright. That kept a drain on short deadlines, but it also
reallocated deadlines that already worked: a 20 second ExitTimeOut, which is
both the shipped LaunchAgent template and launchd's own default, moved from a
10 second reserve and a 5 second drain to 7.5 seconds of each. Cleanup costing
between 7.5 and 10 seconds finished before and would have been cut off.

Bound the reserve by what keeping a drain actually requires instead. The floor
is 5 seconds, which is the drain the 20 second template already yields once the
fixed margin and reserve are subtracted, so funding the full reserve alongside
it takes 15 seconds of budget: exactly what that template resolves to. Every
deadline from 20 seconds up therefore keeps the allocation it had, and only a
deadline the fixed subtraction had already driven under a 5 second drain gives
any reserve up, never below half the budget.

Both allocations stay monotone in the deadline, and the 5 second case is
unchanged at 1875ms of each.
- gateway-shutdown-budget.mjs: replace the floor-invariant claim with the
  real bound (reserve unchanged only at a >=15000ms post-margin budget,
  i.e. a >=20s deadline once the launchd probe's own cost, up to three
  launchctl print calls at 2000ms each, is subtracted); name the 8-20s
  sub-band reserve loss the old comment denied, including 16-19s where a
  flat subtraction already left a positive drain while still funding the
  reserve in full
- docs/gateway/restart-recovery.md: drop the systemd section's "down to
  the millisecond" promise and the launchd section's "exact allocation
  ... before this change" claim; both now state the inspection cost that
  comes off instead
- run-loop-shutdown-budget.test.ts: add a real 13ms elapsed-debit case at
  a 20s exit timeout (asserts reserve=9987, drain=5000, contrasting with
  the existing acceptedAtMs=MAX_SAFE_INTEGER zero-debit fixtures) and
  mirror darwin's 19/16/15/10s sub-20s it.each against a systemd stub,
  which previously had no sub-20s coverage
The sub-20-second systemd cases added in 60e5eb5 left the flat-subtraction
comparison on a single line past the formatter's width, which failed oxfmt --check
and took check-lint and check-docs down with it. Lint itself reported zero warnings
and zero errors. Formatting only, no assertion or value changed.
… debit

The previous wording paired 'gives up exactly what the probe cost' with a probe
bounded near 6 seconds, and those two cannot both hold. Which allowance pays the
debit turns on a 5 second threshold: at or under it the reserve absorbs the whole
cost and the 5 second drain floor is untouched, so a 20 second deadline resolves
10000 minus the debit. Past it the floor is share-bounded as well and the two
converge on half the remainder, so a 6 second debit splits 9000 into 4500/4500
rather than retaining the old reserve. Documents the threshold in the docs and the
root-module comment, and pins the over-threshold case with a test so the boundary
is measured rather than reasoned.
The drain-floor comment asserted that a whole 10 second reserve follows
for every ExitTimeOut of 20 seconds or more once the probe that reads the
deadline is subtracted. The probe cost is charged before the budget is
split, so a 20 second ExitTimeOut clears the 15 second budget that a whole
reserve needs only when that probe costs nothing. At the 13ms measured on
this rig the reserve is 9987, and a whole reserve at that cost needs 20013.

The same comment already states this correctly six lines down, where it
resolves a 20 second deadline to 10000 - cost. This removes the
contradiction by qualifying the claim at its first statement instead of
restating the arithmetic twice.

Comment-only: no non-comment line changes and the export list is unchanged.
roboclaw-bot and others added 4 commits September 28, 2026 22:37
Preserve the observed launcher cap only for launchd-driven stops, and shorten redundant budget documentation without changing the measured split.

Co-authored-by: Patrick-Erichsen <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

RoboClaw review for the delegated repair-and-land request, at 0cca02df4cfdd1f8b325899e5871fa3a04993c90:

  • A stop budget is the time available before the supervisor may force-kill the Gateway. Drain is the first slice used to finish admitted work; cleanup reserve and exit margin follow. The loaded launchd job, not restart ownership or a plist on disk, decides a launchd-driven stop.
  • I kept the existing positive-deadline behavior and simplified the patch by 180+ net lines, chiefly repetitive operator prose and code commentary. The remaining size is mostly lifecycle tests and their isolated run-loop fixture. I corrected a real edge case: ExitTimeOut=0 is unlimited, not an invalid value that should force a 20-second fallback. A directly signaled launcher versus child remains indistinguishable from Node's signal handler; the PR preserves the direct-child drain and names that pre-existing limitation rather than imposing an unproven cap.
  • Under this delegated repair scope I accept the measured allocation for custom deadlines below 20 seconds: more active-work drain in exchange for a smaller cleanup reserve. The 20-second installed LaunchAgent and default 90-second systemd unit keep their nominal split. The residual risk is a slow plugin/service close on a custom short job; the contributor's loaded-run measurements show about 1.2 seconds of cleanup under up to 32 active runs, not a guarantee on every host.
  • An isolated, no-instance-role Linux run at the pre-format head passed the three affected files (91 tests). The earlier real Mac launchd stop captures support the positive-deadline behavior; the new zero-timeout case has focused boundary coverage, not a live Mac stop. The formatter-only head change is published; current-head CI and the guarded landing path remain required. The previous CI attempt identified and prompted that formatter correction, plus unrelated tooling-shard failures now being attributed. No merge is claimed here.

@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen Patrick-Erichsen self-assigned this Sep 28, 2026
@Patrick-Erichsen

Patrick-Erichsen commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Landing review and proof at signed head de0f197:

The root cause is that restart ownership and native stop deadlines are independent. Current main and stable v2026.9.6 inspect systemd but omit the enclosing launchd job. The canonical shutdown owner now discovers that deadline without conflating it with installation ownership. Direct SIGTERM does not invent a launchd deadline, zero stays unlimited, and the launcher consumes the same shared budget.

Best-fix verdict: the native deadline belongs here, not in a transport/restart wrapper. Existing generic launchctl parsing loses top-level state to nested coalition state; the installation runtime also brings unrelated ownership and port probing. Apple launchd.plist's ExitTimeOut contract was checked directly, including zero=infinite.

Reviewed contributor real scratch-Gateway before/after captures:

Scenario Before After
External 47-second launchd stop 325-second shutdown / 315-second drain About 41.98-second shutdown / 31.98-second drain
Custom 5-second stop Zero shutdown allowance About 3.73 seconds, including 1.86 seconds cleanup reserve
8/32 concurrent streaming requests Existing capture baseline Cleanup about 1.16-1.22 seconds

ClawSweeper Revision 26 reviewed the exact de0 head on September 29 at 00:19 UTC with no remaining findings or before-merge actions. As part of the requested landing, I accept the documented smaller cleanup reserve for custom launchd deadlines below 20 seconds. No new configuration is introduced. The normal 20-second policy keeps more cleanup reserve than the earlier half-reserve variant.

Local runtime verification passed 8 files across 3 routed shards in 183 seconds, including 269 CLI cases, real OS-signal subprocess behavior, Linux/systemd siblings, unmanaged/direct signals, queued startup stops, zero/unknown job deadlines, launcher markers and cleanup. The fresh full-Gateway scratch LaunchAgent attempt did not reach readiness within 20 seconds; its labels/processes were removed. This is not claimed as a fresh full-Gateway live pass.

The mainline refresh exposed a small CI import-closure defect introduced by ac59199 (Peter Steinberger; introducing PR unknown): the Docker scenario planner imports provider catalog and record-shared, but frozen verification and copied fixtures omitted them. Main independently landed the closure repair in ae1d3da. The latest signed merge of main2a778ef887d2 preserves that fix and newer candidate-provider hydration682ffe55; its only conflict retained both the byte-integrity check and executable-before-verification tamper sentinel. Remaining CI delta removes the redundant child-only requirement/copy and asserts shared evidence. Nine focused integrity/evidence/planner cases, format, lint and diff checks pass. Two tamper regressions failed before the original repair and pass after; package-source preflight reproduced the missing-module failure before and passed after. No launchd runtime logic changed in either refresh.

Local broad tooling is not all green: the wide run had 996 pass / 2 fail / 2 skip. Its stale isolation assertion was repaired and passes; the other case passes unchanged in its original file order. That file rerun had 120 pass / 3 other cases hitting unchanged 30-second deadlines / 2 skip. Host load 35/36/43 makes contention plausible, not proven. No timeout or assertion weakening; exact-head hosted CI is required before merge.

Fresh runtime and CI-repair autoreviews are scoped-clean at their default P0 threshold; direct owner/caller/callee/sibling review also completed. Current-main delta excludes its independently landed repair: production/declarations+362/-38 (net+324); tests/support+1588/-101; docs+77/-5. The native-job reader and shared parent/child deadline contract justify growth; the remaining CI cleanup removes 5 production lines. No dependency, storage, configuration or protocol surface added.

Provenance: raw-parent inspection of cd3c9b9 / #151142 (steipete author and merger, September 17) shows the Linux repair carried the preexisting Darwin gap forward, not that it introduced it. Signed candidate preserves contributor ancestry; launchd runtime bytes are unchanged from the previously reviewed/tested candidate. GitHub now reports the conflict resolved; exact-head CI remains required.

CI diagnosis: run 36501803818, compact-large-37, hit a native Bun 1.4.3-canary.1 /6b9148b17 SIGSEGV/139 before named results from its fast cohort. The same bundle's Node core-unit-fast, spawn, reply and security cohorts passed. The Bun binary pin and relevant runner/config/bootstrap files match the actual CI base; this is not a failed launchd assertion. The native root cause is unproven. The run still has active jobs, which are not being cancelled. After terminal completion, one supported failed-job diagnostic retry may establish whether this ordered bundle reproduces; no timeout, assertion or dependency changes are being made to hide it. Exact-head CI remains mandatory.

All remaining jobs completed successfully. After the run became terminal with only compact-large-37 and its aggregate gate failing, one failed-job diagnostic retry was requested at unchanged de0f197. It preserves the original ordered bundle. A pass establishes non-reproduction, not a repair or known root cause for the native crash.

Result: attempt 2 completed successfully at unchanged de0f197. The original ordered bundle and exact-head aggregate gate are green. The native crash did not reproduce; no native-crash fix is claimed.

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Sep 28, 2026
# Conflicts:
#	test/scripts/preflight-frozen-target-contracts.test.ts
@Patrick-Erichsen
Patrick-Erichsen merged commit 6eeb120 into openclaw:main Sep 29, 2026
362 of 364 checks passed
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…nclaw#157007)

* fix(gateway): derive the darwin stop budget from the launchd job

resolveGatewayShutdownBudget derives the stop deadline from restart
ownership, so a darwin host running with OPENCLAW_SUPERVISOR_MODE=external
resolves drain=315000ms whatever launchd actually enforces.

The linux-gated systemd probe becomes a platform dispatch, and a new
readLaunchdStopTimeout mirrors readSystemdStopTimeout: it reads the running
job's effective exit timeout and accepts it only when the printed pid is
this process. run-loop.ts is untouched because the reader detects launchd
from the environment itself.

Closes openclaw#156968

* fix(gateway): accept the launchd launcher parent and cap its deadline

The darwin reader accepted the printed job only when its pid was this
process. The installed service can keep a launcher parent while the serving
Gateway runs as its child, so the job prints the launcher's pid, the
enforcing job was rejected, and the Gateway fell back to 20 seconds in the
one layout where an operator's ExitTimeOut was meant to apply.

Accepting that job at face value would be worse than rejecting it.
node-runtime-recovery.mjs builds the launcher's own reap timer from the
compile-time LAUNCH_AGENT_EXIT_TIMEOUT_SECONDS rather than from the job, so
on a forwarded stop it re-sends SIGTERM to its child at 18000ms and SIGKILLs
it at 19000ms. Adopting a 90 second job deadline in that layout would plan a
75000ms drain and then lose it to its own parent, which is the truncated
drain this change exists to prevent. The reader now accepts process.pid or
process.ppid and takes min(jobExitTimeout, 20000) in the launcher case,
naming the cap in the source string only when it binds. A shorter job
deadline still applies in both layouts, because launchd reaps the whole job
regardless of the launcher.

The docs claimed the deadline is read at startup and when accepting
shutdown. run-loop.ts gates the budget refresh on linux at both consumption
sites, so on darwin it is read once, at startup, and nativeStopBudget has no
shutdown-time consumer there. The page now says startup-only and drops the
sentence about a failed shutdown reread retaining the startup budget, which
described linux behaviour only.

* fix(gateway): scope the darwin stop budget to launchd-driven stops

Address the two review findings on the previous revision.

The launcher parent is now identified by an explicit
OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather than a bare ppid
match, so an unknown parent keeps the job's full deadline instead of
being capped on a guess.

The darwin reader inspects the launchd job only while a stop is under
way, and adopts that job's deadline only when the job reports the
SIGTERMed state. An external SIGTERM keeps the platform-neutral drain,
because launchd's ExitTimeOut bounds only a stop launchd itself is
running.

The job state is read with an anchored single-tab pattern. launchctl
print emits further "state = active" lines inside the resource and
jetsam coalition blocks, and the shared key/value parser keeps the last
occurrence, so the shared parser could never observe SIGTERMed. A test
fixture reproduces the nested coalition shape.

* fix(gateway): keep a failed launchd inspection off the native stop budget

`readLaunchdStopTimeout` answered a failed job inspection with the Gateway's own
330000ms stop policy wrapped in a non-null result. `resolveGatewayShutdownBudget`
classifies every non-null result as a native stop budget, so a probe that
established nothing still set `nativeStopBudget`. On an externally supervised
darwin Gateway that caps a longer requested restart drain and can arm a forced
exit against a deadline no supervisor was confirmed to be enforcing.

The reader now reports its two answers separately. `stop` carries a deadline only
while launchd is confirmed to be stopping the job; `warning` reaches the operator
either way. A failed inspection reports `stop: null` and leaves the caller on the
platform-neutral policy it had already resolved, which is the same number as
before, now classified honestly. The reader no longer imports
GATEWAY_SERVICE_STOP_TIMEOUT_MS, because choosing the Gateway's policy number was
never its job.

Tests assert the flag and the downstream restart drain in the failure case, paired
with a confirmed-deadline case so deleting the read outright cannot pass both.

Also fixes TS2532 on the job-state regex: the named group is optional under
`noUncheckedIndexedAccess`, so `.trim()` needed the optional chain.

* test(infra): isolate the hoisted spawn mock and ratchet the OPENCLAW_* count

`spawn` is hoisted once per file, so its call log survived across cases and
`toHaveBeenCalledExactlyOnceWith` could only hold for the first one. Clear it in
`beforeEach`.

CI reports `OPENCLAW_* count 488 exceeds budget 487; update
config/env-var-count-budget.txt` as a warning. The new name is the launcher's
OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration, so the count is correct and the
ratchet moves to 488 with the reason recorded in the file.

* style(infra): apply oxfmt to the new launchd reader assertions

Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line.
`pnpm run format:check` then reports "All matched files use the correct format."

* test(cli): mock the launchd reader and split the darwin run-loop cases out

Activating the darwin stop-budget refresh made `run-loop.test.ts` exercise the real
`readLaunchdStopTimeout`, which spawns three `launchctl print` calls against live
subprocess I/O while the suite holds `vi.useFakeTimers()`. One case ran 120039ms
before failing and the abandoned loop leaked into later cases, for eight failures
in total. All eight clear by mocking the reader; no existing expectation was wrong.

The mock could not simply be added. `run-loop.test.ts` is 3813 lines against a 1000
line cap where `check-line-cap-ratchet` rejects any growth, and an earlier attempt
failed with `3501 -> 3510 counted lines`. Taking the remedy that ratchet names, the
darwin cases move to `run-loop.launchd.test.ts` and the original file shrinks by 82
lines. It keeps the mock too, because four of those cases are registered into it by
shared `register*` helpers whose `it.each` arrays interleave systemd and launchd
variants and cannot be split without touching those support files.

The new file adds one case the default mock would otherwise hide: a job reporting a
30000ms deadline bounds the stop at 25000ms and arms the force exit there.

`node-runtime-recovery.test.ts` asserts the replacement child's spawn env exactly,
so it gains the launcher's own OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS declaration rather
than a loosened matcher. That argv is a non-foreground `doctor --fix`, so the value
is the 1s signal exit grace plus the 1s force-kill grace.

* fix(gateway): only retain a startup budget when the probe was inconclusive

Extending the stop-budget refresh to darwin gave the retained-budget safety net a
new and wrong trigger. On a launchd-owned Gateway the startup budget is already
native, and an in-process restart signals the process without launchd running the
stop, so the job still prints `running` and the reader reports `stop: null`. The
old condition treated any null as unconfirmed, so every in-process restart of a
default macOS install logged "Retaining the startup shutdown budget of 15000ms
because the current supervisor stop timeout could not be confirmed." The timeout
was confirmed; it was confirmed not to apply.

`readNativeStopTimeout` now reports `inconclusive` alongside the deadline, and only
an inconclusive probe retains. Linux keeps its exact previous condition, an absent
unit or a warned read. The budget number was already unaffected, so this is the
message and the wasted `launchctl print` calls, not the deadline.

Two cases pin it: a confirmed not-stopping read warns nothing, and a failed
inspection still retains and still says so.

Also fixes two wording defects found in review. `unresolved()` no longer takes a
label it only ever interpolated as "the launchd job the configured label"; each
failure already names its own target. And the `readJobState` comment said `state`
appears four times in `launchctl print` output when its own next clause counts
three, which is what a live LaunchDaemon prints.

* style(cli): apply oxfmt to the new retained-budget assertions

Run by the repo's own `pnpm run format`; joins one over-wrapped assertion line.
Whitespace only, in a test file, so it cannot change runtime behaviour.

* fix(gateway): a defaulted deadline is not an inconclusive probe

`inconclusive` keyed off the warning alone, so the defaulted-value case counted as a
failed probe. There launchd is confirmed to be stopping the job and only its
deadline had to be guessed, so a clock is genuinely running and there is nothing to
retain. Under launchd ownership that combination logged both "using 20000ms
default" and "could not be confirmed" for the same stop, the second being false.

Now only a warning with no deadline at all counts as inconclusive. A third case
pins it, asserting the defaulted read warns exactly once and about the deadline
rather than about confirmation.

Also corrects a test fixture comment that still said `launchctl print` emits `state`
four times; the arrangement it documents, and a live LaunchDaemon, both show three.

* test(cli): correct the regression guard's account of the reported drain

The comment said active work "had time to finish" during the reported 315 second
drain. The reporting host's log shows the opposite: that drain hit its own timeout
with five tasks still active, and the Sep 20 stop with six. The drain was being
used, which is a stronger reason for the guard, not a weaker one.

* fix(infra): stop exporting a type nothing outside the module reads

Knip's all-exports gate reads LaunchdStopTimeout as dead: the only
public surface is readLaunchdStopTimeout's LaunchdStopRead return, and
nothing imports the nested shape by name. Keep it module-local.

* fix(gateway): keep a proportional drain and cap an undeclared launcher

The fixed 10s reserve and 5s exit margin were sized against the 315s policy
drain. Subtracting them outright from a launchd job's own ExitTimeOut spent a
short deadline entirely on overhead: 5 seconds funded the margin alone and 15
funded margin plus reserve, so active work drained for zero milliseconds in
both. Each allowance now takes at most a share of what it is carved from, so a
deadline long enough to fund them is unchanged and a shorter one keeps a
proportional drain. Drain is now positive for every positive deadline and never
decreases as ExitTimeOut grows.

The shutdown log also subtracted the unscaled reserve constant when reporting
drain, which understated a short budget by the amount the scaled reserve gives
back, so it now reports the margin and drain actually spent.

An already-running launcher published before OPENCLAW_LAUNCHER_STOP_TIMEOUT_MS
existed arms the same reap timer and declares nothing, which is the upgrade
shape: replacing files cannot change a launcher that is already running. Reading
that silence as "no deadline" let a long custom ExitTimeOut be budgeted past a
force-kill the parent was already counting down. The launcher's arithmetic moves
into the shared budget module so the serving Gateway reconstructs the same timer,
used only where the printed job carries OpenClaw's own label and its pid is this
process's immediate parent. In that position the parent is the process launchd
started for OpenClaw's job and the recovery launcher is the only path that puts a
Gateway underneath it, so an unrelated process manager holding the parent slot
still caps nothing.

* fix(infra): gate the launcher reconstruction on the recovery respawn marker

Holding the launchd job's pid is not evidence of a reap timer. An operator
wrapper can keep that pid and start the Gateway itself while running none, so
reconstructing a cap from the parent relation alone would cut a drain nothing was
going to interrupt. The recovery launcher has stamped OPENCLAW_NODE_UPDATE_RESPAWNED
on every child it respawns since long before it declared a stop timer, so that
marker is present in exactly the upgrade case and absent for any other parent.

* fix(infra): declare the new shared budget helpers for the type checker

The root module is typed by a hand-written declaration file rather than being
compiled, so new exports are invisible to src without being declared there.

* docs(gateway): scope the positive-drain claim to the allocation

The elapsed cost of resolving the budget is debited after the allocation, so a
deadline shorter than that cost can still leave nothing to spend. Claiming every
positive deadline yields a positive drain overstated it.

* test(cli): accept the retained-budget attribution on a synthetic launchd label

The fixture declares a launchd label with no matching job, so the per-stop
re-inspection cannot read one and the startup budget is retained. The deadline is
unchanged at 15000ms; only the source attribution differs. The assertion still
fails if the budget comes from the platform-neutral policy instead.

* fix(gateway): derive the launcher's reap deadline instead of declaring it

Measurement showed the declared value and the derived value are the same number:
a published launcher and a candidate launcher both arm an 18000ms exit grace, and
a candidate Gateway resolved an identical 19000ms cap and 14231ms budget under
each. The declaration was therefore carrying no information the child could not
compute, while adding an OPENCLAW_* name and leaving the upgrade path conditional
on which build of the launcher happened to be running.

Both sides now read one expression in gateway-shutdown-budget.mjs, the launcher to
arm its escalation and the Gateway to bound its budget, so they cannot disagree and
there is no published-versus-candidate launcher distinction left to prove. The cap
stays gated on OPENCLAW_NODE_UPDATE_RESPAWNED so a parent that did not respawn this
process still caps nothing.

Drops the env-var count back to 486, so the name ratchet no longer needs an owner
waiver, and takes config/env-var-count-budget.txt out of the diff entirely.

Test deadlines move off 90 seconds onto 55, because launchd clamps ExitTimeOut at
60 and a 90-second case cannot occur on macOS 27.

* test(infra): restore the recovery spawn-env cases to their base form

The launcher no longer declares a deadline, so the assertions these cases grew have
nothing left to check and their explanatory comment described behavior that is gone.

* fix(gateway): cap every respawning launcher, not just the Node-recovery one

All three runRespawnedChild call sites reach the same launcher through the same
function and arm the same escalation, but only the Node-recovery one sets
OPENCLAW_NODE_UPDATE_RESPAWNED. Gating on that marker alone left the two
compile-cache respawns uncapped, and the packaged one can wrap a foreground
gateway run on an installed service: the job's deadline would then be budgeted past
a force-kill the parent had already armed, which is the hazard this cap exists to
prevent.

The marker set moves next to the deadline it authorises, so adding a respawn path
cannot silently escape the cap. Keeping the literals in the root module also keeps
them out of the env-count ratchet's scope: reading the marker from counted
production source promoted a previously test-only name and held the count at 487
even after the declared-timer variable was removed.

Also applies oxfmt's own wrap to the launcher-relation expression.

* fix(infra): re-export the respawn marker set through the infra barrel

The constant existed only on the root module, so the test importing it from the
barrel got undefined and it.each(undefined) threw during collection: the suite
reported zero tests rather than a failure, and typecheck flagged the missing member.
Re-exporting the binding adds no OPENCLAW_* literal under src, so the env-var count
stays at 486.

* fix(gateway): address the pre-review findings on the launchd stop budget

Docs were stale or wrong in four places. The systemd section still promised a fixed
10 second reserve and 5 second margin, but the share caps are platform-neutral and
do change a Linux unit whose TimeoutStopSec is under 25 seconds; that radius is now
stated with the 20 second and 15 second cases spelled out. The direct-SIGTERM
paragraph claimed the platform-neutral drain "is the deadline that actually governs
that stop", which the branch's own kill -TERM capture contradicts: no supervisor
deadline governs that stop at all and the fallback is the template value. The
updated-launcher requirement no longer applies to the stop budget and says so. The
marker sentence named one marker when three are honoured, and one measured figure
was stale.

Two claims in the code were too strong. The marker list asserted every setter arms
the shared escalation, which is false for the compile-cache name: entry.compile-cache
sets it for a runner that reaps on a fixed short grace. That runner refuses a
foreground Gateway run off Windows and this deadline is only read during a darwin
stop, so it cannot be the parent here, and the comment now says that instead of
implying exclusivity. The sync note next to the escalation now records that the other
runner keeps its own copies of the graces.

An absent job state was indistinguishable from a job launchd is not stopping, so a
macOS that printed the block differently would silently revert to the platform-neutral
policy. When a deadline parsed but the state did not, that now warns and marks the read
inconclusive rather than passing as a positive answer.

Tests: launchd cases move off 90 and 315 second deadlines, which launchd clamps to 60
and cannot produce; the marker list is restated locally and tied back to the
implementation so dropping a marker fails; and the real-process case now asserts the
darwin probe actually ran, which it could not before.

Retires five exports with no production consumer that the dead-export scan flagged.

* test(infra): move the empty job state onto the missing-state warning

An empty value yields no state to recognise, so it reaches the same branch as a
missing line and now carries the same warning. Keeping it in the unrecognised-state
table asserted the absence of a field the reader deliberately reports.

* fix(infra): treat a whitespace-only job state as missing, and sharpen two docs claims

The state value is trimmed after matching, so a line carrying only whitespace yielded
an empty string rather than undefined and skipped the warning while behaving exactly
like a missing line.

The systemd section now says the exit margin shrinks below a 20-second deadline, not
just the reserve. The direct-signal paragraph distinguished only the launchd-supervised
budget; external supervisor mode keeps the platform-neutral policy and arms no
force-exit timer, and a signal delivered to the job pid does reach a resident recovery
launcher, which arms its own reap timer even though launchd is not stopping the job.

* docs(gateway): correct the loaded launchd job deadline guidance

launchctl print reports the job launchd has loaded, not the plist on disk,
so editing a loaded job's ExitTimeOut changes nothing until the job is
reloaded. Measured on macOS 27 against a scratch job: the plist moves from
20 to 47 while the loaded job keeps reporting 20, and it still reports 20
after launchctl kickstart -k, which restarts the process without reloading
the job. Only bootout then bootstrap makes it report 47, and that restarts
the Gateway with it.

State what reading per stop actually buys instead: the Gateway never plans
against a deadline it cached at its own startup.

* fix(gateway): keep the full cleanup reserve wherever a deadline funds it

The reserve was capped at half the shutdown budget whenever the budget could
not fund it outright. That kept a drain on short deadlines, but it also
reallocated deadlines that already worked: a 20 second ExitTimeOut, which is
both the shipped LaunchAgent template and launchd's own default, moved from a
10 second reserve and a 5 second drain to 7.5 seconds of each. Cleanup costing
between 7.5 and 10 seconds finished before and would have been cut off.

Bound the reserve by what keeping a drain actually requires instead. The floor
is 5 seconds, which is the drain the 20 second template already yields once the
fixed margin and reserve are subtracted, so funding the full reserve alongside
it takes 15 seconds of budget: exactly what that template resolves to. Every
deadline from 20 seconds up therefore keeps the allocation it had, and only a
deadline the fixed subtraction had already driven under a 5 second drain gives
any reserve up, never below half the budget.

Both allocations stay monotone in the deadline, and the 5 second case is
unchanged at 1875ms of each.

* fix(gateway): correct shutdown-budget probe-debit overclaims

- gateway-shutdown-budget.mjs: replace the floor-invariant claim with the
  real bound (reserve unchanged only at a >=15000ms post-margin budget,
  i.e. a >=20s deadline once the launchd probe's own cost, up to three
  launchctl print calls at 2000ms each, is subtracted); name the 8-20s
  sub-band reserve loss the old comment denied, including 16-19s where a
  flat subtraction already left a positive drain while still funding the
  reserve in full
- docs/gateway/restart-recovery.md: drop the systemd section's "down to
  the millisecond" promise and the launchd section's "exact allocation
  ... before this change" claim; both now state the inspection cost that
  comes off instead
- run-loop-shutdown-budget.test.ts: add a real 13ms elapsed-debit case at
  a 20s exit timeout (asserts reserve=9987, drain=5000, contrasting with
  the existing acceptedAtMs=MAX_SAFE_INTEGER zero-debit fixtures) and
  mirror darwin's 19/16/15/10s sub-20s it.each against a systemd stub,
  which previously had no sub-20s coverage

* test(cli): wrap the flat-subtraction assertion to satisfy oxfmt

The sub-20-second systemd cases added in 60e5eb5 left the flat-subtraction
comparison on a single line past the formatter's width, which failed oxfmt --check
and took check-lint and check-docs down with it. Lint itself reported zero warnings
and zero errors. Formatting only, no assertion or value changed.

* docs(gateway): bound the 20-second allocation claim by the inspection debit

The previous wording paired 'gives up exactly what the probe cost' with a probe
bounded near 6 seconds, and those two cannot both hold. Which allowance pays the
debit turns on a 5 second threshold: at or under it the reserve absorbs the whole
cost and the 5 second drain floor is untouched, so a 20 second deadline resolves
10000 minus the debit. Past it the floor is share-bounded as well and the two
converge on half the remainder, so a 6 second debit splits 9000 into 4500/4500
rather than retaining the old reserve. Documents the threshold in the docs and the
root-module comment, and pins the over-threshold case with a test so the boundary
is measured rather than reasoned.

* docs(gateway): qualify the full-reserve claim by the probe debit

The drain-floor comment asserted that a whole 10 second reserve follows
for every ExitTimeOut of 20 seconds or more once the probe that reads the
deadline is subtracted. The probe cost is charged before the budget is
split, so a 20 second ExitTimeOut clears the 15 second budget that a whole
reserve needs only when that probe costs nothing. At the 13ms measured on
this rig the reserve is 9987, and a whole reserve at that cost needs 20013.

The same comment already states this correctly six lines down, where it
resolves a 20 second deadline to 10000 - cost. This removes the
contradiction by qualifying the claim at its first statement instead of
restating the arithmetic twice.

Comment-only: no non-comment line changes and the export list is unchanged.

* fix(gateway): honor unlimited launchd stops

Preserve the observed launcher cap only for launchd-driven stops, and shorten redundant budget documentation without changing the measured split.

Co-authored-by: Patrick-Erichsen <[email protected]>

* test(gateway): use action-based drain budget

Co-authored-by: Patrick-Erichsen <[email protected]>

* style(gateway): format launchd timeout assertions

Co-authored-by: Patrick-Erichsen <[email protected]>

* fix(ci): complete frozen Docker planner import closures

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Patrick-Erichsen <[email protected]>
Co-authored-by: Patrick Erichsen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. scripts Repository scripts size: XL 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.

[Bug]: darwin shutdown budget resolves from restart ownership, so OPENCLAW_SUPERVISOR_MODE=external ignores the launchd exit timeout

3 participants