Skip to content

Commit d455844

Browse files
fix(gateway): await late sidecar stops and delay sentinel removal
Address review findings on restart-continuation retry lifecycle: - P1: track and await stop() promises for sidecars registered after close started, instead of dropping them via void stop(). The restart-sentinel sidecar's stop() awaits the sentinel wake, so dropping it let producer work continue past shutdown. stopPostReadySidecarsAfterCloseStarted now returns the stop promises; the close path awaits them. - P1: remove the restart sentinel file only after the notice has a durable handoff (continuation enqueued/drained and notice delivered). Previously removal ran before delivery, so an abort in between lost the notice. Delivery is now at-least-once (replayed on next boot) rather than lost.
1 parent b5a8a7a commit d455844

7 files changed

Lines changed: 71 additions & 19 deletions

‎src/gateway/server-close.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,9 @@ export function createGatewayCloseHandler(
392392
stopChannel: (name: ChannelId, accountId?: string) => Promise<void>;
393393
pluginServices: PluginServicesHandle | null;
394394
postReadySidecars?: readonly GatewayPostReadySidecarHandle[];
395+
// Stop promises for sidecars that registered after close started; awaited
396+
// alongside the snapshot so late producers cannot outlive shutdown.
397+
lateSidecarStopPromises?: readonly Promise<void>[];
395398
disposeSessionMcpRuntimes?: () => Promise<void>;
396399
disposeBundleLspRuntimes?: () => Promise<void>;
397400
cron: { stop: () => void };
@@ -541,11 +544,21 @@ export function createGatewayCloseHandler(
541544
if (params.tailscaleCleanup) {
542545
await shutdownStep("tailscale", () => params.tailscaleCleanup!(), warnings);
543546
}
544-
if (params.postReadySidecars?.length) {
547+
if (params.postReadySidecars?.length || params.lateSidecarStopPromises?.length) {
545548
await measureCloseStep("post-ready-sidecars", async () => {
546-
for (const [index, sidecar] of params.postReadySidecars!.entries()) {
549+
for (const [index, sidecar] of (params.postReadySidecars ?? []).entries()) {
547550
await shutdownStep(`post-ready-sidecar/${index}`, () => sidecar.stop(), warnings);
548551
}
552+
// Await sidecars that registered after the snapshot was taken: their
553+
// stop() promises were tracked rather than dropped, so restart-sentinel
554+
// producer work is drained before shutdown proceeds.
555+
if (params.lateSidecarStopPromises?.length) {
556+
await shutdownStep(
557+
"post-ready-sidecar/late",
558+
() => Promise.allSettled(params.lateSidecarStopPromises!).then(() => undefined),
559+
warnings,
560+
);
561+
}
549562
});
550563
}
551564
if (params.pluginServices) {

‎src/gateway/server-restart-sentinel.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,13 @@ describe("scheduleRestartSentinelWake", () => {
451451
});
452452
expect(mocks.recordInboundSessionAndDispatchReply).not.toHaveBeenCalled();
453453
expect(mocks.logWarn).not.toHaveBeenCalled();
454+
// The sentinel file must only be removed after the notice has a durable
455+
// handoff (delivered/enqueued). If removal raced ahead of delivery, an
456+
// abort in between would lose the restart notice entirely.
457+
expect(mocks.removeRestartSentinelFile).toHaveBeenCalledTimes(1);
458+
const deliverOrder = Math.max(...mocks.deliverOutboundPayloads.mock.invocationCallOrder);
459+
const removeOrder = mocks.removeRestartSentinelFile.mock.invocationCallOrder[0];
460+
expect(removeOrder).toBeGreaterThan(deliverOrder);
454461
});
455462

456463
it("retries outbound delivery once and logs a warning without dropping the agent wake", async () => {

‎src/gateway/server-restart-sentinel.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,6 @@ async function loadRestartSentinelStartupTask(params: {
582582
);
583583
}
584584

585-
await removeRestartSentinelFile(sentinelPath);
586585
const routedAgentTurnContinuation =
587586
payload.continuation?.kind === "agentTurn" && continuationRoute !== undefined;
588587
if (!routedAgentTurnContinuation) {
@@ -618,6 +617,12 @@ async function loadRestartSentinelStartupTask(params: {
618617
});
619618
}
620619

620+
// Remove the sentinel only after the restart notice has a durable handoff
621+
// (continuation enqueued/drained and notice delivered). If shutdown aborts
622+
// mid-delivery the sentinel survives and is replayed on the next boot,
623+
// making delivery at-least-once instead of silently lost.
624+
await removeRestartSentinelFile(sentinelPath);
625+
621626
return { status: "ran" as const };
622627
};
623628

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ export type GatewayServerMutableState = {
2323
tailscaleCleanup: (() => Promise<void>) | null;
2424
postReadySidecars: GatewayPostReadySidecarHandle[];
2525
gatewayLifetimeSidecars: GatewayPostReadySidecarHandle[];
26+
// Stop promises for sidecars that registered after close already started.
27+
// The close path awaits these so late-registered producers (e.g. the
28+
// restart-sentinel sidecar) cannot keep running past shutdown.
29+
lateSidecarStopPromises: Promise<void>[];
2630
skillsRefreshTimer: ReturnType<typeof setTimeout> | null;
2731
skillsRefreshDelayMs: number;
2832
skillsChangeUnsub: () => void;
@@ -60,6 +64,7 @@ export function createGatewayServerMutableState(): GatewayServerMutableState {
6064
tailscaleCleanup: null as (() => Promise<void>) | null,
6165
postReadySidecars: [],
6266
gatewayLifetimeSidecars: [],
67+
lateSidecarStopPromises: [],
6368
skillsRefreshTimer: null as ReturnType<typeof setTimeout> | null,
6469
skillsRefreshDelayMs: 30_000,
6570
skillsChangeUnsub: () => {},

‎src/gateway/server-startup-post-attach.test.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1502,15 +1502,30 @@ describe("startGatewayPostAttachRuntime", () => {
15021502
});
15031503
});
15041504

1505-
it("stops post-ready sidecars registered after close started", () => {
1506-
const postReadySidecar = { stop: vi.fn() };
1505+
it("stops post-ready sidecars registered after close started and returns their stop promises", async () => {
1506+
let resolveStop: (() => void) | undefined;
1507+
const stopPromise = new Promise<void>((resolve) => {
1508+
resolveStop = resolve;
1509+
});
1510+
const postReadySidecar = { stop: vi.fn(() => stopPromise) };
15071511

1508-
testing.stopPostReadySidecarsAfterCloseStarted({
1512+
const returnedPromises = testing.stopPostReadySidecarsAfterCloseStarted({
15091513
postReadySidecars: [postReadySidecar],
15101514
closeStarted: true,
15111515
});
15121516

15131517
expect(postReadySidecar.stop).toHaveBeenCalledTimes(1);
1518+
// The stop promise must be returned (not dropped) so the close path can
1519+
// await late-registered producers instead of racing past shutdown.
1520+
expect(returnedPromises).toHaveLength(1);
1521+
let settled = false;
1522+
void Promise.all(returnedPromises).then(() => {
1523+
settled = true;
1524+
});
1525+
expect(settled).toBe(false);
1526+
resolveStop?.();
1527+
await Promise.all(returnedPromises);
1528+
expect(settled).toBe(true);
15141529
});
15151530

15161531
it("keeps post-ready sidecars running when close has not started", () => {

‎src/gateway/server-startup-post-attach.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,15 @@ export type GatewayPostReadySidecarHandle = {
9898
export function stopPostReadySidecarsAfterCloseStarted(params: {
9999
postReadySidecars: readonly GatewayPostReadySidecarHandle[];
100100
closeStarted: boolean;
101-
}): void {
101+
}): Promise<void>[] {
102102
if (!params.closeStarted) {
103-
return;
104-
}
105-
for (const postReadySidecar of params.postReadySidecars) {
106-
void postReadySidecar.stop();
103+
return [];
107104
}
105+
// Return the stop promises rather than dropping them: a sidecar registered
106+
// after the close path already drained its snapshot (e.g. the restart-sentinel
107+
// sidecar, whose stop() awaits the sentinel wake) must still be awaited by
108+
// the close path, or its producer work can continue past shutdown.
109+
return params.postReadySidecars.map((postReadySidecar) => postReadySidecar.stop());
108110
}
109111

110112
/** Measure a post-attach startup step when tracing is active. */

‎src/gateway/server.impl.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,6 +1031,7 @@ export async function startGatewayServer(
10311031
stopChannel,
10321032
pluginServices: runtimeState.pluginServices,
10331033
postReadySidecars: runtimeState.postReadySidecars,
1034+
lateSidecarStopPromises: runtimeState.lateSidecarStopPromises,
10341035
cron: runtimeState.cronState.cron,
10351036
heartbeatRunner: runtimeState.heartbeatRunner,
10361037
updateCheckStop: runtimeState.stopGatewayUpdateCheck,
@@ -1624,20 +1625,24 @@ export async function startGatewayServer(
16241625
},
16251626
onPostReadySidecars: (postReadySidecars) => {
16261627
runtimeState.postReadySidecars = postReadySidecars;
1627-
stopPostReadySidecarsAfterCloseStarted({
1628-
postReadySidecars,
1629-
closeStarted: closePreludeStarted,
1630-
});
1628+
runtimeState.lateSidecarStopPromises.push(
1629+
...stopPostReadySidecarsAfterCloseStarted({
1630+
postReadySidecars,
1631+
closeStarted: closePreludeStarted,
1632+
}),
1633+
);
16311634
if (closePreludeStarted) {
16321635
runtimeState.postReadySidecars = [];
16331636
}
16341637
},
16351638
onGatewayLifetimeSidecars: (gatewayLifetimeSidecars) => {
16361639
runtimeState.gatewayLifetimeSidecars = gatewayLifetimeSidecars;
1637-
stopPostReadySidecarsAfterCloseStarted({
1638-
postReadySidecars: gatewayLifetimeSidecars,
1639-
closeStarted: closePreludeStarted,
1640-
});
1640+
runtimeState.lateSidecarStopPromises.push(
1641+
...stopPostReadySidecarsAfterCloseStarted({
1642+
postReadySidecars: gatewayLifetimeSidecars,
1643+
closeStarted: closePreludeStarted,
1644+
}),
1645+
);
16411646
if (closePreludeStarted) {
16421647
runtimeState.gatewayLifetimeSidecars = [];
16431648
}

0 commit comments

Comments
 (0)