Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(autopilot): stop the drain-worker self-deadlocking at concurrency=1 (#2050) (#3559)

test9b9bd8b24194
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 2da0d18fee..c678860d43 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -30,14 +30,13 @@ import { serializeMarkdown } from '../markdown.ts';
import type { Page, PageType } from '../types.ts';
// #2415: allow-list + output-root resolution shared with the synthesize
// phase — both phases must agree on the configured namespace.
-// runPgliteSubagentsInline is shared too: PGLite has no separate Minions
-// worker process (the embedded data-dir holds an exclusive file lock), so a
-// job submitted via queue.add() sits in 'waiting' forever unless something
-// drives the claim -> run -> complete loop inline. synthesize.ts already
-// does this for its own children; patterns.ts previously submitted and
-// waited without ever draining, so every real (non-dry-run) invocation on a
-// PGLite brain hung until subagentWaitTimeoutMs (default 35 min).
-import { loadAllowedSlugPrefixes, loadOutputRoot, runPgliteSubagentsInline } from './synthesize.ts';
+// runSubagentsInline is shared too: a job submitted via queue.add() sits in
+// 'waiting' forever unless something drives the claim -> run -> complete
+// loop — on PGLite because no separate worker can open the embedded
+// data-dir, on Postgres because the parent phase itself occupies a worker
+// slot and can deadlock a fully-occupied worker (#2050). synthesize.ts
+// drains its own children the same way.
+import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './synthesize.ts';
import { probeChatModel } from '../ai/gateway.ts';
import { normalizeModelId } from '../model-id.ts';
@@ -192,13 +191,12 @@ export async function runPhasePatterns(
}
const queue = new MinionQueue(engine);
- // PGLite children drain inline (no separate worker can open the embedded
- // data-dir), so give this job a private per-run queue: the inline drain
- // must never claim unrelated 'default'-queue jobs a Postgres worker owns.
- // Mirrors synthesize.ts's childQueueName derivation exactly.
- const childQueueName = engine.kind === 'pglite'
- ? `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`
- : 'default';
+ // #2050: children drain inline on BOTH engines (see runSubagentsInline),
+ // so give this job a private per-run queue: the inline drain must never
+ // claim unrelated 'default'-queue jobs, and a 'default'-queue worker must
+ // never claim a child this parent is about to run itself. Mirrors
+ // synthesize.ts's childQueueName derivation exactly.
+ const childQueueName = `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`;
const data: SubagentHandlerData = {
prompt: buildPatternsPrompt(reflections, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix),
model: config.model,
@@ -217,12 +215,11 @@ export async function runPhasePatterns(
allowProtectedSubmit: true,
});
- // PGLite cannot run a separate Minions worker because the embedded DB
- // holds an exclusive file lock. Drain this phase's private child queue
- // inline so the parent observes the terminal state instead of polling
- // waitForCompletion until subagentWaitTimeoutMs expires. No-op on
- // Postgres (a real worker process claims the job there).
- await runPgliteSubagentsInline(engine, queue, childQueueName, opts.yieldDuringPhase);
+ // Drain this phase's private child queue inline so the parent observes
+ // the terminal state instead of polling waitForCompletion until
+ // subagentWaitTimeoutMs expires. Runs on BOTH engines — on Postgres the
+ // parent job otherwise deadlocks a fully-occupied worker (#2050).
+ await runSubagentsInline(engine, queue, childQueueName, opts.yieldDuringPhase);
let outcome: string;
try {
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index 3aaf3eb9e6..9fb1bffcfb 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -37,6 +37,8 @@ import { basename, join, dirname, isAbsolute, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult, PhaseError } from '../cycle.ts';
import { MinionQueue } from '../minions/queue.ts';
+import { reconnectAfterConnectionError } from '../minions/reconnect.ts';
+import { isRetryableConnError } from '../retry-matcher.ts';
import { waitForCompletion, TimeoutError } from '../minions/wait-for-completion.ts';
import { makeSubagentHandler } from '../minions/handlers/subagent.ts';
import type { MinionJobInput, MinionJobContext, MinionHandler, SubagentHandlerData } from '../minions/types.ts';
@@ -276,39 +278,101 @@ export interface SynthesizePhaseOpts {
once?: boolean;
}
-const INLINE_PGLITE_LOCK_MS = 30_000;
+const INLINE_LOCK_MS = 30_000;
/**
- * PGLite cannot be served by a separate Minions worker process: the embedded
- * data-dir holds an exclusive file lock, so subagent children enqueued by the
- * synth parent would sit in 'waiting' until waitForCompletion times out.
- * Drive the same claim → run → complete/fail loop a worker would perform,
- * inline, against this phase's private child queue.
+ * Drain this phase's private child queue inline: drive the same claim → run →
+ * complete/fail loop a worker would perform, from the parent's own slot.
+ *
+ * Why inline on BOTH engines:
+ * - PGLite: no separate Minions worker can run at all (the embedded
+ * data-dir holds an exclusive file lock), so children would sit in
+ * 'waiting' until waitForCompletion times out.
+ * - Postgres (#2050): the parent phase itself runs as a job inside a
+ * `jobs work` process. A worker whose slots are all occupied by such
+ * parents (autopilot spawns its drain worker at the default
+ * concurrency=1) can never claim the child the parent is blocking on —
+ * a structural self-deadlock. Running children inline means a child
+ * never needs a worker slot, so the deadlock is impossible at ANY
+ * concurrency, and no extra DB-pool pressure is added: the child's work
+ * replaces the parent's idle waitForCompletion polling in the slot the
+ * parent already holds.
*
* `yieldDuringPhase` is ticked on a 60s interval while a child runs so the
* 5-min cycle lock TTL keeps refreshing during long (up to 30-min) children.
+ * The child's own claim lock is heartbeated at lockMs/3 (worker cadence
+ * parity) — on Postgres a concurrent worker sweeps handleStalled() across
+ * ALL queues, so without renewal any child running longer than lockMs would
+ * be requeued mid-run and stall-churned to dead.
*/
-export async function runPgliteSubagentsInline(
+export async function runSubagentsInline(
engine: BrainEngine,
queue: MinionQueue,
queueName: string,
yieldDuringPhase?: () => Promise<void>,
handler: MinionHandler = makeSubagentHandler({ engine }),
+ lockMs: number = INLINE_LOCK_MS,
): Promise<void> {
- if (engine.kind !== 'pglite') return;
+ // #3555 interaction: the drain's queue ops used to be bare awaits, so a
+ // transient pooler reap mid-drain threw out of the loop and stranded the
+ // remaining children in this per-run private queue — which no worker will
+ // ever claim. Mirror the worker's recovery: on a retryable connection
+ // error, rebuild the pool (shared reconnectAfterConnectionError) and retry
+ // the loop; non-retryable errors still propagate (real bug → phase fails).
+ const MAX_CONN_ERROR_STREAK = 5;
+ let connErrorStreak = 0;
+ let sawConnError = false;
+ const recoverOrThrow = async (site: string, e: unknown): Promise<void> => {
+ if (!isRetryableConnError(e) || ++connErrorStreak > MAX_CONN_ERROR_STREAK) throw e;
+ sawConnError = true;
+ const msg = e instanceof Error ? e.message : String(e);
+ process.stderr.write(`[dream] inline drain ${site} hit a connection error; reconnecting and retrying: ${msg}\n`);
+ await reconnectAfterConnectionError(engine, `inline-${site}`, e);
+ // Small cooperative backoff (setTimeout keeps the cycle-lock keepalive
+ // and any concurrent timers firing) before the loop retries.
+ await new Promise((r) => setTimeout(r, Math.min(1000, Math.max(50, Math.floor(lockMs / 3)))));
+ };
while (true) {
- // Housekeeping a worker would normally perform, so child rows can reach
- // terminal states (delayed retries promoted, timeouts dead-lettered)
- // before the synth parent enters waitForCompletion polling.
- await queue.promoteDelayed();
- await queue.handleStalled();
- await queue.handleTimeouts();
- await queue.handleWallClockTimeouts(INLINE_PGLITE_LOCK_MS);
-
const lockToken = randomUUID();
- const job = await queue.claim(lockToken, INLINE_PGLITE_LOCK_MS, queueName, ['subagent']);
- if (!job) return;
+ let job: Awaited<ReturnType<MinionQueue['claim']>>;
+ try {
+ // Housekeeping a worker would normally perform, so child rows can reach
+ // terminal states (delayed retries promoted, timeouts dead-lettered)
+ // before the synth parent enters waitForCompletion polling.
+ await queue.promoteDelayed();
+ await queue.handleStalled();
+ await queue.handleTimeouts();
+ await queue.handleWallClockTimeouts(lockMs);
+
+ job = await queue.claim(lockToken, lockMs, queueName, ['subagent']);
+ } catch (e) {
+ await recoverOrThrow('queue-ops', e);
+ continue;
+ }
+ connErrorStreak = 0;
+ if (!job) {
+ if (!sawConnError) return;
+ // A connection-error window may have left a child 'active' under a
+ // lock nobody renews (a claim that committed but whose row never
+ // reached us, or a lost outcome write below). handleStalled() at the
+ // loop top requeues it once the lock expires (≤ lockMs), so only exit
+ // once the queue is actually quiet.
+ let active = 0;
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM minion_jobs WHERE queue = $1 AND status = 'active'`,
+ [queueName],
+ );
+ active = rows[0]?.n ?? 0;
+ } catch (e) {
+ await recoverOrThrow('active-check', e);
+ continue;
+ }
+ if (active === 0) return;
+ await new Promise((r) => setTimeout(r, 1000));
+ continue;
+ }
const abort = new AbortController();
const shutdown = new AbortController();
@@ -364,18 +428,45 @@ export async function runPgliteSubagentsInline(
const keepalive = yieldDuringPhase
? setInterval(() => { yieldDuringPhase().catch(() => { /* best-effort */ }); }, 60_000)
: null;
+ // #2050: heartbeat the child's claim lock while the handler runs so a
+ // concurrent Postgres worker's handleStalled() sweep (all queues, not
+ // just its own) can't requeue a live child. A false return means the row
+ // was cancelled or reclaimed — abort the handler. Errors are swallowed
+ // (best-effort; the next tick retries), never an unhandledRejection.
+ const renewTimer = setInterval(() => {
+ queue.renewLock(job.id, lockToken, lockMs)
+ .then((ok) => {
+ if (!ok && !abort.signal.aborted) abort.abort(new Error('lock-renewal-failed'));
+ })
+ .catch(() => { /* best-effort; next tick retries */ });
+ }, Math.max(50, Math.floor(lockMs / 3)));
+ // Run, then record — separated so a completeJob connection error can't
+ // masquerade as a handler failure, and a failJob connection error can't
+ // escape the drain and strand the remaining children (worker.ts #1720
+ // parity: reconnect + retry the recording once; if it still fails, leave
+ // the row for the loop's own handleStalled to requeue after lock expiry).
+ let result: unknown;
+ let handlerErr: unknown;
+ let handlerRan = false;
try {
- const result = await handler(context);
- await queue.completeJob(
- job.id,
- lockToken,
- result != null ? (typeof result === 'object' ? result as Record<string, unknown> : { value: result }) : undefined,
- );
+ result = await handler(context);
+ handlerRan = true;
} catch (e) {
+ handlerErr = e;
+ }
+ const record = async (): Promise<void> => {
+ if (handlerRan) {
+ await queue.completeJob(
+ job.id,
+ lockToken,
+ result != null ? (typeof result === 'object' ? result as Record<string, unknown> : { value: result }) : undefined,
+ );
+ return;
+ }
// Timeout is terminal (handleTimeouts parity: stall → retry,
// timeout → dead), never a delayed retry.
const timedOut = abort.signal.aborted;
- const errorText = timedOut ? 'timeout exceeded' : (e instanceof Error ? e.message : String(e));
+ const errorText = timedOut ? 'timeout exceeded' : (handlerErr instanceof Error ? handlerErr.message : String(handlerErr));
const attemptsExhausted = job.attempts_made + 1 >= job.max_attempts;
await queue.failJob(
job.id,
@@ -384,9 +475,30 @@ export async function runPgliteSubagentsInline(
timedOut || attemptsExhausted ? 'dead' : 'delayed',
0,
);
+ };
+ try {
+ try {
+ await record();
+ } catch (recordErr) {
+ if (!isRetryableConnError(recordErr)) throw recordErr;
+ sawConnError = true;
+ const msg = recordErr instanceof Error ? recordErr.message : String(recordErr);
+ process.stderr.write(`[dream] inline drain: recording job ${job.id} outcome hit a connection error; reconnecting and retrying once: ${msg}\n`);
+ await reconnectAfterConnectionError(engine, 'inline-record', recordErr);
+ try {
+ await record();
+ } catch (retryErr) {
+ // Leave the row to the loop's own handleStalled: the claim lock
+ // stops renewing (finally clears renewTimer), expires within
+ // lockMs, and the next iteration requeues it on a live pool.
+ const retryMsg = retryErr instanceof Error ? retryErr.message : String(retryErr);
+ process.stderr.write(`[dream] inline drain: outcome recording retry for job ${job.id} also failed (${retryMsg}); leaving the row for stall requeue\n`);
+ }
+ }
} finally {
if (timeoutTimer) clearTimeout(timeoutTimer);
if (keepalive) clearInterval(keepalive);
+ clearInterval(renewTimer);
}
}
}
@@ -572,12 +684,11 @@ export async function runPhaseSynthesize(
}
const queue = new MinionQueue(engine);
- // PGLite children drain inline (no separate worker can open the embedded
- // data-dir), so give them a private per-run queue: the inline drain must
- // never claim unrelated 'default'-queue jobs a Postgres worker owns.
- const childQueueName = engine.kind === 'pglite'
- ? `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`
- : 'default';
+ // #2050: children drain inline on BOTH engines (see runSubagentsInline),
+ // so give them a private per-run queue: the inline drain must never claim
+ // unrelated 'default'-queue jobs, and a 'default'-queue worker must never
+ // claim a child this parent is about to run itself.
+ const childQueueName = `dream-inline-${Date.now()}-${randomUUID().slice(0, 8)}`;
const childIds: number[] = [];
/** Map child job_id → chunk metadata for D6 orchestrator-side slug rewrite. */
const chunkInfo = new Map<number, { idx: number; hash6: string }>();
@@ -685,11 +796,11 @@ export async function runPhaseSynthesize(
}
}
- // PGLite cannot run a separate Minions worker because the embedded DB
- // holds an exclusive file lock. Drain this phase's private child queue
- // inline so the parent observes terminal child states instead of polling
- // waiters until subagentWaitTimeoutMs expires. No-op on Postgres.
- await runPgliteSubagentsInline(engine, queue, childQueueName, opts.yieldDuringPhase);
+ // Drain this phase's private child queue inline so the parent observes
+ // terminal child states instead of polling waiters until
+ // subagentWaitTimeoutMs expires. Runs on BOTH engines — on Postgres the
+ // parent job otherwise deadlocks a fully-occupied worker (#2050).
+ await runSubagentsInline(engine, queue, childQueueName, opts.yieldDuringPhase);
// Wait for every child to reach a terminal state. Tick yieldDuringPhase
// every 5 min so the cycle lock TTL refreshes.
@@ -1709,6 +1820,6 @@ export const __testing = {
buildSynthesisPrompt,
stampDreamProvenance,
reverseWriteRefs,
- runPgliteSubagentsInline,
+ runSubagentsInline,
loadSynthConfig,
};
diff --git a/src/core/minions/reconnect.ts b/src/core/minions/reconnect.ts
new file mode 100644
index 0000000000..3747d8e1cb
--- /dev/null
+++ b/src/core/minions/reconnect.ts
@@ -0,0 +1,24 @@
+/**
+ * Shared "rebuild the DB pool after a retryable connection failure" helper.
+ *
+ * PostgresEngine exposes reconnect(); PGLite and test doubles may not. Absence
+ * is a no-op so non-Postgres callers preserve their legacy behavior.
+ *
+ * Extracted from MinionWorker's private method (#1491/#3555) so the inline
+ * child drain (#2050, cycle/synthesize.ts runSubagentsInline) recovers from
+ * the same transient pooler reaps instead of throwing out of the drain and
+ * stranding children in a per-run queue no worker will ever claim.
+ */
+export async function reconnectAfterConnectionError(
+ engine: unknown,
+ site: string,
+ error: unknown,
+): Promise<void> {
+ const reconnect = (engine as { reconnect?: (ctx?: { error?: unknown }) => Promise<void> }).reconnect;
+ if (!reconnect) return;
+ try {
+ await reconnect.call(engine, { error });
+ } catch (re) {
+ console.error(`[minions] reconnect after ${site} error failed: ${re instanceof Error ? re.message : String(re)}`);
+ }
+}
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index ce4dcfc4eb..6a82891459 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -31,6 +31,7 @@ import {
} from './lock-renewal-tick.ts';
import { lockRenewalAudit } from '../audit/lock-renewal-audit.ts';
import { isRetryableConnError } from '../retry-matcher.ts';
+import { reconnectAfterConnectionError as reconnectEngineAfterConnError } from './reconnect.ts';
/**
* Abort reasons that signal infrastructure failure (PgBouncer outage,
@@ -735,18 +736,10 @@ export class MinionWorker extends EventEmitter {
/**
* Rebuild the worker-owned DB pool after a retryable connection failure.
- *
- * PostgresEngine exposes reconnect(); PGLite and test doubles may not. Absence
- * is a no-op so non-Postgres workers preserve their legacy behavior.
+ * Shared with the inline child drain (#2050) via minions/reconnect.ts.
*/
private async reconnectAfterConnectionError(site: string, error: unknown): Promise<void> {
- const reconnect = (this.engine as { reconnect?: (ctx?: { error?: unknown }) => Promise<void> }).reconnect;
- if (!reconnect) return;
- try {
- await reconnect.call(this.engine, { error });
- } catch (re) {
- console.error(`[worker] reconnect after ${site} error failed: ${re instanceof Error ? re.message : String(re)}`);
- }
+ await reconnectEngineAfterConnError(this.engine, site, error);
}
/** RSS watchdog. Called from the per-job finally and the periodic timer.
diff --git a/test/autopilot-drain-deadlock-2050.test.ts b/test/autopilot-drain-deadlock-2050.test.ts
new file mode 100644
index 0000000000..29f98d4e47
--- /dev/null
+++ b/test/autopilot-drain-deadlock-2050.test.ts
@@ -0,0 +1,237 @@
+/**
+ * #2050 — a patterns/synthesize parent job that blocks on its own subagent
+ * child must not deadlock a fully-occupied Postgres drain worker.
+ *
+ * Pre-fix, the inline child drain was PGLite-only (runPgliteSubagentsInline
+ * returned early unless engine.kind === 'pglite') and Postgres children were
+ * submitted to the 'default' queue. Autopilot spawns its drain worker with no
+ * --concurrency (resolves to 1), so the parent occupied the only slot, the
+ * child was never claimed, and the phase burned the whole
+ * subagent_wait_timeout_ms window before cancelling its own child — every
+ * cycle, forever.
+ *
+ * These tests run the REAL phase/drain code against a PGLite engine masked as
+ * kind='postgres' (only the `kind` property is intercepted; every method call
+ * hits the real engine), which is exactly the branch the production Postgres
+ * environment takes. All assertions are behavioral: on unmodified master they
+ * fail with outcome 'timeout' / a never-claimed 'waiting' child on the
+ * 'default' queue.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { runPhasePatterns } from '../src/core/cycle/patterns.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let schemaVersion: string;
+
+/** Mask a PGLite engine as Postgres: only `kind` is intercepted, every
+ * method executes on the real engine (bound to the target so internal
+ * state is untouched). */
+function maskAsPostgres(target: PGLiteEngine): BrainEngine {
+ return new Proxy(target, {
+ get(t, prop) {
+ if (prop === 'kind') return 'postgres';
+ const v = Reflect.get(t, prop);
+ return typeof v === 'function' ? v.bind(t) : v;
+ },
+ }) as unknown as BrainEngine;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version')) ?? '7';
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+});
+
+async function seedReflections(): Promise<void> {
+ for (let i = 0; i < 3; i++) {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, type, title, compiled_truth)
+ VALUES ($1, 'note', $2, $3)`,
+ [
+ `wiki/personal/reflections/2026-07-0${i + 1}-reflection`,
+ `Reflection ${i + 1}`,
+ `Recurring theme fixture number ${i + 1}.`,
+ ],
+ );
+ }
+}
+
+describe('#2050 — patterns parent must not deadlock on its own child (postgres path)', () => {
+ test('child is drained inline on a private queue instead of waiting out the parent', async () => {
+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-2050-patterns-'));
+ try {
+ await seedReflections();
+ // Small wait window: on master the child is never claimed (no worker in
+ // this process, parent would hold the only slot in production), so the
+ // phase burns this whole window and reports outcome 'timeout'.
+ await engine.setConfig('dream.patterns.subagent_wait_timeout_ms', '2000');
+
+ const pgAlike = maskAsPostgres(engine);
+ const result = await withEnv({ ANTHROPIC_API_KEY: 'sk-ant-test' }, () =>
+ runPhasePatterns(pgAlike, { brainDir, dryRun: false }),
+ );
+
+ // Master: child_outcome 'timeout' + PATTERNS_CHILD_TIMEOUT (self-deadlock,
+ // then the phase cancels its own child). Fixed: the inline drain actually
+ // ran the child (the fake API key fails fast → 'dead'), no deadlock.
+ expect(result.details.child_outcome).toBe('dead');
+ expect(result.error?.code).toBe('PATTERNS_CHILD_DEAD');
+
+ const jobs = await engine.executeRaw<{ queue: string; status: string }>(
+ `SELECT queue, status FROM minion_jobs WHERE name = 'subagent' ORDER BY id DESC LIMIT 1`,
+ );
+ expect(jobs).toHaveLength(1);
+ // Master: queue 'default' (claimable by — and deadlocked behind — the
+ // same worker running the parent), status 'cancelled'.
+ expect(jobs[0].queue).toStartWith('dream-inline-');
+ expect(jobs[0].status).toBe('dead');
+ } finally {
+ rmSync(brainDir, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test('inline drain runs children on a non-pglite engine and heartbeats their lock', async () => {
+ const { __testing } = await import('../src/core/cycle/synthesize.ts');
+ const drain = (__testing as Record<string, unknown>).runSubagentsInline
+ ?? (__testing as Record<string, unknown>).runPgliteSubagentsInline;
+
+ const pgAlike = maskAsPostgres(engine);
+ const queue = new MinionQueue(pgAlike);
+ const job = await queue.add(
+ 'subagent',
+ { prompt: 'noop', model: 'anthropic:claude-sonnet-4-5', max_turns: 1 },
+ { queue: 'inline-2050-test', max_stalled: 3 },
+ { allowProtectedSubmit: true },
+ );
+
+ // Stub handler outliving the (shortened) claim lock: sleeps past lockMs,
+ // then runs the same handleStalled() sweep a concurrent Postgres worker
+ // fires on a timer. With the heartbeat the lock is fresh and the sweep
+ // must NOT touch the running child; without it the child would be
+ // requeued mid-run (stall churn → dead after max_stalled).
+ let sweptWhileRunning = 0;
+ const stub = async () => {
+ await new Promise((r) => setTimeout(r, 1400));
+ const { requeued, dead } = await queue.handleStalled();
+ sweptWhileRunning = [...requeued, ...dead].filter((j) => j.id === job.id).length;
+ return { ok: true };
+ };
+
+ // Master behavioral failure: runPgliteSubagentsInline no-ops on a
+ // kind='postgres' engine, the stub never runs, the job stays 'waiting'.
+ await (drain as (
+ e: BrainEngine, q: MinionQueue, name: string,
+ y?: () => Promise<void>, h?: unknown, lockMs?: number,
+ ) => Promise<void>)(pgAlike, queue, 'inline-2050-test', undefined, stub, 1000);
+
+ const after = await queue.getJob(job.id);
+ expect(after?.status).toBe('completed');
+ expect(sweptWhileRunning).toBe(0);
+ }, 30_000);
+
+ // #3555 interaction: the drain's queue ops must survive a transient pooler
+ // reap (reconnect + retry) instead of throwing out of the loop and
+ // stranding children in the per-run private queue no worker will claim.
+
+ /** Mask as Postgres AND expose a counting reconnect() for the drain's
+ * recovery path (the real PGLite engine has no reconnect method). */
+ function maskAsPostgresWithReconnect(target: PGLiteEngine, onReconnect: () => void): BrainEngine {
+ return new Proxy(target, {
+ get(t, prop) {
+ if (prop === 'kind') return 'postgres';
+ if (prop === 'reconnect') return async () => { onReconnect(); };
+ const v = Reflect.get(t, prop);
+ return typeof v === 'function' ? v.bind(t) : v;
+ },
+ }) as unknown as BrainEngine;
+ }
+
+ const connError = () =>
+ Object.assign(new Error('write CONNECTION_ENDED supavisor reaped the socket'), { code: 'CONNECTION_ENDED' });
+
+ test('a transient connection error on claim reconnects and the child still completes', async () => {
+ const { __testing } = await import('../src/core/cycle/synthesize.ts');
+ const drain = (__testing as Record<string, unknown>).runSubagentsInline;
+
+ let reconnects = 0;
+ const pgAlike = maskAsPostgresWithReconnect(engine, () => { reconnects++; });
+ const queue = new MinionQueue(pgAlike);
+ const job = await queue.add(
+ 'subagent',
+ { prompt: 'noop', model: 'anthropic:claude-sonnet-4-5', max_turns: 1 },
+ { queue: 'inline-2050-conn-claim', max_stalled: 3 },
+ { allowProtectedSubmit: true },
+ );
+
+ let failuresLeft = 1;
+ const realClaim = queue.claim.bind(queue);
+ queue.claim = (async (...args: Parameters<MinionQueue['claim']>) => {
+ if (failuresLeft-- > 0) throw connError();
+ return realClaim(...args);
+ }) as MinionQueue['claim'];
+
+ // Pre-fix: the bare-await claim throws out of the drain, the child
+ // strands 'waiting' in the private queue, and this await rejects.
+ await (drain as (
+ e: BrainEngine, q: MinionQueue, name: string,
+ y?: () => Promise<void>, h?: unknown, lockMs?: number,
+ ) => Promise<void>)(pgAlike, queue, 'inline-2050-conn-claim', undefined, async () => ({ ok: true }), 1000);
+
+ const after = await queue.getJob(job.id);
+ expect(after?.status).toBe('completed');
+ expect(reconnects).toBe(1);
+ }, 30_000);
+
+ test('a transient connection error recording the outcome retries once and the child still completes', async () => {
+ const { __testing } = await import('../src/core/cycle/synthesize.ts');
+ const drain = (__testing as Record<string, unknown>).runSubagentsInline;
+
+ let reconnects = 0;
+ const pgAlike = maskAsPostgresWithReconnect(engine, () => { reconnects++; });
+ const queue = new MinionQueue(pgAlike);
+ const job = await queue.add(
+ 'subagent',
+ { prompt: 'noop', model: 'anthropic:claude-sonnet-4-5', max_turns: 1 },
+ { queue: 'inline-2050-conn-record', max_stalled: 3 },
+ { allowProtectedSubmit: true },
+ );
+
+ let failuresLeft = 1;
+ const realComplete = queue.completeJob.bind(queue);
+ queue.completeJob = (async (...args: Parameters<MinionQueue['completeJob']>) => {
+ if (failuresLeft-- > 0) throw connError();
+ return realComplete(...args);
+ }) as MinionQueue['completeJob'];
+
+ // Pre-fix: completeJob's rejection landed in the drain's catch, which
+ // called failJob for a handler that SUCCEEDED (misrecorded outcome) — or
+ // escaped the drain entirely if failJob also hit the dead pool.
+ await (drain as (
+ e: BrainEngine, q: MinionQueue, name: string,
+ y?: () => Promise<void>, h?: unknown, lockMs?: number,
+ ) => Promise<void>)(pgAlike, queue, 'inline-2050-conn-record', undefined, async () => ({ ok: true }), 1000);
+
+ const after = await queue.getJob(job.id);
+ expect(after?.status).toBe('completed');
+ expect(reconnects).toBe(1);
+ }, 30_000);
+});
diff --git a/test/cycle-patterns-child-outcome.test.ts b/test/cycle-patterns-child-outcome.test.ts
index 60c94f9f5b..c976c16661 100644
--- a/test/cycle-patterns-child-outcome.test.ts
+++ b/test/cycle-patterns-child-outcome.test.ts
@@ -5,7 +5,7 @@
* zero pattern pages written (e.g. when no subagent-capable worker slot was
* free for the whole wait window) — a silent no-op for days.
*
- * A later fix added runPgliteSubagentsInline to this phase (patterns.ts
+ * A later fix added the shared inline drain (now runSubagentsInline) to this phase (patterns.ts
* previously submitted a job and waited without anything ever claiming it on
* PGLite — synthesize.ts already had this inline drain, patterns.ts didn't).
* So a fake ANTHROPIC_API_KEY here now gets claimed and actually attempted;
diff --git a/test/e2e/dream-synthesize-pglite.test.ts b/test/e2e/dream-synthesize-pglite.test.ts
index a0f4f3e4db..f9b862a322 100644
--- a/test/e2e/dream-synthesize-pglite.test.ts
+++ b/test/e2e/dream-synthesize-pglite.test.ts
@@ -644,7 +644,7 @@ describe('E2E synthesize — PGLite inline subagent drain (takeover of #2699)',
);
let ticks = 0;
- await synthTesting.runPgliteSubagentsInline(
+ await synthTesting.runSubagentsInline(
rig.engine,
queue,
queueName,
@@ -685,7 +685,7 @@ describe('E2E synthesize — PGLite inline subagent drain (takeover of #2699)',
{ allowProtectedSubmit: true },
);
- await synthTesting.runPgliteSubagentsInline(
+ await synthTesting.runSubagentsInline(
rig.engine,
queue,
queueName,
@@ -719,7 +719,7 @@ describe('E2E synthesize — PGLite inline subagent drain (takeover of #2699)',
// Handler only ends when ctx.signal fires — like the real subagent
// handler mid-LLM-call. Without the inline timeout timer this awaits
// forever and the drain (and the whole cycle) wedges.
- await synthTesting.runPgliteSubagentsInline(
+ await synthTesting.runSubagentsInline(
rig.engine,
queue,
queueName,