Skip to content

Commit 65f3e42

Browse files
fix(gateway): yield before post-ready background work (#117083)
* fix(gateway): yield before post-ready background work * fix(gateway): gate restart recovery after ready
1 parent 4a27e2d commit 65f3e42

8 files changed

Lines changed: 337 additions & 91 deletions

‎src/agents/main-session-restart-recovery-runtime.ts‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@ export function scheduleRestartAbortedMainSessionRecovery(params: {
333333
maxRetries?: number;
334334
shouldContinue?: () => boolean;
335335
stateDir?: string;
336+
waitForStart?: () => Promise<void>;
336337
gatewayRuntime: GatewayRecoveryRuntime;
337338
}): { stop: () => Promise<void> } {
338339
const initialDelay = params.delayMs ?? DEFAULT_RECOVERY_DELAY_MS;
@@ -343,12 +344,16 @@ export function scheduleRestartAbortedMainSessionRecovery(params: {
343344
let timer: ReturnType<typeof setTimeout> | undefined;
344345
let queuedAttempt: Promise<void> | undefined;
345346
let activeAttempt: Promise<void> | undefined;
347+
let cancelStartWait: (() => void) | undefined;
348+
const startWaitCancelled = new Promise<void>((resolve) => {
349+
cancelStartWait = resolve;
350+
});
346351
const shouldContinue = () =>
347352
!stopped &&
348353
params.shouldContinue?.() !== false &&
349354
isAgentEventLifecycleGenerationCurrent(lifecycleGeneration);
350-
// Only reconcile rows that existed before this startup recovery was scheduled.
351-
// Fresh runs started by this gateway are protected again by the active-run check.
355+
// Capture the cutoff at registration, before any startup gate can release new
356+
// work. Sessions created by this gateway must never become recovery candidates.
352357
const startupRecoveryCutoffMs = Date.now();
353358

354359
const runRecoveryAttempt = (attempt: number, delay: number) => {
@@ -436,28 +441,36 @@ export function scheduleRestartAbortedMainSessionRecovery(params: {
436441
activeAttempt = trackedAttempt;
437442
};
438443

444+
const queueRecoveryAttempt = (attempt: number, delay: number) => {
445+
const pendingStart = Promise.resolve().then(async () => {
446+
if (attempt === 1 && params.waitForStart) {
447+
// Shutdown must cancel an unresolved startup gate so failed startup and
448+
// same-port replacement cannot hang while joining this lifetime owner.
449+
await Promise.race([params.waitForStart(), startWaitCancelled]);
450+
}
451+
if (shouldContinue()) {
452+
runRecoveryAttempt(attempt, delay);
453+
}
454+
});
455+
const trackedStart = pendingStart.finally(() => {
456+
if (queuedAttempt === trackedStart) {
457+
queuedAttempt = undefined;
458+
}
459+
});
460+
queuedAttempt = trackedStart;
461+
};
462+
439463
const scheduleAttempt = (attempt: number, delay: number) => {
440464
if (!shouldContinue()) {
441465
return;
442466
}
443467
if (delay <= 0) {
444-
// Publish the cancellable handle before immediate startup can claim a session.
445-
const pendingStart = Promise.resolve().then(() => {
446-
if (shouldContinue()) {
447-
runRecoveryAttempt(attempt, delay);
448-
}
449-
});
450-
const trackedStart = pendingStart.finally(() => {
451-
if (queuedAttempt === trackedStart) {
452-
queuedAttempt = undefined;
453-
}
454-
});
455-
queuedAttempt = trackedStart;
468+
queueRecoveryAttempt(attempt, delay);
456469
return;
457470
}
458471
timer = setTimeout(() => {
459472
timer = undefined;
460-
runRecoveryAttempt(attempt, delay);
473+
queueRecoveryAttempt(attempt, delay);
461474
}, delay);
462475
timer.unref?.();
463476
};
@@ -468,6 +481,7 @@ export function scheduleRestartAbortedMainSessionRecovery(params: {
468481
// Restart recovery belongs to its startup generation; stale timers must
469482
// never claim a session after that gateway begins draining.
470483
stopped = true;
484+
cancelStartWait?.();
471485
if (timer) {
472486
clearTimeout(timer);
473487
timer = undefined;

‎src/agents/main-session-restart-recovery.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2387,6 +2387,87 @@ describe("main-session-restart-recovery", () => {
23872387
});
23882388
});
23892389

2390+
it("waits for startup release while preserving the registration cutoff", async () => {
2391+
const sessionsDir = await makeSessionsDir();
2392+
const storePath = path.join(sessionsDir, "sessions.json");
2393+
const releaseStartup = createDeferred();
2394+
await writeStore(sessionsDir, {
2395+
"agent:main:main": {
2396+
...runningSessionEntry("pre-start-session"),
2397+
updatedAt: 1,
2398+
},
2399+
});
2400+
await writeTranscript(sessionsDir, "pre-start-session", [
2401+
{ role: "user", content: "resume the interrupted work" },
2402+
{ role: "toolResult", content: "done" },
2403+
]);
2404+
2405+
const recovery = scheduleRestartAbortedMainSessionRecovery({
2406+
cfg: {},
2407+
delayMs: 0,
2408+
stateDir: tmpDir,
2409+
waitForStart: () => releaseStartup.promise,
2410+
});
2411+
await Promise.resolve();
2412+
expect(callGateway).not.toHaveBeenCalled();
2413+
2414+
const postRegistrationUpdatedAt = Date.now() + 60_000;
2415+
await writeStore(sessionsDir, {
2416+
...readStore(storePath),
2417+
"agent:main:fresh": {
2418+
...runningSessionEntry("post-start-session"),
2419+
updatedAt: postRegistrationUpdatedAt,
2420+
},
2421+
});
2422+
await writeTranscript(sessionsDir, "post-start-session", [
2423+
{ role: "user", content: "new work from this gateway" },
2424+
{ role: "toolResult", content: "done" },
2425+
]);
2426+
2427+
releaseStartup.resolve();
2428+
await waitForFast(() => expect(callGateway).toHaveBeenCalledOnce());
2429+
await recovery.stop();
2430+
2431+
const store = readStore(storePath);
2432+
expect(store["agent:main:main"]?.abortedLastRun).toBe(false);
2433+
expect(store["agent:main:fresh"]).toMatchObject({
2434+
sessionId: "post-start-session",
2435+
status: "running",
2436+
});
2437+
expect(store["agent:main:fresh"]?.abortedLastRun).toBeUndefined();
2438+
});
2439+
2440+
it("stops without waiting for an unresolved startup release", async () => {
2441+
const sessionsDir = await makeSessionsDir();
2442+
const storePath = path.join(sessionsDir, "sessions.json");
2443+
const releaseStartup = createDeferred();
2444+
await writeMainSession({
2445+
sessionsDir,
2446+
pendingFinalDelivery: {
2447+
kind: "replayable",
2448+
text: "interrupted response",
2449+
createdAt: Date.now(),
2450+
},
2451+
});
2452+
2453+
const recovery = scheduleRestartAbortedMainSessionRecovery({
2454+
cfg: {},
2455+
delayMs: 0,
2456+
stateDir: tmpDir,
2457+
waitForStart: () => releaseStartup.promise,
2458+
});
2459+
await recovery.stop();
2460+
releaseStartup.resolve();
2461+
await Promise.resolve();
2462+
2463+
expect(callGateway).not.toHaveBeenCalled();
2464+
expect(getActiveGatewayRootWorkCount()).toBe(0);
2465+
expect(loadSessionEntry({ sessionKey: "agent:main:main", storePath })).toMatchObject({
2466+
status: "running",
2467+
abortedLastRun: true,
2468+
});
2469+
});
2470+
23902471
it("fences an in-flight startup recovery before its durable session claim", async () => {
23912472
const sessionsDir = await makeSessionsDir();
23922473
const storePath = path.join(sessionsDir, "sessions.json");

‎src/gateway/server-start.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ const logPlugins = log.child("plugins");
7878
const logWsControl = log.child("ws");
7979
const logSecrets = log.child("secrets");
8080
const gatewayRuntime = runtimeForLogger(log);
81+
const POST_READY_WORK_START_DELAY_MS = 500;
8182

8283
function formatRuntimeGatewayAuthTokenWarning(): string {
8384
const base =
@@ -101,6 +102,10 @@ export async function startGatewayServer(
101102
port = 18789,
102103
opts: GatewayServerOptions = {},
103104
): Promise<GatewayServer> {
105+
let releasePostReadyWork: () => void = () => {};
106+
const postReadyWorkBarrier = new Promise<void>((resolve) => {
107+
releasePostReadyWork = resolve;
108+
});
104109
const bootstrap = await prepareGatewayServerBootstrap({
105110
port,
106111
opts,
@@ -168,11 +173,16 @@ export async function startGatewayServer(
168173
logReload,
169174
logTailscale,
170175
loadGatewayStartupPostAttachModule,
176+
waitForPostReadyWork: () => postReadyWorkBarrier,
171177
});
172178
} catch (err) {
173179
await closeOnStartupFailure();
174180
throw err;
175181
}
182+
// The public server is fully initialized now. Leave a short I/O window before
183+
// background prewarms and cleanup imports compete for the startup CPU.
184+
const postReadyWorkTimer = setTimeout(releasePostReadyWork, POST_READY_WORK_START_DELAY_MS);
185+
postReadyWorkTimer.unref?.();
176186

177187
const close = createCloseHandler();
178188

‎src/gateway/server-startup-finish.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ import {
3030
type GatewayCoreRuntime = Awaited<ReturnType<typeof startGatewayCoreRuntime>>;
3131
type GatewayLogger = ReturnType<typeof createSubsystemLogger>;
3232

33-
const POST_READY_MAINTENANCE_DELAY_MS = 250;
34-
const RETAINED_PLUGIN_CLEANUP_DELAY_MS = 30_000;
33+
const [POST_READY_MAINTENANCE_DELAY_MS, RETAINED_PLUGIN_CLEANUP_DELAY_MS] = [250, 30_000];
3534

3635
export async function finishGatewayStartup(params: {
3736
coreRuntime: GatewayCoreRuntime;
@@ -48,6 +47,7 @@ export async function finishGatewayStartup(params: {
4847
loadGatewayStartupPostAttachModule: () => Promise<
4948
typeof import("./server-startup-post-attach.js")
5049
>;
50+
waitForPostReadyWork: () => Promise<void>;
5151
}) {
5252
const {
5353
coreRuntime: runtime,
@@ -342,15 +342,14 @@ export async function finishGatewayStartup(params: {
342342
import("./server/plugins-http/route-capability.js"),
343343
]),
344344
);
345-
const pluginSurfaceScheme = gatewayTls.enabled ? "https" : "http";
346345
await startupTrace.measure("gateway.ws-attach", () =>
347346
attachGatewayWsHandlers({
348347
wss,
349348
clients,
350349
preauthConnectionBudget,
351350
port,
352351
gatewayHost: bindHost ?? undefined,
353-
pluginSurfaceScheme,
352+
pluginSurfaceScheme: gatewayTls.enabled ? "https" : "http",
354353
getPluginNodeCapabilities: () =>
355354
withCoreCanvasNodeCapability(
356355
listPluginNodeCapabilities(pluginRuntime.registry),
@@ -530,6 +529,7 @@ export async function finishGatewayStartup(params: {
530529
isClosing: () => lifecycle.closePreludeStarted,
531530
startupTrace,
532531
sidecarStartup,
532+
waitForPostReadyWork: params.waitForPostReadyWork,
533533
providerAuthPrewarm: {
534534
getConfig: getRuntimeConfig,
535535
},

‎src/gateway/server-startup-handler-prewarm.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,53 @@ describe("scheduleGatewayHandlerPrewarm", () => {
123123
sidecar.stop();
124124
});
125125

126+
it("waits for gateway readiness before warming handler data", async () => {
127+
vi.useFakeTimers();
128+
let releaseGatewayReady!: () => void;
129+
const gatewayReady = new Promise<void>((resolve) => {
130+
releaseGatewayReady = resolve;
131+
});
132+
const load = vi.fn(async () => {});
133+
134+
const sidecar = scheduleGatewayHandlerPrewarm({
135+
cfgAtStart: {} as never,
136+
log: { warn: vi.fn() },
137+
items: [{ name: "sessions", load }],
138+
waitForPostReadyWork: () => gatewayReady,
139+
});
140+
141+
await vi.advanceTimersToNextTimerAsync();
142+
expect(load).not.toHaveBeenCalled();
143+
144+
releaseGatewayReady();
145+
await vi.runAllTimersAsync();
146+
expect(load).toHaveBeenCalledOnce();
147+
sidecar.stop();
148+
});
149+
150+
it("stays stopped when readiness arrives after shutdown", async () => {
151+
vi.useFakeTimers();
152+
let releaseGatewayReady!: () => void;
153+
const gatewayReady = new Promise<void>((resolve) => {
154+
releaseGatewayReady = resolve;
155+
});
156+
const load = vi.fn(async () => {});
157+
158+
const sidecar = scheduleGatewayHandlerPrewarm({
159+
cfgAtStart: {} as never,
160+
log: { warn: vi.fn() },
161+
items: [{ name: "sessions", load }],
162+
waitForPostReadyWork: () => gatewayReady,
163+
});
164+
165+
await vi.advanceTimersToNextTimerAsync();
166+
sidecar.stop();
167+
releaseGatewayReady();
168+
await vi.runAllTimersAsync();
169+
170+
expect(load).not.toHaveBeenCalled();
171+
});
172+
126173
it("logs failures and continues without changing later request behavior", async () => {
127174
vi.useFakeTimers();
128175
const warn = vi.fn();

‎src/gateway/server-startup-handler-prewarm.ts‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,14 @@ export function scheduleGatewayHandlerPrewarm(params: {
9595
startupTrace?: StartupTrace;
9696
log: { warn: (msg: string) => void };
9797
items?: readonly GatewayHandlerPrewarmItem[];
98+
waitForPostReadyWork?: () => Promise<void>;
9899
}): GatewayHandlerPrewarmHandle {
99100
// Frequent updater restarts make cold dashboard data the remaining slow tier.
100101
// Keep cheap session reads first, process-stable plugin data second, and provider catalogs last.
101102
const items = params.items ?? dashboardDataPrewarmItems(params.cfgAtStart);
102103
let stopped = false;
103104
let nextIndex = 0;
105+
let currentItemName = "unknown";
104106
let timer: ReturnType<typeof setTimeout> | undefined;
105107

106108
const scheduleNext = () => {
@@ -109,23 +111,27 @@ export function scheduleGatewayHandlerPrewarm(params: {
109111
}
110112
timer = setTimeout(() => {
111113
timer = undefined;
112-
if (stopped) {
113-
return;
114-
}
115-
const item = items[nextIndex++];
116-
if (!item) {
117-
return;
118-
}
119-
const load = () => item.load();
120-
void runWithGatewayIndependentRootWorkAdmission(() =>
121-
params.startupTrace
122-
? params.startupTrace.measure(`post-ready.gateway-data.${item.name}`, load)
123-
: load(),
124-
)
114+
void (async () => {
115+
await params.waitForPostReadyWork?.();
116+
if (stopped) {
117+
return;
118+
}
119+
const item = items[nextIndex++];
120+
if (!item) {
121+
return;
122+
}
123+
currentItemName = item.name;
124+
const load = () => item.load();
125+
await runWithGatewayIndependentRootWorkAdmission(() =>
126+
params.startupTrace
127+
? params.startupTrace.measure(`post-ready.gateway-data.${item.name}`, load)
128+
: load(),
129+
);
130+
})()
125131
.catch((err: unknown) => {
126132
// Prewarm only improves latency; readiness and request-time loaders remain authoritative.
127133
params.log.warn(
128-
`post-ready gateway data prewarm failed for ${item.name}: ${String(err)}`,
134+
`post-ready gateway data prewarm failed for ${currentItemName}: ${String(err)}`,
129135
);
130136
})
131137
.finally(scheduleNext);

0 commit comments

Comments
 (0)