Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): replay a pending subagent tool write until it commits (#6063)

time-attack4df045684137
diff --git a/src/core/minions/handlers/subagent-oneshot.ts b/src/core/minions/handlers/subagent-oneshot.ts
index 4407029159..7a20729831 100644
--- a/src/core/minions/handlers/subagent-oneshot.ts
+++ b/src/core/minions/handlers/subagent-oneshot.ts
@@ -31,7 +31,7 @@
* a completed result.
*/
-import { retainToolWriteRequestId, assertToolWriteCommitted, isPendingToolWrite } from '../tool-write-identity.ts';
+import { retainToolWriteRequestId, runToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../../engine.ts';
import type { MinionJobContext, SubagentHandlerData, SubagentResult, ToolDef, ContentBlock, OneshotFallbackReason } from '../types.ts';
@@ -296,8 +296,8 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc
continue;
}
try {
- const output = await args.putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal });
- assertToolWriteCommitted(output, 'brain_put_page');
+ const putPageTool = args.putPageTool;
+ const output = await runToolWrite(() => putPageTool.execute(input, { engine, jobId: ctx.id, remote: true, signal: ctx.signal }), 'brain_put_page', ctx);
await persistToolExecComplete(engine, ctx.id, 1, row.ordinal ?? 0, row.tool_use_id, output);
row.status = 'complete';
} catch (e) {
@@ -575,13 +575,13 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc
if (ctx.signal?.aborted) throw new DOMException('oneshot write loop aborted by job signal', 'AbortError');
let output: unknown;
try {
- output = await args.putPageTool.execute(input, {
+ const putPageTool = args.putPageTool;
+ output = await runToolWrite(() => putPageTool.execute(input, {
engine,
jobId: ctx.id,
remote: true,
signal: ctx.signal,
- });
- assertToolWriteCommitted(output, 'brain_put_page');
+ }), 'brain_put_page', ctx);
} catch (e) {
// Abort/transient-conn errors are not write verdicts (same rule as
// recovery): rethrow, row stays pending, retry re-executes.
diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.ts
index 092427f419..9d0dfce4db 100644
--- a/src/core/minions/handlers/subagent.ts
+++ b/src/core/minions/handlers/subagent.ts
@@ -24,7 +24,7 @@
* as P2 items in the plan file.
*/
-import { retainToolWriteRequestId, assertToolWriteCommitted, isPendingToolWrite } from '../tool-write-identity.ts';
+import { retainToolWriteRequestId, runToolWrite, isPendingToolWrite } from '../tool-write-identity.ts';
import Anthropic from '@anthropic-ai/sdk';
import type { MinionJobContext, MinionJob } from '../types.ts';
import { UnrecoverableError } from '../types.ts';
@@ -706,10 +706,9 @@ export function makeSubagentHandler(deps: SubagentDeps) {
retainToolWriteRequestId(use.input, ctx.id, last.message_idx, useOrdinal, use.id, use.name);
await persistToolExecPending(engine, ctx.id, last.message_idx, useOrdinal, use.id, use.name, use.input);
try {
- const output = await toolDef.execute(use.input, {
+ const output = await runToolWrite(() => toolDef.execute(use.input, {
engine, jobId: ctx.id, remote: true, signal: ctx.signal,
- });
- assertToolWriteCommitted(output, use.name);
+ }), use.name, ctx);
await persistToolExecComplete(engine, ctx.id, last.message_idx, useOrdinal, use.id, output);
synthesizedResults.push({
type: 'tool_result', tool_use_id: use.id,
@@ -1054,13 +1053,12 @@ export function makeSubagentHandler(deps: SubagentDeps) {
const toolStart = Date.now();
try {
- const output = await toolDef.execute(use.input, {
+ const output = await runToolWrite(() => toolDef.execute(use.input, {
engine,
jobId: ctx.id,
remote: true,
signal: ctx.signal,
- });
- assertToolWriteCommitted(output, toolName);
+ }), toolName, ctx);
await persistToolExecComplete(engine, ctx.id, assistantIdx, useOrdinal, use.id, output);
logSubagentHeartbeat({
job_id: ctx.id,
@@ -1203,9 +1201,8 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResu
idempotent: t.idempotent === true,
async execute(input: unknown, signal: AbortSignal): Promise<unknown> {
try {
- const output = await t.execute(input, { engine, jobId: ctx.id, remote: true, signal });
- assertToolWriteCommitted(output, t.name);
- return output;
+ return await runToolWrite(() => t.execute(input, { engine, jobId: ctx.id, remote: true, signal }), t.name,
+ { deadlineAtMs: ctx.deadlineAtMs, signal });
} catch (error) {
if (isPendingToolWrite(error)) pendingToolWrite = error;
throw error;
@@ -1253,6 +1250,7 @@ async function runSubagentViaGateway(args: GatewayRunArgs): Promise<SubagentResu
priorTools: priorToolsV1,
toolDefs,
signal: ctx.signal,
+ deadlineAtMs: ctx.deadlineAtMs,
});
// Terminal early-return (#1151 parity): the prior run already reached
@@ -1518,6 +1516,8 @@ interface ReconcileArgs {
priorTools: PersistedToolExec[];
toolDefs: ToolDef[];
signal: AbortSignal;
+ /** The job deadline that bounds a re-dispatched tool write's wait (#5474). */
+ deadlineAtMs: number | null;
}
interface ReconcileResult {
@@ -1551,7 +1551,7 @@ interface ReconcileResult {
* resume stays balanced.
*/
async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileResult> {
- const { engine, jobId, priorMessages, priorTools, toolDefs, signal } = args;
+ const { engine, jobId, priorMessages, priorTools, toolDefs, signal, deadlineAtMs } = args;
const work = priorMessages.map(m => {
const adapted = adaptContentBlocksToChatBlocks(m.content_blocks);
@@ -1654,8 +1654,8 @@ async function reconcileGatewayReplay(args: ReconcileArgs): Promise<ReconcileRes
retainToolWriteRequestId(call.input, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName);
await persistToolExecPending(engine, jobId, msg.message_idx, callIdx, call.toolCallId, call.toolName, call.input);
try {
- const output = await toolDef.execute(call.input, { engine, jobId, remote: true, signal });
- assertToolWriteCommitted(output, call.toolName);
+ const output = await runToolWrite(() => toolDef.execute(call.input, { engine, jobId, remote: true, signal }), call.toolName,
+ { deadlineAtMs, signal });
await persistToolExecComplete(engine, jobId, msg.message_idx, callIdx, call.toolCallId, output);
results.push({ type: 'tool-result', toolCallId: call.toolCallId, toolName: call.toolName, output });
} catch (e) {
diff --git a/src/core/minions/tool-write-identity.ts b/src/core/minions/tool-write-identity.ts
index 5b5468b6a9..fe7069aaa3 100644
--- a/src/core/minions/tool-write-identity.ts
+++ b/src/core/minions/tool-write-identity.ts
@@ -3,6 +3,9 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { isWriteReceipt } from '../persistence/types.ts';
import { isPersistenceIpcMutation } from '../persistence/ipc.ts';
+import { WRITE_ADMISSION_HEADROOM_MS, replayWhilePending } from '../persistence/write-wait.ts';
+import { WIRE_WRITE_WAIT_MAX_MS } from '../persistence/params.ts';
+import { maintenanceWriteWaitMs } from '../persistence/maintenance-wait.ts';
/** Bind a durable write to its persisted tool execution, including crash replay. */
export function retainToolWriteRequestId(input: unknown, jobId: number, messageIdx: number, ordinal: number, toolUseId: string, toolName: string): void {
@@ -25,6 +28,39 @@ export function assertToolWriteCommitted(output: unknown, toolName: string): voi
{ fix: readFix(`Reads tool write ${output.request_id}'s durable receipt, read-only.`, { argv: ['gbrain', 'write-request', '--', output.request_id] }) });
error.writeRequest = output; error.writeError = code; throw error;
}
+
+/**
+ * A pending tool write stops waiting this long before the job deadline: one
+ * more tool wait at its longest (each replay resends the model's `wait_ms`)
+ * plus admission headroom, so the handler returns `write_pending` (a retry
+ * under a fresh deadline) before the runner's timeout marks the job dead.
+ */
+const TOOL_WRITE_DEADLINE_RESERVE_MS = WIRE_WRITE_WAIT_MAX_MS + WRITE_ADMISSION_HEADROOM_MS;
+
+/**
+ * #5474: run a tool and wait for its accepted write. The tool's own bounded
+ * wait can end while the write is still queued; replaying the same request_id
+ * admits nothing new and calls no model, so the job replays until the write
+ * is terminal, the job is cancelled, or the job deadline less the reserve
+ * arrives (a job without a deadline waits the #5854 maintenance wait). The
+ * job cannot take its next turn without the result. Only then does the write
+ * leave the handler as `write_pending`, its tool row still pending for the
+ * retry: runners count that as a failed attempt, and the dream inline drain
+ * retries at once. Tradeoff: a write that never commits holds the job, and a
+ * serial dream drain behind it, until that deadline. The receipt's
+ * `inspect_owner` advice is no exit signal: it also marks writer-pool
+ * contention and any write older than 2 min, the slow commits this wait is for.
+ */
+export async function runToolWrite(run: () => Promise<unknown>, toolName: string,
+ job: { deadlineAtMs: number | null; signal?: AbortSignal }): Promise<unknown> {
+ const waitMs = job.deadlineAtMs == null ? maintenanceWriteWaitMs()
+ : Math.max(0, job.deadlineAtMs - Date.now() - TOOL_WRITE_DEADLINE_RESERVE_MS);
+ return replayWhilePending(async () => {
+ const output = await run();
+ assertToolWriteCommitted(output, toolName);
+ return output;
+ }, waitMs, { signal: job.signal });
+}
export function isPendingToolWrite(error: unknown): error is OperationError {
return error instanceof OperationError && error.code === 'write_pending' && error.writeRequest !== undefined;
}
diff --git a/src/core/persistence/maintenance-wait.ts b/src/core/persistence/maintenance-wait.ts
index b7a94d65c9..10aaeadc67 100644
--- a/src/core/persistence/maintenance-wait.ts
+++ b/src/core/persistence/maintenance-wait.ts
@@ -31,6 +31,9 @@ export function __setMaintenanceWriteWaitForTests(ms: number | null): () => void
/** The wait for a maintenance publish outside a job budget. */
export function maintenancePublishWaitMs(): number { return testWaitMs ?? MAINTENANCE_PUBLISH_WAIT_MS; }
+/** A job's write wait when it has no deadline; also a subagent tool write's (#5474). */
+export function maintenanceWriteWaitMs(): number { return testWaitMs ?? MAINTENANCE_WRITE_WAIT_MS; }
+
export class MaintenanceWriteWait {
private pending = false;
constructor(private readonly deadlineAtMs: number | null = null, private readonly now: () => number = Date.now) {}
diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.ts
index ea7d602583..3e6967500e 100644
--- a/src/core/persistence/write-wait.ts
+++ b/src/core/persistence/write-wait.ts
@@ -8,6 +8,7 @@ import { loadConfig, type GBrainConfig } from '../config.ts';
import { getCliOptions } from '../cli-options.ts';
import { PENDING_WRITE_EXIT_CODE } from '../exit-codes.ts';
import { OperationError } from '../ops/contract.ts';
+import { abortableSleep } from '../retry.ts';
import { admittedPendingReceipt, type WriteReceipt } from './types.ts';
import { WIRE_WRITE_WAIT_MAX_MS } from './params.ts';
@@ -129,18 +130,22 @@ export function pollCommand(requestId: string): string {
* Keep the caller's wait across transports that wait less than it (an older
* owner, or a remote server's own bounded wait): replay the identical request
* (same request_id, so nothing new is admitted) until it settles or the wait
- * is spent. Only an admitted pending receipt is replayed.
+ * is spent. Only an admitted pending receipt is replayed. An aborted `signal`
+ * ends the pause and stops the replays; the pending error propagates with its
+ * receipt.
*/
export async function replayWhilePending<T>(send: () => Promise<T>, waitMs: number,
- sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms))): Promise<T> {
+ { sleep = abortableSleep, signal }: { sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; signal?: AbortSignal } = {}): Promise<T> {
const deadline = Date.now() + waitMs;
for (;;) {
try { return await send(); }
catch (error) {
const receipt = pendingReceiptOf(error);
const remaining = deadline - Date.now();
- if (!receipt || remaining <= 0) throw error;
- await sleep(Math.min(Math.max(receipt.retry_after_ms ?? 1000, 50), remaining));
+ if (!receipt || remaining <= 0 || signal?.aborted) throw error;
+ await sleep(Math.min(Math.max(receipt.retry_after_ms ?? 1000, 50), remaining), signal)
+ .catch(sleepError => { if (!signal?.aborted) throw sleepError; });
+ if (signal?.aborted) throw error;
}
}
}
diff --git a/test/e2e/subagent-gateway-resume-reconciliation.test.ts b/test/e2e/subagent-gateway-resume-reconciliation.test.ts
index 33ae063b46..03267699f0 100644
--- a/test/e2e/subagent-gateway-resume-reconciliation.test.ts
+++ b/test/e2e/subagent-gateway-resume-reconciliation.test.ts
@@ -33,6 +33,7 @@ import {
type ChatMessage,
type ChatResult,
} from '../../src/core/ai/gateway.ts';
+import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';
let engine: PGLiteEngine;
@@ -130,7 +131,7 @@ function assertBalanced(messages: ChatMessage[]): void {
describe('gateway resume reconciliation', () => {
it('a pending journal write stays pending and replays its UUID before another model turn', async () => {
- let turns = 0; let pending = true; const identities: unknown[] = [];
+ let turns = 0; let queued = Number.POSITIVE_INFINITY; const identities: unknown[] = [];
__setChatTransportForTests(async () => {
turns++;
return { text: turns === 1 ? '' : 'done', blocks: turns === 1
@@ -147,13 +148,18 @@ describe('gateway resume reconciliation', () => {
expect(id).toMatch(/^[0-9a-f-]{36}$/);
const [row] = await engine.executeRaw<{ request_id: string }>("SELECT input->>'request_id' AS request_id FROM subagent_tool_executions WHERE job_id=$1", [jobId]);
expect(row.request_id).toBe(id);
- return { request_id: id, state: pending ? 'queued' : 'committed', retry_after_ms: pending ? 100 : null };
+ return { request_id: id, state: queued-- > 0 ? 'queued' : 'committed', retry_after_ms: 20 };
} }];
- await expect(buildHandler(registry)(ctx)).rejects.toMatchObject({ code: 'write_pending' });
+ // No in-run wait (#5474): the job's write wait would otherwise replay the pending receipt for 30 s.
+ const restoreWait = __setMaintenanceWriteWaitForTests(0);
+ try {
+ await expect(buildHandler(registry)(ctx)).rejects.toMatchObject({ code: 'write_pending' });
+ } finally { restoreWait(); }
expect((await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]))[0].status).toBe('pending');
- pending = false;
+ // The resumed dispatch replays the still-pending write until it commits (#5474).
+ queued = 2;
await buildHandler(registry)(ctx);
- expect(turns).toBe(2); expect(identities).toHaveLength(2); expect(identities[1]).toBe(identities[0]);
+ expect(turns).toBe(2); expect(identities).toEqual(Array(4).fill(identities[0]));
expect((await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]))[0].status).toBe('complete');
});
diff --git a/test/minions/subagent-oneshot.test.ts b/test/minions/subagent-oneshot.test.ts
index cabbac1c0b..483137343e 100644
--- a/test/minions/subagent-oneshot.test.ts
+++ b/test/minions/subagent-oneshot.test.ts
@@ -25,6 +25,7 @@ import {
type OneshotArgs,
} from '../../src/core/minions/handlers/subagent-oneshot.ts';
import type { ChatResult } from '../../src/core/ai/gateway.ts';
+import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;
@@ -184,22 +185,45 @@ describe('extractWikilinkTargets', () => {
});
describe('runSubagentOneshot', () => {
- test('pending write receipts retain the whole ledger and retry without another provider call', async () => {
- const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);
+ /** The real put_page behind a stub that reports the next `queued.left` dispatches as still queued. */
+ function queuedThenCommitted(args: OneshotArgs) {
const realTool = args.putPageTool!; const realChat = args._chat!;
- let chatCalls = 0; let pending = true; const ids: unknown[] = [];
- args._chat = (async (options: Parameters<typeof realChat>[0]) => { chatCalls++; return realChat(options); }) as typeof realChat;
+ const state = { chatCalls: 0, queued: 0, ids: [] as unknown[] };
+ args._chat = (async (options: Parameters<typeof realChat>[0]) => { state.chatCalls++; return realChat(options); }) as typeof realChat;
args.putPageTool = { ...realTool, execute: async (input, context) => {
- const id = (input as Record<string, unknown>).request_id; ids.push(id);
- if (pending) return { request_id: id, state: 'queued', retry_after_ms: 100 };
+ const id = (input as Record<string, unknown>).request_id; state.ids.push(id);
+ if (state.queued-- > 0) return { request_id: id, state: 'queued', retry_after_ms: 20 };
return realTool.execute(input, context);
} };
- await expect(runSubagentOneshot(args)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });
- const rows = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [ctx.id]);
- expect(rows).toHaveLength(2); expect(rows.every(row => row.status === 'pending')).toBe(true);
- pending = false;
+ return state;
+ }
+ const toolRowStatuses = async (jobId: number) =>
+ (await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1 ORDER BY ordinal', [jobId])).map(row => row.status);
+
+ test('pending write receipts retain the whole ledger and retry without another provider call', async () => {
+ const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);
+ const run = queuedThenCommitted(args);
+ run.queued = Number.POSITIVE_INFINITY;
+ // No in-run wait (#5474): the job's write wait would otherwise replay the pending receipt for 30 s.
+ const restoreWait = __setMaintenanceWriteWaitForTests(0);
+ try {
+ await expect(runSubagentOneshot(args)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });
+ } finally { restoreWait(); }
+ expect(await toolRowStatuses(ctx.id)).toEqual(['pending', 'pending']);
+ // Recovery replays a still-pending row until its write commits (#5474).
+ run.queued = 2;
+ expect((await runSubagentOneshot(args)).kind).toBe('done');
+ expect(run.chatCalls).toBe(1); expect(run.ids.slice(0, 4)).toEqual(Array(4).fill(run.ids[0]));
+ expect(await toolRowStatuses(ctx.id)).toEqual(['complete', 'complete']);
+ });
+
+ test('a write that commits during the job wait completes in one run without another provider call (#5474)', async () => {
+ const ctx = await makeCtx(DATA); const args = makeArgs(ctx, DATA, VALID_RESPONSE);
+ const run = queuedThenCommitted(args);
+ run.queued = 2;
expect((await runSubagentOneshot(args)).kind).toBe('done');
- expect(chatCalls).toBe(1); expect(ids[1]).toBe(ids[0]);
+ expect(run.chatCalls).toBe(1); expect(run.ids.slice(0, 3)).toEqual(Array(3).fill(run.ids[0]));
+ expect(await toolRowStatuses(ctx.id)).toEqual(['complete', 'complete']);
});
test('happy path: validates, writes both pages via put_page, ledger rows land, transcript persisted', async () => {
diff --git a/test/subagent-handler.test.ts b/test/subagent-handler.test.ts
index 6aca96e9e7..416050d171 100644
--- a/test/subagent-handler.test.ts
+++ b/test/subagent-handler.test.ts
@@ -195,6 +195,25 @@ describe('subagent handler happy path', () => {
expect(out).toEqual({ echoed: { value: 'v1' } });
});
+ test('a tool write still queued after its own wait is replayed until it commits, without another model call (#5474)', async () => {
+ const ids: unknown[] = [];
+ const tool: ToolDef = { ...makeEchoTool('brain_put_page'), async execute(input) {
+ const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);
+ return { request_id, state: ids.length < 3 ? 'queued' : 'committed', retry_after_ms: 20 };
+ } };
+ const client = new FakeMessagesClient([
+ { content: [{ type: 'tool_use', id: 'tu_1', name: 'brain_put_page', input: { slug: 'notes/pending-example' } } as any], stop_reason: 'tool_use' as any },
+ { content: [{ type: 'text', text: 'done' }] as any, stop_reason: 'end_turn' },
+ ]);
+ const ctx = await makeCtx({ prompt: 'go' });
+ const result = await makeSubagentHandler({ engine, client, toolRegistry: [tool] })(ctx);
+ expect(result.stop_reason).toBe('end_turn');
+ expect(client.calls.length).toBe(2);
+ expect(ids).toEqual(Array(3).fill(ids[0]));
+ const rows = await engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id = $1', [ctx.id]);
+ expect(rows.map(row => row.status)).toEqual(['complete']);
+ });
+
test('tool throws: row goes failed, model sees error, loop continues', async () => {
const tool = makeThrowingTool();
const client = new FakeMessagesClient([
diff --git a/test/subagent-pending-tool-write.test.ts b/test/subagent-pending-tool-write.test.ts
new file mode 100644
index 0000000000..08b8ec8bb2
--- /dev/null
+++ b/test/subagent-pending-tool-write.test.ts
@@ -0,0 +1,172 @@
+/**
+ * #5474: a subagent child whose accepted brain write is still committing when
+ * the tool's own bounded wait ends replays the same request id until the write
+ * is terminal, up to the job deadline, instead of leaving the handler as a
+ * failed attempt. Before the fix every runner counted `write_pending` as an
+ * ordinary failure: the dream inline drain retried at once, the worker after
+ * 1 s and 2 s, so a write committing after its third 5 s wait killed the child
+ * although the page committed, and the next cycle paid to synthesize it again.
+ * Existing tests pin the handler's rejection after one wait and the resumed
+ * replay, not the child's outcome under a runner. Uses the existing gateway
+ * chat-transport and maintenance-wait test seams.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { runSubagentsInline } from '../src/core/cycle/inline-drain.ts';
+import { makeSubagentHandler } from '../src/core/minions/handlers/subagent.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
+import { WIRE_WRITE_WAIT_MAX_MS } from '../src/core/persistence/params.ts';
+import { WRITE_ADMISSION_HEADROOM_MS } from '../src/core/persistence/write-wait.ts';
+import type { MinionJobContext, ToolDef } from '../src/core/minions/types.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+
+let engine: PGLiteEngine;
+let modelTurns = 0;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });
+afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ await engine.setConfig('agent.use_gateway_loop', 'true');
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ expansion_model: 'anthropic:claude-haiku-4-5', env: { ANTHROPIC_API_KEY: 'stub', OPENAI_API_KEY: 'stub' } } as never);
+ modelTurns = 0;
+ __setChatTransportForTests(async () => {
+ modelTurns++;
+ return { text: modelTurns === 1 ? '' : 'done', blocks: modelTurns === 1
+ ? [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'brain_put_page', input: { slug: 'notes/pending-example', content: 'fixture' } }]
+ : [{ type: 'text', text: 'done' }], stopReason: modelTurns === 1 ? 'tool_calls' : 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'openai:gpt-4o', providerId: 'openai' } satisfies ChatResult;
+ });
+});
+
+type Shape = 'returned receipt' | 'thrown write_pending';
+/** A put_page whose write commits on dispatch `commitsOn`; earlier dispatches report it queued, as the real tool does after its 5 s wait. */
+function putPage(shape: Shape, commitsOn: number, retryAfterMs: (dispatch: number) => number = () => 20) {
+ const ids: unknown[] = [];
+ const tool: ToolDef = { name: 'brain_put_page', description: 'p', input_schema: { type: 'object' }, idempotent: true,
+ execute: async input => {
+ const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);
+ if (ids.length >= commitsOn) return { request_id, state: 'committed', retry_after_ms: null };
+ const receipt = { request_id, state: 'queued', retry_after_ms: retryAfterMs(ids.length) };
+ if (shape === 'returned receipt') return receipt;
+ const error = new OperationError('write_pending', 'The write is accepted and is still pending.', 'Read the receipt until it is terminal.');
+ error.writeRequest = receipt as never; error.writeError = 'write_pending';
+ throw error;
+ } };
+ return { tool, ids };
+}
+const handlerFor = (tool: ToolDef) => makeSubagentHandler({ engine, config: {} as never, toolRegistry: [tool],
+ makeAnthropic: () => ({ messages: { create: async () => { throw new Error('legacy path unused'); } } }) as never });
+const toolRows = (jobId: number) => engine.executeRaw<{ status: string }>('SELECT status FROM subagent_tool_executions WHERE job_id=$1', [jobId]);
+
+async function runOnWorker(handler: ReturnType<typeof handlerFor>): Promise<number> {
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });
+ const worker = new MinionWorker(engine, { pollInterval: 25 });
+ worker.register('subagent', handler);
+ const running = worker.start();
+ for (let i = 0; i < 400 && !['completed', 'dead', 'failed'].includes((await queue.getJob(job.id))!.status); i++) await new Promise(r => setTimeout(r, 25));
+ worker.stop(); await running;
+ return job.id;
+}
+async function runInline(handler: ReturnType<typeof handlerFor>): Promise<number> {
+ const queue = new MinionQueue(engine);
+ const queueName = `dream-inline-${Date.now()}-5474abcd`;
+ const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, { queue: queueName }, { allowProtectedSubmit: true });
+ await runSubagentsInline(engine, queue, queueName, undefined, handler);
+ return job.id;
+}
+
+describe('a child waits for its accepted tool write instead of dying (#5474)', () => {
+ // A child with a deadline waits up to it: the maintenance wait (here 50 ms)
+ // bounds only a job without one.
+ let restoreWait: () => void = () => {};
+ beforeEach(() => { restoreWait = __setMaintenanceWriteWaitForTests(50); });
+ afterEach(() => restoreWait());
+
+ const cases = (['dream inline drain', 'worker'] as const).flatMap(runner =>
+ (['returned receipt', 'thrown write_pending'] as const).map(shape => [runner, shape] as const));
+ test.each(cases)('%s, %s: the write commits after several bounded waits and the child completes', async (runner, shape) => {
+ const { tool, ids } = putPage(shape, 8);
+ const jobId = await (runner === 'worker' ? runOnWorker : runInline)(handlerFor(tool));
+ const job = (await new MinionQueue(engine).getJob(jobId))!;
+ expect({ status: job.status, error: job.error_text }).toEqual({ status: 'completed', error: null });
+ expect(ids).toHaveLength(8);
+ expect(new Set(ids).size).toBe(1);
+ expect(modelTurns).toBe(2);
+ expect((await toolRows(jobId)).map(row => row.status)).toEqual(['complete']);
+ }, 20_000);
+
+ test.each([
+ // Inside the reserve (the longest model wait_ms plus admission headroom) the wait ends at once,
+ // so the retry starts before the runner's timeout marks the job dead.
+ ['the job deadline is inside its reserve', { deadlineInMs: 30_000, abortInMs: null, replays: false }],
+ // The fourth receipt asks for a 10 s pause; the cancellation must end it.
+ ['the job is cancelled', { deadlineInMs: 120_000, abortInMs: 300, replays: true }],
+ ] as const)('a write still pending when %s leaves the handler pending before the deadline', async (_when, { deadlineInMs, abortInMs, replays }) => {
+ const { tool, ids } = putPage('thrown write_pending', Number.POSITIVE_INFINITY, dispatch => dispatch < 4 ? 20 : 10_000);
+ const queue = new MinionQueue(engine);
+ const job = await queue.add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });
+ const abort = new AbortController();
+ if (abortInMs !== null) setTimeout(() => abort.abort(new Error('cancelled')), abortInMs);
+ const deadlineAtMs = Date.now() + deadlineInMs;
+ const ctx = { id: job.id, name: 'subagent', data: job.data, attempts_made: 0, signal: abort.signal, deadlineAtMs, shutdownSignal: new AbortController().signal,
+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as MinionJobContext;
+ const started = Date.now();
+ const error = await handlerFor(tool)(ctx).then(() => null, (e: unknown) => e as OperationError);
+ expect(error).toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued', request_id: ids[0] } });
+ expect(Date.now()).toBeLessThan(deadlineAtMs);
+ expect(Date.now() - started).toBeLessThan(5_000);
+ expect(ids.length > 1).toBe(replays);
+ expect(new Set(ids).size).toBe(1);
+ expect(modelTurns).toBe(1);
+ expect((await toolRows(job.id)).map(row => row.status)).toEqual(['pending']);
+ // An aborted wait stops replaying: no dispatch lands after the handler left.
+ const dispatched = ids.length;
+ await new Promise(r => setTimeout(r, 200));
+ expect(ids).toHaveLength(dispatched);
+ }, 20_000);
+
+ async function directCtx(deadlineAtMs: number | null) {
+ const job = await new MinionQueue(engine).add('subagent', { prompt: 'persist the fixture', model: 'openai:gpt-4o' }, {}, { allowProtectedSubmit: true });
+ return { id: job.id, name: 'subagent', data: job.data, attempts_made: 0, signal: new AbortController().signal, deadlineAtMs,
+ shutdownSignal: new AbortController().signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {},
+ isActive: async () => true, readInbox: async () => [] } as MinionJobContext;
+ }
+
+ test('a write that never commits holds the job until the deadline less the reserve, then leaves it pending', async () => {
+ const holdMs = 600;
+ const { tool, ids } = putPage('returned receipt', Number.POSITIVE_INFINITY);
+ const deadlineAtMs = Date.now() + WIRE_WRITE_WAIT_MAX_MS + WRITE_ADMISSION_HEADROOM_MS + holdMs;
+ const ctx = await directCtx(deadlineAtMs);
+ const started = Date.now();
+ await expect(handlerFor(tool)(ctx)).rejects.toMatchObject({ code: 'write_pending', writeRequest: { state: 'queued' } });
+ const held = Date.now() - started;
+ expect(held).toBeGreaterThanOrEqual(holdMs - 100);
+ expect(held).toBeLessThan(holdMs + 2_000);
+ expect(ids.length).toBeGreaterThan(5);
+ expect(new Set(ids).size).toBe(1);
+ expect(modelTurns).toBe(1);
+ expect((await toolRows(ctx.id)).map(row => row.status)).toEqual(['pending']);
+ }, 20_000);
+
+ test('a write that ended failed is not replayed; the model sees the failure on its next turn', async () => {
+ const ids: unknown[] = [];
+ const tool: ToolDef = { name: 'brain_put_page', description: 'p', input_schema: { type: 'object' }, idempotent: true,
+ execute: async input => {
+ const request_id = (input as Record<string, unknown>).request_id; ids.push(request_id);
+ return { request_id, state: 'failed', retry_after_ms: null };
+ } };
+ const ctx = await directCtx(Date.now() + 120_000);
+ await handlerFor(tool)(ctx);
+ expect(ids).toHaveLength(1);
+ expect(modelTurns).toBe(2);
+ }, 20_000);
+});