Skip to content

Commit 1704ea5

Browse files
authored
fix(gateway): confirm restart lease handoff (#118026)
1 parent 603321a commit 1704ea5

9 files changed

Lines changed: 356 additions & 2 deletions

‎src/agents/session-write-lock-error.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@ export class SessionWriteLockStaleError extends Error {
3333
}
3434
}
3535

36+
/** Returns whether another owner replaced the active SQLite session lease. */
37+
export function isSessionWriteLockLeaseLostError(error: unknown): boolean {
38+
const code = (error as { code?: unknown } | null)?.code;
39+
const staleReasons = (error as { staleReasons?: unknown } | null)?.staleReasons;
40+
return (
41+
(error instanceof SessionWriteLockStaleError || code === STALE_CODE) &&
42+
Array.isArray(staleReasons) &&
43+
staleReasons.includes("lease-lost")
44+
);
45+
}
46+
3647
export function isSessionWriteLockAcquireError(error: unknown): boolean {
3748
const code = (error as { code?: unknown } | null)?.code;
3849
return (

‎src/auto-reply/reply/agent-runner-error-handler.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
AGENT_RUN_RESTART_ABORT_STOP_REASON,
2121
resolveAgentRunErrorLifecycleFields,
2222
} from "../../agents/run-termination.js";
23+
import { isSessionWriteLockLeaseLostError } from "../../agents/session-write-lock-error.js";
2324
import { logVerbose } from "../../globals.js";
2425
import { emitAgentEvent } from "../../infra/agent-events.js";
2526
import { sleepWithAbort } from "../../infra/backoff.js";
@@ -108,6 +109,24 @@ type ErrorAction =
108109
| { kind: "retry"; liveModelSwitchError?: LiveSessionModelSwitchError }
109110
| Extract<AgentTurnInternalResult, { kind: "final" }>;
110111

112+
function isSessionLeaseLoss(error: unknown): boolean {
113+
const pending = [error];
114+
const seen = new Set<unknown>();
115+
for (const candidate of pending) {
116+
if (!candidate || seen.has(candidate)) {
117+
continue;
118+
}
119+
seen.add(candidate);
120+
if (isSessionWriteLockLeaseLostError(candidate)) {
121+
return true;
122+
}
123+
if (candidate instanceof Error && "cause" in candidate && candidate.cause !== undefined) {
124+
pending.push(candidate.cause);
125+
}
126+
}
127+
return false;
128+
}
129+
111130
export async function handleAgentExecutionError(params: {
112131
turn: AgentTurnParams;
113132
error: unknown;
@@ -234,6 +253,16 @@ export async function handleAgentExecutionError(params: {
234253
if (replyOperationAbortAction) {
235254
return replyOperationAbortAction;
236255
}
256+
if (
257+
isSessionLeaseLoss(err) &&
258+
(await turn.confirmRestartRecoveryArmedAfterLeaseLoss?.()) === true
259+
) {
260+
// The replacement owns recovery only after the latest SQLite row confirms
261+
// the active claim or its terminal marker. The old owner then exits silently.
262+
turn.replyOperation?.abortForRestart();
263+
takePendingLifecycleTerminal()?.emit("end", err);
264+
return { kind: "final", payload: { text: SILENT_REPLY_TOKEN } };
265+
}
237266
const restartLifecycleError = resolveRestartLifecycleError(err);
238267
if (
239268
restartLifecycleError instanceof GatewayDrainingError ||

‎src/auto-reply/reply/agent-runner-execute.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ type ExecutePreparedReplyAgentRunInput = Pick<
7474
checkpointBeforeAgentReply: ReturnType<
7575
typeof createReplyRestartRecoveryClaimController
7676
>["checkpointBeforeAgentReply"];
77+
confirmRestartRecoveryArmedAfterLeaseLoss: ReturnType<
78+
typeof createReplyRestartRecoveryClaimController
79+
>["confirmRestartRecoveryArmedAfterLeaseLoss"];
7780
getActiveIsNewSession: () => boolean;
7881
getActiveSessionEntry: () => SessionEntry | undefined;
7982
isHeartbeat: boolean;
@@ -113,6 +116,7 @@ export async function executePreparedReplyAgentRun(
113116
blockStreamingEnabled,
114117
cfg,
115118
checkpointBeforeAgentReply: checkpointBeforeAgentReplyWithRecovery,
119+
confirmRestartRecoveryArmedAfterLeaseLoss,
116120
commandBody,
117121
defaultModel,
118122
followupRun,
@@ -386,6 +390,7 @@ export async function executePreparedReplyAgentRun(
386390
resolvedVerboseLevel,
387391
toolProgressDetail,
388392
replyMediaContext,
393+
confirmRestartRecoveryArmedAfterLeaseLoss,
389394
isRestartRecoveryArmed,
390395
}),
391396
),
@@ -483,6 +488,7 @@ export function createReplyAgentRestartRecoveryController(
483488
beginBeforeAgentReply,
484489
checkpointBeforeAgentReply,
485490
clear: clearRestartRecoveryDeliveryClaim,
491+
confirmRestartRecoveryArmedAfterLeaseLoss,
486492
isArmed: isRestartRecoveryArmed,
487493
} = createReplyRestartRecoveryClaimController({
488494
admissionRunId:
@@ -551,6 +557,7 @@ export function createReplyAgentRestartRecoveryController(
551557
admitUserTurn,
552558
beginBeforeAgentReply,
553559
checkpointBeforeAgentReply,
560+
confirmRestartRecoveryArmedAfterLeaseLoss,
554561
clear: clearRestartRecoveryDeliveryClaim,
555562
isArmed: isRestartRecoveryArmed,
556563
};

‎src/auto-reply/reply/agent-runner-execution-terminal-failures.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { FailoverError } from "../../agents/failover-error.js";
33
import { AgentHarnessSessionSupersededError } from "../../agents/harness/errors.js";
4+
import { SessionWriteLockStaleError } from "../../agents/session-write-lock-error.js";
45
import { CommandLaneClearedError, GatewayDrainingError } from "../../process/command-queue.js";
56
import { getReplyPayloadMetadata } from "../reply-payload.js";
67
import type { TemplateContext } from "../templating.js";
@@ -381,6 +382,55 @@ describe("executeAgentTurn: terminal failures", () => {
381382
).toBe(true);
382383
});
383384

385+
it("hands a confirmed restart lease loss to the replacement owner", async () => {
386+
const agentEvents = await import("../../infra/agent-events.js");
387+
const emitAgentEvent = vi.mocked(agentEvents.emitAgentEvent);
388+
const { replyOperation, failMock } = createMockReplyOperation();
389+
const abortForRestart = vi.spyOn(replyOperation, "abortForRestart");
390+
abortForRestart.mockImplementationOnce(() => {
391+
Object.defineProperty(replyOperation, "result", {
392+
value: { kind: "aborted", code: "aborted_for_restart" } as const,
393+
configurable: true,
394+
});
395+
return true;
396+
});
397+
state.runEmbeddedAgentMock.mockRejectedValueOnce(
398+
new Error("embedded runner failed", {
399+
cause: new SessionWriteLockStaleError({
400+
lockPath: "sqlite:session-write:agent:main:main",
401+
owner: "replacement gateway",
402+
staleReasons: ["lease-lost"],
403+
}),
404+
}),
405+
);
406+
const confirmRestartRecoveryArmedAfterLeaseLoss = vi.fn(async () => true);
407+
408+
const executeAgentTurn = await getExecuteAgentTurnForTest();
409+
const result = await executeAgentTurn({
410+
...createMinimalRunAgentTurnParams({ replyOperation }),
411+
confirmRestartRecoveryArmedAfterLeaseLoss,
412+
isRestartRecoveryArmed: () => false,
413+
});
414+
415+
expect(result).toEqual({ kind: "final", payload: { text: SILENT_REPLY_TOKEN } });
416+
expect(confirmRestartRecoveryArmedAfterLeaseLoss).toHaveBeenCalledOnce();
417+
expect(abortForRestart).toHaveBeenCalledOnce();
418+
expect(failMock).not.toHaveBeenCalled();
419+
expect(
420+
emitAgentEvent.mock.calls.filter(
421+
([event]) =>
422+
event.stream === "lifecycle" &&
423+
event.data.phase === "end" &&
424+
event.data.stopReason === "restart",
425+
),
426+
).toHaveLength(1);
427+
expect(
428+
emitAgentEvent.mock.calls.some(
429+
([event]) => event.stream === "lifecycle" && event.data.phase === "error",
430+
),
431+
).toBe(false);
432+
});
433+
384434
it("preserves restart ownership when an aborted embedded runner resolves normally", async () => {
385435
const agentEvents = await import("../../infra/agent-events.js");
386436
const emitAgentEvent = vi.mocked(agentEvents.emitAgentEvent);

‎src/auto-reply/reply/agent-runner-execution.types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ export type AgentTurnParams = {
105105
toolProgressDetail?: "explain" | "raw";
106106
replyMediaContext?: ReplyMediaContext;
107107
onCompactionNoticePayload?: (payload: ReplyPayload) => Promise<void> | void;
108+
confirmRestartRecoveryArmedAfterLeaseLoss?: () => Promise<boolean>;
108109
isRestartRecoveryArmed?: () => boolean;
109110
};
110111

‎src/auto-reply/reply/agent-runner-run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,7 @@ export async function runReplyAgent(
577577
beginBeforeAgentReply,
578578
checkpointBeforeAgentReply,
579579
clear: clearRestartRecoveryDeliveryClaim,
580+
confirmRestartRecoveryArmedAfterLeaseLoss,
580581
isArmed: isRestartRecoveryArmed,
581582
} = createReplyAgentRestartRecoveryController({
582583
activeSessionStore,
@@ -645,6 +646,7 @@ export async function runReplyAgent(
645646
blockStreamingEnabled,
646647
cfg,
647648
checkpointBeforeAgentReply,
649+
confirmRestartRecoveryArmedAfterLeaseLoss,
648650
commandBody,
649651
defaultModel,
650652
followupRun,

‎src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
7+
import { SessionWriteLockStaleError } from "../../agents/session-write-lock-error.js";
78
import { clearRuntimeConfigSnapshot, setRuntimeConfigSnapshot } from "../../config/config.js";
89
import type { SessionEntry } from "../../config/sessions.js";
910
import {
@@ -24,6 +25,7 @@ import {
2425
import { createUserTurnTranscriptRecorder } from "../../sessions/user-turn-transcript.js";
2526
import { createTestUserTurnTranscriptTarget } from "../../sessions/user-turn-transcript.test-support.js";
2627
import type { TemplateContext } from "../templating.js";
28+
import { SILENT_REPLY_TOKEN } from "../tokens.js";
2729
import type { GetReplyOptions } from "../types.js";
2830
import {
2931
GENERIC_EXTERNAL_RUN_FAILURE_TEXT,
@@ -2251,6 +2253,77 @@ describe("runReplyAgent pending final delivery capture", () => {
22512253
}
22522254
});
22532255

2256+
it("preserves an adopted restart claim when the replacement takes the SQLite lease", async () => {
2257+
const sessionEntry: SessionEntry = {
2258+
abortedLastRun: false,
2259+
restartRecoveryDeliveryRequestFingerprint: "request-fingerprint",
2260+
restartRecoveryDeliveryRunId: "msg",
2261+
restartRecoveryDeliverySourceRunId: "control-ui-run",
2262+
sessionId: "session",
2263+
status: "running",
2264+
updatedAt: Date.now(),
2265+
};
2266+
const sessionStore = { main: sessionEntry };
2267+
const storePath = await createSessionStoreFile(sessionEntry);
2268+
const replyOperation = createReplyOperation({
2269+
sessionKey: "main",
2270+
sessionId: "session",
2271+
resetTriggered: false,
2272+
});
2273+
replyOperation.setPhase("running");
2274+
state.runEmbeddedAgentMock.mockImplementationOnce(async () => {
2275+
const current = await readStoredMainSession(storePath);
2276+
expect(current.restartRecoveryDeliveryRunId).toBe("msg");
2277+
await replaceSessionEntry(
2278+
{ storePath, sessionKey: "main" },
2279+
{
2280+
...current,
2281+
abortedLastRun: true,
2282+
status: "killed",
2283+
updatedAt: Date.now(),
2284+
},
2285+
);
2286+
throw new SessionWriteLockStaleError({
2287+
lockPath: "sqlite:session-write:agent:main:main",
2288+
owner: "replacement gateway",
2289+
staleReasons: ["lease-lost"],
2290+
});
2291+
});
2292+
2293+
try {
2294+
const { run } = createMinimalRun({
2295+
replyOperation,
2296+
sessionCtx: {
2297+
Provider: "webchat",
2298+
OriginatingChannel: "webchat",
2299+
},
2300+
runOverrides: { agentId: "main", messageProvider: "webchat" },
2301+
sessionEntry,
2302+
sessionStore,
2303+
sessionKey: "main",
2304+
storePath,
2305+
});
2306+
2307+
await expect(run()).resolves.toEqual({ text: SILENT_REPLY_TOKEN });
2308+
2309+
expect(replyOperation.result).toEqual({
2310+
kind: "aborted",
2311+
code: "aborted_for_restart",
2312+
});
2313+
expect(await readStoredMainSession(storePath)).toMatchObject({
2314+
abortedLastRun: true,
2315+
restartRecoveryDeliveryRunId: "msg",
2316+
restartRecoveryDeliverySourceRunId: "control-ui-run",
2317+
status: "killed",
2318+
});
2319+
expect(
2320+
(await readStoredMainSession(storePath)).restartRecoveryTerminalRunIds,
2321+
).toBeUndefined();
2322+
} finally {
2323+
replyOperation.complete();
2324+
}
2325+
});
2326+
22542327
it("fires onAdopted after restart recovery delivery context persist completes", async () => {
22552328
const sessionEntry: SessionEntry = {
22562329
sessionId: "session",

0 commit comments

Comments
 (0)