Skip to content

Commit f00bf01

Browse files
committed
fix(agents): serialize subagent orphan recovery
1 parent b6b440d commit f00bf01

3 files changed

Lines changed: 293 additions & 8 deletions

File tree

Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { GatewayRecoveryRuntime } from "../gateway/server-instance-runtime.types.js";
3+
import {
4+
resetOrphanRecoveryCoordinationForTest,
5+
scheduleOrphanRecovery,
6+
} from "./subagent-orphan-recovery.js";
7+
import * as subagentRegistrySteerRuntime from "./subagent-registry-steer-runtime.js";
8+
import type { SubagentRunRecord } from "./subagent-registry.types.js";
9+
import { createSubagentRunRecord } from "./subagent-test-fixtures.test-helpers.js";
10+
11+
const sessionMocks = vi.hoisted(() => {
12+
type MockSessionEntry = Record<string, unknown>;
13+
type MockSessionStore = Record<string, MockSessionEntry>;
14+
const loadSessionStore = vi.fn((): MockSessionStore => ({}));
15+
const patchSessionEntry = vi.fn(
16+
async (
17+
scope: { sessionKey: string },
18+
update: (
19+
entry: MockSessionEntry,
20+
) => MockSessionEntry | Partial<MockSessionEntry> | null | Promise<MockSessionEntry | null>,
21+
) => {
22+
const store = loadSessionStore();
23+
const current = store[scope.sessionKey];
24+
if (!current) {
25+
return null;
26+
}
27+
const next = await update({ ...current });
28+
if (!next) {
29+
return current;
30+
}
31+
store[scope.sessionKey] = next;
32+
return next;
33+
},
34+
);
35+
return { loadSessionStore, patchSessionEntry };
36+
});
37+
38+
vi.mock("../config/config.js", () => ({
39+
getRuntimeConfig: vi.fn(() => ({ session: { store: undefined } })),
40+
}));
41+
42+
vi.mock("../config/sessions.js", () => ({
43+
resolveAgentIdFromSessionKey: vi.fn(() => "main"),
44+
resolveStorePath: vi.fn(() => "/tmp/test-sessions.json"),
45+
}));
46+
47+
vi.mock("../config/sessions/session-accessor.js", () => ({
48+
loadSessionEntry: vi.fn(
49+
(scope: { sessionKey: string }) => sessionMocks.loadSessionStore()[scope.sessionKey],
50+
),
51+
patchSessionEntry: sessionMocks.patchSessionEntry,
52+
}));
53+
54+
vi.mock("../logging/subsystem.js", () => ({
55+
createSubsystemLogger: () => ({ info: vi.fn(), warn: vi.fn() }),
56+
}));
57+
58+
vi.mock("./subagent-registry-steer-runtime.js", () => ({
59+
finalizeInterruptedSubagentRun: vi.fn(async () => 1),
60+
replaceSubagentRunAfterSteer: vi.fn(() => true),
61+
reserveSwarmCollectorLaunch: vi.fn(() => true),
62+
}));
63+
64+
const childSessionKey = "agent:main:subagent:recovery-coordination";
65+
const dispatchAgent = vi.fn(async () => ({ runId: "recovery-run" }));
66+
const readSessionMessages = vi.fn(async () => [] as unknown[]);
67+
const gatewayRuntime: GatewayRecoveryRuntime = {
68+
dispatchAgent: dispatchAgent as GatewayRecoveryRuntime["dispatchAgent"],
69+
waitForAgent: vi.fn(),
70+
sendRecoveryNotice: vi.fn(),
71+
};
72+
73+
function createRun(): SubagentRunRecord {
74+
return createSubagentRunRecord({
75+
runId: "interrupted-run",
76+
childSessionKey,
77+
requesterSessionKey: "agent:main:main",
78+
requesterDisplayKey: "main",
79+
task: "continue the interrupted task",
80+
cleanup: "keep",
81+
createdAt: Date.now() - 60_000,
82+
startedAt: Date.now() - 55_000,
83+
});
84+
}
85+
86+
function createActiveRuns(): Map<string, SubagentRunRecord> {
87+
const run = createRun();
88+
return new Map([[run.runId, run]]);
89+
}
90+
91+
function mockAbortedSession() {
92+
const store = {
93+
[childSessionKey]: {
94+
sessionId: "session-1",
95+
updatedAt: Date.now(),
96+
abortedLastRun: true,
97+
},
98+
};
99+
sessionMocks.loadSessionStore.mockReturnValue(store);
100+
return store;
101+
}
102+
103+
function schedule(
104+
getActiveRuns: () => Map<string, SubagentRunRecord>,
105+
options: {
106+
delayMs?: number;
107+
getGatewayRuntime?: () => GatewayRecoveryRuntime | undefined;
108+
maxRetries?: number;
109+
} = {},
110+
) {
111+
scheduleOrphanRecovery({
112+
getGatewayRuntime: options.getGatewayRuntime ?? (() => gatewayRuntime),
113+
getActiveRuns,
114+
readSessionMessages,
115+
delayMs: options.delayMs ?? 1,
116+
maxRetries: options.maxRetries ?? 0,
117+
});
118+
}
119+
120+
describe("subagent orphan recovery coordination", () => {
121+
beforeEach(() => {
122+
vi.useFakeTimers();
123+
vi.clearAllMocks();
124+
resetOrphanRecoveryCoordinationForTest();
125+
dispatchAgent.mockResolvedValue({ runId: "recovery-run" });
126+
readSessionMessages.mockResolvedValue([]);
127+
vi.mocked(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).mockResolvedValue(1);
128+
});
129+
130+
afterEach(() => {
131+
resetOrphanRecoveryCoordinationForTest();
132+
vi.useRealTimers();
133+
});
134+
135+
it("coalesces duplicate schedules before the recovery scan starts", async () => {
136+
mockAbortedSession();
137+
const activeRuns = createActiveRuns();
138+
const getActiveRuns = vi.fn(() => activeRuns);
139+
140+
schedule(getActiveRuns);
141+
schedule(getActiveRuns);
142+
await vi.advanceTimersByTimeAsync(1);
143+
144+
expect(getActiveRuns).toHaveBeenCalledOnce();
145+
expect(dispatchAgent).toHaveBeenCalledOnce();
146+
expect(sessionMocks.patchSessionEntry).toHaveBeenCalledOnce();
147+
});
148+
149+
it("queues one follow-up scan when recovery is requested during an active scan", async () => {
150+
mockAbortedSession();
151+
const activeRuns = createActiveRuns();
152+
const getActiveRuns = vi.fn(() => activeRuns);
153+
let releaseDispatch: () => void = () => {};
154+
let markDispatchStarted: () => void = () => {};
155+
const dispatchStarted = new Promise<void>((resolve) => {
156+
markDispatchStarted = resolve;
157+
});
158+
const dispatchRelease = new Promise<void>((resolve) => {
159+
releaseDispatch = resolve;
160+
});
161+
dispatchAgent.mockImplementationOnce(async () => {
162+
markDispatchStarted();
163+
await dispatchRelease;
164+
return { runId: "recovery-run" };
165+
});
166+
167+
schedule(getActiveRuns);
168+
await vi.advanceTimersByTimeAsync(1);
169+
await dispatchStarted;
170+
171+
schedule(getActiveRuns);
172+
releaseDispatch();
173+
await vi.advanceTimersByTimeAsync(0);
174+
expect(getActiveRuns).toHaveBeenCalledOnce();
175+
176+
await vi.advanceTimersByTimeAsync(1);
177+
178+
expect(getActiveRuns).toHaveBeenCalledTimes(2);
179+
expect(dispatchAgent).toHaveBeenCalledOnce();
180+
});
181+
182+
it("queues one follow-up scan when recovery is requested during retry backoff", async () => {
183+
mockAbortedSession();
184+
const activeRuns = createActiveRuns();
185+
const getActiveRuns = vi.fn(() => activeRuns);
186+
dispatchAgent
187+
.mockRejectedValueOnce(new Error("gateway unavailable"))
188+
.mockResolvedValueOnce({ runId: "recovery-run" });
189+
190+
schedule(getActiveRuns, { maxRetries: 1 });
191+
await vi.advanceTimersByTimeAsync(1);
192+
193+
schedule(getActiveRuns);
194+
await vi.advanceTimersByTimeAsync(2);
195+
196+
expect(getActiveRuns).toHaveBeenCalledTimes(2);
197+
expect(dispatchAgent).toHaveBeenCalledTimes(2);
198+
199+
await vi.advanceTimersByTimeAsync(1);
200+
201+
expect(getActiveRuns).toHaveBeenCalledTimes(3);
202+
expect(dispatchAgent).toHaveBeenCalledTimes(2);
203+
});
204+
205+
it.each([
206+
["missing runtime", () => undefined],
207+
[
208+
"thrown runtime lookup",
209+
() => {
210+
throw new Error("runtime unavailable");
211+
},
212+
],
213+
])("releases coordination after terminal %s", async (_label, getGatewayRuntime) => {
214+
mockAbortedSession();
215+
const activeRuns = createActiveRuns();
216+
const getActiveRuns = vi.fn(() => activeRuns);
217+
218+
schedule(getActiveRuns, { getGatewayRuntime });
219+
await vi.advanceTimersByTimeAsync(1);
220+
221+
schedule(getActiveRuns);
222+
await vi.advanceTimersByTimeAsync(1);
223+
224+
expect(getActiveRuns).toHaveBeenCalledOnce();
225+
expect(dispatchAgent).toHaveBeenCalledOnce();
226+
});
227+
228+
it("releases coordination after terminal finalization is exhausted", async () => {
229+
mockAbortedSession();
230+
const activeRuns = createActiveRuns();
231+
const getActiveRuns = vi.fn(() => activeRuns);
232+
dispatchAgent.mockRejectedValueOnce(new Error("gateway unavailable"));
233+
vi.mocked(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).mockResolvedValue(0);
234+
235+
schedule(getActiveRuns);
236+
await vi.advanceTimersByTimeAsync(4);
237+
238+
expect(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).toHaveBeenCalledTimes(3);
239+
240+
schedule(getActiveRuns);
241+
await vi.advanceTimersByTimeAsync(1);
242+
243+
expect(getActiveRuns).toHaveBeenCalledTimes(2);
244+
expect(dispatchAgent).toHaveBeenCalledTimes(2);
245+
});
246+
});

‎src/agents/subagent-orphan-recovery.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { resolveInternalSessionEffectsTarget } from "./internal-session-effects.
1313
import * as announceDelivery from "./subagent-announce-delivery.js";
1414
import {
1515
recoverOrphanedSubagentSessions as recoverOrphanedSubagentSessionsWithRuntime,
16+
resetOrphanRecoveryCoordinationForTest,
1617
scheduleOrphanRecovery as scheduleOrphanRecoveryWithRuntime,
1718
} from "./subagent-orphan-recovery.js";
1819
import * as subagentRegistrySteerRuntime from "./subagent-registry-steer-runtime.js";
@@ -224,6 +225,7 @@ describe("subagent-orphan-recovery", () => {
224225
vi.useFakeTimers();
225226
vi.clearAllMocks();
226227
resetGatewayWorkAdmission();
228+
resetOrphanRecoveryCoordinationForTest();
227229
dispatchAgent.mockReset();
228230
dispatchAgent.mockResolvedValue({ runId: "test-run-id" });
229231
readSessionMessages.mockReset();
@@ -235,6 +237,7 @@ describe("subagent-orphan-recovery", () => {
235237

236238
afterEach(() => {
237239
resetGatewayWorkAdmission();
240+
resetOrphanRecoveryCoordinationForTest();
238241
vi.useRealTimers();
239242
vi.restoreAllMocks();
240243
});

‎src/agents/subagent-orphan-recovery.ts‎

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,24 @@ const log = createSubsystemLogger("subagent-interrupted-resume");
4444
/** Delay before attempting recovery to let the gateway finish bootstrapping. */
4545
const DEFAULT_RECOVERY_DELAY_MS = 5_000;
4646

47+
type OrphanRecoveryScheduleParams = {
48+
getGatewayRuntime: () => GatewayRecoveryRuntime | undefined;
49+
getActiveRuns: () => Map<string, SubagentRunRecord>;
50+
readSessionMessages?: typeof readSessionMessagesAsync;
51+
delayMs?: number;
52+
maxRetries?: number;
53+
};
54+
55+
let scheduledRecoveryPhase: "scheduled" | "running" | undefined;
56+
let scheduledRecoveryHasStarted = false;
57+
let pendingRecoverySchedule: OrphanRecoveryScheduleParams | undefined;
58+
59+
export function resetOrphanRecoveryCoordinationForTest(): void {
60+
scheduledRecoveryPhase = undefined;
61+
scheduledRecoveryHasStarted = false;
62+
pendingRecoverySchedule = undefined;
63+
}
64+
4765
function isLegacyRestartInterruptedTimeout(
4866
runRecord: SubagentRunRecord,
4967
entry: SessionEntry | undefined,
@@ -603,21 +621,34 @@ async function finalizeInterruptedRunWithRetry(params: {
603621
* The delay gives the gateway time to fully bootstrap after restart.
604622
* If recovery fails (e.g. gateway not yet ready), retries with exponential backoff.
605623
*/
606-
export function scheduleOrphanRecovery(params: {
607-
getGatewayRuntime: () => GatewayRecoveryRuntime | undefined;
608-
getActiveRuns: () => Map<string, SubagentRunRecord>;
609-
/** Test seam for transcript reads; production uses the canonical reader. */
610-
readSessionMessages?: typeof readSessionMessagesAsync;
611-
delayMs?: number;
612-
maxRetries?: number;
613-
}): void {
624+
export function scheduleOrphanRecovery(params: OrphanRecoveryScheduleParams): void {
625+
if (scheduledRecoveryPhase) {
626+
if (scheduledRecoveryHasStarted) {
627+
pendingRecoverySchedule = params;
628+
}
629+
return;
630+
}
631+
632+
scheduledRecoveryPhase = "scheduled";
614633
const initialDelay = params.delayMs ?? DEFAULT_RECOVERY_DELAY_MS;
615634
const maxRetries = params.maxRetries ?? MAX_RECOVERY_RETRIES;
616635

617636
const resumedSessionKeys = new Set<string>();
618637
const pendingStaleFinalizations = new Map<string, string>();
638+
const finishSchedule = () => {
639+
const pending = pendingRecoverySchedule;
640+
pendingRecoverySchedule = undefined;
641+
scheduledRecoveryPhase = undefined;
642+
scheduledRecoveryHasStarted = false;
643+
if (pending) {
644+
scheduleOrphanRecovery(pending);
645+
}
646+
};
619647
const attemptRecovery = (attempt: number, delay: number) => {
648+
scheduledRecoveryPhase = "scheduled";
620649
setTimeout(() => {
650+
scheduledRecoveryPhase = "running";
651+
scheduledRecoveryHasStarted = true;
621652
// Every delayed/retry scan owns a fresh root lease. Keep terminal
622653
// mutation in the same lease so suspension cannot become ready mid-attempt.
623654
void runWithGatewayIndependentRootWorkAdmission(async () => {
@@ -627,6 +658,8 @@ export function scheduleOrphanRecovery(params: {
627658
if (!gatewayRuntime) {
628659
if (attempt < maxRetries) {
629660
attemptRecovery(attempt + 1, delay * RETRY_BACKOFF_MULTIPLIER);
661+
} else {
662+
finishSchedule();
630663
}
631664
return;
632665
}
@@ -646,6 +679,7 @@ export function scheduleOrphanRecovery(params: {
646679
return;
647680
}
648681
if (result.failedRuns.length === 0) {
682+
finishSchedule();
649683
return;
650684
}
651685
const attempts = attempt + 1;
@@ -668,6 +702,7 @@ export function scheduleOrphanRecovery(params: {
668702
{ runIds: incomplete },
669703
);
670704
}
705+
finishSchedule();
671706
}).catch((err: unknown) => {
672707
if (attempt < maxRetries) {
673708
const nextDelay = delay * RETRY_BACKOFF_MULTIPLIER;
@@ -677,6 +712,7 @@ export function scheduleOrphanRecovery(params: {
677712
attemptRecovery(attempt + 1, nextDelay);
678713
} else {
679714
log.warn(`scheduled orphan recovery failed after ${maxRetries} retries: ${String(err)}`);
715+
finishSchedule();
680716
}
681717
});
682718
}, delay).unref?.();

0 commit comments

Comments
 (0)