Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): UnrecoverableError during shutdown dead-letters, hand-backs keep the error (W9F item 6)

time-attack7723e1f981c4
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 17a28d44cd..7e20cfc192 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -29,4 +29,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.
- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.
-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #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), 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).
+- `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 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).
diff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.ts
index bfd45b1708..7c294a1d67 100644
--- a/src/core/minions/child-job-runner.ts
+++ b/src/core/minions/child-job-runner.ts
@@ -163,7 +163,10 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {
if (configurationError) throw configurationError;
if (isLocalConfigurationError(error)) throw error;
const abortReason = opts.abortSignal.reason instanceof Error ? opts.abortSignal.reason.message : String(opts.abortSignal.reason ?? '');
- if (opts.shutdownSignal.aborted && (isLocalConfigurationError(opts.shutdownSignal.reason) || !PER_JOB_ABORT_REASONS.has(abortReason))) {
+ // An UnrecoverableError from a child whose stop is confirmed dead-letters
+ // (W9F Decision 7); an unconfirmed stop keeps the claim off the queue.
+ if (opts.shutdownSignal.aborted && !(error instanceof UnrecoverableError && executionStopped)
+ && (isLocalConfigurationError(opts.shutdownSignal.reason) || !PER_JOB_ABORT_REASONS.has(abortReason))) {
throw new ChildWorkerShutdownError('Job child stopped reporting during worker shutdown; cleanup evidence determines whether its claim can be released.', executionStopped);
}
throw error;
@@ -445,8 +448,9 @@ async function runJobChildProcess(opts: RunJobInChildOpts): Promise<unknown> {
// and report an error): release with no attempt burned rather than
// punishing exactly the well-behaved handlers on every deploy
// (adversarial-review P2). Worst case a genuinely-failing job that
- // coincided with a deploy gets one free retry — bounded and benign.
- if (isShutdownClass) {
+ // coincided with a deploy gets one free retry — bounded and benign. An
+ // UnrecoverableError is deterministic, so it dead-letters as usual.
+ if (isShutdownClass && !(handlerError instanceof UnrecoverableError)) {
throw new ChildWorkerShutdownError(
'Job child reported an error during worker shutdown; execution stop is unconfirmed, so lease expiry remains the fallback.',
);
diff --git a/src/core/minions/worker-shutdown.ts b/src/core/minions/worker-shutdown.ts
index 8f3d678c7f..3fbaf461bd 100644
--- a/src/core/minions/worker-shutdown.ts
+++ b/src/core/minions/worker-shutdown.ts
@@ -8,17 +8,21 @@
import type { BrainEngine } from '../engine.ts';
import type { MinionJob } from './types.ts';
-/** Hand one claim back to `waiting`. False when the claim already moved on. */
-export async function releaseShutdownClaim(engine: BrainEngine, id: number, lockToken: string): Promise<boolean> {
+/**
+ * Hand one claim back to `waiting`. False when the claim already moved on.
+ * `errorText` is the handler's own error, kept after the `worker_shutdown`
+ * marker so the reason the handler gave is not lost.
+ */
+export async function releaseShutdownClaim(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 = 'worker_shutdown',
+ error_text = $3,
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],
+ [id, lockToken, errorText ? `worker_shutdown: ${errorText}` : 'worker_shutdown'],
);
return rows.length > 0;
}
@@ -36,7 +40,7 @@ export async function settleShutdownInterruptedJob(
return;
}
try {
- const released = await releaseShutdownClaim(engine, job.id, lockToken);
+ const released = await releaseShutdownClaim(engine, job.id, lockToken, errorText);
console.log(`Job ${job.id} (${job.name}) ${released ? 'handed back to the queue' : 'claim already moved on'} after worker shutdown (${errorText}; no attempt burned)`);
} catch (e) {
console.error(`[worker] shutdown release failed for job ${job.id}: ${e instanceof Error ? e.message : String(e)}`);
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index f4ca926c8e..e640045510 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -1640,7 +1640,11 @@ export class MinionWorker extends EventEmitter {
}
return;
}
- if (err instanceof ChildWorkerShutdownError || (!isolated && this.shutdownAbort.signal.aborted && !abort.signal.aborted)) {
+ // Decision 7 (W9F item 6): an error during shutdown is presumed
+ // shutdown-induced (cooperative handlers throw plain errors when they
+ // bail), except UnrecoverableError, which is deterministic and dead-letters.
+ if (err instanceof ChildWorkerShutdownError
+ || (!isolated && this.shutdownAbort.signal.aborted && !abort.signal.aborted && !(err instanceof UnrecoverableError))) {
return settleShutdownInterruptedJob(this.engine, job, lockToken, errorText, !(err instanceof ChildWorkerShutdownError) || err.executionStopped === true);
}
if (err instanceof ChildNotClaimedError) {
diff --git a/test/child-job-runner.test.ts b/test/child-job-runner.test.ts
index 9279882d5a..01f3baea2b 100644
--- a/test/child-job-runner.test.ts
+++ b/test/child-job-runner.test.ts
@@ -249,6 +249,28 @@ describe('runJobInChild (real children)', () => {
await expect(p).rejects.toBeInstanceOf(ChildWorkerShutdownError);
}, TEST_TIMEOUT_MS);
+ test('UnrecoverableError outcome during worker shutdown dead-letters as usual (W9F item 6, Decision 7)', async () => {
+ // A deterministic failure that coincides with a deploy must not be handed
+ // back for a second (possibly paid) run with its real error lost.
+ const harness = makeHarness(
+ 'shutdown-unrecoverable-report',
+ `process.on('SIGTERM', () => {\n` +
+ ` writeOutcome({ outcome: 'error', errorKind: 'unrecoverable', message: 'invalid params: slug is required' });\n` +
+ ` process.exit(0);\n` +
+ `});\n` +
+ `setInterval(() => {}, 1000);\n`,
+ );
+ const shutdown = new AbortController();
+ const ready = readiness('shutdown-unrecoverable-report');
+ const opts = { ...baseOpts(harness), shutdownSignal: shutdown.signal, killGraceMs: 5_000, env: ready.env };
+ const p = runJobInChild(opts);
+ await ready.wait();
+ shutdown.abort(new Error('worker-shutdown'));
+ const err = await p.then(() => null, (e: unknown) => e);
+ expect(err).toBeInstanceOf(UnrecoverableError);
+ expect((err as Error).message).toBe('invalid params: slug is required');
+ }, TEST_TIMEOUT_MS);
+
test('watchdog drain (BOTH signals aborted, non-per-job reason) → shutdown class, not a burned attempt (adversarial P3)', async () => {
const harness = makeHarness(
'watchdog-stubborn',
diff --git a/test/worker-shutdown-error-matrix.test.ts b/test/worker-shutdown-error-matrix.test.ts
new file mode 100644
index 0000000000..e2720b47ad
--- /dev/null
+++ b/test/worker-shutdown-error-matrix.test.ts
@@ -0,0 +1,87 @@
+/**
+ * W9F item 6 (Decision 7): which handler errors during a worker shutdown burn
+ * an attempt, for an in-process worker.
+ *
+ * Protects: during `requestShutdown()` a handler error is presumed
+ * shutdown-induced (cooperative handlers throw plain errors when they bail:
+ * subagent, shell), so the claim goes back to `waiting` with no attempt burned
+ * and the handler's own text kept after the `worker_shutdown` marker; an
+ * `UnrecoverableError` is deterministic and dead-letters on attempt 1 with its
+ * original text. The watchdog and configuration-block rows pin today's
+ * behavior so a later change to them is deliberate.
+ * Fails when: an UnrecoverableError thrown during shutdown is requeued as
+ * `worker_shutdown` (the pre-fix behavior: a second, possibly paid, run of a
+ * deterministic failure with its real error lost), or a shutdown hand-back
+ * overwrites the handler's error text.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.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';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+type Trigger = 'requestShutdown' | 'watchdog' | 'configuration';
+const ERRORS: Record<string, (ctx: MinionJobContext) => unknown> = {
+ reason: ctx => ctx.shutdownSignal.reason ?? ctx.signal.reason,
+ abortErrorWithCause: ctx => Object.assign(new Error('The operation was aborted'), { name: 'AbortError', cause: ctx.shutdownSignal.reason }),
+ wrappedAbort: ctx => new Error('subagent aborted during tool dispatch', { cause: ctx.shutdownSignal.reason }),
+ unrecoverable: () => new UnrecoverableError('invalid params: slug is required'),
+ plain: () => new Error('handler failed: upstream returned 500'),
+};
+
+async function runCase(trigger: Trigger, kind: keyof typeof ERRORS) {
+ const queue = new MinionQueue(engine);
+ const worker = new MinionWorker(engine, { pollInterval: 10, lockDuration: 60_000, healthCheckInterval: 0, stalledInterval: 600_000 });
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const name = `matrix-${trigger}-${kind}`;
+ worker.register(name, async (ctx) => { await gate; throw ERRORS[kind]!(ctx); });
+ const job = await queue.add(name, {}, { max_attempts: 3 }, { allowProtectedSubmit: true });
+ const running = worker.start();
+ for (let i = 0; i < 400 && (await queue.getJob(job.id))?.status !== 'active'; i++) await Bun.sleep(10);
+ if (trigger === 'requestShutdown') worker.requestShutdown();
+ else if (trigger === 'watchdog') (worker as unknown as { gracefulShutdown(reason: string): void }).gracefulShutdown('watchdog');
+ else worker.blockForConfiguration(new LocalConfigurationError('postgres_cancellation_unavailable', 'fixture cancellation unavailable'));
+ release();
+ let row = await queue.getJob(job.id);
+ for (let i = 0; i < 500 && row?.status === 'active'; i++) { await Bun.sleep(10); row = await queue.getJob(job.id); }
+ worker.stop();
+ await running;
+ row = await queue.getJob(job.id);
+ return { status: row?.status, attempts: row?.attempts_made, error: row?.error_text };
+}
+
+describe('worker shutdown error matrix (W9F item 6, in-process)', () => {
+ test('requestShutdown: only UnrecoverableError burns an attempt; every hand-back keeps the handler text', async () => {
+ const reasonText = 'shutdown';
+ expect(await runCase('requestShutdown', 'reason')).toEqual({ status: 'waiting', attempts: 0, error: `worker_shutdown: ${reasonText}` });
+ expect(await runCase('requestShutdown', 'abortErrorWithCause')).toEqual({ status: 'waiting', attempts: 0, error: 'worker_shutdown: The operation was aborted' });
+ expect(await runCase('requestShutdown', 'wrappedAbort')).toEqual({ status: 'waiting', attempts: 0, error: 'worker_shutdown: subagent aborted during tool dispatch' });
+ expect(await runCase('requestShutdown', 'plain')).toEqual({ status: 'waiting', attempts: 0, error: 'worker_shutdown: handler failed: upstream returned 500' });
+ expect(await runCase('requestShutdown', 'unrecoverable')).toEqual({ status: 'dead', attempts: 1, error: 'invalid params: slug is required' });
+ }, 60_000);
+
+ test('watchdog: the per-job abort fires, so the job takes the abort path (attempt burned; UnrecoverableError dead)', async () => {
+ for (const kind of ['reason', 'abortErrorWithCause', 'wrappedAbort', 'plain'] as const) {
+ expect(await runCase('watchdog', kind)).toEqual({ status: 'delayed', attempts: 1, error: 'aborted: watchdog' });
+ }
+ expect(await runCase('watchdog', 'unrecoverable')).toEqual({ status: 'dead', attempts: 1, error: 'aborted: watchdog' });
+ }, 60_000);
+
+ test('configuration block: every error releases through the configuration path with no attempt burned', async () => {
+ for (const kind of Object.keys(ERRORS)) {
+ const row = await runCase('configuration', kind);
+ expect(row.attempts).toBe(0);
+ expect(row.status).not.toBe('dead');
+ }
+ }, 60_000);
+});