Skip to content

Commit f30e672

Browse files
authored
fix(agents): preserve reply cleanup when cancellation throws (#122252)
* refactor(agents): canonicalize reply abort cleanup * refactor(agents): document reply abort cleanup invariant
1 parent ec86b02 commit f30e672

2 files changed

Lines changed: 93 additions & 41 deletions

File tree

‎src/auto-reply/reply/reply-run-registry.operation.ts‎

Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -183,18 +183,32 @@ export function createReplyOperation(params: {
183183
terminalSettleTimer.scheduleOnce(REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS);
184184
};
185185

186-
const abortWithReason = (
186+
const abortOperation = (
187187
reason: ReplyBackendCancelReason,
188188
abortReason: unknown,
189-
opts?: { abortedCode?: ReplyOperationAbortCode },
189+
abortedCode: ReplyOperationAbortCode,
190190
) => {
191-
if (opts?.abortedCode && !result) {
192-
setResult({ kind: "aborted", code: opts.abortedCode });
191+
const phaseBeforeAbort = phase;
192+
if (!result) {
193+
setResult({ kind: "aborted", code: abortedCode });
193194
detachUpstreamAbort();
194195
}
195196
phase = "aborted";
196197
abortInternally(abortReason);
197-
getAttachedBackend(operation)?.cancel(reason);
198+
// Cancellation may throw, but lifecycle cleanup still must run. Pre-backend
199+
// non-retained owners release now; retained/running owners await terminal settle.
200+
try {
201+
getAttachedBackend(operation)?.cancel(reason);
202+
} finally {
203+
if (
204+
isReplyOperationPreBackendPhase(phaseBeforeAbort) &&
205+
!retainStateUntilCompleteOperations.has(operation)
206+
) {
207+
clearState();
208+
} else {
209+
scheduleTerminalSettle();
210+
}
211+
}
198212
};
199213

200214
const operation: ReplyOperation = {
@@ -463,36 +477,14 @@ export function createReplyOperation(params: {
463477
if (!isReplyOperationAbortable(operation)) {
464478
return false;
465479
}
466-
const phaseBeforeAbort = phase;
467-
abortWithReason("user_abort", createUserAbortError(), {
468-
abortedCode: "aborted_by_user",
469-
});
470-
if (
471-
isReplyOperationPreBackendPhase(phaseBeforeAbort) &&
472-
!retainStateUntilCompleteOperations.has(operation)
473-
) {
474-
clearState();
475-
} else {
476-
scheduleTerminalSettle();
477-
}
480+
abortOperation("user_abort", createUserAbortError(), "aborted_by_user");
478481
return true;
479482
},
480483
abortForRestart() {
481484
if (!isReplyOperationAbortable(operation)) {
482485
return false;
483486
}
484-
const phaseBeforeAbort = phase;
485-
abortWithReason("restart", createAgentRunRestartAbortError(), {
486-
abortedCode: "aborted_for_restart",
487-
});
488-
if (
489-
isReplyOperationPreBackendPhase(phaseBeforeAbort) &&
490-
!retainStateUntilCompleteOperations.has(operation)
491-
) {
492-
clearState();
493-
} else {
494-
scheduleTerminalSettle();
495-
}
487+
abortOperation("restart", createAgentRunRestartAbortError(), "aborted_for_restart");
496488
return true;
497489
},
498490
};
@@ -638,18 +630,11 @@ export function createReplyOperation(params: {
638630
return;
639631
}
640632
const restart = isAgentRunRestartAbortReason(upstreamAbortSignal.reason);
641-
const phaseBeforeAbort = phase;
642-
abortWithReason(restart ? "restart" : "user_abort", upstreamAbortSignal.reason, {
643-
abortedCode: restart ? "aborted_for_restart" : "aborted_by_user",
644-
});
645-
if (
646-
isReplyOperationPreBackendPhase(phaseBeforeAbort) &&
647-
!retainStateUntilCompleteOperations.has(operation)
648-
) {
649-
clearState();
650-
} else {
651-
scheduleTerminalSettle();
652-
}
633+
abortOperation(
634+
restart ? "restart" : "user_abort",
635+
upstreamAbortSignal.reason,
636+
restart ? "aborted_for_restart" : "aborted_by_user",
637+
);
653638
};
654639
if (upstreamAbortSignal.aborted) {
655640
abortFromUpstream();

‎src/auto-reply/reply/reply-run-registry.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,6 +1163,73 @@ describe("reply run registry", () => {
11631163
operation.complete();
11641164
});
11651165

1166+
it.each([
1167+
{
1168+
name: "user abort while queued",
1169+
abort: (operation: ReturnType<typeof createTestReplyOperation>) => operation.abortByUser(),
1170+
code: "aborted_by_user",
1171+
reason: "user_abort",
1172+
phase: "queued",
1173+
},
1174+
{
1175+
name: "restart abort while queued",
1176+
abort: (operation: ReturnType<typeof createTestReplyOperation>) =>
1177+
operation.abortForRestart(),
1178+
code: "aborted_for_restart",
1179+
reason: "restart",
1180+
phase: "queued",
1181+
},
1182+
{
1183+
name: "user abort while running",
1184+
abort: (operation: ReturnType<typeof createTestReplyOperation>) => operation.abortByUser(),
1185+
code: "aborted_by_user",
1186+
reason: "user_abort",
1187+
phase: "running",
1188+
},
1189+
{
1190+
name: "restart abort while running",
1191+
abort: (operation: ReturnType<typeof createTestReplyOperation>) =>
1192+
operation.abortForRestart(),
1193+
code: "aborted_for_restart",
1194+
reason: "restart",
1195+
phase: "running",
1196+
},
1197+
] as const)("preserves cleanup when backend cancellation throws: $name", async (testCase) => {
1198+
await withFakeReplyTimers(async () => {
1199+
const cancelError = new Error("cancel failed");
1200+
const cancel = vi.fn(() => {
1201+
throw cancelError;
1202+
});
1203+
const operation = createTestReplyOperation({
1204+
sessionKey: `agent:main:${testCase.reason}-${testCase.phase}`,
1205+
sessionId: `session-${testCase.reason}-${testCase.phase}`,
1206+
});
1207+
operation.attachBackend({ kind: "embedded", cancel, isStreaming: () => true });
1208+
operation.setPhase(testCase.phase);
1209+
const afterClear = vi.fn();
1210+
runAfterReplyOperationClear(operation, afterClear);
1211+
1212+
expect(() => testCase.abort(operation)).toThrow(cancelError);
1213+
expect(operation.result).toEqual({ kind: "aborted", code: testCase.code });
1214+
expect(operation.phase).toBe("aborted");
1215+
expect(operation.abortSignal.aborted).toBe(true);
1216+
expect(cancel).toHaveBeenCalledOnce();
1217+
expect(cancel).toHaveBeenCalledWith(testCase.reason);
1218+
1219+
const retained = testCase.phase === "running";
1220+
expect(replyRunRegistry.isActive(operation.key)).toBe(retained);
1221+
expect(afterClear).toHaveBeenCalledTimes(retained ? 0 : 1);
1222+
expect(vi.getTimerCount()).toBe(retained ? 1 : 0);
1223+
1224+
await vi.advanceTimersByTimeAsync(REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS);
1225+
expect(replyRunRegistry.isActive(operation.key)).toBe(false);
1226+
expect(afterClear).toHaveBeenCalledOnce();
1227+
operation.complete();
1228+
expect(afterClear).toHaveBeenCalledOnce();
1229+
expect(cancel).toHaveBeenCalledOnce();
1230+
});
1231+
});
1232+
11661233
it("force-releases a running aborted operation when the owner never returns", async () => {
11671234
await withFakeReplyTimers(async () => {
11681235
const cancel = vi.fn();

0 commit comments

Comments
 (0)