Skip to content

Commit 8333892

Browse files
committed
fix(agents): retain reply owners through cancellation
1 parent 8757119 commit 8333892

6 files changed

Lines changed: 306 additions & 33 deletions

File tree

‎src/agents/embedded-agent-runner/runs.force-clear-terminal.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ describe("force-clear terminal state persistence", () => {
7474
forceClear: true,
7575
settleMs: 100,
7676
});
77-
expect(isReplyRunActiveForSessionId(sessionId)).toBe(false);
77+
expect(isReplyRunActiveForSessionId(sessionId)).toBe(true);
7878
expect(followupObservedActiveHandle).toEqual([]);
7979

8080
clearActiveEmbeddedRun(sessionId, handle, sessionKey);
@@ -169,6 +169,68 @@ describe("force-clear terminal state persistence", () => {
169169
});
170170
});
171171

172+
it("force-clears a reply-only backend that accepts cancellation without completing", async () => {
173+
const sessionKey = "agent:main:reply-only-cancel-pending";
174+
const sessionId = "session-reply-only-cancel-pending";
175+
const operation = createReplyOperation({ sessionKey, sessionId, resetTriggered: false });
176+
const cancel = vi.fn();
177+
operation.attachBackend({
178+
kind: "embedded",
179+
cancel,
180+
isStreaming: () => true,
181+
});
182+
operation.setPhase("running");
183+
184+
const followupObservedActiveOwner: boolean[] = [];
185+
runAfterReplyOperationClear(operation, () => {
186+
followupObservedActiveOwner.push(isReplyRunActiveForSessionId(sessionId));
187+
});
188+
189+
const result = await abortAndDrainEmbeddedAgentRun({
190+
sessionId,
191+
sessionKey,
192+
reason: "stuck_recovery",
193+
forceClear: true,
194+
settleMs: 20,
195+
});
196+
197+
expect(result).toEqual({ aborted: false, drained: false, forceCleared: true });
198+
expect(cancel).toHaveBeenCalledWith("superseded");
199+
expect(operation.result).toEqual({ kind: "failed", code: "run_stalled" });
200+
expect(isReplyRunActiveForSessionId(sessionId)).toBe(false);
201+
await vi.waitFor(() => {
202+
expect(followupObservedActiveOwner).toEqual([false]);
203+
});
204+
});
205+
206+
it("force-clears active handle and reply owners when cancellation never completes", async () => {
207+
const sessionKey = "agent:main:handle-cancel-pending";
208+
const sessionId = "session-handle-cancel-pending";
209+
const operation = createReplyOperation({ sessionKey, sessionId, resetTriggered: false });
210+
const abort = vi.fn();
211+
const handle = createRunHandle({ abort });
212+
operation.attachBackend({
213+
kind: "embedded",
214+
cancel: handle.abort,
215+
isStreaming: handle.isStreaming,
216+
});
217+
operation.setPhase("running");
218+
setActiveEmbeddedRun(sessionId, handle, sessionKey);
219+
220+
const result = await abortAndDrainEmbeddedAgentRun({
221+
sessionId,
222+
sessionKey,
223+
reason: "stuck_recovery",
224+
forceClear: true,
225+
settleMs: 20,
226+
});
227+
228+
expect(result).toEqual({ aborted: true, drained: false, forceCleared: true });
229+
expect(abort).toHaveBeenCalled();
230+
expect(isReplyRunActiveForSessionId(sessionId)).toBe(false);
231+
expect(isEmbeddedAgentRunHandleActive(sessionId)).toBe(false);
232+
});
233+
172234
it("persists killed status after a force-cleared run", async () => {
173235
const sessionKey = "agent:main:main";
174236
const sessionId = "session-1";

‎src/agents/embedded-agent-runner/runs.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -914,29 +914,31 @@ export async function abortAndDrainEmbeddedAgentRun(params: {
914914
};
915915
try {
916916
if (expiredReplyRun && !ACTIVE_EMBEDDED_RUNS.has(params.sessionId)) {
917-
// Reply expiry aborts synchronously and clears registry ownership. Let the
918-
// command lane observe that abort before recovery decides whether to reset it.
917+
// Let the command lane observe synchronous reply completion before recovery
918+
// decides whether to reset it, but keep all owners on the shared drain path.
919919
await new Promise<void>((resolve) => {
920920
setImmediate(resolve);
921921
});
922-
const embeddedDrained = await waitForEmbeddedAgentRunEnd(params.sessionId, settleMs);
923-
const ownerSettled = await waitForExpiredOwnerSettlement();
924-
const drained = embeddedDrained && ownerSettled;
925-
return { aborted: true, drained, forceCleared: false };
926922
}
927-
const aborted = abortEmbeddedAgentRun(params.sessionId) || expiredReplyRun;
928-
const embeddedDrained = aborted
929-
? await waitForEmbeddedAgentRunEnd(params.sessionId, settleMs)
930-
: false;
923+
let aborted = abortEmbeddedAgentRun(params.sessionId) || expiredReplyRun;
924+
const embeddedDrained =
925+
aborted || stampedStaleReplyRun
926+
? await waitForEmbeddedAgentRunEnd(params.sessionId, settleMs)
927+
: false;
931928
const ownerSettled = await waitForExpiredOwnerSettlement();
932929
const drained = embeddedDrained && ownerSettled;
930+
// A retained cancel request can complete asynchronously after expire()
931+
// returns. Count that exact owner settlement as the accepted abort.
932+
if (!aborted && stampedStaleReplyRun && drained) {
933+
aborted = true;
934+
}
933935
const persistenceSnapshot =
934936
params.forceClear === true && params.sessionKey
935937
? tryLoadForceClearSessionSnapshot(params.sessionKey)
936938
: undefined;
937939
const forceCleared =
938940
params.forceClear === true &&
939-
((!expiredReplyRun && stampedStaleReplyRun) || !aborted || !drained)
941+
((!expiredReplyRun && stampedStaleReplyRun && !ownerSettled) || !aborted || !drained)
940942
? forceClearEmbeddedAgentRun(
941943
params.sessionId,
942944
embeddedRunHandle,

‎src/auto-reply/reply/dispatch-from-config.stale-recovery.test.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { buildTestCtx } from "./test-ctx.js";
1515
let dispatchReplyFromConfig: typeof import("./dispatch-from-config.js").dispatchReplyFromConfig;
1616
let createReplyOperation: typeof import("./reply-run-registry.js").createReplyOperation;
1717
let expireStaleReplyOperation: typeof import("./reply-run-registry.js").expireStaleReplyOperation;
18+
let REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS: typeof import("./reply-run-registry.js").REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS;
1819
let replyRunRegistry: typeof import("./reply-run-registry.js").replyRunRegistry;
1920
let replyRunTesting: typeof import("./reply-run-registry.test-support.js").testing;
2021
let resetInboundDedupe: typeof import("./inbound-dedupe.js").resetInboundDedupe;
@@ -48,8 +49,12 @@ function createVisibleDispatchParams(
4849
describe("dispatchReplyFromConfig stale visible admission recovery", () => {
4950
beforeAll(async () => {
5051
({ dispatchReplyFromConfig } = await import("./dispatch-from-config.js"));
51-
({ createReplyOperation, expireStaleReplyOperation, replyRunRegistry } =
52-
await import("./reply-run-registry.js"));
52+
({
53+
createReplyOperation,
54+
expireStaleReplyOperation,
55+
REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS,
56+
replyRunRegistry,
57+
} = await import("./reply-run-registry.js"));
5358
({ testing: replyRunTesting } = await import("./reply-run-registry.test-support.js"));
5459
({ resetInboundDedupe } = await import("./inbound-dedupe.js"));
5560
});
@@ -79,6 +84,9 @@ describe("dispatchReplyFromConfig stale visible admission recovery", () => {
7984
resetTriggered: false,
8085
});
8186
activeOperation.setPhase("running");
87+
activeOperation.abortSignal.addEventListener("abort", () => activeOperation.complete(), {
88+
once: true,
89+
});
8290
const waitChanges: boolean[] = [];
8391
const replyResolver = vi.fn(async () => ({ text: "telegram reply" }) satisfies ReplyPayload);
8492
const dispatchParams = {
@@ -113,7 +121,7 @@ describe("dispatchReplyFromConfig stale visible admission recovery", () => {
113121
expect(waitChanges).toEqual([true, false]);
114122
});
115123

116-
it("reclaims stale visible reply work through admission and dispatches the turn", async () => {
124+
it("reclaims stale pre-backend work after bounded terminal settlement", async () => {
117125
vi.useFakeTimers();
118126
const startedAt = Date.now();
119127
const activeOperation = createReplyOperation({
@@ -126,7 +134,14 @@ describe("dispatchReplyFromConfig stale visible admission recovery", () => {
126134
const dispatchParams = createVisibleDispatchParams(replyResolver);
127135
vi.setSystemTime(startedAt + RUN_STALE_TAKEOVER_MS + 1);
128136

129-
const result = await dispatchReplyFromConfig(dispatchParams);
137+
const resultPromise = dispatchReplyFromConfig(dispatchParams);
138+
await vi.waitFor(() => {
139+
expect(activeOperation.result).toEqual({ kind: "failed", code: "run_stalled" });
140+
});
141+
expect(replyRunRegistry.get(sessionKey)).toBe(activeOperation);
142+
143+
await vi.advanceTimersByTimeAsync(REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS);
144+
const result = await resultPromise;
130145

131146
expect(diagnosticMocks.requestStuckDiagnosticSessionRecovery).not.toHaveBeenCalled();
132147
expect(activeOperation.result).toEqual({ kind: "failed", code: "run_stalled" });
@@ -159,7 +174,7 @@ describe("dispatchReplyFromConfig stale visible admission recovery", () => {
159174
await resolverStartedPromise;
160175
const operation = replyRunRegistry.get(sessionKey);
161176
expect(operation).toBeDefined();
162-
expect(expireStaleReplyOperation(operation!, reason)).toBe(true);
177+
expect(expireStaleReplyOperation(operation!, reason)).toBe(false);
163178

164179
await expect(dispatchPromise).resolves.toMatchObject({ queuedFinal: true });
165180
expect(dispatchParams.dispatcher.sendFinalReply).toHaveBeenCalledWith({

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

Lines changed: 118 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -385,8 +385,8 @@ describe("reply run registry", () => {
385385
const operation = createTestReplyOperation({ sessionId: "session-stale-owner" });
386386
operation.setPhase("running");
387387

388-
expect(expireStaleReplyOperation(operation, "stuck_recovery")).toBe(true);
389-
expect(replyRunRegistry.isActive("agent:main:main")).toBe(false);
388+
expect(expireStaleReplyOperation(operation, "stuck_recovery")).toBe(false);
389+
expect(replyRunRegistry.isActive("agent:main:main")).toBe(true);
390390

391391
const settlement = waitForReplyOperationOwnerSettlement(operation, 1_000);
392392
let settled = false;
@@ -513,6 +513,112 @@ describe("reply run registry", () => {
513513
expect(replyRunRegistry.get("agent:main:main")).toBeUndefined();
514514
});
515515

516+
it("retains exact ownership when stale backend cancellation awaits terminal completion", async () => {
517+
const operation = createTestReplyOperation({ sessionId: "session-cancel-pending" });
518+
operation.setPhase("running");
519+
const cancel = vi.fn();
520+
operation.attachBackend({
521+
kind: "embedded",
522+
cancel,
523+
isStreaming: () => true,
524+
});
525+
let releaseRecovery: () => void = () => {};
526+
const recoveryBarrier = new Promise<void>((resolve) => {
527+
releaseRecovery = resolve;
528+
});
529+
const afterClear = vi.fn();
530+
runAfterReplyOperationClear(operation, afterClear);
531+
532+
expect(
533+
expireStaleReplyOperation(operation, "stuck_recovery", {
534+
afterClearBarrier: recoveryBarrier,
535+
}),
536+
).toBe(false);
537+
expect(cancel).toHaveBeenCalledWith("superseded");
538+
expect(operation.result).toEqual({ kind: "failed", code: "run_stalled" });
539+
expect(operation.abortSignal.aborted).toBe(true);
540+
expect(replyRunRegistry.get("agent:main:main")).toBe(operation);
541+
542+
releaseRecovery();
543+
await recoveryBarrier;
544+
await Promise.resolve();
545+
expect(afterClear).not.toHaveBeenCalled();
546+
547+
expect(forceClearReplyOperation(operation, new Error("terminal completion timed out"))).toBe(
548+
true,
549+
);
550+
await vi.waitFor(() => {
551+
expect(afterClear).toHaveBeenCalledWith("session-cancel-pending");
552+
});
553+
expect(replyRunRegistry.get("agent:main:main")).toBeUndefined();
554+
});
555+
556+
it("retains pre-backend ownership and rejects a backend that attaches after expiry", async () => {
557+
const operation = createTestReplyOperation({ sessionId: "session-cancel-before-attach" });
558+
operation.setPhase("running");
559+
let releaseRecovery: () => void = () => {};
560+
const recoveryBarrier = new Promise<void>((resolve) => {
561+
releaseRecovery = resolve;
562+
});
563+
const afterClear = vi.fn();
564+
runAfterReplyOperationClear(operation, afterClear);
565+
566+
expect(
567+
expireStaleReplyOperation(operation, "stuck_recovery", {
568+
afterClearBarrier: recoveryBarrier,
569+
}),
570+
).toBe(false);
571+
expect(operation.abortSignal.aborted).toBe(true);
572+
expect(replyRunRegistry.get("agent:main:main")).toBe(operation);
573+
574+
const lateCancel = vi.fn();
575+
operation.attachBackend({
576+
kind: "embedded",
577+
cancel: lateCancel,
578+
isStreaming: () => true,
579+
});
580+
expect(lateCancel).toHaveBeenCalledWith("superseded");
581+
expect(replyRunRegistry.get("agent:main:main")).toBe(operation);
582+
583+
releaseRecovery();
584+
await recoveryBarrier;
585+
await Promise.resolve();
586+
expect(afterClear).not.toHaveBeenCalled();
587+
588+
expect(forceClearReplyOperation(operation)).toBe(true);
589+
await vi.waitFor(() => {
590+
expect(afterClear).toHaveBeenCalledWith("session-cancel-before-attach");
591+
});
592+
expect(replyRunRegistry.get("agent:main:main")).toBeUndefined();
593+
});
594+
595+
it("bounds retained ownership when stale cancellation awaits terminal completion", async () => {
596+
vi.useFakeTimers();
597+
try {
598+
const operation = createTestReplyOperation({ sessionId: "session-cancel-pending-bound" });
599+
operation.setPhase("running");
600+
operation.attachBackend({
601+
kind: "embedded",
602+
cancel: () => {},
603+
isStreaming: () => true,
604+
});
605+
const afterClear = vi.fn();
606+
runAfterReplyOperationClear(operation, afterClear);
607+
608+
expect(expireStaleReplyOperation(operation, "no_activity")).toBe(false);
609+
await vi.advanceTimersByTimeAsync(REPLY_RUN_TERMINAL_SETTLE_TIMEOUT_MS - 1);
610+
expect(replyRunRegistry.get("agent:main:main")).toBe(operation);
611+
expect(afterClear).not.toHaveBeenCalled();
612+
613+
await vi.advanceTimersByTimeAsync(1);
614+
expect(replyRunRegistry.get("agent:main:main")).toBeUndefined();
615+
expect(afterClear).toHaveBeenCalledWith("session-cancel-pending-bound");
616+
} finally {
617+
await vi.runOnlyPendingTimersAsync();
618+
vi.useRealTimers();
619+
}
620+
});
621+
516622
it("bounds retained ownership when stale cancellation throws undefined", async () => {
517623
vi.useFakeTimers();
518624
try {
@@ -590,12 +696,17 @@ describe("reply run registry", () => {
590696
expireStaleReplyOperation(operation, "stuck_recovery", {
591697
afterClearBarrier: recoveryBarrier,
592698
}),
593-
).toBe(true);
699+
).toBe(false);
594700
const afterClear = vi.fn();
595701
runAfterReplyOperationClear(operation, afterClear);
596702
expect(afterClear).not.toHaveBeenCalled();
597703

598704
releaseRecovery();
705+
await recoveryBarrier;
706+
await Promise.resolve();
707+
expect(afterClear).not.toHaveBeenCalled();
708+
709+
expect(forceClearReplyOperation(operation)).toBe(true);
599710
await vi.waitFor(() => {
600711
expect(afterClear).toHaveBeenCalledWith("session-late-callback");
601712
});
@@ -1005,7 +1116,7 @@ describe("reply run registry", () => {
10051116
}
10061117
});
10071118

1008-
it("keeps run_stalled attribution when backend cancel re-enters abortByUser", () => {
1119+
it("keeps run_stalled attribution and ownership when cancel re-enters abortByUser", () => {
10091120
const operation = createTestReplyOperation({
10101121
sessionKey: "agent:main:reentrant-expire",
10111122
sessionId: "reentrant-session",
@@ -1021,8 +1132,10 @@ describe("reply run registry", () => {
10211132
});
10221133
operation.setPhase("running");
10231134

1024-
expect(expireStaleReplyOperation(operation, "no_activity")).toBe(true);
1135+
expect(expireStaleReplyOperation(operation, "no_activity")).toBe(false);
10251136
expect(operation.result).toEqual({ kind: "failed", code: "run_stalled" });
1137+
expect(replyRunRegistry.get("agent:main:reentrant-expire")).toBe(operation);
1138+
expect(forceClearReplyOperation(operation)).toBe(true);
10261139
expect(replyRunRegistry.get("agent:main:reentrant-expire")).toBeUndefined();
10271140
});
10281141

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

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,9 +1062,10 @@ export function createReplyOperation(params: {
10621062
options.followupAdmissionBarrierTimeout,
10631063
);
10641064
}
1065+
const backend = getAttachedBackend(operation);
10651066
let cancelFailed = false;
10661067
try {
1067-
getAttachedBackend(operation)?.cancel("superseded");
1068+
backend?.cancel("superseded");
10681069
} catch (error) {
10691070
cancelFailed = true;
10701071
diag.warn(
@@ -1076,13 +1077,15 @@ export function createReplyOperation(params: {
10761077
logStaleTakeoverRelease();
10771078
return true;
10781079
}
1079-
if (cancelFailed) {
1080-
scheduleTerminalSettle();
1081-
return false;
1080+
// cancel() only requests shutdown. A missing backend can also be a live
1081+
// pre-attachment owner, so only complete() may release the exact lane token.
1082+
if (!cancelFailed) {
1083+
diag.warn(
1084+
`reply run stale takeover retained: sessionKey=${currentSessionKey} reason=${reason} owner=awaiting_terminal_completion backend=${backend ? "attached" : "pending"}`,
1085+
);
10821086
}
1083-
clearState();
1084-
logStaleTakeoverRelease();
1085-
return true;
1087+
scheduleTerminalSettle();
1088+
return false;
10861089
});
10871090
const finalizationLease = replyRunSettle.createReplyRunFinalizationLease({
10881091
owner: operation,
@@ -1103,7 +1106,12 @@ export function createReplyOperation(params: {
11031106
result,
11041107
)} ageMs=${Date.now() - lastActivityAtMs} ranForMs=${Date.now() - startedAtMs}`,
11051108
);
1106-
expireReplyOperationByOperation.get(operation)?.("finalization_stalled");
1109+
const expired = expireReplyOperationByOperation.get(operation)?.("finalization_stalled");
1110+
if (expired === false && replyRunState.activeRunsByKey.get(currentSessionKey) === operation) {
1111+
// This lease is the finalization owner's bounded shutdown deadline.
1112+
// Do not grant a second terminal-settle lifetime after it expires.
1113+
forceClearReplyOperation(operation);
1114+
}
11071115
},
11081116
});
11091117
const terminalSettleTimer = replyRunSettle.createReplyRunSettleTimer({

0 commit comments

Comments
 (0)