Skip to content

Commit ee74ca5

Browse files
committed
fix(agents): rearm yielded requester wake
Punchcard-Session: silver-valley-valley-dt
1 parent 1f0269e commit ee74ca5

3 files changed

Lines changed: 196 additions & 18 deletions

File tree

‎src/agents/subagent-announce.requester-settle-wake.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ export async function maybeWakeRequesterAfterAllChildrenSettled(params: {
221221
if (!requesterSessionKey || !initialState) {
222222
return false;
223223
}
224+
const admittedRearmGeneration = initialState.rearmGeneration;
224225
if (isCronSessionKey(requesterSessionKey)) {
225226
completeRequesterSettleWakeBatch({
226227
runIds: [params.settledEntry.runId],
@@ -235,14 +236,17 @@ export async function maybeWakeRequesterAfterAllChildrenSettled(params: {
235236
const requesterRuns = Array.isArray(listedRuns) ? listedRuns : [];
236237
const currentSettledEntry =
237238
requesterRuns.find((entry) => entry.runId === params.settledEntry.runId) ?? params.settledEntry;
238-
if (!currentSettledEntry.requesterSettleWake) {
239+
const currentState = currentSettledEntry.requesterSettleWake;
240+
// A requester yield may re-arm this row while runtime loading is in flight.
241+
// Only the admitted generation may inspect descendants or mutate its batch.
242+
if (!currentState || currentState.rearmGeneration !== admittedRearmGeneration) {
239243
return false;
240244
}
241245
const requesterHasUnsettledDescendants = () =>
242246
registryRuntime.hasDescendantRunAwaitingSettle(requesterSessionKey, currentSettledEntry.runId);
243247

244-
const frozenBatchRunIds = currentSettledEntry.requesterSettleWake.batchRunIds;
245-
const currentRearmGeneration = currentSettledEntry.requesterSettleWake.rearmGeneration;
248+
const frozenBatchRunIds = currentState.batchRunIds;
249+
const currentRearmGeneration = currentState.rearmGeneration;
246250
const hasUnsettledDescendants = requesterHasUnsettledDescendants();
247251
if ((!frozenBatchRunIds || frozenBatchRunIds.length === 0) && hasUnsettledDescendants) {
248252
return false;

‎src/agents/subagent-registry-requester-yield.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,45 @@ describe("settleRequesterTurnAfterSessionSpawns", () => {
169169
expect(schedule).not.toHaveBeenCalled();
170170
});
171171

172+
it("persists a mixed delivered and in-progress yielded batch without scheduling", () => {
173+
const alpha = makeRun("run-alpha");
174+
const beta = makeRun("run-beta");
175+
beta.delivery = { status: "in_progress" };
176+
const calls: string[] = [];
177+
const persistOrThrow = vi.fn(() => calls.push("persist"));
178+
const schedule = vi.fn(() => calls.push("schedule"));
179+
180+
expect(
181+
settleRequesterTurnAfterSessionSpawns({
182+
requesterSessionKey: REQUESTER,
183+
requesterTurnRunId: REQUESTER_TURN,
184+
requesterYielded: true,
185+
acceptedSessionSpawns: [accepted(alpha), accepted(beta)],
186+
runs: new Map([
187+
[alpha.runId, alpha],
188+
[beta.runId, beta],
189+
]),
190+
persistOrThrow,
191+
schedule,
192+
}),
193+
).toBe(true);
194+
195+
const frozenState = {
196+
status: "pending",
197+
attemptCount: 0,
198+
batchRunIds: ["run-alpha", "run-beta"],
199+
requesterYieldBatch: true,
200+
afterRequesterYield: true,
201+
rearmGeneration: 1,
202+
} as const;
203+
expect(alpha.requesterSettleWake).toEqual(frozenState);
204+
expect(beta.requesterSettleWake).toEqual(frozenState);
205+
expect(alpha.requesterTurnRunId).toBeUndefined();
206+
expect(beta.requesterTurnRunId).toBeUndefined();
207+
expect(calls).toEqual(["persist"]);
208+
expect(schedule).not.toHaveBeenCalled();
209+
});
210+
172211
it.each([true, false])(
173212
"ignores same-turn non-completion spawns during settlement (yielded: %s)",
174213
(requesterYielded) => {

‎src/agents/subagent-registry.lifecycle-retry-grace.e2e.test.ts‎

Lines changed: 150 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ type GatewayRequest = {
5858

5959
let lifecycleHandler: ((evt: LifecycleEvent) => void) | undefined;
6060
let agentCallPlan: Array<"ok" | "throw"> = [];
61+
let agentCallGates = new Map<string, Promise<void>>();
6162
let chatHistoryBySessionKey = new Map<string, Array<Record<string, unknown>>>();
6263
let sessionStore: Record<string, SessionStoreEntry> = {};
6364

@@ -75,6 +76,11 @@ const callGatewayMock = vi.fn(async (request: GatewayRequest) => {
7576
};
7677
}
7778
if (method === "agent") {
79+
const sourceSessionKey = request.params?.inputProvenance?.sourceSessionKey;
80+
const gate = sourceSessionKey ? agentCallGates.get(sourceSessionKey) : undefined;
81+
if (gate) {
82+
await gate;
83+
}
7884
const next = agentCallPlan.shift() ?? "ok";
7985
if (next === "throw") {
8086
throw new Error("announce delivery failed");
@@ -118,6 +124,20 @@ vi.mock("./subagent-depth.js", () => ({
118124
getSubagentDepthFromSessionStore: () => 0,
119125
}));
120126

127+
const loadSubagentRegistryRuntimeForTest = async () =>
128+
({
129+
countActiveDescendantRuns: mod.countActiveDescendantRuns,
130+
countPendingDescendantRuns: mod.countPendingDescendantRuns,
131+
countPendingDescendantRunsExcludingRun: mod.countPendingDescendantRunsExcludingRun,
132+
hasDescendantRunAwaitingSettle: announceRead.hasDescendantRunAwaitingSettle,
133+
getLatestSubagentRunByChildSessionKey: mod.getLatestSubagentRunByChildSessionKey,
134+
isSubagentSessionRunActive: mod.isSubagentSessionRunActive,
135+
listSubagentRunsForRequester: mod.listSubagentRunsForRequester,
136+
replaceSubagentRunAfterSteer: mod.replaceSubagentRunAfterSteer,
137+
resolveRequesterForChildSession: mod.resolveRequesterForChildSession,
138+
shouldIgnorePostCompletionAnnounceForSession: mod.shouldIgnorePostCompletionAnnounceForSession,
139+
}) as unknown as typeof import("./subagent-registry-runtime.js");
140+
121141
describe("subagent registry lifecycle error grace", () => {
122142
let previousFastTestEnv: string | undefined;
123143

@@ -132,6 +152,7 @@ describe("subagent registry lifecycle error grace", () => {
132152
session: { mainKey: "main", scope: "per-sender" },
133153
});
134154
agentCallPlan = [];
155+
agentCallGates = new Map();
135156
chatHistoryBySessionKey = new Map();
136157
sessionStore = new Proxy<Record<string, SessionStoreEntry>>(
137158
{
@@ -163,20 +184,6 @@ describe("subagent registry lifecycle error grace", () => {
163184
onAgentEvent:
164185
onAgentEventMock as unknown as typeof import("../infra/agent-events.js").onAgentEvent,
165186
});
166-
const loadSubagentRegistryRuntimeForTest = async () =>
167-
({
168-
countActiveDescendantRuns: mod.countActiveDescendantRuns,
169-
countPendingDescendantRuns: mod.countPendingDescendantRuns,
170-
countPendingDescendantRunsExcludingRun: mod.countPendingDescendantRunsExcludingRun,
171-
hasDescendantRunAwaitingSettle: announceRead.hasDescendantRunAwaitingSettle,
172-
getLatestSubagentRunByChildSessionKey: mod.getLatestSubagentRunByChildSessionKey,
173-
isSubagentSessionRunActive: mod.isSubagentSessionRunActive,
174-
listSubagentRunsForRequester: mod.listSubagentRunsForRequester,
175-
replaceSubagentRunAfterSteer: mod.replaceSubagentRunAfterSteer,
176-
resolveRequesterForChildSession: mod.resolveRequesterForChildSession,
177-
shouldIgnorePostCompletionAnnounceForSession:
178-
mod.shouldIgnorePostCompletionAnnounceForSession,
179-
}) as unknown as typeof import("./subagent-registry-runtime.js");
180187
subagentAnnounceTesting.setDepsForTest({
181188
callGateway: callGatewayMock as typeof import("../gateway/call.js").callGateway,
182189
getRuntimeConfig: loadConfigMock as typeof import("../config/config.js").getRuntimeConfig,
@@ -294,9 +301,15 @@ describe("subagent registry lifecycle error grace", () => {
294301
throw new Error(`run ${runId} frozen result did not refresh`);
295302
};
296303

297-
function registerCompletionRun(runId: string, childSuffix: string, task: string) {
304+
function registerCompletionRun(
305+
runId: string,
306+
childSuffix: string,
307+
task: string,
308+
requesterTurnRunId?: string,
309+
) {
298310
mod.registerSubagentRun({
299311
runId,
312+
requesterTurnRunId,
300313
childSessionKey: `agent:main:subagent:${childSuffix}`,
301314
requesterSessionKey: MAIN_REQUESTER_SESSION_KEY,
302315
requesterDisplayKey: MAIN_REQUESTER_DISPLAY_KEY,
@@ -370,6 +383,128 @@ describe("subagent registry lifecycle error grace", () => {
370383
});
371384
}
372385

386+
it("lets the delivered cleanup own a yielded batch after a stale wake loses generation", async () => {
387+
const requesterTurnRunId = "run-requester-yield-race";
388+
const alphaSessionKey = "agent:main:subagent:yield-alpha";
389+
const betaSessionKey = "agent:main:subagent:yield-beta";
390+
registerCompletionRun("run-yield-alpha", "yield-alpha", "yield alpha", requesterTurnRunId);
391+
registerCompletionRun("run-yield-beta", "yield-beta", "yield beta", requesterTurnRunId);
392+
setAssistantOutput(alphaSessionKey, "alpha complete");
393+
setAssistantOutput(betaSessionKey, "beta complete");
394+
395+
let releaseAlphaWakeRuntime: (() => void) | undefined;
396+
const alphaWakeRuntimeGate = new Promise<void>((resolve) => {
397+
releaseAlphaWakeRuntime = resolve;
398+
});
399+
let settleWakeRuntimeLoads = 0;
400+
settleWakeTesting.setDepsForTest({
401+
loadSubagentRegistryRuntime: async () => {
402+
settleWakeRuntimeLoads += 1;
403+
if (settleWakeRuntimeLoads === 1) {
404+
await alphaWakeRuntimeGate;
405+
}
406+
return await loadSubagentRegistryRuntimeForTest();
407+
},
408+
});
409+
410+
let releaseBetaDelivery: (() => void) | undefined;
411+
agentCallGates.set(
412+
betaSessionKey,
413+
new Promise<void>((resolve) => {
414+
releaseBetaDelivery = resolve;
415+
}),
416+
);
417+
418+
emitLifecycleEvent("run-yield-alpha", { phase: "end", endedAt: Date.now() });
419+
await waitForAgentCallCount(1);
420+
await vi.waitFor(() => expect(settleWakeRuntimeLoads).toBe(1));
421+
422+
emitLifecycleEvent("run-yield-beta", { phase: "end", endedAt: Date.now() + 1 });
423+
await waitForAgentCallCount(2);
424+
const betaBeforeYield = mod
425+
.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY)
426+
.find((run) => run.runId === "run-yield-beta");
427+
if (!betaBeforeYield) {
428+
throw new Error("expected beta run before requester yield");
429+
}
430+
betaBeforeYield.delivery = { ...betaBeforeYield.delivery, status: "in_progress" };
431+
432+
expect(
433+
mod.markRequesterTurnYielded({
434+
requesterSessionKey: MAIN_REQUESTER_SESSION_KEY,
435+
requesterTurnRunId,
436+
}),
437+
).toBe(2);
438+
expect(
439+
mod.settleRequesterAfterSessionSpawns({
440+
requesterSessionKey: MAIN_REQUESTER_SESSION_KEY,
441+
requesterTurnRunId,
442+
requesterYielded: true,
443+
acceptedSessionSpawns: [
444+
{ runId: "run-yield-alpha", childSessionKey: alphaSessionKey },
445+
{ runId: "run-yield-beta", childSessionKey: betaSessionKey },
446+
],
447+
}),
448+
).toBe(true);
449+
450+
releaseAlphaWakeRuntime?.();
451+
await vi.advanceTimersByTimeAsync(0);
452+
await flushAsync();
453+
454+
const yieldedBatch = mod.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY);
455+
expect(
456+
yieldedBatch.map((run) => ({
457+
runId: run.runId,
458+
delivery: run.delivery?.status,
459+
nextAttemptAt: run.requesterSettleWake?.nextAttemptAt,
460+
rearmGeneration: run.requesterSettleWake?.rearmGeneration,
461+
})),
462+
).toEqual([
463+
{
464+
runId: "run-yield-alpha",
465+
delivery: "delivered",
466+
nextAttemptAt: undefined,
467+
rearmGeneration: 1,
468+
},
469+
{
470+
runId: "run-yield-beta",
471+
delivery: "in_progress",
472+
nextAttemptAt: undefined,
473+
rearmGeneration: 1,
474+
},
475+
]);
476+
const requesterWakeCalls = () =>
477+
getAgentCalls().filter((request) => {
478+
const idempotencyKey = (request.params as Record<string, unknown> | undefined)
479+
?.idempotencyKey;
480+
return (
481+
typeof idempotencyKey === "string" &&
482+
idempotencyKey.startsWith("announce:requester-settle:")
483+
);
484+
});
485+
expect(requesterWakeCalls()).toHaveLength(0);
486+
487+
agentCallGates.delete(betaSessionKey);
488+
releaseBetaDelivery?.();
489+
await waitForAgentCallCount(3);
490+
await waitForDeliveredCleanup("run-yield-alpha");
491+
await waitForDeliveredCleanup("run-yield-beta");
492+
493+
expect(requesterWakeCalls()).toHaveLength(1);
494+
expect(requesterWakeCalls()[0]?.params?.idempotencyKey).toContain(":yield-1");
495+
expect(requesterWakeCalls()[0]?.params?.message).toContain("visible final answer");
496+
expect(
497+
mod
498+
.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY)
499+
.filter((run) => run.runId === "run-yield-alpha" || run.runId === "run-yield-beta")
500+
.every((run) => run.requesterSettleWake === undefined),
501+
).toBe(true);
502+
503+
await vi.advanceTimersByTimeAsync(30_000);
504+
await flushAsync();
505+
expect(requesterWakeCalls()).toHaveLength(1);
506+
});
507+
373508
it("ignores transient lifecycle errors when run retries and then ends successfully", async () => {
374509
registerCompletionRun("run-transient-error", "transient-error", "transient error test");
375510
setAssistantOutput("agent:main:subagent:transient-error", "Final answer transient");

0 commit comments

Comments
 (0)