Skip to content

Commit 9de2b23

Browse files
steipetevincentkoc
andauthored
fix(agents): stop canceled subagents reporting timeouts (#125407)
* fix(agents): preserve cancelled subagent outcomes * fix(agents): preserve provisional cancellation precedence * fix(agents): scope cancellation precedence to subagents * fix(agents): preserve provider timeout precedence --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent eb502d9 commit 9de2b23

8 files changed

Lines changed: 187 additions & 107 deletions

‎src/agents/subagents/announce/subagent-announce-output.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,15 @@ import type { SessionTranscriptRuntimeTarget } from "../../../config/sessions/se
1010
import { resolveFreshSessionTotalTokens } from "../../../config/sessions/types.js";
1111
import { isFastTestRuntimeEnv } from "../../../infra/env.js";
1212
import { formatDurationCompact } from "../../../infra/format-time/format-duration.js";
13-
import {
14-
buildAgentRunTerminalOutcomeFromWaitResult,
15-
classifyAgentRunTerminalOutcome,
16-
} from "../../agent-run-terminal-outcome.js";
13+
import { buildAgentRunTerminalOutcomeFromWaitResult } from "../../agent-run-terminal-outcome.js";
1714
import { wrapPromptDataBlock } from "../../sanitize-for-prompt.js";
1815
import { extractStoredAssistantText, sanitizeTextContent } from "../../tools/chat-history-text.js";
1916
import {
2017
isAnnounceSkip,
2118
selectDeliverableSessionsReply,
2219
} from "../../tools/sessions-send-tokens.js";
2320
import { compareSubagentRunGeneration } from "../registry/subagent-run-generation.js";
21+
import { classifySubagentTerminalOutcome } from "../subagent-terminal-outcome.js";
2422
import {
2523
captureSubagentCompletionReplyUsing,
2624
readLatestSubagentOutputWithRetryUsing,
@@ -356,7 +354,7 @@ export function applySubagentWaitOutcome(params: {
356354
// primary normalizers, so apply the canonical classification here instead
357355
// of re-enumerating reason groups.
358356
if (terminalOutcome) {
359-
switch (classifyAgentRunTerminalOutcome(terminalOutcome)) {
357+
switch (classifySubagentTerminalOutcome(terminalOutcome)) {
360358
case "timeout":
361359
outcome = { status: "timeout" };
362360
break;

‎src/agents/subagents/registry/subagent-registry-listener.ts‎

Lines changed: 45 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
import type { AgentEventPayload } from "../../../infra/agent-events.js";
22
import { runWithGatewayIndependentRootWorkAdmission } from "../../../process/gateway-work-admission.js";
3-
import {
4-
formatAbandonedLivenessError,
5-
formatBlockedLivenessError,
6-
isAbandonedLivenessState,
7-
isBlockedLivenessState,
8-
} from "../../../shared/agent-liveness.js";
3+
import { buildAgentRunTerminalOutcomeFromLifecycleEvent } from "../../agent-run-terminal-outcome.js";
94
import { normalizeAgentRunTerminalReplySnapshot } from "../../agent-run-terminal-reply.js";
10-
import { isAbortedAgentStopReason } from "../../run-termination.js";
5+
import { classifySubagentTerminalOutcome } from "../subagent-terminal-outcome.js";
116
import {
127
SUBAGENT_ENDED_REASON_COMPLETE,
138
SUBAGENT_ENDED_REASON_ERROR,
@@ -82,11 +77,6 @@ export function createSubagentRegistryListener(config: {
8277
}
8378
const endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
8479
const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : undefined;
85-
const error = typeof evt.data?.error === "string" ? evt.data.error : undefined;
86-
const livenessState =
87-
typeof evt.data?.livenessState === "string" ? evt.data.livenessState : undefined;
88-
const stopReason =
89-
typeof evt.data?.stopReason === "string" ? evt.data.stopReason : undefined;
9080
const terminalReply = normalizeAgentRunTerminalReplySnapshot(evt.data?.terminalReply);
9181
// sessions_yield ends the turn by aborting the run signal, so a yielded
9282
// terminal can also look aborted. An explicit yield is authoritative — pause,
@@ -106,72 +96,69 @@ export function createSubagentRegistryListener(config: {
10696
}
10797
return;
10898
}
109-
if (isAbortedAgentStopReason(stopReason)) {
110-
pendingLifecycle.clear(evt.runId);
111-
await completeSubagentRunWithRecovery(
112-
{
113-
runId: evt.runId,
114-
endedAt,
115-
outcome: {
116-
status: "error",
117-
error: "subagent run terminated",
118-
},
119-
reason: SUBAGENT_ENDED_REASON_KILLED,
120-
sendFarewell: true,
121-
accountId: entry.requesterOrigin?.accountId,
122-
triggerCleanup: true,
123-
startedAt,
124-
terminalReply,
125-
},
126-
"lifecycle-killed-event",
127-
);
128-
return;
129-
}
130-
if (phase === "error") {
131-
pendingLifecycle.scheduleError({
99+
const terminalOutcome = buildAgentRunTerminalOutcomeFromLifecycleEvent({
100+
phase,
101+
data: evt.data,
102+
startedAt,
103+
endedAt,
104+
});
105+
const classification = classifySubagentTerminalOutcome(terminalOutcome);
106+
if (
107+
classification === "cancellation" &&
108+
evt.data?.aborted === true &&
109+
evt.data.stopReason === undefined &&
110+
evt.data.status === undefined &&
111+
evt.data.timeoutPhase === undefined
112+
) {
113+
pendingLifecycle.scheduleCancellation({
132114
runId: evt.runId,
133115
endedAt,
134116
startedAt,
135117
terminalReply,
136-
error,
137118
});
138119
return;
139120
}
140-
const blocked = isBlockedLivenessState(livenessState);
141-
const abandoned = isAbandonedLivenessState(livenessState);
142-
if (blocked || abandoned) {
143-
pendingLifecycle.clear(evt.runId);
144-
const blockedParams = {
121+
if (classification === "timeout") {
122+
pendingLifecycle.scheduleTimeout({
145123
runId: evt.runId,
146124
endedAt,
147-
outcome: {
148-
status: "error" as const,
149-
error: blocked
150-
? formatBlockedLivenessError(error)
151-
: formatAbandonedLivenessError(error),
152-
},
153-
reason: SUBAGENT_ENDED_REASON_ERROR,
154-
sendFarewell: true,
155-
accountId: entry.requesterOrigin?.accountId,
156-
triggerCleanup: true,
157125
startedAt,
158126
terminalReply,
159-
};
160-
await completeSubagentRunWithRecovery(
161-
blockedParams,
162-
blocked ? "lifecycle-blocked-event" : "lifecycle-abandoned-event",
163-
);
127+
});
164128
return;
165129
}
166-
if (evt.data?.aborted) {
167-
pendingLifecycle.scheduleTimeout({
130+
if (phase === "error" && classification === "failure") {
131+
pendingLifecycle.scheduleError({
168132
runId: evt.runId,
169133
endedAt,
170134
startedAt,
171135
terminalReply,
136+
error: terminalOutcome.error,
172137
});
173138
return;
174139
}
140+
if (classification !== "success") {
141+
const cancelled = classification === "cancellation";
142+
pendingLifecycle.clear(evt.runId);
143+
await completeSubagentRunWithRecovery(
144+
{
145+
runId: evt.runId,
146+
endedAt,
147+
outcome: {
148+
status: "error" as const,
149+
error: cancelled ? "subagent run terminated" : terminalOutcome.error,
150+
},
151+
reason: cancelled ? SUBAGENT_ENDED_REASON_KILLED : SUBAGENT_ENDED_REASON_ERROR,
152+
sendFarewell: true,
153+
accountId: entry.requesterOrigin?.accountId,
154+
triggerCleanup: true,
155+
startedAt,
156+
terminalReply,
157+
},
158+
cancelled ? "lifecycle-killed-event" : `lifecycle-${terminalOutcome.reason}-event`,
159+
);
160+
return;
161+
}
175162
pendingLifecycle.clear(evt.runId);
176163
const completionParams = {
177164
runId: evt.runId,

‎src/agents/subagents/registry/subagent-registry-pending-lifecycle.ts‎

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
1+
import { AGENT_RUN_TERMINAL_RETRY_GRACE_MS } from "../../agent-run-terminal-outcome.js";
12
import {
23
SUBAGENT_ENDED_REASON_COMPLETE,
34
SUBAGENT_ENDED_REASON_ERROR,
5+
SUBAGENT_ENDED_REASON_KILLED,
46
} from "./subagent-lifecycle-events.js";
57
import type { SubagentCompletionRequest, SubagentRunRecord } from "./subagent-registry.types.js";
68

7-
const LIFECYCLE_RETRY_GRACE_MS = 15_000;
89
const PENDING_LIFECYCLE_TERMINAL_TTL_MS = 5 * 60_000;
910

1011
type PendingLifecycleKind = "error" | "timeout";
1112

12-
type PendingLifecycleTerminal = {
13-
kind: PendingLifecycleKind;
14-
timer: NodeJS.Timeout;
13+
type PendingLifecycleParams = {
14+
runId: string;
1515
endedAt: number;
1616
startedAt?: number;
17+
cancellation?: true;
1718
error?: string;
1819
terminalReply?: SubagentCompletionRequest["terminalReply"];
1920
};
2021

22+
type PendingLifecycleTerminal = PendingLifecycleParams & {
23+
kind: PendingLifecycleKind;
24+
timer: NodeJS.Timeout;
25+
};
26+
2127
export function createPendingLifecycleScheduler(params: {
2228
runs: Map<string, SubagentRunRecord>;
2329
completeInBackground: (completion: SubagentCompletionRequest, source: string) => void;
@@ -38,16 +44,7 @@ export function createPendingLifecycleScheduler(params: {
3844
pendingByRunId.clear();
3945
}
4046

41-
function schedule(
42-
kind: PendingLifecycleKind,
43-
scheduleParams: {
44-
runId: string;
45-
endedAt: number;
46-
startedAt?: number;
47-
error?: string;
48-
terminalReply?: SubagentCompletionRequest["terminalReply"];
49-
},
50-
) {
47+
function schedule(kind: PendingLifecycleKind, scheduleParams: PendingLifecycleParams) {
5148
clearKind(scheduleParams.runId);
5249
const timer = setTimeout(() => {
5350
const pending = pendingByRunId.get(scheduleParams.runId);
@@ -72,17 +69,26 @@ export function createPendingLifecycleScheduler(params: {
7269
runId: scheduleParams.runId,
7370
endedAt: pending.endedAt,
7471
outcome:
75-
kind === "error" ? { status: "error", error: pending.error } : { status: "timeout" },
76-
reason: kind === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
72+
kind === "timeout"
73+
? { status: "timeout" }
74+
: {
75+
status: "error",
76+
error: pending.cancellation ? "subagent run terminated" : pending.error,
77+
},
78+
reason: pending.cancellation
79+
? SUBAGENT_ENDED_REASON_KILLED
80+
: kind === "error"
81+
? SUBAGENT_ENDED_REASON_ERROR
82+
: SUBAGENT_ENDED_REASON_COMPLETE,
7783
sendFarewell: true,
7884
accountId: entry.requesterOrigin?.accountId,
7985
triggerCleanup: true,
8086
startedAt: pending.startedAt,
8187
terminalReply: pending.terminalReply,
8288
},
83-
`lifecycle-${kind}-grace`,
89+
pending.cancellation ? "lifecycle-cancellation-grace" : `lifecycle-${kind}-grace`,
8490
);
85-
}, LIFECYCLE_RETRY_GRACE_MS);
91+
}, AGENT_RUN_TERMINAL_RETRY_GRACE_MS);
8692
timer.unref?.();
8793
pendingByRunId.set(scheduleParams.runId, { ...scheduleParams, kind, timer });
8894
}
@@ -92,6 +98,8 @@ export function createPendingLifecycleScheduler(params: {
9298
clearError: (runId: string) => clearKind(runId, "error"),
9399
clearTimeout: (runId: string) => clearKind(runId, "timeout"),
94100
clearAll,
101+
scheduleCancellation: (scheduleParams: Parameters<typeof schedule>[1]) =>
102+
schedule("error", { ...scheduleParams, cancellation: true }),
95103
scheduleError: (scheduleParams: Parameters<typeof schedule>[1]) =>
96104
schedule("error", scheduleParams),
97105
scheduleTimeout: (scheduleParams: Parameters<typeof schedule>[1]) =>

‎src/agents/subagents/registry/subagent-registry-run-wait.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@ import { callGateway } from "../../../gateway/call.js";
66
import { isFastTestRuntimeEnv } from "../../../infra/env.js";
77
import { createSubsystemLogger } from "../../../logging/subsystem.js";
88
import type { DetachedTaskFindResult } from "../../../tasks/detached-task-runtime-contract.js";
9-
import {
10-
buildAgentRunTerminalOutcomeFromWaitResult,
11-
classifyAgentRunTerminalOutcome,
12-
} from "../../agent-run-terminal-outcome.js";
9+
import { buildAgentRunTerminalOutcomeFromWaitResult } from "../../agent-run-terminal-outcome.js";
1310
import { isRecoverableAgentWaitError, waitForAgentRun } from "../../run-wait.js";
1411
import {
1512
type SubagentRunOutcome,
1613
withSubagentOutcomeTiming,
1714
} from "../announce/subagent-announce-output.js";
15+
import { classifySubagentTerminalOutcome } from "../subagent-terminal-outcome.js";
1816
import { clearDeliveryState, ensureCompletionState } from "./subagent-delivery-state.js";
1917
import {
2018
SUBAGENT_ENDED_REASON_COMPLETE,
@@ -293,7 +291,7 @@ export class SubagentWaitManager {
293291
const waitBlocked = waitTerminalOutcome?.reason === "blocked";
294292
const waitAborted =
295293
waitTerminalOutcome !== undefined &&
296-
classifyAgentRunTerminalOutcome(waitTerminalOutcome) === "cancellation";
294+
classifySubagentTerminalOutcome(waitTerminalOutcome) === "cancellation";
297295
const waitStatus = waitTerminalOutcome?.status ?? wait.status;
298296
if (wait.yielded === true && waitStatus !== "timeout" && !waitBlocked) {
299297
this.options.clearPendingLifecycleError(runId);

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

Lines changed: 55 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ type LifecycleData = {
1919
endedAt?: number;
2020
aborted?: boolean;
2121
error?: string;
22+
stopReason?: string;
2223
terminalReply?: AgentRunTerminalReplySnapshot;
24+
status?: string;
25+
timeoutPhase?: string;
26+
providerStarted?: boolean;
2327
};
2428
type LifecycleEvent = {
2529
stream?: string;
@@ -840,41 +844,81 @@ describe("subagent registry lifecycle error grace", () => {
840844
expect(run.completion?.capturedAt).toBeTypeOf("number");
841845
});
842846

843-
it("completes with timeout status when aborted end event fires after grace window", async () => {
844-
registerCompletionRun("run-timeout", "timeout", "timeout test");
845-
setAssistantOutput("agent:main:subagent:timeout", "Partial output before timeout");
847+
it("records a bare aborted end event as cancellation after retry grace", async () => {
848+
registerCompletionRun("run-aborted", "aborted", "aborted test");
849+
setAssistantOutput("agent:main:subagent:aborted", "Partial output before cancellation");
846850

847-
// Emit an end event with aborted=true which triggers the timeout grace path
848-
emitLifecycleEvent("run-timeout", {
851+
emitLifecycleEvent("run-aborted", {
849852
phase: "end",
850853
aborted: true,
851854
endedAt: 3_000,
852-
} as LifecycleData & { aborted: boolean });
855+
});
853856
await flushAsync();
857+
854858
expect(getAgentCalls()).toHaveLength(0);
859+
expect(
860+
mod
861+
.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY)
862+
.find((candidate) => candidate.runId === "run-aborted")?.execution.status,
863+
).toBe("running");
855864

856-
// Advance past the lifecycle timeout retry grace window
857-
await vi.advanceTimersByTimeAsync(30_000);
865+
await vi.advanceTimersByTimeAsync(15_000);
858866
await flushAsync();
859867

868+
const run = mod
869+
.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY)
870+
.find((candidate) => candidate.runId === "run-aborted");
871+
expect(run).toMatchObject({
872+
endedReason: "subagent-killed",
873+
execution: { outcome: { status: "error", error: "subagent run terminated" } },
874+
});
875+
expect(getAgentCalls()).toHaveLength(0);
876+
});
877+
878+
it("announces a provider hard timeout from its canonical lifecycle metadata", async () => {
879+
registerCompletionRun("run-provider-timeout", "provider-timeout", "provider timeout test");
880+
setAssistantOutput(
881+
"agent:main:subagent:provider-timeout",
882+
"Partial output before provider timeout",
883+
);
884+
885+
emitLifecycleEvent("run-provider-timeout", {
886+
phase: "end",
887+
aborted: true,
888+
stopReason: "restart",
889+
status: "timeout",
890+
timeoutPhase: "provider",
891+
providerStarted: true,
892+
endedAt: 3_000,
893+
error: "provider timed out",
894+
});
895+
await flushAsync();
896+
expect(getAgentCalls()).toHaveLength(0);
897+
898+
await vi.advanceTimersByTimeAsync(30_000);
899+
await flushAsync();
860900
await waitForAgentCallCount(1);
861901

902+
expect(readFirstAnnounceOutcome()?.status).toBe("timeout");
862903
const run = mod
863904
.listSubagentRunsForRequester(MAIN_REQUESTER_SESSION_KEY)
864-
.find((candidate) => candidate.runId === "run-timeout");
905+
.find((candidate) => candidate.runId === "run-provider-timeout");
865906
expect(run?.execution.outcome?.status).toBe("timeout");
866907
});
867908

868909
it("cancels timeout grace when a successful end event arrives before the grace window expires", async () => {
869910
registerCompletionRun("run-timeout-cancel", "timeout-cancel", "timeout cancel test");
870911
setAssistantOutput("agent:main:subagent:timeout-cancel", "Final answer after recovery");
871912

872-
// Emit an aborted end event (starts timeout grace)
913+
// Emit a structured timeout terminal (starts timeout grace).
873914
emitLifecycleEvent("run-timeout-cancel", {
874915
phase: "end",
875916
aborted: true,
917+
status: "timeout",
918+
timeoutPhase: "provider",
919+
providerStarted: true,
876920
endedAt: 4_000,
877-
} as LifecycleData & { aborted: boolean });
921+
});
878922
await flushAsync();
879923
expect(getAgentCalls()).toHaveLength(0);
880924

0 commit comments

Comments
 (0)