Skip to content

Commit f830b8c

Browse files
NianJiuZststeipete
andauthored
fix(gateway): prevent interrupt failures from blocking session lifecycle (#126546)
* fix(gateway): release interrupted chat admission * fix(gateway): unify interrupted chat admission cleanup Co-authored-by: NianJiuZst <[email protected]> * chore(gateway): leave changelog to release generation --------- Co-authored-by: NianJiuZst <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent 12e52a1 commit f830b8c

2 files changed

Lines changed: 138 additions & 58 deletions

File tree

‎src/gateway/server-methods/chat-send-admission.ts‎

Lines changed: 52 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -411,68 +411,63 @@ export async function admitChatSend(params: {
411411
});
412412
return { ok: false as const };
413413
}
414-
let interruptedActiveRun = false;
415-
let interruptionSettled = true;
416-
if (runInterruptTarget) {
417-
interruptedActiveRun = true;
418-
interruptionSettled = (
419-
await interruptReplyRunTarget(runInterruptTarget, REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS)
420-
).settled;
421-
} else if (p.queueMode === "interrupt") {
422-
const identities = [sessionKey, backingSessionId, admittedSessionId];
423-
// The fallback runs inside the new admission so the lifecycle owner excludes itself.
424-
// A captured reply operation never falls through to this identity-scoped path.
425-
const fallback = await gatewayWorkAdmission.run(async () => {
426-
if (!isCompetingSessionWorkAdmissionActive(storePath, identities)) {
427-
return { interrupted: false, settled: true };
428-
}
429-
return {
430-
interrupted: true,
431-
settled: await interruptSessionWorkAdmissions({
432-
scope: storePath,
433-
identities,
434-
timeoutMs: REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
435-
}),
436-
};
437-
});
438-
interruptedActiveRun = fallback.interrupted;
439-
interruptionSettled = fallback.settled;
440-
}
441-
if (!interruptionSettled) {
414+
let releaseGatewayRootContinuation = () => {};
415+
// Until dispatch takes custody, interruption and callback failures own the same three resources.
416+
const cleanupPreDispatchAdmission = () => {
442417
activeRunAbort.cleanup({ force: true });
443418
gatewayWorkAdmission.release();
444-
respond(
445-
false,
446-
undefined,
447-
errorShape(
448-
ErrorCodes.UNAVAILABLE,
449-
"Previous run is still shutting down. Please try again in a moment.",
450-
{ retryable: true, retryAfterMs: 250 },
451-
),
452-
);
453-
return { ok: false as const };
454-
}
455-
// Reserved here, while the request's root is provably live, rather than after the ACK: the
456-
// detached dispatch must keep that root until terminal persistence settles or restart drain
457-
// completes early and loses the session's terminal state. Callers outside a Gateway request
458-
// envelope (internal chat entries) hold no root, so there is nothing to extend for them.
459-
const releaseGatewayRootContinuation = retainGatewayRootWorkAdmissionContinuation() ?? (() => {});
460-
if (params.onAdmissionOwned) {
461-
let proceed: boolean;
462-
try {
463-
proceed = await gatewayWorkAdmission.run(params.onAdmissionOwned);
464-
} catch (error) {
465-
activeRunAbort.cleanup({ force: true });
466-
gatewayWorkAdmission.release();
467-
releaseGatewayRootContinuation();
468-
throw error;
419+
releaseGatewayRootContinuation();
420+
};
421+
let interruptedActiveRun = false;
422+
try {
423+
let interruptionSettled = true;
424+
if (runInterruptTarget) {
425+
interruptedActiveRun = true;
426+
interruptionSettled = (
427+
await interruptReplyRunTarget(runInterruptTarget, REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS)
428+
).settled;
429+
} else if (p.queueMode === "interrupt") {
430+
const identities = [sessionKey, backingSessionId, admittedSessionId];
431+
// The fallback runs inside the new admission so the lifecycle owner excludes itself.
432+
// A captured reply operation never falls through to this identity-scoped path.
433+
const fallback = await gatewayWorkAdmission.run(async () => {
434+
if (!isCompetingSessionWorkAdmissionActive(storePath, identities)) {
435+
return { interrupted: false, settled: true };
436+
}
437+
return {
438+
interrupted: true,
439+
settled: await interruptSessionWorkAdmissions({
440+
scope: storePath,
441+
identities,
442+
timeoutMs: REPLY_RUN_IDLE_SETTLE_TIMEOUT_MS,
443+
}),
444+
};
445+
});
446+
interruptedActiveRun = fallback.interrupted;
447+
interruptionSettled = fallback.settled;
469448
}
470-
if (!proceed) {
471-
activeRunAbort.cleanup({ force: true });
472-
gatewayWorkAdmission.release();
473-
releaseGatewayRootContinuation();
449+
if (!interruptionSettled) {
450+
cleanupPreDispatchAdmission();
451+
respond(
452+
false,
453+
undefined,
454+
errorShape(
455+
ErrorCodes.UNAVAILABLE,
456+
"Previous run is still shutting down. Please try again in a moment.",
457+
{ retryable: true, retryAfterMs: 250 },
458+
),
459+
);
460+
return { ok: false as const };
461+
}
462+
// Reserve while the request root is live: detached dispatch retains it until terminal persistence.
463+
releaseGatewayRootContinuation = retainGatewayRootWorkAdmissionContinuation() ?? (() => {});
464+
if (params.onAdmissionOwned && !(await gatewayWorkAdmission.run(params.onAdmissionOwned))) {
465+
cleanupPreDispatchAdmission();
474466
return { ok: false as const };
475467
}
468+
} catch (error) {
469+
cleanupPreDispatchAdmission();
470+
throw error;
476471
}
477472

478473
const acquiredGatewayWorkAdmission = gatewayWorkAdmission;

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

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import path from "node:path";
66
import { beforeEach, describe, expect, test, vi } from "vitest";
77
import { WebSocket } from "ws";
88
import { createDeferred } from "../../test/helpers/promise.js";
9+
import { replyRunRegistry } from "../auto-reply/reply/reply-run-registry.js";
910
import { loadSessionEntry } from "../config/sessions/session-accessor.js";
1011
import { replaceTranscriptEvents } from "../config/sessions/session-accessor.sqlite-transcript-write.js";
1112
import { emitAgentEvent } from "../infra/agent-events.js";
@@ -22,7 +23,10 @@ import {
2223
resetGatewayWorkAdmission,
2324
tryBeginGatewaySuspendAdmission,
2425
} from "../process/gateway-work-admission.js";
25-
import { beginSessionWorkAdmission } from "../sessions/session-lifecycle-admission.js";
26+
import {
27+
beginSessionWorkAdmission,
28+
getActiveSessionWorkAdmissionCount,
29+
} from "../sessions/session-lifecycle-admission.js";
2630
import { extractFirstTextBlock } from "../shared/chat-message-content.js";
2731
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
2832
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
@@ -441,6 +445,87 @@ describe("gateway server chat", () => {
441445
});
442446
});
443447

448+
test("chat.send interrupt releases its admission when backend cancellation throws", async () => {
449+
await withMainSessionStore(async () => {
450+
const activeRunStarted = createDeferred();
451+
mockGetReplyFromConfigOnce(async (_ctx, opts) => {
452+
activeRunStarted.resolve(undefined);
453+
if (!opts?.abortSignal?.aborted) {
454+
await new Promise<void>((resolve) => {
455+
opts?.abortSignal?.addEventListener("abort", () => resolve(), { once: true });
456+
});
457+
}
458+
return undefined;
459+
});
460+
const active = await rpcReq(ws, "chat.send", {
461+
sessionKey: "main",
462+
message: "captured active turn",
463+
idempotencyKey: "idem-chat-interrupt-throw-old",
464+
});
465+
expect(active.ok).toBe(true);
466+
await activeRunStarted.promise;
467+
468+
const operation = replyRunRegistry.get("agent:main:main");
469+
expect(operation).toBeDefined();
470+
operation?.attachBackend({
471+
kind: "embedded",
472+
cancel: () => {
473+
throw new Error("cancel failed");
474+
},
475+
isStreaming: () => true,
476+
});
477+
478+
const res = await rpcReq(ws, "chat.send", {
479+
sessionKey: "main",
480+
message: "replace the captured turn",
481+
queueMode: "interrupt",
482+
idempotencyKey: "idem-chat-interrupt-throw-new",
483+
});
484+
expect(res.ok).toBe(false);
485+
await waitForFast(() => expect(getActiveSessionWorkAdmissionCount()).toBe(0));
486+
await waitForFast(() => expect(getActiveGatewayRootWorkCount()).toBe(0));
487+
488+
const reset = await rpcReq(ws, "sessions.reset", { key: "main", reason: "new" });
489+
expect(reset.ok).toBe(true);
490+
});
491+
});
492+
493+
test("chat.send interrupt releases its admission when session interruption throws", async () => {
494+
await withMainSessionStore(async () => {
495+
const storePath = testState.sessionStorePath;
496+
if (!storePath) {
497+
throw new Error("session store path was not initialized");
498+
}
499+
const activeAdmission = await beginSessionWorkAdmission({
500+
scope: storePath,
501+
identities: ["agent:main:main", "sess-main"],
502+
assertAllowed: () => {},
503+
onInterrupt: () => {
504+
activeAdmission.release();
505+
throw new Error("session interruption failed");
506+
},
507+
});
508+
509+
try {
510+
const res = await rpcReq(ws, "chat.send", {
511+
sessionKey: "main",
512+
message: "replace non-reply session work",
513+
queueMode: "interrupt",
514+
idempotencyKey: "idem-chat-interrupt-non-reply-throw",
515+
});
516+
517+
expect(res.ok).toBe(false);
518+
await waitForFast(() => expect(getActiveSessionWorkAdmissionCount()).toBe(0));
519+
await waitForFast(() => expect(getActiveGatewayRootWorkCount()).toBe(0));
520+
521+
const reset = await rpcReq(ws, "sessions.reset", { key: "main", reason: "new" });
522+
expect(reset.ok).toBe(true);
523+
} finally {
524+
activeAdmission.release();
525+
}
526+
});
527+
});
528+
444529
test("chat.send interrupt drains a non-reply session admission before dispatching", async () => {
445530
await withMainSessionStore(async () => {
446531
const storePath = testState.sessionStorePath;

0 commit comments

Comments
 (0)