Skip to content

Commit b8d6e79

Browse files
RileyJJYsteipete
andauthored
fix: agent.wait can return error before the same run later ends successfully (#120606)
* fix(gateway): preserve agent wait through late success * fix(gateway): keep timed-out agent waits fail-closed * fix(gateway): recover late lifecycle success across observers * fix(tui): preserve authoritative terminal outcomes --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 84fd10d commit b8d6e79

9 files changed

Lines changed: 424 additions & 104 deletions

‎src/agents/agent-run-terminal-outcome.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
buildAgentRunTerminalOutcome,
55
buildAgentRunTerminalOutcomeFromLifecycleEvent,
66
classifyAgentRunTerminalOutcome,
7+
isDefinitiveRunLifecycle,
78
isStickyAgentRunTerminalOutcome,
89
mergeAgentRunAttemptTerminal,
910
mergeAgentRunTerminalOutcome,
@@ -28,6 +29,21 @@ describe("agent run terminal outcome", () => {
2829
expect(classifyAgentRunTerminalOutcome({ reason })).toBe(classification);
2930
});
3031

32+
it.each([
33+
{ label: "retryable provider failure", data: { error: "provider failed" }, definitive: false },
34+
{
35+
label: "exhausted provider failure",
36+
data: { error: "provider failed", fallbackExhaustedFailure: true },
37+
definitive: true,
38+
},
39+
{ label: "blocked run", data: { livenessState: "blocked" }, definitive: true },
40+
{ label: "abandoned run", data: { livenessState: "abandoned" }, definitive: true },
41+
{ label: "explicit cancellation", data: { aborted: true }, definitive: true },
42+
{ label: "provider timeout", data: { timeoutPhase: "provider" }, definitive: true },
43+
])("recognizes whether $label is a definitive lifecycle error", ({ data, definitive }) => {
44+
expect(isDefinitiveRunLifecycle({ phase: "error", data })).toBe(definitive);
45+
});
46+
3147
it("normalizes lifecycle signals with timeout, cancellation, failure precedence", () => {
3248
expect(
3349
buildAgentRunTerminalOutcomeFromLifecycleEvent({

‎src/agents/agent-run-terminal-outcome.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -633,10 +633,7 @@ export function isDefinitiveRunLifecycle(input: AgentRunLifecycleInput) {
633633
phase: "error",
634634
data: input.data,
635635
});
636-
return (
637-
input.data?.fallbackExhaustedFailure === true ||
638-
classifyAgentRunTerminalOutcome(outcome) !== "failure"
639-
);
636+
return input.data?.fallbackExhaustedFailure === true || outcome.reason !== "failed";
640637
}
641638

642639
function hasNestedAbortReason(value: unknown, matches: (candidate: unknown) => boolean): boolean {

‎src/gateway/agent-turn/agent-job.timeout-fallback.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,173 @@ describe("waitForAgentJob timeout fallback", () => {
193193
});
194194
});
195195

196+
it("publishes a later lifecycle failure after an aborted end at retry grace", async () => {
197+
const runId = `run-timeout-fallback-aborted-end-${runSequence++}`;
198+
let terminalOutcome: Awaited<ReturnType<typeof waitForAgentJob>> | undefined;
199+
const waitPromise = waitForAgentJob({ runId, timeoutMs: 20_000 }).then((outcome) => {
200+
terminalOutcome = outcome;
201+
return outcome;
202+
});
203+
204+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
205+
emitAgentEvent({
206+
runId,
207+
stream: "lifecycle",
208+
data: { phase: "end", startedAt: 1_000, endedAt: 1_100, aborted: true },
209+
});
210+
emitAgentEvent({
211+
runId,
212+
stream: "lifecycle",
213+
data: { phase: "error", startedAt: 1_000, endedAt: 1_200, error: "final error" },
214+
});
215+
216+
await vi.advanceTimersByTimeAsync(15_000);
217+
expect(terminalOutcome).toMatchObject({
218+
status: "error",
219+
endedAt: 1_200,
220+
error: "final error",
221+
});
222+
await expect(waitPromise).resolves.toMatchObject({ status: "error", endedAt: 1_200 });
223+
});
224+
225+
it.each([1, 2])(
226+
"keeps an active waiter open across %i expired retryable failure grace periods",
227+
async (failureCount) => {
228+
const runId = `run-timeout-fallback-late-recovery-${runSequence++}`;
229+
let settled = false;
230+
const waitPromise = waitForAgentJob({ runId, timeoutMs: 60_000 }).then((outcome) => {
231+
settled = true;
232+
return outcome;
233+
});
234+
235+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
236+
for (let attempt = 0; attempt < failureCount; attempt += 1) {
237+
emitAgentEvent({
238+
runId,
239+
stream: "lifecycle",
240+
data: {
241+
phase: "error",
242+
startedAt: 1_000,
243+
endedAt: 1_100 + attempt,
244+
error: `Retryable provider failure ${attempt + 1}`,
245+
},
246+
});
247+
await vi.advanceTimersByTimeAsync(15_000);
248+
expect(settled).toBe(false);
249+
}
250+
251+
emitAgentEvent({
252+
runId,
253+
stream: "lifecycle",
254+
data: { phase: "end", startedAt: 1_000, endedAt: 40_000 },
255+
});
256+
257+
await expect(waitPromise).resolves.toMatchObject({ status: "ok", endedAt: 40_000 });
258+
await expect(waitForAgentJob({ runId, timeoutMs: 0 })).resolves.toMatchObject({
259+
status: "ok",
260+
endedAt: 40_000,
261+
});
262+
},
263+
);
264+
265+
it("returns an expired retryable failure only at the active waiter's own deadline", async () => {
266+
const runId = `run-timeout-fallback-expired-wait-${runSequence++}`;
267+
let settled = false;
268+
const waitPromise = waitForAgentJob({ runId, timeoutMs: 20_000 }).then((outcome) => {
269+
settled = true;
270+
return outcome;
271+
});
272+
273+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
274+
emitAgentEvent({
275+
runId,
276+
stream: "lifecycle",
277+
data: { phase: "error", endedAt: 1_100, error: "Retryable provider failure" },
278+
});
279+
await vi.advanceTimersByTimeAsync(15_000);
280+
expect(settled).toBe(false);
281+
282+
await vi.advanceTimersByTimeAsync(5_000);
283+
await expect(waitPromise).resolves.toMatchObject({
284+
status: "error",
285+
endedAt: 1_100,
286+
error: "Retryable provider failure",
287+
});
288+
await expect(waitForAgentJob({ runId, timeoutMs: 0 })).resolves.toMatchObject({
289+
status: "error",
290+
error: "Retryable provider failure",
291+
});
292+
});
293+
294+
it("keeps a waiter admitted after retry grace open for the same authoritative outcome", async () => {
295+
const runId = `run-timeout-fallback-late-waiter-${runSequence++}`;
296+
const firstWait = waitForAgentJob({ runId, timeoutMs: 60_000 });
297+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
298+
emitAgentEvent({
299+
runId,
300+
stream: "lifecycle",
301+
data: { phase: "error", endedAt: 1_100, error: "Retryable provider failure" },
302+
});
303+
await vi.advanceTimersByTimeAsync(15_000);
304+
305+
let laterWaitSettled = false;
306+
const laterWait = waitForAgentJob({ runId, timeoutMs: 30_000 }).then((outcome) => {
307+
laterWaitSettled = true;
308+
return outcome;
309+
});
310+
await Promise.resolve();
311+
expect(laterWaitSettled).toBe(false);
312+
313+
emitAgentEvent({
314+
runId,
315+
stream: "lifecycle",
316+
data: { phase: "end", startedAt: 1_000, endedAt: 20_000 },
317+
});
318+
await expect(Promise.all([firstWait, laterWait])).resolves.toEqual([
319+
expect.objectContaining({ status: "ok" }),
320+
expect.objectContaining({ status: "ok" }),
321+
]);
322+
});
323+
324+
it("keeps a second waiter alive when the first expires after retry grace", async () => {
325+
const runId = `run-timeout-fallback-two-waiters-${runSequence++}`;
326+
const earlyWait = waitForAgentJob({ runId, timeoutMs: 20_000 });
327+
const lateWait = waitForAgentJob({ runId, timeoutMs: 60_000 });
328+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
329+
emitAgentEvent({
330+
runId,
331+
stream: "lifecycle",
332+
data: { phase: "error", endedAt: 1_100, error: "Retryable provider failure" },
333+
});
334+
335+
await vi.advanceTimersByTimeAsync(20_000);
336+
await expect(earlyWait).resolves.toMatchObject({ status: "error" });
337+
emitAgentEvent({
338+
runId,
339+
stream: "lifecycle",
340+
data: { phase: "end", startedAt: 1_000, endedAt: 25_000 },
341+
});
342+
await expect(lateWait).resolves.toMatchObject({ status: "ok", endedAt: 25_000 });
343+
});
344+
345+
it.each(["blocked", "abandoned"] as const)(
346+
"does not keep a %s lifecycle failure pending beyond the terminal grace",
347+
async (livenessState) => {
348+
const runId = `run-timeout-fallback-definitive-${livenessState}-${runSequence++}`;
349+
const waitPromise = waitForAgentJob({ runId, timeoutMs: 60_000 });
350+
351+
emitAgentEvent({ runId, stream: "lifecycle", data: { phase: "start", startedAt: 1_000 } });
352+
emitAgentEvent({
353+
runId,
354+
stream: "lifecycle",
355+
data: { phase: "error", endedAt: 1_100, livenessState },
356+
});
357+
358+
await vi.advanceTimersByTimeAsync(15_000);
359+
await expect(waitPromise).resolves.toMatchObject({ status: "error", livenessState });
360+
},
361+
);
362+
196363
it.each([
197364
{ label: "failure", metadata: {} },
198365
{

‎src/gateway/agent-turn/agent-job.ts‎

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ type AgentRunObservation = AgentJobTerminalSnapshot & {
5959
type AgentRunSnapshot = AgentRunObservation & { cachedAt: number };
6060
type PendingAgentRunTerminal = {
6161
snapshot: AgentRunObservation;
62-
timer: NodeJS.Timeout;
62+
timer?: NodeJS.Timeout;
6363
};
6464
type AgentJobRecord = {
6565
cachedAt: number;
@@ -195,12 +195,6 @@ function mergeSnapshot(
195195
};
196196
}
197197

198-
function notifyAgentRunWaiters(runId: string) {
199-
for (const waiter of agentRunWaiters.get(runId) ?? []) {
200-
waiter();
201-
}
202-
}
203-
204198
function recordAgentRunSnapshot(
205199
snapshot: Omit<AgentRunObservation, "version">,
206200
version = nextAgentRunVersion(),
@@ -218,31 +212,24 @@ function recordAgentRunSnapshot(
218212
snapshotsBySource,
219213
});
220214
enforceAgentRunCacheMaxEntries();
221-
notifyAgentRunWaiters(entry.runId);
222-
}
223-
224-
function clearPendingAgentRunError(runId: string) {
225-
const pending = pendingAgentRunErrors.get(runId);
226-
if (!pending) {
227-
return;
215+
for (const waiter of agentRunWaiters.get(entry.runId) ?? []) {
216+
waiter();
228217
}
229-
clearTimeout(pending.timer);
230-
pendingAgentRunErrors.delete(runId);
231218
}
232219

233-
function clearPendingAgentRunTimeout(runId: string) {
234-
const pending = pendingAgentRunTimeouts.get(runId);
235-
if (!pending) {
236-
return;
220+
function clearPendingAgentRunTerminals(runId: string) {
221+
for (const pendingRuns of [pendingAgentRunErrors, pendingAgentRunTimeouts]) {
222+
const pending = pendingRuns.get(runId);
223+
if (pending) {
224+
clearTimeout(pending.timer);
225+
pendingRuns.delete(runId);
226+
}
237227
}
238-
clearTimeout(pending.timer);
239-
pendingAgentRunTimeouts.delete(runId);
240228
}
241229

242230
function beginAgentJob(runId: string, startedAt?: number) {
243231
nextAgentRunVersion();
244-
clearPendingAgentRunError(runId);
245-
clearPendingAgentRunTimeout(runId);
232+
clearPendingAgentRunTerminals(runId);
246233
agentJobs.delete(runId);
247234
if (startedAt !== undefined) {
248235
agentRunStarts.set(runId, startedAt);
@@ -267,13 +254,22 @@ function schedulePendingAgentRunTerminal(
267254
terminalSnapshot.version = snapshot.version;
268255
return;
269256
}
270-
clearPendingAgentRunError(snapshot.runId);
271-
clearPendingAgentRunTimeout(snapshot.runId);
257+
const replacesPendingTimeout = pendingAgentRunTimeouts.has(snapshot.runId);
258+
clearPendingAgentRunTerminals(snapshot.runId);
272259
const timer = setSafeTimeout(() => {
273260
const pending = pendingRuns.get(snapshot.runId);
274261
if (!pending || pending.timer !== timer) {
275262
return;
276263
}
264+
if (
265+
pendingRuns === pendingAgentRunErrors &&
266+
!replacesPendingTimeout &&
267+
terminalOutcomeFromSnapshot(pending.snapshot)?.reason === "failed" &&
268+
agentRunWaiters.has(snapshot.runId)
269+
) {
270+
pending.timer = undefined;
271+
return;
272+
}
277273
pendingRuns.delete(snapshot.runId);
278274
recordAgentRunSnapshot(pending.snapshot, pending.snapshot.version);
279275
}, AGENT_RUN_TERMINAL_RETRY_GRACE_MS);
@@ -375,8 +371,7 @@ function ensureAgentRunListener() {
375371
return;
376372
}
377373
const terminalSnapshot = mergePendingAgentRunTerminal(snapshot);
378-
clearPendingAgentRunError(evt.runId);
379-
clearPendingAgentRunTimeout(evt.runId);
374+
clearPendingAgentRunTerminals(evt.runId);
380375
recordAgentRunSnapshot(terminalSnapshot, snapshot.version);
381376
});
382377
}
@@ -564,6 +559,11 @@ function addAgentRunWaiter(runId: string, waiter: AgentJobWaiter): () => void {
564559
waiters.delete(waiter);
565560
if (waiters.size === 0) {
566561
agentRunWaiters.delete(runId);
562+
const pendingError = pendingAgentRunErrors.get(runId);
563+
if (pendingError && !pendingError.timer) {
564+
pendingAgentRunErrors.delete(runId);
565+
recordAgentRunSnapshot(pendingError.snapshot, pendingError.snapshot.version);
566+
}
567567
}
568568
};
569569
}
@@ -635,10 +635,12 @@ export async function waitForAgentJob(params: {
635635
removeWaiter = addAgentRunWaiter(params.runId, onWake);
636636
const timeoutHandle = setSafeTimeout(() => {
637637
if (!params.source) {
638-
const pendingError = pendingAgentRunErrors.get(params.runId)?.snapshot;
638+
const pending = pendingAgentRunErrors.get(params.runId);
639+
const pendingError = pending?.snapshot;
639640
if (pendingError && pendingError.version > afterVersion) {
640641
finish(
641-
isStickyAgentRunTerminalOutcome(terminalOutcomeFromSnapshot(pendingError))
642+
!pending.timer ||
643+
isStickyAgentRunTerminalOutcome(terminalOutcomeFromSnapshot(pendingError))
642644
? publicSnapshot(pendingError)
643645
: createPendingErrorTimeoutSnapshot(pendingError),
644646
);

‎src/gateway/server.chat.gateway-server-chat.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2578,7 +2578,8 @@ describe("gateway server chat", () => {
25782578
event.type === "event" &&
25792579
event.event === "sessions.changed" &&
25802580
event.payload?.reason === "chat.run.settled" &&
2581-
event.payload?.sessionKey === "agent:main:main",
2581+
event.payload?.sessionKey === "agent:main:main" &&
2582+
event.payload?.lastRunId === runId,
25822583
8_000,
25832584
);
25842585
blockedReply.resolve();

0 commit comments

Comments
 (0)