Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): GBRA-130 A-30 charge only a job that trips the RSS watchdog alone
garrytandf14896c6c87
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 2e62832f8b..88a4718ddb 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE.+- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `prune()` archives each completed `dream:synth%` subagent key into `dream_synthesis_completions` in the same statement that deletes the row, so pruning never re-arms paid synthesis. `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). The same trusted arg carries `{allowPgliteInlineWorker: true}`, a narrowly scoped exception used only when `gbrain jobs submit embed-backfill --follow` starts and awaits a worker in that process. Before config, schema, policy, SQL, or transaction access, `add()` invokes the centralized embed-backfill admission gate; PGLite and unknown engine kinds refuse, while explicit Postgres preserves queued submission. `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). The submission backpressure guard covers two options sharing one `pg_advisory_xact_lock` namespace keyed on `(name, queue, source)`: `maxWaiting` (rate cap, counts `waiting` only, NULL-source-as-wildcard scope) and `maxPending` (single-flight, counts `waiting` + live-lock `active` rows where `lock_until > now()`, EXACT source scope via `COALESCE(data->>'sourceId', data->>'source_id')` — an expired-lock active never suppresses, keeping the waitingClaimable wedge detectors fed). All three coalesce return paths (idempotency fast-path, cap-hit, ON CONFLICT race fallback) stamp non-persisted `coalesced: true` metadata on the returned job. Both filter on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other. `claim` and `renewLock` issue their UPDATE via `engine.executeRawDirect` (not `executeRaw`) so the lock heartbeat runs on the direct session-mode pool that the transaction pooler won't recycle mid-hold; on PGLite this is identical to `executeRaw`. The two terminal dead-letter paths (`handleWallClockTimeouts` wall-clock kill and the stall dead-letter CTE in the stall sweep) BOTH increment `attempts_made` so a long job killed there reads as an honest attempt instead of `attempts 0 / started N`; the stall path also bumps `stalled_counter`, surfaced by `gbrain jobs get` as `Attempts: M/N (started: X, stalled: S/MaxS)`. At submit, `add()` stamps a default `timeout_ms` via `defaultTimeoutMsFor(jobName)` (from `handler-timeouts.ts`) when the caller passed none, and `claim()` COALESCEs a still-NULL `timeout_ms` from `HANDLER_DEFAULT_TIMEOUT_MS` (raw-object jsonb bind) deriving `timeout_at` from the coalesced value — the durable invariant covering rows that predate submit-time stamping; an explicit `opts.timeout_ms` always wins. The lock lease follows the identical three-layer shape: `add()` stamps `opts.lock_duration_ms` (clamped [5s,1h] via the shared `clampLockDurationMs`; INSERT-only — an idempotency-key re-submit never mutates the first submitter's lease) else `defaultLockDurationMsFor(jobName)`; `claim()` derives `lock_until` from `COALESCE(lock_duration_ms, map, worker default)` and stamps the resolved lease, SQL-clamping the row/map-resolved value to [5s,1h] (the worker-default fallback passes through unclamped — operator-configured, and tests legitimately use sub-5s leases) so a bypass-written out-of-range row can't produce a pathological lease; `handleWallClockTimeouts`' null-timeout fallback uses `COALESCE(lock_duration_ms, worker default)`. `handleStalled(graceMsOverride?)` applies the stall-sweep reclaim grace (`GBRAIN_MINION_STALL_RECLAIM_GRACE_MS`, default 15s, 0 = legacy predicate, capped at 600s with a warn-once clamp so an oversized value can't disable stalled-job recovery) to all three sweep predicates — a lease that lapsed within the grace is a starved owner's head start, not a steal candidate. Guarded by `test/queue-lock-retry.test.ts` (claim never falls back to `executeRaw`), `test/postgres-execute-raw-direct.test.ts` (routing decision matrix), and `test/minions.test.ts` (attempt accounting + default-timeout stamping). `MinionQueue.add()` gates `subagent` jobs on capability, not provider: `data.model` is classified via `classifyCapabilities()` (lazy-imported from `src/core/ai/capabilities.ts` to keep queue's eager-load surface small) and rejected only when the model cannot run a tool loop (`unusable:no_tools`) or names an unknown provider; degraded verdicts pass through with a gateway cost warning. Layer 1 of the three-layer subagent capability enforcement (layers 2+3: `model-config.ts:enforceSubagentCapable` runtime fallback + `src/commands/doctor/checks/search-eval.ts` `subagent_capability` check). Pinned by `test/agent-cli.test.ts`. All three terminal reaper paths (stall dead-letter, wall-clock kill, cascade) route through the ONE private `killJobs(tx, rows, cause, message)` tail: it emits `child_done(outcome)` to each non-terminal parent's inbox and flips any `waiting-children` parent whose last open child just died back to `waiting` — so a dead-lettered child can never strand its aggregator parent. Callers lock parents FIRST via `lockParentsOrdered` (ascending-id row locks, matching `failJob`'s parent-before-child order) so the reapers and `failJob` can never deadlock on parent/child lock acquisition. An idempotent stranded-parent sweep runs once per stall tick (~30s): any `waiting-children` parent with zero non-terminal children flips back to `waiting` (single UPDATE, NOT EXISTS on an indexed FK) — self-heals every stranding class, including parents stranded before the sweep existed. Every automatic re-run path clears `started_at` (`failJob`'s delayed retry branch, the stall requeue, lease release, `promoteDelayed`, and the parent-unblock flips) so the per-attempt wall clock measures execution, not backoff/queue wait — a retried job can't be dead-lettered by the wall-clock sweep before executing a line. Pinned by `test/queue-stall-parent-unblock.test.ts` + `test/queue-started-at-retry.test.ts`. `renewLock` accepts optional `{signal}` forwarded to executeRawDirect so the renewal tick's timeout race CANCELS a hung UPDATE instead of orphaning a checked-out pool slot (best-effort — the token fence is the correctness authority; a late-landing renewal can only extend a lease nobody else claimed). Re-submitting an idempotency key held by a dead or cancelled row nulls that row's key and records it as `data.__released_idempotency_key`, so the dream paid-loop breaker and daily cap still see the death. The trusted arg's `spendAuthorization` stores a consent-gated producer's record in `spend_authorization` (never job data); a coalesced live row with no record or a `legacy_default` record adopts it by compare-and-set, an `authorized` row keeps its own. `claim()` sets `spend_claim_token = claim_generation + 1` (the fence the protocol trigger requires for spend-authorized rows, so older workers cannot claim them) and stamps NULL rows of `book-mirror:`/`enrich:`/`cli:enrich:` keys `legacy_default` in the same UPDATE. `claim(..., { excludeWatchdogSuspects })` skips jobs carrying `WATCHDOG_SUSPECT_MARK` (re-exported from `watchdog-attribution.ts`) for a worker with jobs in flight; `releaseWatchdogClaim` is the token-fenced uncharged release; `handleStalled` first passes its candidates to `requeueCoRunnerStalls`.- `src/core/minions/rate-leases.ts` — lease-based concurrency cap for outbound providers (default key `anthropic:messages`, max via `GBRAIN_ANTHROPIC_MAX_INFLIGHT`). Owner-tagged rows with `expires_at` auto-prune on acquire; `pg_advisory_xact_lock` guards check-then-insert; CASCADE on owning job deletion. `renewLeaseWithBackoff` retries 3x (250/500/1000ms). Canonical home of `RateLeaseUnavailableError` (thrown when acquire finds no slot; the worker and the inline dream drain both recognize it and requeue WITHOUT burning an attempt — lease-full is a scheduling condition, not a failure; `subagent.ts` re-exports it for compatibility) and `leaseFullBackoffMs()` (the shared 1–3s jittered lease-full requeue backoff `worker.ts` and `inline-drain.ts` both use, so the two curves cannot silently desync).@@ -37,4 +37,6 @@ 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. #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 (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), 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). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the `aborted: <reason>` path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired).+- `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 (`worker-shutdown.ts`: token-fenced, no attempt burned, `error_text = 'worker_shutdown: <handler error>'`); any handler error during shutdown is presumed shutdown-induced (`endedByShutdown` in `worker-shutdown.ts`) except `UnrecoverableError`, which dead-letters with its original text (W9F Decision 7; in-process and, for a child whose stop is confirmed, isolated; `test/worker-shutdown-error-matrix.test.ts`), 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). The RSS watchdog's `gracefulShutdown(reason)` aborts every `inFlight` job and records the reason; a claim whose `UPDATE … RETURNING` committed before the shutdown but whose result had not reached the poll loop is not in `inFlight` yet, so `launchJob` aborts it with the recorded reason as soon as it registers it, and the job takes the abort path instead of running unaborted through the drain (forced case in `test/worker-shutdown-error-matrix.test.ts`, which holds the claim result until the watchdog has fired). Each `inFlight` entry carries `shared` (another job ran beside it, or it registered after the drain began); the catch hands a watchdog-aborted shared job to `settleWatchdogAbort` (back to `waiting` uncharged, marked to run alone), so only a job that ran alone is charged `aborted: watchdog`, and it is marked too. A worker running a marked job claims nothing else, and a worker with jobs in flight claims no marked job.++- `src/core/minions/watchdog-attribution.ts` — RSS watchdog attribution (GBRA-130 A-30). The watchdog measures the whole worker process, so a drain with several jobs in flight cannot name the job that grew: `settleWatchdogAbort` requeues each such job token-fenced with no attempt burned (`error_text` `WATCHDOG_DRAIN_RELEASE`) and appends `WATCHDOG_SUSPECT_MARK` once to its `stacktrace`, the job's durable history; a job that ran alone is marked and its caller charges it. An isolated child whose stop is unconfirmed, or any error during the release, leaves the claim to the stall sweep. `unmarkedJobSql` is the claim filter. `requeueCoRunnerStalls` requeues, marked and with no stall counted, the stalled claims of a worker that held other expired claims (lock tokens share the `<worker id>:` prefix, or a co-runner was already requeued with `worker_stalled_with_co_runners: <worker id>`); a marked or lone job's stall counts as before, so a kernel OOM kill gets the same attribution. Doctor's watchdog-kill counts (`error_text = 'aborted: watchdog'` on dead/failed rows) therefore count only jobs charged for a solo trip. Pinned by `test/pathological/a30-watchdog-attribution.test.ts` (both engines) and `test/worker-shutdown-error-matrix.test.ts`.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ebfcfd6f82..7fc551a242 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -24,12 +24,12 @@ src/core/pglite-engine.ts 3083 ratchet +5 agent operator gate fixes: repair-failsrc/core/postgres-engine.ts 3105 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane mergesrc/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.tssrc/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)-src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)+src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)-src/core/minions/worker.ts 1777 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired+src/core/minions/worker.ts 1782 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired; +5 GBRA-130 A-30: watchdog-attribution import, InFlightJob.shared (interface field), the suspect-alone claim gate and option, and the watchdog settle call in the executeJob catch (logic in minions/watchdog-attribution.ts)src/commands/sources.ts 2059 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help rowsrc/core/link-extraction.ts 2421 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts); +1 at the #6869 gate-ahead merge: the #6803 wave EXTRACTOR_BUMP_NOTES comment composed with lane 2e (2420 + 1)src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budgetdiff --git a/src/core/minions/queue.ts b/src/core/minions/queue.tsindex 20f2b17671..05f871fa16 100644--- a/src/core/minions/queue.ts+++ b/src/core/minions/queue.ts@@ -15,6 +15,8 @@ import type {MinionQueueOpts, ChildDoneMessage, ChildOutcome, Attachment, AttachmentInput,} from './types.ts';import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';+import { WATCHDOG_SUSPECT_MARK, releaseWatchdogClaim, requeueCoRunnerStalls, unmarkedJobSql } from './watchdog-attribution.ts';+export { WATCHDOG_SUSPECT_MARK } from './watchdog-attribution.ts';import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';import { adoptSpendAuthorization, legacyDefaultClaimSetSql, legacyDefaultClaimParams, type SpendAuthorization } from './spend-authorization.ts';import { validateAttachment } from './attachments.ts';@@ -1440,7 +1442,8 @@ export class MinionQueue {* The map binds as a RAW object (never JSON.stringify into ::jsonb — the* postgres.js double-encode trap; PGLite hides it, real PG does not).*/- async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[]): Promise<MinionJob | null> {+ /** `excludeWatchdogSuspects`: a worker with jobs in flight never claims a job marked by a shared watchdog drain (watchdog-attribution.ts). */+ async claim(lockToken: string, lockDurationMs: number, queue: string, registeredNames: string[], opts: { excludeWatchdogSuspects?: boolean } = {}): Promise<MinionJob | null> {if (registeredNames.length === 0) return null;await assertNoUnreviewedJobs(this.engine);@@ -1478,17 +1481,21 @@ export class MinionQueue {updated_at = now()WHERE id = (SELECT id FROM minion_jobs- WHERE queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND name = ANY($4)+ WHERE queue = $3 AND status = 'waiting' AND submission_authority IS NOT NULL AND name = ANY($4)${opts.excludeWatchdogSuspects ? ` AND ${unmarkedJobSql('$9')}` : ''}ORDER BY priority ASC, created_at ASCFOR UPDATE SKIP LOCKEDLIMIT 1)RETURNING *`,- [lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS, HANDLER_DEFAULT_LOCK_DURATION_MS, ...legacyDefaultClaimParams()]+ [lockToken, lockDurationMs, queue, registeredNames, HANDLER_DEFAULT_TIMEOUT_MS, HANDLER_DEFAULT_LOCK_DURATION_MS, ...legacyDefaultClaimParams(),+ ...(opts.excludeWatchdogSuspects ? [WATCHDOG_SUSPECT_MARK] : [])]);return rows.length > 0 ? rowToMinionJob(rows[0]) : null;}+ /** A co-runner of a watchdog drain back to waiting, marked, no attempt burned (token-fenced). */+ releaseWatchdogClaim(id: number, lockToken: string, errorText: string): Promise<boolean> { return releaseWatchdogClaim(this.engine, id, lockToken, errorText); }+/*** Dead-letter active jobs whose timeout_at has passed.*@@ -2140,11 +2147,13 @@ export class MinionQueue {[graceMs]);if (candidates.length === 0) return { requeued: [], dead: [] };- const ids = candidates.map(c => c.id);+ // GBRA-130 A-30: the claims of a worker that held several (a kernel OOM kill) requeue marked, no stall counted.+ const coRunners = await requeueCoRunnerStalls(tx, candidates, graceMs);+ const ids = coRunners.rest.map(c => c.id);// Only the dead-letter branch touches parents; lock just those, sorted.await this.lockParentsOrdered(tx,- candidates.filter(c => Number(c.stalled_counter) + 1 >= Number(c.max_stalled)),+ coRunners.rest.filter(c => Number(c.stalled_counter) + 1 >= Number(c.max_stalled)),);const requeuedRows = await tx.executeRaw<Record<string, unknown>>(@@ -2184,7 +2193,7 @@ export class MinionQueue {// other terminal kill. Outcome 'dead' (not 'timeout') so consumers can// distinguish "died via max-stall" from "timed out during run".await this.killJobs(tx, deadRows, 'dead', 'max stalled count exceeded');- return { requeued: requeuedRows.map(rowToMinionJob), dead: deadRows.map(rowToMinionJob) };+ return { requeued: [...coRunners.requeued, ...requeuedRows].map(rowToMinionJob), dead: deadRows.map(rowToMinionJob) };}).then(async (result) => {// W0 ship-review (data-migration): the per-kill unblock above is// forward-only — parents stranded in 'waiting-children' by PRE-upgradediff --git a/src/core/minions/watchdog-attribution.ts b/src/core/minions/watchdog-attribution.tsnew file mode 100644index 0000000000..8664404e8b--- /dev/null+++ b/src/core/minions/watchdog-attribution.ts@@ -0,0 +1,139 @@+/**+ * Watchdog attribution (GBRA-130 A-30): an RSS watchdog drain, or a worker the+ * kernel killed, charges only the job that was running alone.+ *+ * The RSS watchdog measures the whole worker process, so when it trips with+ * several jobs in flight it cannot tell which one grew. Each job that shared+ * the drain goes back to the queue with no attempt burned and+ * `WATCHDOG_SUSPECT_MARK` appended to its history (`stacktrace`, append-only,+ * so the mark outlives the worker and survives handler progress writes). A+ * marked job is claimed only by a worker with nothing in flight, and that+ * worker claims nothing else beside it (worker.ts), so the next trip is+ * attributable: a job that trips the watchdog while it ran alone is charged+ * (an attempt, dead at max attempts) and stays marked.+ *+ * A worker the kernel OOM-kills leaves every claim to the stall sweep. A+ * stalled job whose worker held other expired claims (lock tokens share+ * the `<worker id>:` prefix, or a co-runner of that worker was already+ * requeued this way) is requeued with the mark and no stall counted; a marked or lone+ * job's stall counts as before.+ */+import type { BrainEngine } from '../engine.ts';+import type { MinionQueue } from './queue.ts';+import type { MinionJob } from './types.ts';++/** The history entry that marks a job a watchdog drain or a dead worker could not clear: it runs alone from then on. */+export const WATCHDOG_SUSPECT_MARK = 'rss_watchdog_suspect: an RSS watchdog drain or a worker kill could not be attributed to this job alone; it runs alone from now on';++/** SQL that appends the mark ($n) to `stacktrace` once. */+export function appendSuspectMarkSql(param: string): string {+ return `CASE WHEN COALESCE(stacktrace, '[]'::jsonb) @> jsonb_build_array(${param}::text) THEN stacktrace+ ELSE COALESCE(stacktrace, '[]'::jsonb) || jsonb_build_array(${param}::text) END`;+}++/** SQL true for a job carrying the mark ($n). */+function markedJobSql(param: string): string {+ return `(COALESCE(stacktrace, '[]'::jsonb) @> jsonb_build_array(${param}::text))`;+}++/** SQL true for a job without the mark ($n): what a worker with other jobs in flight may claim. */+export function unmarkedJobSql(param: string): string {+ return `NOT ${markedJobSql(param)}`;+}++/** A co-runner of a watchdog drain back to `waiting`, token-fenced, marked, no attempt burned. False when the claim moved on. */+export async function releaseWatchdogClaim(engine: BrainEngine, id: number, lockToken: string, errorText: string): Promise<boolean> {+ const rows = await engine.executeRaw<{ id: number }>(+ `UPDATE minion_jobs SET status = 'waiting', error_text = $3, stacktrace = ${appendSuspectMarkSql('$4')},+ 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, errorText, WATCHDOG_SUSPECT_MARK],+ );+ return rows.length > 0;+}++/**+ * The worker's catch for a job the watchdog drain aborted. True when it is+ * settled here (`shared`: requeued uncharged and marked); false for a job that+ * ran alone, which is marked and left for the caller to charge.+ */+export async function settleWatchdogAbort(queue: Pick<MinionQueue, 'releaseWatchdogClaim'>, engine: BrainEngine, job: MinionJob, lockToken: string, shared: boolean, stopped: boolean): Promise<boolean> {+ if (shared) {+ await releaseWatchdogCoRunner(queue, job, lockToken, stopped);+ return true;+ }+ await markWatchdogSuspect(engine, job.id);+ return false;+}++/** Keeps a job charged for a solo trip marked, so its retry runs alone too. Best-effort: the charge does not depend on it. */+async function markWatchdogSuspect(engine: BrainEngine, id: number): Promise<void> {+ try {+ await engine.executeRaw(`UPDATE minion_jobs SET stacktrace = ${appendSuspectMarkSql('$2')} WHERE id = $1`, [id, WATCHDOG_SUSPECT_MARK]);+ } catch (e) {+ console.error(`[worker] could not mark job ${id} to run alone after its RSS watchdog trip: ${e instanceof Error ? e.message : String(e)}`);+ }+}++/** Whether a job carries the mark: a worker runs it alone. */+export const isWatchdogSuspect = (job: MinionJob): boolean => job.stacktrace.includes(WATCHDOG_SUSPECT_MARK);++/** The error text of a job a watchdog drain requeued uncharged. */+export const WATCHDOG_DRAIN_RELEASE = 'rss_watchdog_drain: the RSS watchdog drained the worker and could not attribute it to this job alone; requeued with no attempt burned';++/**+ * A job the watchdog drain aborted while another job shared the worker, or+ * that was claimed as the drain began: back to `waiting`, marked, no attempt+ * burned. An isolated child whose stop is+ * unconfirmed, or any error releasing the claim (the worker is exiting), leaves+ * the claim to the stall sweep, which attributes a dead worker's claims the+ * same way.+ */+async function releaseWatchdogCoRunner(queue: Pick<MinionQueue, 'releaseWatchdogClaim'>, job: MinionJob, lockToken: string, stopped: boolean): Promise<void> {+ if (!stopped) {+ console.log(`Job ${job.id} (${job.name}) shared an RSS watchdog drain and its child's stop is unconfirmed; stall detector will requeue (no attempt burned)`);+ return;+ }+ try {+ const released = await queue.releaseWatchdogClaim(job.id, lockToken, WATCHDOG_DRAIN_RELEASE);+ console.log(`Job ${job.id} (${job.name}) ${released ? 'requeued to run alone' : 'claim already moved on'} after sharing an RSS watchdog drain (no attempt burned)`);+ } catch (e) {+ console.error(`[worker] watchdog release failed for job ${job.id}; stall detector will requeue: ${e instanceof Error ? e.message : String(e)}`);+ }+}+++const CO_RUNNER_STALL = 'worker_stalled_with_co_runners: ';+const workerOf = (token: string | null): string | null => token && token.includes(':') ? token.slice(0, token.indexOf(':')) : null;++/**+ * The stalled candidates whose worker held other expired claims (a live+ * worker keeps renewing the claims it still runs), requeued with the+ * mark and no stall counted (FOR UPDATE SKIP LOCKED, with the sweep's grace).+ * Returns the requeued rows and the candidates left to the counting sweep.+ */+export async function requeueCoRunnerStalls<C extends { id: number }>(tx: BrainEngine, candidates: C[], graceMs: number): Promise<{ requeued: Record<string, unknown>[]; rest: C[] }> {+ const rows = await tx.executeRaw<{ id: number; lock_token: string | null; marked: boolean }>(+ `SELECT id, lock_token, ${markedJobSql('$2')} AS marked FROM minion_jobs WHERE status = 'active' AND (lock_until < now() OR id = ANY($1::bigint[]))`,+ [candidates.map(c => c.id), WATCHDOG_SUSPECT_MARK]);+ const evidence = new Set((await tx.executeRaw<{ error_text: string }>(+ `SELECT DISTINCT error_text FROM minion_jobs WHERE status IN ('waiting', 'active', 'delayed') AND starts_with(error_text, $1)`, [CO_RUNNER_STALL])).map(r => r.error_text));+ const perWorker = new Map<string, number>();+ for (const row of rows) { const worker = workerOf(row.lock_token); if (worker) perWorker.set(worker, (perWorker.get(worker) ?? 0) + 1); }+ const byId = new Map(rows.map(row => [Number(row.id), row]));+ const shared = new Set(candidates.filter(c => {+ const row = byId.get(Number(c.id));+ const worker = workerOf(row?.lock_token ?? null);+ return row && !row.marked && worker !== null && ((perWorker.get(worker) ?? 0) > 1 || evidence.has(CO_RUNNER_STALL + worker));+ }).map(c => Number(c.id)));+ if (shared.size === 0) return { requeued: [], rest: candidates };+ const requeued = await tx.executeRaw<Record<string, unknown>>(+ `UPDATE minion_jobs SET status = 'waiting', error_text = $3 || split_part(lock_token, ':', 1), stacktrace = ${appendSuspectMarkSql('$4')},+ started_at = NULL, lock_token = NULL, lock_until = NULL, updated_at = now()+ WHERE id IN (SELECT id FROM minion_jobs WHERE id = ANY($1::bigint[]) AND status = 'active'+ AND lock_until < now() - ($2::double precision * interval '1 millisecond') FOR UPDATE SKIP LOCKED)+ RETURNING *`,+ [[...shared], graceMs, CO_RUNNER_STALL, WATCHDOG_SUSPECT_MARK]);+ return { requeued, rest: candidates.filter(c => !shared.has(Number(c.id))) };+}diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 4fdf5c6dde..109c24fafa 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -87,6 +87,7 @@ import { randomUUID } from 'crypto';import { EventEmitter } from 'events';import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';import { endedByShutdown, releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';+import { isWatchdogSuspect, settleWatchdogAbort } from './watchdog-attribution.ts';import { readFileSync } from 'fs';/**@@ -185,6 +186,8 @@ interface InFlightJob {lockTimer: ReturnType<typeof setInterval>;abort: AbortController;promise: Promise<void>;+ /** Another job ran beside it, or it registered after a drain began: an RSS watchdog drain requeues it uncharged and marked (watchdog-attribution.ts). */+ shared: boolean;}export interface ConfigurationReleaseResult {@@ -838,7 +841,7 @@ export class MinionWorker extends EventEmitter {console.log('[worker] pause marker cleared — resuming job claims.');this.pausedByMarkerAnnounced = false;}- if (this.inFlight.size < this.opts.concurrency) {+ if (this.inFlight.size < this.opts.concurrency && ![...this.inFlight.values()].some(f => isWatchdogSuspect(f.job))) {const lockToken = `${this.workerId}:${randomUUID()}`;let job: MinionJob | null;try {@@ -847,6 +850,7 @@ export class MinionWorker extends EventEmitter {this.opts.lockDuration,this.opts.queue,this.registeredNames,+ { excludeWatchdogSuspects: this.inFlight.size > 0 },).then(claimed => {if (claimed) {this.executions.set(lockToken, { job: claimed, lockToken, stopped: true });@@ -1462,7 +1466,8 @@ export class MinionWorker extends EventEmitter {} catch { /* audit best-effort */ }});- this.inFlight.set(job.id, { job, lockToken, lockTimer, abort, promise });+ for (const entry of this.inFlight.values()) entry.shared = true;+ this.inFlight.set(job.id, { job, lockToken, lockTimer, abort, promise, shared: this.inFlight.size > 0 || this.gracefulShutdownReason !== null });execution.promise = promise;if (this.gracefulShutdownReason !== null && !abort.signal.aborted) abort.abort(new Error(this.gracefulShutdownReason));}@@ -1580,8 +1585,7 @@ export class MinionWorker extends EventEmitter {// already flipped status, our call no-ops cleanly. The prior silent-return// left jobs stranded in 'active' until a secondary sweep, breaking// timeout/cancel contracts downstream callers rely on.- let errorText: string;- let abortReason: string | null = null;+ let errorText: string, abortReason: string | null = null;if (abort.signal.aborted) {abortReason = abort.signal.reason instanceof Error? abort.signal.reason.message@@ -1590,6 +1594,7 @@ export class MinionWorker extends EventEmitter {} else {errorText = err instanceof Error ? err.message : String(err);}+ if (abortReason === 'watchdog' && await settleWatchdogAbort(this.queue, this.engine, job, lockToken, this.inFlight.get(job.id)?.shared !== false, execution?.stopped !== false)) return;// v0.41.22.2 (D8a / codex C6): infrastructure aborts (lock-renewal-failed,// lock-lost) are NOT job defects — they're connection / coordinationdiff --git a/test/pathological/a30-watchdog-attribution.test.ts b/test/pathological/a30-watchdog-attribution.test.tsnew file mode 100644index 0000000000..acde0041af--- /dev/null+++ b/test/pathological/a30-watchdog-attribution.test.ts@@ -0,0 +1,159 @@+/**+ * A-30 (GBRA-130): an RSS watchdog drain charges only the job that trips the+ * watchdog while running alone, never the jobs that shared the worker.+ *+ * Protects: with concurrency 2, a job whose memory crosses --max-rss next to+ * an innocent job makes the watchdog drain both, and both go back to the queue+ * with no attempt burned and a persisted watchdog mark (the job's history+ * records it, so the mark survives the worker's exit); a marked job is then+ * claimed only when nothing else runs and nothing else is claimed beside it,+ * so the hog trips alone and is charged (delayed, then dead at max attempts)+ * while the innocent job keeps its attempts and lands on its own run. The+ * kernel OOM variant (the process dies, every lease expires) gets the same+ * attribution: stalled jobs whose worker held others are requeued with the+ * mark and no stall counted, and a marked job's solo stall counts. A lone job+ * that trips the watchdog is charged as before. A run-scoped failure while+ * releasing a co-runner leaves its claim for the stall sweep, unmarked and+ * uncharged.+ * Fails when: the drain aborts every job with reason `watchdog` and the+ * catch charges each one (`attempts_made` + 1 for the innocent job), a marked+ * job is claimed beside another job, or the stall sweep counts a stall against+ * every job of a dead worker.+ * Seams: `getRss` (the worker option the watchdog tests use) reports the+ * hog's memory; the run case wraps the worker's queue method. PGLite always,+ * Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { MinionQueue, WATCHDOG_SUSPECT_MARK } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import type { MinionJob, MinionJobContext } from '../../src/core/minions/types.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { expectItemFailure, expectUnitNotAborted, pathologicalArms, runScopedErrors } from './harness.ts';++const MB = 1024 * 1024;++interface Run { worker: MinionWorker; started: Set<string>; maxConcurrent: number }++/** A worker whose RSS reads over the cap while `hogging()` is true; handlers wait for their abort unless `finish` lets them return. */+function makeWorker(engine: BrainEngine, hogging: () => boolean, finish: Set<string>): Run {+ const worker = new MinionWorker(engine, { concurrency: 2, maxRssMb: 100, getRss: () => (hogging() ? 500 : 10) * MB, rssCheckInterval: 20,+ pollInterval: 10, lockDuration: 60_000, healthCheckInterval: 0, stalledInterval: 600_000 });+ const run: Run = { worker, started: new Set(), maxConcurrent: 0 };+ let running = 0;+ const handler = (name: string) => async (ctx: MinionJobContext) => {+ run.started.add(name);+ running++;+ run.maxConcurrent = Math.max(run.maxConcurrent, running);+ try {+ if (finish.has(name)) return { ok: true };+ await new Promise<void>((_, reject) => ctx.signal.addEventListener('abort', () => reject(new Error(`${name} stopped`)), { once: true }));+ } finally { running--; }+ };+ for (const name of ['hog', 'sleeper', 'solo']) worker.register(name, handler(name));+ return run;+}++const row = async (queue: MinionQueue, id: number) => {+ const job = (await queue.getJob(id)) as MinionJob;+ return { status: job.status, attempts: job.attempts_made, error: job.error_text, marked: job.stacktrace.includes(WATCHDOG_SUSPECT_MARK) };+};++async function waitFor(check: () => Promise<boolean> | boolean, what: string) {+ for (let i = 0; i < 1000; i++) { if (await check()) return; await Bun.sleep(10); }+ throw new Error(`timed out waiting for ${what}`);+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-30 watchdog attribution (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); }, 120_000);+ afterAll(async () => { await close(); });++ test('A-30 item: a drain shared with an innocent job charges neither; the marked hog re-runs alone and is charged; the innocent job lands', async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ const queue = new MinionQueue(engine);+ const hog = await queue.add('hog', {}, { max_attempts: 2, backoff_delay: 60_000 }, { allowProtectedSubmit: true });+ const sleeper = await queue.add('sleeper', {}, { max_attempts: 2, backoff_delay: 60_000 }, { allowProtectedSubmit: true });++ let hogging = false;+ const first = makeWorker(engine, () => hogging, new Set());+ const running = first.worker.start();+ await waitFor(() => first.started.has('hog') && first.started.has('sleeper'), 'both jobs running');+ hogging = true;+ await expectUnitNotAborted(() => running);+ expect(first.worker.rssWatchdogTriggered).toBe(true);+ expect(await row(queue, sleeper.id)).toMatchObject({ status: 'waiting', attempts: 0, marked: true });+ expect(await row(queue, hog.id)).toMatchObject({ status: 'waiting', attempts: 0, marked: true });++ hogging = false;+ const second = makeWorker(engine, () => second.started.has('hog') && second.started.size === 1, new Set());+ await expectUnitNotAborted(() => second.worker.start());+ expect([...second.started]).toEqual(['hog']);+ expect(second.maxConcurrent).toBe(1);+ const charged = await row(queue, hog.id);+ expect(charged).toMatchObject({ status: 'delayed', attempts: 1, marked: true });+ expectItemFailure({ key: String(hog.id), code: charged.error ?? undefined }, { key: String(hog.id), code: 'aborted: watchdog' });+ expect(await row(queue, sleeper.id)).toMatchObject({ status: 'waiting', attempts: 0 });++ const third = makeWorker(engine, () => false, new Set(['sleeper']));+ const done = third.worker.start();+ await waitFor(async () => (await row(queue, sleeper.id)).status === 'completed', 'the innocent job to complete');+ third.worker.stop();+ await done;+ expect(third.maxConcurrent).toBe(1);+ expect(await row(queue, sleeper.id)).toMatchObject({ status: 'completed', attempts: 0 });+ }, 60_000);++ test('A-30 item: a job alone in the worker that trips the watchdog is charged, and at max attempts dead-letters', async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ const queue = new MinionQueue(engine);+ const solo = await queue.add('solo', {}, { max_attempts: 1 }, { allowProtectedSubmit: true });+ const run = makeWorker(engine, () => run.started.has('solo'), new Set());+ await expectUnitNotAborted(() => run.worker.start());+ expect(await row(queue, solo.id)).toMatchObject({ status: 'dead', attempts: 1, error: 'aborted: watchdog' });+ }, 60_000);++ test('A-30 item: the stall sweep requeues the jobs of a dead worker that held several with the mark and no stall counted; a marked solo stall counts', async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ const queue = new MinionQueue(engine);+ const ids: number[] = [];+ for (const name of ['hog', 'sleeper', 'solo', 'solo']) ids.push((await queue.add(name, {}, { max_attempts: 3 }, { allowProtectedSubmit: true })).id);+ const [a, b, lone, marked] = ids as [number, number, number, number];+ const stall = (id: number, token: string, expiredMs: number) => engine.executeRaw(+ `UPDATE minion_jobs SET status = 'active', lock_token = $2, lock_until = now() - ($3::double precision * interval '1 millisecond'), started_at = now(), claim_generation = claim_generation + 1 WHERE id = $1`, [id, token, expiredMs]);+ await stall(a, 'worker-a:1', 60_000);+ await stall(b, 'worker-a:2', 1_000);+ await stall(lone, 'worker-b:1', 60_000);+ await engine.executeRaw(`UPDATE minion_jobs SET stacktrace = COALESCE(stacktrace, '[]'::jsonb) || to_jsonb($2::text) WHERE id = $1`, [marked, WATCHDOG_SUSPECT_MARK]);+ await stall(marked, 'worker-c:1', 60_000);+ await queue.handleStalled(30_000);+ expect(await row(queue, a)).toMatchObject({ status: 'waiting', marked: true });+ expect(await row(queue, b)).toMatchObject({ status: 'active' });+ await queue.handleStalled(0);+ const counters = await engine.executeRaw<{ id: number; stalled_counter: number }>('SELECT id, stalled_counter FROM minion_jobs ORDER BY id');+ expect(counters.map(r => [Number(r.id), Number(r.stalled_counter)])).toEqual([[a, 0], [b, 0], [lone, 1], [marked, 1]]);+ expect(await row(queue, b)).toMatchObject({ status: 'waiting', marked: true });+ expect(await row(queue, lone)).toMatchObject({ status: 'waiting', marked: false });+ }, 60_000);++ for (const injected of runScopedErrors().filter(e => e.name === 'connection lost' || e.name === 'failed transaction (25P02)')) {+ test(`A-30 run: a run-scoped error (${injected.name}) releasing a co-runner leaves its claim to the stall sweep, unmarked and uncharged`, async () => {+ await engine.executeRaw('DELETE FROM minion_jobs');+ const queue = new MinionQueue(engine);+ const hog = await queue.add('hog', {}, { max_attempts: 2 }, { allowProtectedSubmit: true });+ const sleeper = await queue.add('sleeper', {}, { max_attempts: 2 }, { allowProtectedSubmit: true });+ let hogging = false;+ const run = makeWorker(engine, () => hogging, new Set());+ const internals = run.worker as unknown as { queue: MinionQueue };+ internals.queue.releaseWatchdogClaim = (async () => { throw injected.error(); }) as MinionQueue['releaseWatchdogClaim'];+ const running = run.worker.start();+ await waitFor(() => run.started.has('hog') && run.started.has('sleeper'), 'both jobs running');+ hogging = true;+ await expectUnitNotAborted(() => running);+ for (const id of [hog.id, sleeper.id]) expect(await row(queue, id)).toMatchObject({ status: 'active', attempts: 0, marked: false });+ }, 60_000);+ }+ });+}diff --git a/test/worker-shutdown-error-matrix.test.ts b/test/worker-shutdown-error-matrix.test.tsindex aa7978bf80..c1b6703dc9 100644--- a/test/worker-shutdown-error-matrix.test.ts+++ b/test/worker-shutdown-error-matrix.test.ts@@ -19,14 +19,18 @@* job is not in `inFlight` when the watchdog fires. Before the fix the job* launched unaborted and took the requestShutdown path (`worker_shutdown`* hand-back, or the handler's own text for an UnrecoverableError) instead of- * `aborted: watchdog`; this is the window the un-forced watchdog test hit- * on a CI Postgres.+ * the watchdog abort; this is the window the un-forced watchdog test hit on a+ * CI Postgres. Since GBRA-130 A-30 the watchdog charges only a job that ran+ * alone when it tripped, so a claim that registers after the drain began goes+ * back to `waiting` uncharged and marked to run alone+ * (watchdog-attribution.ts).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../src/core/engine.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';import { MinionQueue } from '../src/core/minions/queue.ts';+import { WATCHDOG_DRAIN_RELEASE } from '../src/core/minions/watchdog-attribution.ts';import { MinionWorker } from '../src/core/minions/worker.ts';import { UnrecoverableError, type MinionJobContext } from '../src/core/minions/types.ts';import { LocalConfigurationError } from '../src/core/minions/configuration-error.ts';@@ -110,9 +114,9 @@ for (const backend of testBackends()) describe(`worker shutdown error matrix (W9expect(await runCase(engine, 'watchdog', 'unrecoverable')).toEqual({ status: 'dead', attempts: 1, error: 'aborted: watchdog' });}, 60_000);- test('watchdog inside the claim round trip: a claim committed before the shutdown is aborted when it registers', async () => {- expect(await runCase(engine, 'watchdog', 'plain', true)).toEqual({ status: 'delayed', attempts: 1, error: 'aborted: watchdog' });- expect(await runCase(engine, 'watchdog', 'unrecoverable', true)).toEqual({ status: 'dead', attempts: 1, error: 'aborted: watchdog' });+ test('watchdog inside the claim round trip: a claim committed before the shutdown is aborted when it registers and goes back uncharged (it did not run alone when the watchdog tripped)', async () => {+ expect(await runCase(engine, 'watchdog', 'plain', true)).toEqual({ status: 'waiting', attempts: 0, error: WATCHDOG_DRAIN_RELEASE });+ expect(await runCase(engine, 'watchdog', 'unrecoverable', true)).toEqual({ status: 'waiting', attempts: 0, error: WATCHDOG_DRAIN_RELEASE });}, 60_000);test('configuration block: every error releases through the configuration path with no attempt burned', async () => {