Skip to content

Commit c37ba84

Browse files
authored
perf(agents): index subagent recovery ownership (#119793)
* perf(agents): benchmark indexed recovery ownership * perf(agents): index recovery owner lookups
1 parent f5125a7 commit c37ba84

7 files changed

Lines changed: 159 additions & 63 deletions

‎scripts/bench-agent-concurrency-worker.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -575,10 +575,15 @@ function sweepRow(child: number, generation: number, now: number): SubagentRunRe
575575
}
576576

577577
async function runSweepSample(childCount: number): Promise<Sample> {
578-
const { createSubagentRegistrySweeper } =
579-
await import("../src/agents/subagent-registry-sweeper.js");
578+
const [
579+
{ getSubagentRunsForChildSession, subagentRuns: runs },
580+
{ createSubagentRegistrySweeper },
581+
] = await Promise.all([
582+
import("../src/agents/subagent-registry-memory.js"),
583+
import("../src/agents/subagent-registry-sweeper.js"),
584+
]);
580585
const now = Date.now();
581-
const runs = new Map<string, SubagentRunRecord>();
586+
runs.clear();
582587
for (let child = 0; child < childCount; child += 1) {
583588
for (const generation of [3, 2, 1]) {
584589
const entry = sweepRow(child, generation, now);
@@ -632,8 +637,7 @@ async function runSweepSample(childCount: number): Promise<Sample> {
632637
sessionEffects += 1;
633638
},
634639
retireSupersededRun: async () => {},
635-
getRunsForChildSession: (childSessionKey) =>
636-
[...runs.values()].filter((entry) => entry.childSessionKey === childSessionKey),
640+
getRunsForChildSession: getSubagentRunsForChildSession,
637641
getRunsForCollectorGroup: () => [],
638642
warn: () => {},
639643
});
@@ -668,6 +672,7 @@ async function runSweepSample(childCount: number): Promise<Sample> {
668672
};
669673
} finally {
670674
sweeper.reset();
675+
runs.clear();
671676
}
672677
}
673678

‎src/agents/subagent-registry-restart-recovery-coordinator.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type RecoveryRetry = {
1919

2020
type RecoveryCoordinatorParams = {
2121
runs: Map<string, SubagentRunRecord>;
22+
getRunsForChildSession: (childSessionKey: string) => Iterable<SubagentRunRecord>;
2223
getGatewayRuntime: () => GatewayRecoveryRuntime | undefined;
2324
abandonLaunch: ReturnType<
2425
typeof createSubagentRunManager
@@ -61,7 +62,10 @@ export function createInterruptedRecoveryCoordinator(params: RecoveryCoordinator
6162
const retries = new Map<string, RecoveryRetry>();
6263
const ownsCurrentGeneration = (runId: string, entry: SubagentRunRecord) =>
6364
params.runs.get(runId) === entry &&
64-
getLatestSubagentRunByChildSessionKeyFromRuns(params.runs, entry.childSessionKey) === entry;
65+
getLatestSubagentRunByChildSessionKeyFromRuns(
66+
params.getRunsForChildSession(entry.childSessionKey),
67+
entry.childSessionKey,
68+
) === entry;
6569

6670
function defer(runId: string, retry: Omit<RecoveryRetry, "at">, delayMs: number) {
6771
retries.set(runId, { ...retry, at: Date.now() + delayMs });
@@ -119,7 +123,7 @@ export function createInterruptedRecoveryCoordinator(params: RecoveryCoordinator
119123
entry,
120124
now,
121125
gatewayRuntime: params.getGatewayRuntime(),
122-
isCurrent: () => ownsCurrentGeneration(runId, entry),
126+
isCurrent: ownsCurrentGeneration,
123127
abandonLaunch: params.abandonLaunch,
124128
clearAcceptedRecovery: params.clearAcceptedRecovery,
125129
getRun: (targetRunId) => params.runs.get(targetRunId),

‎src/agents/subagent-registry-restart-recovery.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
consumeSessionWorkAdmissionHandoff,
77
type SessionWorkAdmissionLease,
88
} from "../sessions/session-lifecycle-admission.js";
9+
import { getLatestSubagentRunByChildSessionKeyFromRuns } from "./subagent-registry-queries.js";
910
import { recoverInterruptedSubagentRow } from "./subagent-registry-restart-recovery.js";
1011
import type { SubagentRunRecord } from "./subagent-registry.types.js";
1112
import {
@@ -789,6 +790,59 @@ describe("subagent registry restart recovery", () => {
789790
expect(mocks.entries[childSessionKey]!.abortedLastRun).toBe(false);
790791
});
791792

793+
it.each([
794+
["during settlement", true, true],
795+
["after settlement", false, false],
796+
])(
797+
"preserves accepted recovery when a newer generation wins %s",
798+
async (_name, beforeCommit, expectedAborted) => {
799+
const entry = run();
800+
const runs = new Map([[entry.runId, entry]]);
801+
const isCurrent: RecoveryParams["isCurrent"] = (runId, candidate) =>
802+
runs.get(runId) === candidate &&
803+
getLatestSubagentRunByChildSessionKeyFromRuns(runs, candidate.childSessionKey) ===
804+
candidate;
805+
replaceRun.mockImplementationOnce((params: ReplaceRunParams) => {
806+
runs.delete(params.previousRunId);
807+
entry.runId = params.nextRunId;
808+
entry.execution.restartRecovery = params.restartRecovery;
809+
runs.set(entry.runId, entry);
810+
return true;
811+
});
812+
mocks.patchSessionEntry.mockImplementationOnce(async ({ sessionKey }, update, options) => {
813+
const next = update({ ...mocks.entries[sessionKey]! });
814+
const advanceOwner = () => {
815+
const newer = run({
816+
runId: "newer-accepted-run",
817+
generation: (entry.generation ?? 0) + 1,
818+
});
819+
runs.set(newer.runId, newer);
820+
};
821+
if (beforeCommit) {
822+
advanceOwner();
823+
}
824+
options?.assertCommitAllowed?.();
825+
mocks.entries[sessionKey] = next;
826+
if (!beforeCommit) {
827+
advanceOwner();
828+
}
829+
return next;
830+
});
831+
832+
await expect(
833+
recover(entry, {
834+
getRun: (runId) => runs.get(runId),
835+
isCurrent,
836+
}),
837+
).resolves.toEqual({ status: "deferred" });
838+
839+
expect(mocks.entries[childSessionKey]!.abortedLastRun).toBe(expectedAborted);
840+
expect(entry.execution.restartRecovery).toMatchObject({ phase: "accepted" });
841+
expect(clearAcceptedRecovery).not.toHaveBeenCalled();
842+
expect(resumeAcceptedRecovery).not.toHaveBeenCalled();
843+
},
844+
);
845+
792846
it("terminalizes a retired accepted receipt without clearing newer restart evidence", async () => {
793847
const entry = run({
794848
execution: {

‎src/agents/subagent-registry-restart-recovery.ts‎

Lines changed: 27 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { getSubagentSessionStartedAt } from "./subagent-session-metrics.js";
3636

3737
const MAX_RECOVERY_ATTEMPTS = 2;
3838
const RECOVERY_ATTEMPT_WINDOW_MS = 2 * 60_000;
39+
type SubagentRunManager = ReturnType<typeof createSubagentRunManager>;
3940

4041
export type RestartRecoveryResult =
4142
| { status: "ignored" }
@@ -56,33 +57,17 @@ export type RestartRecoveryParams = {
5657
entry: SubagentRunRecord;
5758
now: number;
5859
gatewayRuntime: GatewayRecoveryRuntime | undefined;
59-
isCurrent: () => boolean;
60-
abandonLaunch: ReturnType<
61-
typeof createSubagentRunManager
62-
>["abandonSubagentRestartRecoveryLaunch"];
63-
clearAcceptedRecovery: ReturnType<
64-
typeof createSubagentRunManager
65-
>["clearAcceptedSubagentRestartRecovery"];
60+
isCurrent: (runId: string, entry: SubagentRunRecord) => boolean;
61+
abandonLaunch: SubagentRunManager["abandonSubagentRestartRecoveryLaunch"];
62+
clearAcceptedRecovery: SubagentRunManager["clearAcceptedSubagentRestartRecovery"];
6663
getRun: (runId: string) => SubagentRunRecord | undefined;
67-
replaceRun: ReturnType<typeof createSubagentRunManager>["replaceSubagentRunAfterSteer"];
68-
markLaunchAttempted: ReturnType<
69-
typeof createSubagentRunManager
70-
>["markSubagentRestartRecoveryLaunchAttempted"];
71-
markLaunchAccepted: ReturnType<
72-
typeof createSubagentRunManager
73-
>["markSubagentRestartRecoveryLaunchAccepted"];
74-
markLaunchConsumed: ReturnType<
75-
typeof createSubagentRunManager
76-
>["markSubagentRestartRecoveryLaunchConsumed"];
77-
resetLaunchAttempt: ReturnType<
78-
typeof createSubagentRunManager
79-
>["resetSubagentRestartRecoveryLaunchAttempt"];
80-
reserveLaunch: ReturnType<
81-
typeof createSubagentRunManager
82-
>["reserveSubagentRestartRecoveryLaunch"];
83-
resumeAcceptedRecovery: ReturnType<
84-
typeof createSubagentRunManager
85-
>["resumeSettledSubagentRestartRecovery"];
64+
replaceRun: SubagentRunManager["replaceSubagentRunAfterSteer"];
65+
markLaunchAttempted: SubagentRunManager["markSubagentRestartRecoveryLaunchAttempted"];
66+
markLaunchAccepted: SubagentRunManager["markSubagentRestartRecoveryLaunchAccepted"];
67+
markLaunchConsumed: SubagentRunManager["markSubagentRestartRecoveryLaunchConsumed"];
68+
resetLaunchAttempt: SubagentRunManager["resetSubagentRestartRecoveryLaunchAttempt"];
69+
reserveLaunch: SubagentRunManager["reserveSubagentRestartRecoveryLaunch"];
70+
resumeAcceptedRecovery: SubagentRunManager["resumeSettledSubagentRestartRecovery"];
8671
warn: (message: string, meta?: Record<string, unknown>) => void;
8772
};
8873

@@ -95,7 +80,7 @@ async function reconcileAcceptedRecovery(params: {
9580
clearAcceptedRecovery: RestartRecoveryParams["clearAcceptedRecovery"];
9681
entry: SubagentRunRecord;
9782
getRun: RestartRecoveryParams["getRun"];
98-
isCurrent: () => boolean;
83+
isCurrent: RestartRecoveryParams["isCurrent"];
9984
now: number;
10085
receipt: SubagentRestartRecoveryReceipt;
10186
replaceRun: RestartRecoveryParams["replaceRun"];
@@ -117,7 +102,7 @@ async function reconcileAcceptedRecovery(params: {
117102
let remapped = false;
118103
try {
119104
remapped =
120-
params.isCurrent() &&
105+
params.isCurrent(params.runId, params.entry) &&
121106
params.replaceRun({
122107
previousRunId: params.runId,
123108
nextRunId: params.receipt.idempotencyKey,
@@ -143,7 +128,11 @@ async function reconcileAcceptedRecovery(params: {
143128
};
144129
}
145130
const successor = params.getRun(params.receipt.idempotencyKey);
146-
if (!successor || successor.execution.restartRecovery !== params.receipt) {
131+
if (
132+
!successor ||
133+
successor.execution.restartRecovery !== params.receipt ||
134+
!params.isCurrent(successor.runId, successor)
135+
) {
147136
params.warn("accepted subagent restart recovery lost its remapped owner", {
148137
runId: params.runId,
149138
childSessionKey: params.childSessionKey,
@@ -152,6 +141,10 @@ async function reconcileAcceptedRecovery(params: {
152141
}
153142
owner = successor;
154143
}
144+
const ownsAcceptedTarget = () =>
145+
params.isCurrent(owner.runId, owner) &&
146+
owner.execution.restartRecovery === params.receipt &&
147+
isRestartRecoveryLifecycleCurrent(params.receipt);
155148

156149
if (
157150
!params.currentSessionId ||
@@ -173,10 +166,7 @@ async function reconcileAcceptedRecovery(params: {
173166
!(await settleAcceptedRecoverySession({
174167
attempts: params.attempts,
175168
childSessionKey: params.childSessionKey,
176-
isOwnerCurrent: () =>
177-
params.getRun(owner.runId) === owner &&
178-
owner.execution.restartRecovery === params.receipt &&
179-
isRestartRecoveryLifecycleCurrent(params.receipt),
169+
isOwnerCurrent: ownsAcceptedTarget,
180170
sessionId: params.receipt.sessionId,
181171
sessionLifecycleRevision: params.receipt.sessionLifecycleRevision,
182172
now: params.now,
@@ -222,9 +212,9 @@ async function reconcileAcceptedRecovery(params: {
222212
target: { runId: owner.runId, entry: owner },
223213
};
224214
}
225-
226215
try {
227216
if (
217+
!ownsAcceptedTarget() ||
228218
!params.clearAcceptedRecovery({
229219
runId: owner.runId,
230220
expected: owner,
@@ -247,6 +237,7 @@ async function reconcileAcceptedRecovery(params: {
247237
return { status: "deferred" };
248238
}
249239
if (
240+
!params.isCurrent(owner.runId, owner) ||
250241
!params.resumeAcceptedRecovery({
251242
runId: owner.runId,
252243
expected: owner,
@@ -272,10 +263,10 @@ export async function recoverInterruptedSubagentRow(
272263
params.entry.execution.outcome?.status === "timeout" &&
273264
typeof params.entry.execution.endedAt === "number";
274265
const acceptedRecoveryCurrent =
275-
initialRecoveryReceipt?.phase === "accepted" && params.isCurrent();
266+
initialRecoveryReceipt?.phase === "accepted" && params.isCurrent(params.runId, params.entry);
276267
const isRecoverySourceCurrent = () =>
277268
isRecoveryAttemptLifecycleCurrent() &&
278-
params.isCurrent() &&
269+
params.isCurrent(params.runId, params.entry) &&
279270
params.entry.pauseReason !== "sessions_yield" &&
280271
params.entry.suppressAnnounceReason !== "steer-restart" &&
281272
params.entry.killReconciliation === undefined &&

‎src/agents/subagent-registry-sweep-kill.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ export async function reconcileDurableSubagentKillIntent(params: {
8989
runId: string;
9090
entry: SubagentRunRecord;
9191
runs: Map<string, SubagentRunRecord>;
92+
getRunsForChildSession: (childSessionKey: string) => Iterable<SubagentRunRecord>;
9293
loadKillRuntime: () => Promise<typeof import("./subagent-control.runtime.js")>;
9394
completeSubagentRunWithRecovery: (
9495
completion: SubagentCompletionRequest,
@@ -104,13 +105,14 @@ export async function reconcileDurableSubagentKillIntent(params: {
104105
if (params.runs.get(params.runId) !== params.entry) {
105106
return false;
106107
}
108+
const childRuns = () => params.getRunsForChildSession(params.entry.childSessionKey);
107109
const latest = getLatestSubagentRunByChildSessionKeyFromRuns(
108-
params.runs,
110+
childRuns(),
109111
params.entry.childSessionKey,
110112
);
111113
if (latest !== params.entry) {
112114
try {
113-
const taskResolution = resolveSubagentTaskForRun(params.runs.values(), params.entry);
115+
const taskResolution = resolveSubagentTaskForRun(childRuns(), params.entry);
114116
const task = taskResolution.task;
115117
if (taskResolution.lookup === "unavailable" || isUnstableTask(task)) {
116118
const finalized = finalizeTaskRunByRunId({
@@ -133,7 +135,7 @@ export async function reconcileDurableSubagentKillIntent(params: {
133135
}
134136
if (
135137
params.runs.get(params.runId) !== params.entry ||
136-
getLatestSubagentRunByChildSessionKeyFromRuns(params.runs, params.entry.childSessionKey) ===
138+
getLatestSubagentRunByChildSessionKeyFromRuns(childRuns(), params.entry.childSessionKey) ===
137139
params.entry
138140
) {
139141
return false;
@@ -154,7 +156,7 @@ export async function reconcileDurableSubagentKillIntent(params: {
154156
params.entry.killIntent === killIntent &&
155157
killIntent.lifecycleGeneration !== undefined &&
156158
isAgentEventLifecycleGenerationCurrent(killIntent.lifecycleGeneration) &&
157-
getLatestSubagentRunByChildSessionKeyFromRuns(params.runs, params.entry.childSessionKey) ===
159+
getLatestSubagentRunByChildSessionKeyFromRuns(childRuns(), params.entry.childSessionKey) ===
158160
params.entry;
159161
const cfg = getRuntimeConfig();
160162
const storePath = resolveStorePath(cfg.session?.store, {

0 commit comments

Comments
 (0)