Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): supervisor/worker stop drains under a signal owner; stop fails closed (#5062)

time-attack71185a4d7ac5
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index 1d8877dfb9..f3f8ddf076 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/child-job-runner.ts` — parent-side runner: `runJobInChild(opts)` spawns the child (detached + tini when available, stdio inherit for handler logs, per-job lifecycle log lines), maps per-job abort → group SIGTERM now + group SIGKILL at +25s (`CHILD_KILL_GRACE_MS`, inside the 30s force-evict backstop), gives worker-shutdown children the drain window to finish AND report (a non-reporting shutdown kill throws `ChildWorkerShutdownError` with separate `executionStopped` evidence; group cleanup retains its kill backstop after direct-child exit, and unconfirmed cleanup must not authorize configuration release). `onExecutionStopped` publishes confirmed no-execution failures or supported Linux owned-group/observed-descendant stop evidence once, including normal exits; a handler outcome alone is not that proof. After direct-child exit, termination settles as soon as supported Linux cleanup proof confirms the owned groups gone (bounded backoff poll); without proof the group is SIGKILLed immediately and the stop stays unconfirmed; surviving members still receive the grace SIGKILL. The runner classifies missing/non-executable child paths as `LocalConfigurationError` and other pre-exec spawn failures as `ChildSpawnInfraError` (no attempt burned), and bounds child pools via env (`GBRAIN_POOL_SIZE` default 3, `GBRAIN_DIRECT_POOL_SIZE=1`). A spend-authorized row (`opts.spendAuthorized`) is never handed to a child that did not advertise `spend-enforcement-v1` at readiness: `SpendEnforcementUnavailableError` releases it through the lease path for an upgraded worker. Pinned by `test/child-job-runner.test.ts` (real children) + `test/worker-job-isolation.test.ts` (full parent path on PGLite).
-- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure spawn-loop class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. `WORKER_EXIT_CONFIGURATION` and the generation-scoped `OwnerProcessingState` channel block spawning before generic crash accounting; `configurationBlocked` also prevents intentional watchdog/wedge restarts. The owner remains alive with additive readiness diagnostics until explicit restart after repair. Startup stages and retry deadlines remain visible, and missing readiness is bounded by the startup timeout and forced-stop backstop before ordinary crash-budget handling. The shared `processing-state.ts` validates bounded/redacted identities, correlates worker updates to the active runtime token, and does not turn a missing status file into readiness. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). Opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so a `!this._child.killed` guard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op. `restartCurrentChild(graceMs)` (wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the `run()` loop does not fire `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` carries `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases).
+- `src/core/minions/child-worker-supervisor.ts` — shared spawn-and-respawn core reused by both `MinionSupervisor` (standalone `gbrain jobs supervisor` daemon) and `src/commands/autopilot.ts` (autopilot daemon), so the two consumers can't drift into parallel-loop bugs. Pure spawn-loop class: NO PID file, NO signal handlers, NO `process.exit`, NO health check. `WORKER_EXIT_CONFIGURATION` and the generation-scoped `OwnerProcessingState` channel block spawning before generic crash accounting; `configurationBlocked` also prevents intentional watchdog/wedge restarts. The owner remains alive with additive readiness diagnostics until explicit restart after repair. Startup stages and retry deadlines remain visible, and missing readiness is bounded by the startup timeout and forced-stop backstop before ordinary crash-budget handling. The shared `processing-state.ts` validates bounded/redacted identities, correlates worker updates to the active runtime token, and does not turn a missing status file into readiness. Lifecycle events fire via injected `onEvent: (ChildSupervisorEvent) => void`. Exit classifier: `code === 0` leaves `crashCount` UNCHANGED (preserves flap detection across mixed exit sequences); `code != 0` follows `runDuration > stableRunResetMs ? 1 : ++crashCount`. Clean-restart budget: sliding window of code=0 exits; when count exceeds `cleanRestartBudget` (default 10) inside `cleanRestartWindowMs` (default 60s), emits `health_warn { reason: 'clean_restart_budget_exceeded' }` and applies `cleanRestartBudgetBackoffMs` (default 1s). The exit classifier special-cases `WORKER_EXIT_RSS_WATCHDOG` — `likely_cause='rss_watchdog'`, and that exit does NOT bump `crashCount` (routes to its own breaker); a dedicated `_watchdogExitTimestamps` sliding window trips a loud `rss_watchdog_loop` health_warn naming the cap when N watchdog exits land inside the window, INDEPENDENT of the stable-run reset (which would otherwise hide a >5-min-run watchdog drain loop). Opts `watchdogLoopBudget` (3), `watchdogLoopWindowMs` (600000), `watchdogBackoffMs` (30000); `ChildSupervisorEvent` extended. Public read-only accessors `childAlive`, `inBackoff`, `crashCount`; `killChild(signal)` gates on liveness (`exitCode === null && signalCode === null`), NOT `.killed` — `.killed` flips true once a signal is *sent*, so a `!this._child.killed` guard would make a follow-up SIGKILL after an ignored SIGTERM a silent no-op. `restartCurrentChild(graceMs)` (wedge self-heal) captures the CURRENT child ref, SIGTERM→grace→SIGKILLs THAT ref (never the respawn — closes the timer-kills-fresh-worker race), and flags `_intentionalRestart` so the exit is `likelyCause='wedge_restart'`, leaves `crashCount` UNTOUCHED (never trips `max_crashes`; like `rss_watchdog`), and respawns immediately (`backoff ms:0 reason='wedge_restart'`). `awaitChildExit(timeoutMs)` short-circuits when `child.exitCode !== null || child.signalCode !== null` so fast-SIGTERM responders don't cause a 35s shutdown hang. Degraded-retry: the `run()` loop does not fire `onMaxCrashesExceeded` at the soft `maxCrashes`; it announces `health_warn { reason: 'crash_budget_degraded' }` once per episode and keeps respawning with capped backoff (the 60s cap makes it a paced retry, not a hot loop), re-arming after a stable-run reset drops the count. Permanent give-up fires only at `hardStopMaxCrashes` (default `maxCrashes × HARD_STOP_CRASH_MULTIPLIER` = 10×; `0` disables). Test hooks `_backoffFloorMs`, `_now`. `supervisor-audit.ts` carries `rss_watchdog` as a non-clean cause + its own `CrashSummary.by_cause` bucket, and `wedge_restart` to `CLEAN_EXIT_CAUSES` (a self-heal, not a crash; denylist preserved so future causes route to `legacy`). Pinned by `test/child-worker-supervisor.test.ts` (12 cases). #5062: `lastExit` records how the most recent child exited, including on the shutdown path, so the composer can tell a clean drain from a forced stop.
- `src/core/minions/db-probe.ts` — hermetic DB-liveness probe with pool-starvation disambiguation: `runDbProbe(deps)` probes the read pool (signal-cancelled at `timeoutMs`), on failure probes the DIRECT lane (`DIRECT_PROBE_TIMEOUT_MS`, only when dual-pool is genuinely active) and returns a verdict — `pool_starved` ("server IS reachable; fault is in the transaction-pooler path — client pool exhaustion or a pooler-layer fault", deliberately an honest disjunction), `server_unreachable`, `unknown`, or typed `client_misconfigured`. `runDbReadinessProbe` checks every required lane even after read success; a `LocalConfigurationError` on either lane wins over outage classification. Ordinary abort/network/timeout errors stay transient. Gauge counts render as a labeled tracked SUBSET; no waiter/available arithmetic. Pinned by `test/db-probe.test.ts`.
@@ -46,7 +46,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/handlers/shell-validate.ts` — `validateShellJobParams(data, opts?)` shared pre-enqueue validator. Throws `UnrecoverableError` with paste-ready operator hints on every failure. Three rules: (1) cmd/argv/cwd/env shape, (2) inherit array shape + snake_case regex per element (prototype-pollution defense), (3) fail-fast on missing config value with `gbrain config set <key>` hint. Optional `redact_secrets?: boolean` for output-side scrubbing. Deliberately does NOT police WHICH secrets the agent passes — single-uid trust model. Test seam: `opts.config` drives the validator hermetically without mocking. Re-called at `shell.ts` handler entry for defense-in-depth (catches rows that bypassed the pre-enqueue validator).
-- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (`registerBuiltinHandlers`) and self-gated: unless `GBRAIN_ALLOW_SHELL_JOBS === '1'` in the worker env — set by `gbrain jobs work --allow-shell-jobs` after the cwd-`.env` preflight, or exported from the operator's shell (a cwd `.env` cannot set it: `env-trust.ts`) — a claimed job throws `UnrecoverableError` naming `--allow-shell-jobs` (dead-letter, no retries). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker.
+- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (`registerBuiltinHandlers`) and self-gated: unless `GBRAIN_ALLOW_SHELL_JOBS === '1'` in the worker env — set by `gbrain jobs work --allow-shell-jobs` after the cwd-`.env` preflight, or exported from the operator's shell (a cwd `.env` cannot set it: `env-trust.ts`) — a claimed job throws `UnrecoverableError` naming `--allow-shell-jobs` (dead-letter, no retries). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker. #5062: on POSIX the job runs in its own process group (`detached`); abort signals the whole group, escalates SIGTERM→SIGKILL by group liveness (`processGroupAlive` in `job-isolation.ts`, not `proc.killed`), and after the leader exits anything left in the group is terminated and confirmed gone before the job settles (a backgrounded `cmd &` no longer outlives its job). Windows keeps the direct-child kill. Pinned by `test/minions-shell-process-tree.test.ts`.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 7c4520c4e4..9c51a06cbd 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`.
+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, retries ordinary crashes with exponential backoff and runs periodic health checks. The default launcher prefers the current source/compiled CLI over PATH; internal `cliArgsPrefix` carries source-entrypoint arguments while explicit `--cli-path` remains authoritative. Private-queue recovery belongs to the ready worker, not the parent spawn hook. A typed local configuration fault leaves the owner alive but blocks respawns, recovery and progress-watchdog actions; repair plus explicit owner restart is required. `OwnerProcessingState` supplies additive live readiness and redacted runtime identities. `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets. Worker exit classifier emits `likely_cause` on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. Consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in `tini -s` subreaper mode when tini is on `PATH` (without assuming PID 1) (handles native-addon zombie reaping the in-process SIGCHLD reaper can't reach); exposes `isTiniDetected` read-only accessor. The spawn-and-respawn loop is the shared `ChildWorkerSupervisor` core: MinionSupervisor composes it via `runSuperviseLoop()` → `new ChildWorkerSupervisor({...})` and maps `ChildSupervisorEvent` back through `emit()` SupervisorEvent (JSONL audit consumers see byte-compatible output). PID lock, signal handlers, health check, and `process.exit` on the HARD crash ceiling stay in MinionSupervisor. Crossing the SOFT budget (`maxCrashes`) does not permanently give up: the core drops into degraded retry (capped backoff + a `crash_budget_degraded` health_warn) and self-heals when a respawn runs stably; permanent `process.exit(MAX_CRASHES)` fires only at the hard ceiling `resolveHardStopMaxCrashes(maxCrashes)` (default `maxCrashes × 10`, env `GBRAIN_SUPERVISOR_HARD_STOP_CRASHES`, `0` = never). Separately, `gbrain jobs supervisor status` + `gbrain doctor` detect a live supervisor through this queue lock (`inspectLock` + `isLockHolderLive`, freshness-keyed so PID reuse can't false-positive) when the `$HOME`-derived pidfile is absent, so a split-`$HOME` deployment does not read a healthy supervisor as "not running". `code=0` leaves `crashCount` untouched (so a worker alternating real crashes + watchdog drains still trips `max_crashes`); `cleanRestartBudget` (default 10 restarts per 60s) caps the macOS/non-Linux-fallback tight-loop via `health_warn { reason: 'clean_restart_budget_exceeded' }` + backoff. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Progress watchdog: `healthCheck()` restarts an alive-but-wedged child via `childSupervisor.restartCurrentChild(35_000)` when a queue has claimable work, 0 live-lock active jobs, and stale completions across `wedgeRestartChecks` (default 3) consecutive checks past `wedgeRestartMinutes` (default 15, 0 disables) + a `startupGraceMs` window; bounded by `wedgeRestartLoopBudget` (default 3 / `wedgeRestartLoopWindowMs`) which switches to a one-shot `wedge_restart_loop` alert. The wedge query is the exported `queryWedgeSignals(engine, queue, handlerNames)` — name+queue-scoped, `active_healthy` = live-lock only (an expired-lock active row does NOT mask the wedge), due-delayed counted. Claimable names are derived at start via a throwaway `registerBuiltinHandlers` worker (its new `quiet` opt). Flags `--wedge-restart-minutes` / `--wedge-restart-checks` + env `GBRAIN_WEDGE_RESTART_MINUTES` / `GBRAIN_WEDGE_RESTART_CHECKS`. The worker argv is built by the exported pure `buildWorkerArgs(opts)` (appends `--nice N` when `opts.nice_requested` is set, alongside `--concurrency`/`--queue`/`--max-rss`); the niceness apply RESULT (`nice_requested`/`nice_effective`/`nice_error`, computed by the CLI in jobs.ts — the supervisor doesn't call setPriority) rides on the `started`/`worker_spawned` audit emissions. Queue-scoped singleton: the real authority is a DB lock (`tryAcquireDbLock` from `src/core/db-lock.ts`) keyed on `supervisorLockId(queue)` = `gbrain-supervisor:<queue>` — keyed on the QUEUE ALONE because the lock row lives inside the target database, so the (database) half of the mutex is physical, not part of the key (mixing in a config-derived DB identity would let two supervisors on the same physical DB via different-but-equivalent URLs compute different ids and both acquire). Two supervisors with different `$HOME`/`--pid-file` against the same `(database, queue)` cannot both run with conflicting `--max-rss`: the second exits `LOCK_HELD`. The pidfile-cleanup `process.on('exit')` listener is installed BEFORE the DB-lock acquisition so the `LOCK_HELD` early-exit can't strand the pidfile this process just created. The default pidfile is brain-scoped (`supervisor-<brainId>.pid`) so different brains under one HOME don't false-block. The lock refreshes on its own `setInterval` (TTL 5min, refresh 60s, max 3 failures = 180s < TTL); a refresh that THROWS past the threshold exits `LOCK_LOST` (code 4) rather than risk a split-brain, while a fenced refresh returning `false` (0 rows matched — the lock was stolen or force-cleared) is treated as CERTAIN loss, not a blip: the supervisor emits `health_error { reason: 'supervisor_lock_lost' }` and exits `LOCK_LOST` immediately (counting it toward the failure threshold would let two supervisors drain the same queue for up to two more refresh windows). `shutdown()` releases the lock so a clean restart re-acquires immediately. The `started` audit records `max_rss_mb` so `gbrain doctor`'s `supervisor_singleton` check can surface the effective cap. Exports `supervisorLockId()` and the pure `classifySupervisorSingleton({lockLive, lockHolderHost, lockHolderPid, localHost, localPid}) → 'no_lock'|'single'|'mismatch'` (host+pid compare, bare pid meaningless cross-host) that doctor consumes. Pinned by `test/supervisor.test.ts` (16 cases), `test/supervisor-tini.test.ts`, `test/supervisor-wedge.test.ts`, `test/supervisor-build-worker-args.test.ts`, and `test/supervisor-db-lock.test.ts`. `SupervisorOpts.jobIsolation` passes `--job-isolation process` to the spawned worker via a CONDITIONAL `buildWorkerArgs` push (inline argv stays byte-identical). `queryWedgeSignals`/`probeQueueState` thread a per-probe AbortSignal; the probe timeout cancels the losing query (pool-slot release under exhaustion). `buildWorkerArgs` also appends `--allow-shell-jobs` when `opts.allowShellJobs` (conditional push like `--job-isolation`, so existing argv stays byte-identical; pinned by `test/supervisor-build-worker-args.test.ts`). Rationale: the worker's startup cwd-.env quarantine drops `GBRAIN_ALLOW_SHELL_JOBS` whenever a .env in the worker's cwd assigns it, so the env copy in `runSuperviseLoop` alone could silently disable shell jobs; `jobs work` parses the flag and re-sets `process.env.GBRAIN_ALLOW_SHELL_JOBS='1'` after preflight (read sites in jobs.ts / handlers/shell.ts unchanged). `allowShellJobs` sets the env var on the child AND pushes `--allow-shell-jobs`. #5062: registers as the CLI signal owner; `shutdown()` is one shared promise (repeated signals join it) that keeps refreshing the queue lock while the worker drains (SIGTERM, 35s, SIGKILL by liveness, 5s confirmation), then releases the lock and emits `stopped` with `drained` / `worker_forced` / `worker_exit_code` / `lock_released`. `gbrain jobs supervisor stop` (`src/commands/jobs/supervisor.ts`) reports `drained` only when the pid is gone, the supervisor's own `stopped` row follows its `shutting_down` with `drained: true`, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (`no_stopped_event`, `worker_still_running`, `lock_unverified`, `lock_still_held`, `forced`) and exits 1.
- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. Pending receipts leave tool ledgers pending for retry and never count as written pages.
@@ -29,4 +29,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.
- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.
-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate.
+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`queue.releaseShutdownJob`, token-fenced, no attempt burned), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17).
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 70927c0fe5..0cee62b009 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests and `sync-import-provenance` rows of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.
- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).
-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`.
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`.
diff --git a/src/commands/jobs/supervisor.ts b/src/commands/jobs/supervisor.ts
index 0bf82bfd01..b63d303a5a 100644
--- a/src/commands/jobs/supervisor.ts
+++ b/src/commands/jobs/supervisor.ts
@@ -6,6 +6,7 @@ import { WORKER_EXIT_CONFIGURATION } from '../../core/minions/worker-exit-codes.
import { writeStdoutFinal } from '../../core/cli-force-exit.ts';
import { opError } from '../../core/ops/contract.ts';
import { usageError, writeCliRefusal } from '../../cli/cli-error.ts';
+import type { BrainEngine } from '../../core/engine.ts';
export async function runJobsSupervisor({ args, engine, engineOrNull }: JobsCommandContext): Promise<void> {
// Dispatcher for supervisor subcommands:
@@ -32,7 +33,7 @@ export async function runJobsSupervisor({ args, engine, engineOrNull }: JobsComm
// ----- stop subcommand -----
if (isStopCmd) {
- await stopSupervisor(pidFile, jsonMode);
+ await stopSupervisor(engine, args, pidFile, jsonMode);
return;
}
@@ -291,26 +292,48 @@ async function showSupervisorStatus(
process.exit(running ? 0 : 1);
}
-/** `gbrain jobs supervisor stop`: SIGTERM + drain wait; always exits the process. */
-async function stopSupervisor(pidFile: string, jsonMode: boolean): Promise<void> {
+/** #5062: supervisor's own 35s worker drain + 5s SIGKILL confirmation + slack. */
+const STOP_WAIT_MS = 45_000;
+
+/**
+ * `gbrain jobs supervisor stop`: SIGTERM, wait for the exit, then verify the
+ * stop before calling it drained; always exits the process. #5062: "the pid
+ * is gone" is not enough. Success also needs the supervisor's own `stopped`
+ * audit row (after its `shutting_down`) saying the worker drained, every
+ * worker it spawned gone, and its queue lock row released. Anything less is
+ * reported with the failing check and exits 1.
+ */
+async function stopSupervisor(engine: BrainEngine, args: string[], pidFile: string, jsonMode: boolean): Promise<void> {
const { existsSync, readFileSync } = await import('fs');
- if (!existsSync(pidFile)) {
- const payload = { stopped: false, reason: 'pid_file_missing', pid_file: pidFile };
+ const { hostname } = await import('os');
+ const { readSupervisorEvents } = await import('../../core/minions/handlers/supervisor-audit.ts');
+ const { supervisorLockId } = await import('../../core/minions/supervisor.ts');
+ const { inspectLock } = await import('../../core/db-lock.ts');
+ const report = (payload: Record<string, unknown>, human: string, ok: boolean): never => {
if (jsonMode) console.log(JSON.stringify(payload));
- else console.error(`No PID file at ${pidFile}; supervisor not running.`);
- process.exit(1);
+ else if (ok) console.log(human);
+ else console.error(human);
+ process.exit(ok ? 0 : 1);
+ };
+ const isAlive = (pid: number): boolean => {
+ try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
+ };
+
+ if (!existsSync(pidFile)) {
+ report({ stopped: false, reason: 'pid_file_missing', pid_file: pidFile }, `No PID file at ${pidFile}; supervisor not running.`, false);
}
let supervisorPid: number;
try {
supervisorPid = parseInt(readFileSync(pidFile, 'utf8').trim().split('\n')[0], 10);
if (isNaN(supervisorPid) || supervisorPid <= 0) throw new Error('invalid pid');
} catch (err) {
- const payload = { stopped: false, reason: 'pid_file_corrupt', error: String(err) };
- if (jsonMode) console.log(JSON.stringify(payload));
- else console.error(`PID file corrupt: ${err}`);
- process.exit(1);
+ return report({ stopped: false, reason: 'pid_file_corrupt', error: String(err) }, `PID file corrupt: ${err}`, false);
}
+ const ownEvents = () => readSupervisorEvents().filter(e => e.supervisor_pid === supervisorPid);
+ const startedEvt = ownEvents().filter(e => e.event === 'started').pop();
+ const queue = (typeof startedEvt?.queue === 'string' ? startedEvt.queue : undefined) ?? parseFlag(args, '--queue') ?? 'default';
+
try { process.kill(supervisorPid, 'SIGTERM'); }
catch (err: unknown) {
const code = (err as NodeJS.ErrnoException)?.code;
@@ -324,21 +347,48 @@ async function stopSupervisor(pidFile: string, jsonMode: boolean): Promise<void>
process.exit(code === 'ESRCH' ? 0 : 1);
}
- // Poll for up to 40s (supervisor's own 35s drain + 5s slack).
- const deadline = Date.now() + 40_000;
- let stoppedCleanly = false;
- while (Date.now() < deadline) {
- try { process.kill(supervisorPid, 0); }
- catch { stoppedCleanly = true; break; }
+ const deadline = Date.now() + STOP_WAIT_MS;
+ while (Date.now() < deadline && isAlive(supervisorPid)) {
await new Promise(r => setTimeout(r, 250));
}
+ if (isAlive(supervisorPid)) {
+ report({ stopped: false, supervisor_pid: supervisorPid, reason: 'timeout', waited_ms: STOP_WAIT_MS },
+ `Supervisor ${supervisorPid} did not exit within ${STOP_WAIT_MS / 1000}s.`, false);
+ }
- const payload = {
- stopped: stoppedCleanly,
- supervisor_pid: supervisorPid,
- reason: stoppedCleanly ? 'drained' : 'timeout_40s',
+ const events = ownEvents();
+ const shuttingIdx = events.map(e => e.event).lastIndexOf('shutting_down');
+ const stoppedEvt = shuttingIdx >= 0 ? events.slice(shuttingIdx + 1).find(e => e.event === 'stopped') : undefined;
+ const spawned = events
+ .filter(e => e.event === 'worker_spawned' && typeof e.pid === 'number')
+ .map(e => e.pid as number);
+ const liveWorkers = spawned.filter(isAlive);
+ let lockReleased: boolean | null;
+ try {
+ const snap = await inspectLock(engine, supervisorLockId(queue));
+ lockReleased = !(snap && snap.holder_pid === supervisorPid && snap.holder_host === hostname());
+ } catch {
+ lockReleased = null;
+ }
+ const checks = {
+ process_exited: true,
+ stopped_event: stoppedEvt !== undefined,
+ worker_drained: stoppedEvt?.drained === true,
+ workers_exited: liveWorkers.length === 0,
+ lock_released: lockReleased,
};
- if (jsonMode) console.log(JSON.stringify(payload));
- else console.log(stoppedCleanly ? `Supervisor ${supervisorPid} stopped.` : `Supervisor ${supervisorPid} did not exit within 40s.`);
- process.exit(stoppedCleanly ? 0 : 1);
+ const reason = !checks.stopped_event ? 'no_stopped_event'
+ : !checks.workers_exited ? 'worker_still_running'
+ : lockReleased === null ? 'lock_unverified'
+ : !lockReleased ? 'lock_still_held'
+ : !checks.worker_drained ? 'forced'
+ : 'drained';
+ const drained = reason === 'drained';
+ const human = drained
+ ? `Supervisor ${supervisorPid} stopped; worker drained.`
+ : `Supervisor ${supervisorPid} exited but the stop is not verified as drained (${reason}): ` +
+ `${JSON.stringify(checks)}${liveWorkers.length > 0 ? `; live worker pid(s): ${liveWorkers.join(', ')}` : ''}. ` +
+ 'Inspect in-flight jobs with `gbrain jobs list --status active`.';
+ report({ stopped: true, supervisor_pid: supervisorPid, queue, reason, drained, checks,
+ ...(liveWorkers.length > 0 ? { live_worker_pids: liveWorkers } : {}) }, human, drained);
}
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index 6e7a30f5a9..130460e558 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -4,7 +4,8 @@ import { applyNiceness, formatNice } from '../../core/minions/niceness.ts';
import { resolveChildCliInvocation } from '../../core/minions/job-isolation.ts';
import { checkWorkerStartup, reportWorkerConfiguration, reportWorkerReady, reportWorkerStarting } from '../jobs-readiness.ts';
import { LocalConfigurationError, isLocalConfigurationError } from '../../core/minions/configuration-error.ts';
-import { WORKER_EXIT_CONFIGURATION, WORKER_EXIT_RSS_WATCHDOG } from '../../core/minions/worker-exit-codes.ts';
+import { WORKER_EXIT_CONFIGURATION, WORKER_EXIT_DRAIN_FORCED, WORKER_EXIT_RSS_WATCHDOG } from '../../core/minions/worker-exit-codes.ts';
+import { registerSignalOwner } from '../../core/process-cleanup.ts';
import { MinionWorker, type UnhealthyReason } from '../../core/minions/worker.ts';
import type { MinionQueue } from '../../core/minions/queue.ts';
import type { BrainEngine } from '../../core/engine.ts';
@@ -243,12 +244,17 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
});
process.on('exit', () => unregisterWorker());
+ // #5062: own SIGTERM/SIGHUP/broken-pipe so the generic CLI cleanup pass
+ // cannot exit(143) ahead of the drain and orphan in-flight jobs.
+ const releaseSignalOwner = registerSignalOwner('jobs-work', () => worker.requestShutdown());
+
try {
reportWorkerStarting('worker_startup');
worker.once('ready', () => reportWorkerReady(childIdentity));
await worker.start();
} finally {
unregisterWorker();
+ releaseSignalOwner();
if (worker.configurationError) {
const releases = worker.configurationReleaseResults;
const unconfirmed = releases.filter(result => result.outcome === 'unconfirmed').length;
@@ -284,6 +290,12 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
if (worker.rssWatchdogTriggered) {
process.exit(WORKER_EXIT_RSS_WATCHDOG);
}
+ // #5062: claims were handed back while their handlers still ran; exit
+ // now (a running handler would otherwise keep the process alive) with a
+ // code that says the drain did not complete.
+ if (worker.drainForced) {
+ process.exit(WORKER_EXIT_DRAIN_FORCED);
+ }
}
}
diff --git a/src/core/minions/child-worker-supervisor.ts b/src/core/minions/child-worker-supervisor.ts
index 9452817516..10989941cc 100644
--- a/src/core/minions/child-worker-supervisor.ts
+++ b/src/core/minions/child-worker-supervisor.ts
@@ -193,6 +193,7 @@ export class ChildWorkerSupervisor {
private readonly tiniPath: string;
private _crashCount = 0;
private _lastExitCode: number | null = null;
+ private _lastExit: { code: number | null; signal: NodeJS.Signals | null } | null = null;
private _cleanRestartTimestamps: number[] = [];
/** Sliding window of RSS-watchdog exit timestamps (issue #1678). Separate
* from crashCount so the >5-min stable-run reset can't defeat the breaker. */
@@ -224,6 +225,12 @@ export class ChildWorkerSupervisor {
get crashCount(): number {
return this._crashCount;
}
+ /** #5062: how the most recent child exited, recorded on the shutdown path
+ * too, so a composer can tell a clean drain (code 0) from a forced or
+ * failed stop. */
+ get lastExit(): { code: number | null; signal: NodeJS.Signals | null } | null {
+ return this._lastExit;
+ }
get configurationBlocked(): boolean {
if (this.opts.processingState?.blocked) this.markConfigurationBlocked();
return this._configurationBlocked;
@@ -585,6 +592,7 @@ export class ChildWorkerSupervisor {
settled = true;
cleanup();
this._child = null;
+ this._lastExit = { code, signal };
if (code === WORKER_EXIT_CONFIGURATION) {
this.opts.processingState?.workerExited();
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 6be9038c0f..ac580289ea 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -2029,6 +2029,25 @@ export class MinionQueue {
}
}
+ /**
+ * #5062: hand a claim back to the queue because the worker is shutting
+ * down (token-fenced; attempts_made is untouched). Returns false when the
+ * claim already moved on (reclaimed, completed, cancelled).
+ */
+ async releaseShutdownJob(id: number, lockToken: string): Promise<boolean> {
+ const rows = await this.engine.executeRaw<{ id: number }>(
+ `UPDATE minion_jobs SET
+ status = 'waiting',
+ error_text = 'worker_shutdown',
+ started_at = NULL, timeout_at = NULL,
+ lock_token = NULL, lock_until = NULL, updated_at = now()
+ WHERE id = $1 AND status = 'active' AND lock_token = $2
+ RETURNING id`,
+ [id, lockToken],
+ );
+ return rows.length > 0;
+ }
+
/** Update job progress (token-fenced). */
async updateProgress(id: number, lockToken: string, progress: unknown): Promise<boolean> {
const rows = await this.engine.executeRaw<Record<string, unknown>>(
diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.ts
index f6395187ba..ee6a556d4d 100644
--- a/src/core/minions/supervisor.ts
+++ b/src/core/minions/supervisor.ts
@@ -49,6 +49,7 @@ import type { BrainEngine } from '../engine.ts';
import { tryAcquireDbLock, waitForDbLockTakeover, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';
import { currentBrainId, readWorkers } from './worker-registry.ts';
import { autopilotOperatorPauseMarkerPath, autopilotPaused } from '../autopilot-paths.ts';
+import { registerSignalOwner, triggerCleanupAndExit } from '../process-cleanup.ts';
import { resolveEnvNumber } from '../env-number.ts';
export type SupervisorEvent =
@@ -216,6 +217,13 @@ export function buildWorkerArgs(
/** Grace before SIGKILL when restarting a wedged child — reuses the 35s
* shutdown() drain window (issue #1801, D3). */
const WEDGE_RESTART_GRACE_MS = 35_000;
+/** #5062: shutdown drain window for the worker (its own 30s job drain + slack). */
+const WORKER_DRAIN_GRACE_MS = 35_000;
+/** #5062: how long to wait for the kernel to confirm a SIGKILLed worker. */
+const WORKER_KILL_CONFIRM_MS = 5_000;
+/** Shutdown reasons that come from an operator signal (always honored, even
+ * when the owner is configuration-blocked). */
+const SIGNAL_REASONS: ReadonlySet<string> = new Set(['SIGTERM', 'SIGINT', 'SIGHUP', 'SIGPIPE']);
/**
* issue #1994: resolve the hard permanent-give-up ceiling. Default
@@ -568,6 +576,8 @@ export class MinionSupervisor {
private exitListener: (() => void) | null = null;
private sigtermListener: (() => void) | null = null;
private sigintListener: (() => void) | null = null;
+ private releaseSignalOwner: (() => void) | null = null;
+ private shutdownPromise: Promise<void> | null = null;
private lockAcquired = false;
private consecutiveHealthFailures = 0;
// #1849: queue-scoped DB singleton lock (the real authority) + its refresh
@@ -806,6 +816,12 @@ export class MinionSupervisor {
this.sigintListener = () => { void this.shutdown('SIGINT', ExitCodes.CLEAN); };
process.on('SIGTERM', this.sigtermListener);
process.on('SIGINT', this.sigintListener);
+ // #5062: own the CLI's termination signals so the generic cleanup pass
+ // (which DELETEs this supervisor's lock row and exits 143) cannot pre-empt
+ // the drain above.
+ this.releaseSignalOwner = registerSignalOwner('jobs-supervisor', (signal) => {
+ void this.shutdown(signal, ExitCodes.CLEAN);
+ });
// 4. Health monitoring. Skip when healthInterval=0 — that's the explicit
// "disable" contract documented on `--health-interval 0`. setInterval(0)
@@ -881,21 +897,47 @@ export class MinionSupervisor {
}
}
- /** Unified shutdown path. Reason becomes the audit event name; exitCode is process exit. */
- private async shutdown(reason: string, exitCode: number): Promise<void> {
- if (this.configurationBlocked && reason !== 'SIGTERM' && reason !== 'SIGINT') return;
- if (this.stopping) return;
+ /**
+ * Unified shutdown path. Reason becomes the audit event name; exitCode is
+ * process exit. #5062: every caller (repeated signals included) joins the
+ * same promise. The ordered sequence is: stop restarts (and, via
+ * `stopping`, health actions), keep refreshing the singleton lock while the worker drains (a second
+ * supervisor cannot start mid-drain), stop the worker (SIGTERM, 35s drain,
+ * SIGKILL by liveness, confirmed exit), release the lock, emit `stopped`
+ * with whether the worker actually drained, then run the remaining cleanup
+ * callbacks and exit.
+ */
+ private shutdown(reason: string, exitCode: number): Promise<void> {
+ if (this.configurationBlocked && !SIGNAL_REASONS.has(reason)) return Promise.resolve();
+ this.shutdownPromise ??= this.runShutdown(reason, exitCode);
+ return this.shutdownPromise;
+ }
+
+ private async runShutdown(reason: string, exitCode: number): Promise<void> {
this.stopping = true;
this.emit('shutting_down', { reason, exit_code: exitCode });
- if (this.childSupervisor) {
- this.childSupervisor.killChild('SIGTERM');
- await this.childSupervisor.awaitChildExit(35_000);
- if (this.childSupervisor.childAlive) this.childSupervisor.killChild('SIGKILL');
+ // Stop the worker: SIGTERM, drain window, SIGKILL by liveness, then wait
+ // for the kernel to confirm the kill.
+ const child = this.childSupervisor;
+ const hadWorker = child?.childAlive === true;
+ let forced = false;
+ let workerGone = true;
+ if (child) {
+ child.killChild('SIGTERM');
+ await child.awaitChildExit(WORKER_DRAIN_GRACE_MS);
+ if (child.childAlive) {
+ forced = true;
+ child.killChild('SIGKILL');
+ await child.awaitChildExit(WORKER_KILL_CONFIRM_MS);
+ }
+ workerGone = !(child as ChildWorkerSupervisor).childAlive;
}
- if (this.configurationBlocked && reason !== 'SIGTERM' && reason !== 'SIGINT') {
+ const workerExit = hadWorker ? child?.lastExit ?? null : null;
+ if (this.configurationBlocked && !SIGNAL_REASONS.has(reason)) {
this.stopping = false;
+ this.shutdownPromise = null;
return;
}
@@ -907,14 +949,17 @@ export class MinionSupervisor {
// #1849: stop refreshing + release the DB singleton lock so a clean
// restart (or a different host) can re-acquire immediately instead of
// waiting out the TTL. release() is best-effort; the TTL covers a crash.
+ // #5062: only now, after the worker is gone; the refresh timer kept the
+ // lock alive through the drain.
if (this.lockRefreshTimer) {
clearInterval(this.lockRefreshTimer);
this.lockRefreshTimer = null;
}
+ let lockReleased = this.dbLock === null;
if (this.dbLock) {
const lock = this.dbLock;
this.dbLock = null;
- try { await lock.release(); } catch { /* best-effort; TTL fallback covers it */ }
+ try { await lock.release(); lockReleased = true; } catch { /* best-effort; TTL fallback covers it */ }
}
// Remove signal handlers so tests that spin up multiple supervisors on
@@ -928,9 +973,22 @@ export class MinionSupervisor {
process.removeListener('SIGINT', this.sigintListener);
this.sigintListener = null;
}
-
- this.emit('stopped', { reason, exit_code: exitCode });
- process.exit(exitCode);
+ this.releaseSignalOwner?.();
+ this.releaseSignalOwner = null;
+
+ // A worker that needed SIGKILL, is still alive, or exited with anything
+ // but a clean drain did not drain: `jobs supervisor stop` reads this flag.
+ const drained = !hadWorker || (!forced && workerGone && workerExit?.code === 0);
+ this.emit('stopped', {
+ reason,
+ exit_code: exitCode,
+ drained,
+ worker_forced: forced,
+ worker_exit_code: workerExit?.code ?? null,
+ worker_signal: workerExit?.signal ?? null,
+ lock_released: lockReleased,
+ });
+ await triggerCleanupAndExit(exitCode);
}
/** #1849: the queue-scoped DB lock id for this supervisor's queue. */
@@ -956,7 +1014,13 @@ export class MinionSupervisor {
* tolerated (counter resets on the next success).
*/
private async refreshDbLock(): Promise<void> {
- if (!this.dbLock || this.stopping) return;
+ if (!this.dbLock) return;
+ if (this.stopping) {
+ // #5062: still the singleton while the worker drains; a failed refresh
+ // here cannot start a second shutdown (the TTL still covers the drain).
+ try { await this.dbLock.refresh(); } catch { /* best-effort during drain */ }
+ return;
+ }
try {
const stillOwned = await this.dbLock.refresh();
if (this.configurationBlocked) return;
diff --git a/src/core/minions/worker-exit-codes.ts b/src/core/minions/worker-exit-codes.ts
index c6dda3d536..2bd87ef8c5 100644
--- a/src/core/minions/worker-exit-codes.ts
+++ b/src/core/minions/worker-exit-codes.ts
@@ -25,6 +25,10 @@ export const WORKER_EXIT_RSS_WATCHDOG = 12;
export const WORKER_EXIT_CONFIGURATION = 16;
+/** #5062: the shutdown drain timed out; claims still running were handed back
+ * to the queue. The worker stopped, but it did not drain. */
+export const WORKER_EXIT_DRAIN_FORCED = 17;
+
// --- `gbrain jobs run-child` exit codes (issue #5 process isolation) -------
//
// The parent (child-job-runner.ts) classifies a child by RESULT-FILE PRESENCE
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 73da308f93..262dde6595 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -235,6 +235,7 @@ export class MinionWorker extends EventEmitter {
private jobsCompleted = 0;
/** Idempotency latch for gracefulShutdown — per-job and periodic check sites can race. */
private gracefulShutdownFired = false;
+ private _drainForced = false;
/**
* Set true when the RSS watchdog (not a normal SIGTERM) initiated the
* drain. The CLI handler (src/commands/jobs.ts case 'work') reads this
@@ -540,13 +541,7 @@ export class MinionWorker extends EventEmitter {
// `ctx.shutdownSignal` (currently: shell handler) can run their own cleanup
// BEFORE the 30s cleanup race expires. Non-shell handlers ignore shutdown
// and keep running — they get the full 30s window.
- const shutdown = () => {
- console.log('Minion worker shutting down...');
- this.running = false;
- if (!this.shutdownAbort.signal.aborted) {
- this.shutdownAbort.abort(new Error('shutdown'));
- }
- };
+ const shutdown = () => this.requestShutdown();
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
@@ -943,11 +938,14 @@ export class MinionWorker extends EventEmitter {
} else if (this.executions.size > 0) {
console.log(`Waiting for ${this.executions.size} in-flight job(s) to finish (30s timeout)...`);
const pending = Array.from(this.executions.values()).map(f => f.promise);
+ let drainTimer: ReturnType<typeof setTimeout> | undefined;
await Promise.race([
Promise.allSettled(pending),
- new Promise(resolve => setTimeout(resolve, 30000)),
+ new Promise(resolve => { drainTimer = setTimeout(resolve, 30000); }),
]);
+ clearTimeout(drainTimer);
if (this.configurationError) await this.drainConfiguration();
+ else await this.releaseUndrainedClaims();
}
// The worker does NOT disconnect the engine: it doesn't own the
@@ -1044,6 +1042,62 @@ export class MinionWorker extends EventEmitter {
}
}
+ /**
+ * #5062: begin the signal-driven shutdown (SIGTERM / SIGINT, or the CLI's
+ * signal-owner callback for SIGHUP and a broken pipe). Stops claiming and
+ * fires `shutdownSignal` so handlers that own processes (shell) terminate
+ * them; start() then drains in-flight jobs and resolves. Idempotent.
+ */
+ requestShutdown(): void {
+ if (this.shutdownAbort.signal.aborted && !this.running) return;
+ console.log('Minion worker shutting down...');
+ this.running = false;
+ if (!this.shutdownAbort.signal.aborted) {
+ this.shutdownAbort.abort(new Error('shutdown'));
+ }
+ }
+
+ /**
+ * #5062: true when the shutdown drain timed out and in-flight claims had to
+ * be handed back while their handlers were still running. The CLI exits
+ * with WORKER_EXIT_DRAIN_FORCED so a supervisor never reports `drained`.
+ */
+ get drainForced(): boolean {
+ return this._drainForced;
+ }
+
+ /** #5062: after the 30s shutdown drain, hand every claim still held back to
+ * the queue (token-fenced, no attempt burned) instead of leaving it active
+ * until its lease expires and the stall sweep charges a stall. */
+ private async releaseUndrainedClaims(): Promise<void> {
+ const remaining = Array.from(this.executions.values());
+ if (remaining.length === 0) return;
+ this._drainForced = true;
+ for (const execution of remaining) {
+ try {
+ const released = await this.queue.releaseShutdownJob(execution.job.id, execution.lockToken);
+ console.warn(
+ `Job ${execution.job.id} (${execution.job.name}) did not finish within the shutdown drain; ` +
+ (released ? 'handed back to the queue (no attempt burned).' : 'claim already moved on (lock token mismatch).'),
+ );
+ } catch (e) {
+ console.error(`[worker] shutdown release failed for job ${execution.job.id}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+ }
+
+ private async releaseAfterShutdown(job: MinionJob, lockToken: string, errorText: string): Promise<void> {
+ try {
+ const released = await this.queue.releaseShutdownJob(job.id, lockToken);
+ console.log(
+ `Job ${job.id} (${job.name}) ${released ? 'handed back to the queue' : 'claim already moved on'} ` +
+ `after worker shutdown (${errorText}; no attempt burned)`,
+ );
+ } catch (e) {
+ console.error(`[worker] shutdown release failed for job ${job.id}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+
/** Stop the worker gracefully. */
stop(): void {
this.running = false;
@@ -1637,12 +1691,23 @@ export class MinionWorker extends EventEmitter {
return;
}
if (err instanceof ChildWorkerShutdownError) {
+ if (err.executionStopped === true) {
+ await this.releaseAfterShutdown(job, lockToken, errorText);
+ return;
+ }
console.log(
`Job ${job.id} (${job.name}) released after worker shutdown (${errorText}); ` +
`stall detector will requeue (no attempt burned)`,
);
return;
}
+ // #5062: the handler ended because the worker is shutting down (the
+ // shell handler terminated its process group), not because the job
+ // failed. Hand the claim back instead of burning an attempt.
+ if (!isolated && this.shutdownAbort.signal.aborted && !abort.signal.aborted) {
+ await this.releaseAfterShutdown(job, lockToken, errorText);
+ return;
+ }
if (err instanceof ChildNotClaimedError) {
// The child proved the claim is gone (reclaimed/cancelled before the
// handler ran). The token-fenced failJob would no-op anyway — return
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index b3be1e55d2..acced74c83 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -51,6 +51,11 @@ interface CleanupEntry {
}
const registry = new Map<symbol, CleanupEntry>();
+/** #5062: long-lived commands that run their own ordered shutdown. The most
+ * recent registration wins; while one is registered, termination signals
+ * and a broken stdout/stderr pipe go to it instead of the generic
+ * cleanup-then-exit pass. */
+const signalOwners: Array<{ key: symbol; onSignal: (signal: NodeJS.Signals) => void }> = [];
let installed = false;
let cleanupPass: Promise<void> | null = null;
/** Refs to every listener attached by installSignalHandlers, keyed by
@@ -83,6 +88,39 @@ export function registerCleanup(name: string, fn: () => Promise<void>): () => vo
};
}
+/**
+ * #5062: claim the process's termination signals (SIGTERM, SIGHUP, SIGPIPE
+ * and a broken stdout/stderr pipe). Without an owner the generic handler
+ * runs every cleanup callback (which DELETEs held DB locks) and exits at
+ * once, so a supervisor or worker loses its singleton lock and dies before
+ * it can drain. With an owner registered the generic handler only forwards
+ * the signal; the owner stops admissions, drains, releases its own locks and
+ * then calls `triggerCleanupAndExit` (or exits) itself. Repeated signals are
+ * forwarded again, so `onSignal` must be idempotent. Crashes
+ * (uncaughtException / unhandledRejection) keep the generic path.
+ *
+ * Returns a deregister handle (idempotent).
+ */
+export function registerSignalOwner(name: string, onSignal: (signal: NodeJS.Signals) => void): () => void {
+ const key = Symbol(name);
+ signalOwners.push({ key, onSignal });
+ return () => {
+ const i = signalOwners.findIndex((o) => o.key === key);
+ if (i >= 0) signalOwners.splice(i, 1);
+ };
+}
+
+function forwardToSignalOwner(signal: NodeJS.Signals): boolean {
+ const owner = signalOwners[signalOwners.length - 1];
+ if (!owner) return false;
+ try { owner.onSignal(signal); }
+ catch (err) {
+ try { process.stderr.write(`[process-cleanup] signal owner: ${err instanceof Error ? err.message : String(err)}\n`); }
+ catch { /* stderr might be broken */ }
+ }
+ return true;
+}
+
/**
* Read the currently registered cleanup count. Test seam.
*
@@ -153,6 +191,7 @@ export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean }
const keepServing = opts.keepServingOnLogEpipe === true;
const handleSignal = (signal: NodeJS.Signals) => {
+ if (forwardToSignalOwner(signal)) return;
void runCleanupPass().finally(() => {
// Match GNU `kill` exit-code convention: 128 + signal number for
// signal-terminated processes. The actual integer doesn't matter
@@ -193,6 +232,7 @@ export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean }
// through the cleanup pass so locks release BEFORE we exit.
attach(process.stdout, 'error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EPIPE' && !keepServing) {
+ if (forwardToSignalOwner('SIGPIPE')) return;
void triggerCleanupAndExit(0);
}
});
@@ -200,6 +240,7 @@ export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean }
// stderr was rerouted to stdout).
attach(process.stderr, 'error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EPIPE' && !keepServing) {
+ if (forwardToSignalOwner('SIGPIPE')) return;
// No stderr means no useful logs on the way out; still cleanup.
void triggerCleanupAndExit(0);
}
@@ -214,6 +255,7 @@ export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean }
*/
export function _resetForTests(): void {
registry.clear();
+ signalOwners.length = 0;
// Detach every listener installSignalHandlers attached — clearing flags
// alone leaves a live SIGTERM→exit(143) listener on the shared test-runner
// process, which a later synthetic `process.emit('SIGTERM')` would trigger,
diff --git a/test/child-worker-supervisor.test.ts b/test/child-worker-supervisor.test.ts
index c5c2a9a91f..014b1abf1f 100644
--- a/test/child-worker-supervisor.test.ts
+++ b/test/child-worker-supervisor.test.ts
@@ -808,6 +808,58 @@ describe('ChildWorkerSupervisor', () => {
h.cleanup();
}
}, TEST_TIMEOUT_MS);
+
+ // #5062 (fix wave 9): the composer shutdown path (MinionSupervisor) is
+ // SIGTERM → drain window → SIGKILL by liveness → confirmed exit, and it
+ // decides "drained" from lastExit, which must be recorded while stopping.
+ async function runForStop(cliPath: string, args: string[]) {
+ let stopping = false;
+ let resolveSpawn: (pid: number) => void;
+ const firstSpawn = new Promise<number>((r) => { resolveSpawn = r; });
+ const sup = new ChildWorkerSupervisor({
+ cliPath,
+ args,
+ maxCrashes: 100,
+ _backoffFloorMs: 5,
+ isStopping: () => stopping,
+ onMaxCrashesExceeded: () => { stopping = true; },
+ onEvent: (e) => { if (e.kind === 'worker_spawned') resolveSpawn(e.pid); },
+ });
+ const runPromise = sup.run();
+ const pid = await firstSpawn;
+ return { sup, pid, runPromise, beginStop: () => { stopping = true; } };
+ }
+
+ it.skipIf(process.platform === 'win32')('stop sequence: a SIGTERM-ignoring worker needs SIGKILL and lastExit records the kill (#5062)', async () => {
+ const ctx = await runForStop('/bin/sh', ['-c', 'trap "" TERM; exec sleep 30']);
+ await sleep(200);
+ ctx.beginStop();
+ ctx.sup.killChild('SIGTERM');
+ await ctx.sup.awaitChildExit(300);
+ expect(ctx.sup.childAlive).toBe(true);
+ ctx.sup.killChild('SIGKILL');
+ await ctx.sup.awaitChildExit(5_000);
+ expect(ctx.sup.childAlive).toBe(false);
+ expect(isAlive(ctx.pid)).toBe(false);
+ expect(ctx.sup.lastExit).toEqual({ code: null, signal: 'SIGKILL' });
+ await ctx.runPromise;
+ }, TEST_TIMEOUT_MS);
+
+ it('stop sequence: a worker that drains on SIGTERM leaves lastExit code 0 (#5062)', async () => {
+ const h = makeHarness('stop-cooperative', "process.on('SIGTERM', () => process.exit(0));\nsetTimeout(() => {}, 30_000);");
+ try {
+ const ctx = await runForStop(h.cliPath, h.args);
+ await sleep(300);
+ ctx.beginStop();
+ ctx.sup.killChild('SIGTERM');
+ await ctx.sup.awaitChildExit(10_000);
+ expect(ctx.sup.childAlive).toBe(false);
+ expect(ctx.sup.lastExit).toEqual({ code: 0, signal: null });
+ await ctx.runPromise;
+ } finally {
+ h.cleanup();
+ }
+ }, TEST_TIMEOUT_MS);
});
// A worker that can NEVER launch (bad cliPath, missing binary, a target the
diff --git a/test/e2e/supervisor-stop-drain-5062.test.ts b/test/e2e/supervisor-stop-drain-5062.test.ts
new file mode 100644
index 0000000000..ec22b05ad9
--- /dev/null
+++ b/test/e2e/supervisor-stop-drain-5062.test.ts
@@ -0,0 +1,279 @@
+/**
+ * #5062 (fix wave 9, S1) — `jobs supervisor` / `jobs work` stop must drain:
+ * real CLI processes against a throwaway Postgres.
+ *
+ * Pre-fix, a SIGTERM reached the generic CLI cleanup handler first: it
+ * DELETEd the supervisor's queue lock and exited 143 before the supervisor
+ * emitted `stopped`; the worker died the same way, leaving its in-flight
+ * shell job `active` and the job's children orphaned to PID 1, while
+ * `jobs supervisor stop` reported `drained`.
+ *
+ * The barrier job is a shell job whose leader and grandchild both ignore
+ * SIGTERM, so every drain takes the shell handler's full SIGTERM→SIGKILL
+ * grace window (~5s): long enough to probe the lock and start a second
+ * supervisor mid-drain.
+ */
+
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { hostname, tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const describeDatabase = hasDatabase() ? describe : describe.skip;
+const REPO = resolve(import.meta.dir, '../..');
+const CLI = join(REPO, 'src/cli.ts');
+
+type Proc = ReturnType<typeof Bun.spawn>;
+
+function makeHome(tag: string): string {
+ const home = mkdtempSync(join(tmpdir(), `sup-5062-${tag}-`));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'postgres', database_url: process.env.DATABASE_URL,
+ }));
+ return home;
+}
+
+function childEnv(home: string, extra: Record<string, string> = {}): Record<string, string | undefined> {
+ const env: Record<string, string | undefined> = {
+ ...process.env, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', ...extra,
+ };
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_ALLOW_SHELL_JOBS', 'GBRAIN_AUDIT_DIR', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY']) delete env[key];
+ return env;
+}
+
+function spawnCli(home: string, args: string[], extra: Record<string, string> = {}): { proc: Proc; out: () => Promise<string> } {
+ const proc = Bun.spawn({
+ cmd: [process.execPath, '--no-env-file', CLI, ...args],
+ env: childEnv(home, extra),
+ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ const stdout = new Response(proc.stdout as ReadableStream).text();
+ const stderr = new Response(proc.stderr as ReadableStream).text();
+ return { proc, out: async () => `${await stdout}\n${await stderr}` };
+}
+
+async function until(pred: () => Promise<boolean> | boolean, ms: number, what: string): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ if (await pred()) return;
+ await Bun.sleep(100);
+ }
+ throw new Error(`timed out waiting for ${what}`);
+}
+
+function alive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+function readPid(path: string): number {
+ return Number(readFileSync(path, 'utf8').trim());
+}
+
+/** Barrier shell job: records each start, then leader + grandchild ignore SIGTERM. */
+function barrierCmd(dir: string): string {
+ return [
+ `echo start >> ${dir}/starts`,
+ `sh -c 'trap "" TERM; echo $$ > ${dir}/grandchild.pid; exec sleep 300' &`,
+ `echo $$ > ${dir}/leader.pid`,
+ `trap "" TERM`,
+ `sleep 301`,
+ ].join('\n');
+}
+
+function events(output: string): Array<Record<string, unknown>> {
+ const rows: Array<Record<string, unknown>> = [];
+ for (const line of output.split('\n')) {
+ if (!line.startsWith('{')) continue;
+ try {
+ const row = JSON.parse(line) as Record<string, unknown>;
+ if (typeof row.event === 'string') rows.push(row);
+ } catch { /* not an event line */ }
+ }
+ return rows;
+}
+
+describeDatabase('#5062 supervisor and worker stop drains real work', () => {
+ let queue: MinionQueue;
+ beforeAll(async () => {
+ await setupDB();
+ queue = new MinionQueue(getEngine());
+ });
+ afterAll(async () => { await teardownDB(); });
+
+ const lockRow = async (queueName: string) => {
+ const rows = await getEngine().executeRaw<{ holder_pid: number; holder_host: string }>(
+ 'SELECT holder_pid, holder_host FROM gbrain_cycle_locks WHERE id = $1', [`gbrain-supervisor:${queueName}`]);
+ return rows[0] ?? null;
+ };
+
+ async function startSupervisorWithBarrier(tag: string) {
+ const home = makeHome(tag);
+ const queueName = `w9-${tag}-${process.pid}`;
+ const pidFile = join(home, 'sup.pid');
+ const sup = spawnCli(home, ['jobs', 'supervisor', 'start', '--queue', queueName, '--allow-shell-jobs', '--json',
+ '--health-interval', '0', '--max-rss', '0', '--pid-file', pidFile]);
+ await until(async () => (await lockRow(queueName)) !== null, 30_000, 'supervisor lock');
+ const job = await queue.add('shell', { cmd: barrierCmd(home), cwd: home }, { queue: queueName }, { allowProtectedSubmit: true });
+ await until(() => existsSync(join(home, 'grandchild.pid')) && existsSync(join(home, 'leader.pid')), 30_000, 'barrier job start');
+ const tree = [readPid(join(home, 'leader.pid')), readPid(join(home, 'grandchild.pid'))];
+ expect(tree.every(alive)).toBe(true);
+ return { home, queueName, pidFile, sup, job, tree };
+ }
+
+ async function expectSettled(s: Awaited<ReturnType<typeof startSupervisorWithBarrier>>, output: string) {
+ const ev = events(output);
+ const names = ev.map(e => e.event);
+ expect(names.filter(n => n === 'shutting_down').length, output).toBe(1);
+ expect(names.filter(n => n === 'stopped').length, output).toBe(1);
+ expect(names.indexOf('stopped')).toBeGreaterThan(names.indexOf('shutting_down'));
+ expect(names.indexOf('shutting_down')).toBeGreaterThan(names.indexOf('worker_spawned'));
+ const stopped = ev.find(e => e.event === 'stopped')!;
+ expect(stopped.drained).toBe(true);
+ expect(stopped.lock_released).toBe(true);
+ expect(await lockRow(s.queueName)).toBeNull();
+ const row = await queue.getJob(s.job.id);
+ expect(row?.status).toBe('waiting');
+ expect(row?.attempts_made).toBe(0);
+ expect(row?.lock_token).toBeNull();
+ expect(s.tree.filter(alive)).toEqual([]);
+ expect(readFileSync(join(s.home, 'starts'), 'utf8').trim().split('\n')).toEqual(['start']);
+ await queue.removeJob(s.job.id);
+ rmSync(s.home, { recursive: true, force: true });
+ }
+
+ test('SIGTERM twice: one ordered drain, lock held through it, second supervisor refused, nothing orphaned', async () => {
+ const s = await startSupervisorWithBarrier('term');
+ const supPid = s.sup.proc.pid;
+ s.sup.proc.kill('SIGTERM');
+ await Bun.sleep(300);
+ s.sup.proc.kill('SIGTERM');
+
+ await Bun.sleep(700);
+ const during = await lockRow(s.queueName);
+ expect(during?.holder_pid).toBe(supPid);
+ expect(during?.holder_host).toBe(hostname());
+ expect(alive(supPid)).toBe(true);
+
+ const second = spawnCli(s.home, ['jobs', 'supervisor', 'start', '--queue', s.queueName, '--json',
+ '--health-interval', '0', '--max-rss', '0', '--pid-file', join(s.home, 'second.pid')],
+ { GBRAIN_SUPERVISOR_LOCK_WAIT_SECONDS: '0' });
+ expect(await second.proc.exited, await second.out()).toBe(2);
+ expect(alive(supPid)).toBe(true);
+
+ expect(await s.sup.proc.exited).toBe(0);
+ await expectSettled(s, await s.sup.out());
+ }, 120_000);
+
+ test('SIGINT drains the same way', async () => {
+ const s = await startSupervisorWithBarrier('int');
+ s.sup.proc.kill('SIGINT');
+ expect(await s.sup.proc.exited).toBe(0);
+ await expectSettled(s, await s.sup.out());
+ }, 120_000);
+
+ test('`jobs supervisor stop` reports drained only after a verified drain', async () => {
+ const s = await startSupervisorWithBarrier('stop');
+ const stop = spawnCli(s.home, ['jobs', 'supervisor', 'stop', '--json', '--pid-file', s.pidFile]);
+ const code = await stop.proc.exited;
+ const out = await stop.out();
+ expect(code, out).toBe(0);
+ const payload = JSON.parse(out.split('\n').find(l => l.startsWith('{"stopped"'))!);
+ expect(payload.reason).toBe('drained');
+ expect(payload.checks).toEqual({
+ process_exited: true, stopped_event: true, worker_drained: true, workers_exited: true, lock_released: true,
+ });
+ expect(await s.sup.proc.exited).toBe(0);
+ await expectSettled(s, await s.sup.out());
+ }, 120_000);
+
+ test('bare `jobs work`: SIGTERM hands the job back and reaps its process group', async () => {
+ const home = makeHome('work');
+ const queueName = `w9-work-${process.pid}`;
+ const job = await queue.add('shell', { cmd: barrierCmd(home), cwd: home }, { queue: queueName }, { allowProtectedSubmit: true });
+ const worker = spawnCli(home, ['jobs', 'work', '--queue', queueName, '--allow-shell-jobs', '--health-interval', '0', '--max-rss', '0']);
+ try {
+ await until(() => existsSync(join(home, 'grandchild.pid')) && existsSync(join(home, 'leader.pid')), 30_000, 'barrier job start');
+ const tree = [readPid(join(home, 'leader.pid')), readPid(join(home, 'grandchild.pid'))];
+ worker.proc.kill('SIGTERM');
+ expect(await worker.proc.exited, await worker.out()).toBe(0);
+ expect(tree.filter(alive)).toEqual([]);
+ const row = await queue.getJob(job.id);
+ expect(row?.status).toBe('waiting');
+ expect(row?.attempts_made).toBe(0);
+ } finally {
+ worker.proc.kill('SIGKILL');
+ await queue.removeJob(job.id);
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 120_000);
+
+ describe('`jobs supervisor stop` fails closed', () => {
+ const FAKE = (home: string) => {
+ const path = join(home, 'fake-supervisor.ts');
+ writeFileSync(path, `
+import { writeFileSync } from 'node:fs';
+import { writeSupervisorEvent } from ${JSON.stringify(join(REPO, 'src/core/minions/handlers/supervisor-audit.ts'))};
+const [mode, pidFile, queue] = process.argv.slice(2);
+writeFileSync(pidFile, String(process.pid));
+const emit = (event: string, extra: Record<string, unknown> = {}) =>
+ writeSupervisorEvent({ event, ts: new Date().toISOString(), ...extra } as never, process.pid);
+emit('started', { queue });
+process.on('SIGTERM', () => {
+ emit('shutting_down', { reason: 'SIGTERM' });
+ if (mode === 'forced') emit('stopped', { drained: false, worker_forced: true });
+ if (mode === 'lock') emit('stopped', { drained: true });
+ process.exit(0);
+});
+console.log('ready');
+setInterval(() => {}, 1000);
+`);
+ return path;
+ };
+
+ async function runFake(mode: string, prepare?: (pid: number, queueName: string) => Promise<void>) {
+ const home = makeHome(`fake-${mode}`);
+ const queueName = `w9-fake-${mode}-${process.pid}`;
+ const pidFile = join(home, 'sup.pid');
+ const fake = Bun.spawn({
+ cmd: [process.execPath, '--no-env-file', FAKE(home), mode, pidFile, queueName],
+ env: childEnv(home), stdin: 'ignore', stdout: 'pipe', stderr: 'inherit',
+ });
+ const reader = (fake.stdout as ReadableStream).getReader();
+ await reader.read();
+ await prepare?.(fake.pid, queueName);
+ const stop = spawnCli(home, ['jobs', 'supervisor', 'stop', '--json', '--pid-file', pidFile]);
+ const code = await stop.proc.exited;
+ const out = await stop.out();
+ fake.kill('SIGKILL');
+ rmSync(home, { recursive: true, force: true });
+ return { code, payload: JSON.parse(out.split('\n').find(l => l.startsWith('{"stopped"'))!) as Record<string, unknown> };
+ }
+
+ test('no `stopped` row after `shutting_down` (the pre-fix exit-143 shape)', async () => {
+ const { code, payload } = await runFake('vanish');
+ expect(code).toBe(1);
+ expect(payload.reason).toBe('no_stopped_event');
+ expect(payload.drained).toBe(false);
+ }, 60_000);
+
+ test('a forced worker stop is never reported as drained', async () => {
+ const { code, payload } = await runFake('forced');
+ expect(code).toBe(1);
+ expect(payload.reason).toBe('forced');
+ }, 60_000);
+
+ test('a queue lock row still held by the exited supervisor', async () => {
+ const { code, payload } = await runFake('lock', async (pid, queueName) => {
+ await getEngine().executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
+ VALUES ($1, $2, $3, now(), now() + interval '5 minutes', now())`,
+ [`gbrain-supervisor:${queueName}`, pid, hostname()]);
+ });
+ expect(code).toBe(1);
+ expect(payload.reason).toBe('lock_still_held');
+ }, 60_000);
+ });
+});
diff --git a/test/e2e/worker-readiness-cli.test.ts b/test/e2e/worker-readiness-cli.test.ts
index 0c1fa51e7e..28b1816fc7 100644
--- a/test/e2e/worker-readiness-cli.test.ts
+++ b/test/e2e/worker-readiness-cli.test.ts
@@ -78,7 +78,9 @@ describeDatabase('worker CLI admission against Postgres', () => {
expect(current?.attempts_made).toBe(0);
expect(current?.stalled_counter).toBe(0);
expect(current?.result?.stdout_tail).toBe('ready-fixture');
- expect(child.exitCode, diagnostic).toBe(143);
+ // #5062: SIGTERM now drains through the worker's signal owner and exits
+ // 0; 143 was the generic cleanup handler killing it before the drain.
+ expect(child.exitCode, diagnostic).toBe(0);
} finally {
if (child.exitCode === null) child.kill('SIGKILL');
await child.exited;
@@ -120,7 +122,9 @@ describeDatabase('worker CLI admission against Postgres', () => {
expect(diagnostic).not.toContain('could not be published');
expect(current?.status, diagnostic).toBe('completed');
expect(current?.result?.stdout_tail).toBe('legacy-owner-fixture');
- expect(child.exitCode, diagnostic).toBe(143);
+ // #5062: SIGTERM now drains through the worker's signal owner and exits
+ // 0; 143 was the generic cleanup handler killing it before the drain.
+ expect(child.exitCode, diagnostic).toBe(0);
} finally {
if (child.exitCode === null) child.kill('SIGKILL');
await child.exited;
diff --git a/test/process-cleanup.test.ts b/test/process-cleanup.test.ts
index f3353e9629..4a97b9ae78 100644
--- a/test/process-cleanup.test.ts
+++ b/test/process-cleanup.test.ts
@@ -23,6 +23,7 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import {
registerCleanup,
+ registerSignalOwner,
triggerCleanupAndExit,
installSignalHandlers,
_registeredCleanupCountForTests,
@@ -253,3 +254,64 @@ describe('installSignalHandlers', () => {
expect(process.stderr.listenerCount('error')).toBe(before.stderrErr);
});
});
+
+describe('registerSignalOwner (#5062)', () => {
+ test('an owner receives every termination signal; nothing runs cleanup or exits behind its back', async () => {
+ let cleanupRan = false;
+ registerCleanup('supervisor-lock', async () => { cleanupRan = true; });
+ const seen: string[] = [];
+ registerSignalOwner('supervisor', (signal) => { seen.push(signal); });
+ const exits: number[] = [];
+ const origExit = process.exit;
+ (process as any).exit = (code?: number) => { exits.push(code ?? 0); };
+ try {
+ installSignalHandlers();
+ process.emit('SIGTERM');
+ process.emit('SIGTERM');
+ process.emit('SIGHUP');
+ process.emit('SIGPIPE');
+ process.stdout.emit('error', Object.assign(new Error('write EPIPE'), { code: 'EPIPE' }));
+ await new Promise(r => setTimeout(r, 20));
+ } finally {
+ (process as any).exit = origExit;
+ }
+ expect(seen).toEqual(['SIGTERM', 'SIGTERM', 'SIGHUP', 'SIGPIPE', 'SIGPIPE']);
+ expect(exits).toEqual([]);
+ expect(cleanupRan).toBe(false);
+ });
+
+ test('the owner exits through triggerCleanupAndExit, which still runs the remaining callbacks', async () => {
+ let cleanupRan = false;
+ registerCleanup('other-lock', async () => { cleanupRan = true; });
+ const exits: number[] = [];
+ const origExit = process.exit;
+ (process as any).exit = (code?: number) => { exits.push(code ?? 0); };
+ try {
+ registerSignalOwner('supervisor', () => { void triggerCleanupAndExit(0); });
+ installSignalHandlers();
+ process.emit('SIGTERM');
+ await new Promise(r => setTimeout(r, 20));
+ } finally {
+ (process as any).exit = origExit;
+ }
+ expect(cleanupRan).toBe(true);
+ expect(exits).toEqual([0]);
+ });
+
+ test('after deregistration the generic cleanup-then-exit path is back', async () => {
+ const release = registerSignalOwner('worker', () => { throw new Error('must not be called'); });
+ release();
+ release();
+ const exits: number[] = [];
+ const origExit = process.exit;
+ (process as any).exit = (code?: number) => { exits.push(code ?? 0); };
+ try {
+ installSignalHandlers();
+ process.emit('SIGTERM');
+ await new Promise(r => setTimeout(r, 20));
+ } finally {
+ (process as any).exit = origExit;
+ }
+ expect(exits).toEqual([143]);
+ });
+});