Skip to content

Commit f735922

Browse files
roboclaw-botTakhoffman
authored andcommitted
fix(gateway): keep restart abort lifecycle-scoped
Co-authored-by: Tak Hoffman <[email protected]>
1 parent d67d9f1 commit f735922

9 files changed

Lines changed: 37 additions & 102 deletions

File tree

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ vi.mock("../../infra/agent-events.js", async (importOriginal) => ({
7777

7878
function createRunHandle(params: {
7979
abort?: EmbeddedAgentQueueHandle["abort"];
80+
compacting?: boolean;
8081
diagnosticOwner?: DiagnosticEmbeddedRunOwner;
8182
queueMessage: EmbeddedAgentQueueHandle["queueMessage"];
8283
runId: string;
@@ -92,7 +93,7 @@ function createRunHandle(params: {
9293
queueMessage: params.queueMessage,
9394
isStreaming: () => true,
9495
isAbortable: () => false,
95-
isCompacting: () => false,
96+
isCompacting: () => params.compacting === true,
9697
abort: params.abort ?? (() => {}),
9798
};
9899
}
@@ -106,6 +107,24 @@ describe("embedded run registry lifecycle generations", () => {
106107
lifecycleMock.reset();
107108
});
108109

110+
it("aborts a rootless compacting run when its gateway lifecycle rotates", () => {
111+
const abort = vi.fn();
112+
setActiveEmbeddedRun(
113+
"rootless-session",
114+
createRunHandle({
115+
abort,
116+
compacting: true,
117+
queueMessage: vi.fn(async () => {}),
118+
runId: "rootless-run",
119+
}),
120+
);
121+
122+
rotateAgentEventLifecycleGeneration();
123+
124+
expect(abort).toHaveBeenCalledWith("restart");
125+
expect(listActiveEmbeddedRunSessionIds()).not.toContain("rootless-session");
126+
});
127+
109128
it("rejects a delayed prior-lifecycle registration for a current session owner", async () => {
110129
const priorLifecycleGeneration = getAgentEventLifecycleGeneration();
111130
const staleQueueMessage = vi.fn(async () => {});

‎src/cli/gateway-cli/lifecycle.runtime.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// run-loop.ts primes this hub before the HTTP listener binds, so each re-export
33
// must target the module that defines the symbol rather than a re-export facade;
44
// a facade also evaluates its siblings and drags their graphs onto cold start.
5+
export { abortEmbeddedAgentRun } from "../../agents/embedded-agent-runner/runs.js";
56
export {
67
respawnGatewayProcessForUpdate,
78
restartGatewayProcessWithFreshPid,

‎src/cli/gateway-cli/run-loop.test.ts‎

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,6 @@ const abortPendingChannelReloads = vi.fn();
152152
const abortEmbeddedAgentRun = vi.fn(
153153
(_sessionId?: string, _opts?: { mode?: "all" | "compacting"; reason?: "restart" }) => false,
154154
);
155-
const listActiveEmbeddedRunSessionIds = vi.fn(() => [] as string[]);
156-
const listActiveEmbeddedRunSessionKeys = vi.fn(() => [] as string[]);
157-
const markRestartAbortedMainSessions = vi.fn(async (_params: unknown) => ({
158-
marked: 1,
159-
skipped: 0,
160-
}));
161-
const loadConfig = vi.fn(() => ({}));
162155
const DEFAULT_RESTART_DEFERRAL_TIMEOUT_MS = 300_000;
163156
const gatewayLog = {
164157
debug: vi.fn(),
@@ -269,17 +262,6 @@ vi.mock("../../agents/embedded-agent-runner/runs.js", () => ({
269262
sessionId?: string,
270263
opts?: { mode?: "all" | "compacting"; reason?: "restart" },
271264
) => abortEmbeddedAgentRun(sessionId, opts),
272-
listActiveEmbeddedRunSessionIds: () => listActiveEmbeddedRunSessionIds(),
273-
listActiveEmbeddedRunSessionKeys: () => listActiveEmbeddedRunSessionKeys(),
274-
}));
275-
276-
vi.mock("../../agents/main-session-recovery/main-session-restart-recovery-marking.js", () => ({
277-
markRestartAbortedMainSessions: (params: unknown) => markRestartAbortedMainSessions(params),
278-
}));
279-
280-
vi.mock("../../config/config.js", () => ({
281-
getRuntimeConfig: () => loadConfig(),
282-
loadConfig: () => loadConfig(),
283265
}));
284266

285267
vi.mock("../../logging/subsystem.js", () => ({
@@ -1049,7 +1031,7 @@ describe("runGatewayLoop", () => {
10491031
});
10501032
});
10511033

1052-
it("does not mark drain-start runs before server close revalidates them", async () => {
1034+
it("waits for the drain before handing recovery ownership to server close", async () => {
10531035
vi.clearAllMocks();
10541036
consumeGatewayRestartIntentPayloadSync.mockReturnValueOnce({ waitMs: 0 });
10551037
const drainStart = createActiveWorkSnapshot({ embeddedRuns: 2 }, [
@@ -1060,13 +1042,9 @@ describe("runGatewayLoop", () => {
10601042
releaseDrain = resolve;
10611043
});
10621044
createGatewayActiveWorkSnapshot.mockReturnValueOnce(drainStart);
1063-
listActiveEmbeddedRunSessionIds.mockReturnValue(["session-finished", "session-active"]);
1064-
listActiveEmbeddedRunSessionKeys.mockReturnValue(["agent:main:finished", "agent:main:active"]);
10651045
waitForGatewayActiveWork.mockImplementationOnce(async () => {
1066-
// One run settles while the other keeps the restart drain open. Recovery
1067-
// ownership must be collected later by server close, after this window.
1068-
listActiveEmbeddedRunSessionIds.mockReturnValue(["session-active"]);
1069-
listActiveEmbeddedRunSessionKeys.mockReturnValue(["agent:main:active"]);
1046+
// Recovery ownership must be collected later by server close, after this
1047+
// window lets active work settle.
10701048
await pendingDrain;
10711049
return { drained: true, snapshot: idleActiveWorkSnapshot };
10721050
});
@@ -1079,8 +1057,10 @@ describe("runGatewayLoop", () => {
10791057
sigterm();
10801058
await vi.waitFor(() => expect(waitForGatewayActiveWork).toHaveBeenCalledOnce());
10811059

1082-
expect(markRestartAbortedMainSessions).not.toHaveBeenCalled();
1083-
expect(abortEmbeddedAgentRun).not.toHaveBeenCalled();
1060+
expect(abortEmbeddedAgentRun).toHaveBeenCalledWith(undefined, {
1061+
mode: "compacting",
1062+
reason: "restart",
1063+
});
10841064
expect(close).not.toHaveBeenCalled();
10851065

10861066
releaseDrain?.();

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -597,8 +597,11 @@ export async function runGatewayLoop(params: {
597597
await measureGatewayRestartTrace(
598598
"restart.drain",
599599
async () => {
600-
const { createGatewayActiveWorkSnapshot, waitForGatewayActiveWork } =
601-
await loadGatewayLifecycleRuntimeModule();
600+
const {
601+
abortEmbeddedAgentRun,
602+
createGatewayActiveWorkSnapshot,
603+
waitForGatewayActiveWork,
604+
} = await loadGatewayLifecycleRuntimeModule();
602605
const formatBlockers = (
603606
snapshot: ReturnType<typeof createGatewayActiveWorkSnapshot>,
604607
) => snapshot.blockers.map((blocker) => blocker.message).join("; ");
@@ -609,6 +612,9 @@ export async function runGatewayLoop(params: {
609612
const initialSnapshot = createGatewayActiveWorkSnapshot();
610613
activeWorkAtDrainStart = initialSnapshot.counts.totalActive;
611614
activeRunsAtDrainStart = initialSnapshot.counts.embeddedRuns;
615+
if (activeRunsAtDrainStart > 0) {
616+
abortEmbeddedAgentRun(undefined, { mode: "compacting", reason: "restart" });
617+
}
612618

613619
if (!initialSnapshot.idle) {
614620
gatewayLog.info(
@@ -979,7 +985,7 @@ export async function runGatewayLoop(params: {
979985
waitForActiveCronJobs,
980986
waitForActiveCronTaskRuns,
981987
} = await loadGatewayLifecycleRuntimeModule();
982-
// Rotate ownership before reset pumps preserved queue entries.
988+
// Rotation aborts rootless stale owners before reset pumps preserved queues.
983989
rotateAgentEventLifecycleGeneration();
984990
advanceCronActiveJobGeneration();
985991
abortActiveCronTaskRuns("Gateway restarting.");

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

Lines changed: 0 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1236,61 +1236,6 @@ describe("createGatewayCloseHandler", () => {
12361236
).toBe(false);
12371237
});
12381238

1239-
it("cancels rootless embedded work after recovery marking on forced restart", async () => {
1240-
const events: string[] = [];
1241-
const restartRecoveryCandidates = new Map([
1242-
[
1243-
"rootless-run",
1244-
{
1245-
runId: "rootless-run",
1246-
lifecycleGeneration: "generation-1",
1247-
sessionKey: "agent:main:rootless",
1248-
sessionId: "rootless-session",
1249-
},
1250-
],
1251-
]);
1252-
const close = createGatewayCloseHandler(
1253-
createGatewayCloseTestDeps({
1254-
abortEmbeddedRunsForRestart: vi.fn(() => {
1255-
events.push("embedded-abort");
1256-
return true;
1257-
}),
1258-
markMainSessionsAbortedForRestart: vi.fn(async () => {
1259-
events.push("marker");
1260-
}),
1261-
restartRecoveryCandidates,
1262-
}),
1263-
);
1264-
1265-
await close({
1266-
reason: "forced gateway restart",
1267-
restartExpectedMs: 123,
1268-
drainTimeoutMs: 0,
1269-
});
1270-
1271-
expect(events).toEqual(["marker", "embedded-abort"]);
1272-
expect(restartRecoveryCandidates.size).toBe(0);
1273-
});
1274-
1275-
it("cancels rootless embedded work when restart reply drain times out", async () => {
1276-
const abortEmbeddedRunsForRestart = vi.fn(() => true);
1277-
const close = createGatewayCloseHandler(
1278-
createGatewayCloseTestDeps({
1279-
abortEmbeddedRunsForRestart,
1280-
getPendingReplyCount: vi.fn(() => 1),
1281-
}),
1282-
);
1283-
1284-
const result = await close({
1285-
reason: "gateway restart drain timeout",
1286-
restartExpectedMs: 123,
1287-
drainTimeoutMs: 0,
1288-
});
1289-
1290-
expect(result.warnings).toContain("restart-reply-drain");
1291-
expect(abortEmbeddedRunsForRestart).toHaveBeenCalledOnce();
1292-
});
1293-
12941239
it("keeps post-terminal caller work in restart drain and recovery", async () => {
12951240
const controller = new AbortController();
12961241
const markMainSessionsAbortedForRestart = vi.fn<MarkMainSessionsAbortedForRestart>();

‎src/gateway/server-close.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,6 @@ type RestartRunAbortParams = {
227227
}) => boolean;
228228
}) => Promise<void> | void;
229229
resolveActiveSessionIdForKey?: (sessionKey: string) => string | undefined;
230-
abortEmbeddedRunsForRestart?: () => boolean;
231230
};
232231

233232
/** Wait for pending replies and active runs to drain before restart shutdown. */
@@ -458,7 +457,6 @@ function abortActiveRunsForRestart(params: RestartRunAbortParams): number {
458457
aborted += 1;
459458
}
460459
}
461-
params.abortEmbeddedRunsForRestart?.();
462460
return aborted;
463461
}
464462

@@ -530,7 +528,6 @@ async function drainRestartPendingRepliesForShutdown(
530528
(params.restartRecoveryCandidates?.size ?? 0) === 0 &&
531529
listRestartRecoveryRuns(params.chatAbortControllers).length === 0
532530
) {
533-
params.abortEmbeddedRunsForRestart?.();
534531
return;
535532
}
536533

@@ -850,7 +847,6 @@ export function createGatewayCloseHandler(
850847
agentRunSeq: params.agentRunSeq,
851848
broadcast: params.broadcast,
852849
nodeSendToSession: params.nodeSendToSession,
853-
abortEmbeddedRunsForRestart: params.abortEmbeddedRunsForRestart,
854850
markMainSessionsAbortedForRestart: params.markMainSessionsAbortedForRestart,
855851
resolveActiveSessionIdForKey: params.resolveActiveSessionIdForKey,
856852
timeoutMs: drainTimeoutMs,

‎src/gateway/server-lifecycle.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -528,8 +528,6 @@ export async function prepareGatewayLifecycle(params: {
528528
agentRunSeq,
529529
nodeSendToSession,
530530
resolveActiveSessionIdForKey: resolveActiveEmbeddedRunSessionId,
531-
abortEmbeddedRunsForRestart: () =>
532-
shutdownRuntime.abortEmbeddedAgentRun(undefined, { mode: "all", reason: "restart" }),
533531
markMainSessionsAbortedForRestart: async ({
534532
sessionKeys,
535533
sessionIds,

‎src/gateway/server-shutdown.runtime.test.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ const state = vi.hoisted(() => ({
77
stopPlugins: vi.fn(),
88
clearPluginRegistry: vi.fn(),
99
preparePluginRegistryShutdown: vi.fn(async () => undefined),
10-
abortEmbeddedAgentRun: vi.fn(),
1110
}));
1211

1312
vi.mock("./server-close.runtime.js", () => {
@@ -65,10 +64,6 @@ vi.mock("../plugins/runtime.js", () => {
6564
prepareActivePluginRegistryShutdown: state.preparePluginRegistryShutdown,
6665
};
6766
});
68-
vi.mock("../agents/embedded-agent-runner/runs.js", () => {
69-
state.loaded.push("embedded-runs");
70-
return { abortEmbeddedAgentRun: state.abortEmbeddedAgentRun };
71-
});
7267

7368
const { prepareGatewayShutdownRuntime } = await import("./server-shutdown.runtime.js");
7469

@@ -90,14 +85,12 @@ describe("gateway shutdown runtime", () => {
9085
"code-mode",
9186
"provider-transports",
9287
"plugin-runtime",
93-
"embedded-runs",
9488
].toSorted(),
9589
);
9690
expect(runtime.createGatewayCloseHandler).toBe(state.close);
9791
expect(runtime.flushPendingSessionsChangedEvents).toBe(state.flushSessionChanges);
9892
expect(runtime.runGlobalGatewayStopSafely).toBe(state.stopPlugins);
9993
expect(runtime.clearActivePluginRegistry).toBe(state.clearPluginRegistry);
100-
expect(runtime.abortEmbeddedAgentRun).toBe(state.abortEmbeddedAgentRun);
10194
expect(state.preparePluginRegistryShutdown).toHaveBeenCalledOnce();
10295
});
10396
});

‎src/gateway/server-shutdown.runtime.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ export async function prepareGatewayShutdownRuntime() {
1212
{ disposeAllCodeModeRuns },
1313
{ closeProviderTransportDispatcherPool },
1414
{ clearActivePluginRegistry, prepareActivePluginRegistryShutdown },
15-
{ abortEmbeddedAgentRun },
1615
] = await Promise.all([
1716
import("./server-close.runtime.js"),
1817
import("../plugins/hook-runner-global.js"),
@@ -26,7 +25,6 @@ export async function prepareGatewayShutdownRuntime() {
2625
import("../agents/code-mode-state.js"),
2726
import("../agents/provider-transport-dispatcher-pool.js"),
2827
import("../plugins/runtime.js"),
29-
import("../agents/embedded-agent-runner/runs.js"),
3028
]);
3129
await prepareActivePluginRegistryShutdown();
3230

@@ -45,7 +43,6 @@ export async function prepareGatewayShutdownRuntime() {
4543
disposeAllCodeModeRuns,
4644
closeProviderTransportDispatcherPool,
4745
clearActivePluginRegistry,
48-
abortEmbeddedAgentRun,
4946
};
5047
}
5148

0 commit comments

Comments
 (0)