Skip to content

Commit 6b506e9

Browse files
authored
improve(gateway): reduce context-cache startup delay (#106117)
* perf(gateway): defer context cache prewarm * refactor(gateway): keep prewarm internals private
1 parent cb1b577 commit 6b506e9

5 files changed

Lines changed: 103 additions & 35 deletions
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import type { OpenClawConfig } from "../config/types.openclaw.js";
2+
import { runWithGatewayIndependentRootWorkAdmission } from "../process/gateway-work-admission.js";
3+
4+
const CONTEXT_CACHE_PREWARM_START_DELAY_MS = 5_000;
5+
6+
type StartupTrace = {
7+
measure: <T>(name: string, run: () => T | Promise<T>) => Promise<T>;
8+
};
9+
10+
type ContextCachePrewarmHandle = {
11+
stop: () => void | Promise<void>;
12+
};
13+
14+
export function scheduleContextCachePrewarm(params: {
15+
cfgAtStart: OpenClawConfig;
16+
startupTrace?: StartupTrace;
17+
log: { warn: (msg: string) => void };
18+
}): ContextCachePrewarmHandle {
19+
let stopped = false;
20+
let timer: ReturnType<typeof setTimeout> | undefined;
21+
const warm = async () => {
22+
if (stopped) {
23+
return;
24+
}
25+
const { ensureContextWindowCacheLoaded } = await import("../agents/context.js");
26+
if (!stopped) {
27+
await ensureContextWindowCacheLoaded(params.cfgAtStart);
28+
}
29+
};
30+
31+
// Source-backed provider discovery can consume the main thread. Give
32+
// readiness probes and immediate client work a clean event-loop window.
33+
timer = setTimeout(() => {
34+
timer = undefined;
35+
void runWithGatewayIndependentRootWorkAdmission(() =>
36+
params.startupTrace
37+
? params.startupTrace.measure("post-ready.context-window-cache", warm)
38+
: warm(),
39+
).catch((err: unknown) => {
40+
params.log.warn(`post-ready.context-window-cache failed after gateway ready: ${String(err)}`);
41+
});
42+
}, CONTEXT_CACHE_PREWARM_START_DELAY_MS);
43+
timer.unref?.();
44+
45+
return {
46+
stop: () => {
47+
stopped = true;
48+
if (timer) {
49+
clearTimeout(timer);
50+
timer = undefined;
51+
}
52+
},
53+
};
54+
}

‎src/gateway/server-startup-early.test.ts‎

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ describe("startGatewayEarlyRuntime", () => {
128128

129129
expect(mocks.setSkillsRemoteRegistry).toHaveBeenCalledWith(nodeRegistry);
130130
await Promise.resolve();
131-
expect(mocks.ensureContextWindowCacheLoaded).toHaveBeenCalledWith({});
131+
expect(mocks.ensureContextWindowCacheLoaded).not.toHaveBeenCalled();
132132
expect(mocks.primeRemoteSkillsCache).toHaveBeenCalledTimes(1);
133133
expect(mocks.ensureTaskRuntimeStateReady).toHaveBeenCalledTimes(1);
134134
expect(mocks.configureTaskRegistryMaintenance).toHaveBeenCalledTimes(1);
@@ -146,22 +146,6 @@ describe("startGatewayEarlyRuntime", () => {
146146
expect(mocks.skillsChangeUnsub).toHaveBeenCalledTimes(1);
147147
});
148148

149-
it("does not block gateway early runtime on context-window cache warmup", async () => {
150-
const pendingWarmup = new Promise<void>(() => {});
151-
mocks.ensureContextWindowCacheLoaded.mockReturnValueOnce(pendingWarmup);
152-
153-
const earlyRuntime = await startGatewayEarlyRuntime(
154-
earlyRuntimeInput({
155-
minimalTestGateway: false,
156-
cfgAtStart: { agents: { defaults: { model: "openai/gpt-5.5" } } } as never,
157-
}),
158-
);
159-
160-
await Promise.resolve();
161-
expect(mocks.ensureContextWindowCacheLoaded).toHaveBeenCalledTimes(1);
162-
expect(earlyRuntime).toHaveProperty("startMaintenance");
163-
});
164-
165149
it("fails before discovery and task maintenance when task state cannot restore", async () => {
166150
mocks.ensureTaskRuntimeStateReady.mockImplementationOnce(() => {
167151
throw new Error("task-flow registry restore failed");

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

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,6 @@ export async function startGatewayEarlyRuntime(params: {
123123
let getActiveTaskCount = () => 0;
124124

125125
if (!params.minimalTestGateway) {
126-
void import("../agents/context.js")
127-
.then(({ ensureContextWindowCacheLoaded }) =>
128-
ensureContextWindowCacheLoaded(params.cfgAtStart),
129-
)
130-
.catch((err: unknown) => {
131-
params.log.warn(`Context-window cache warmup failed to start: ${String(err)}`);
132-
});
133-
134126
const [{ primeRemoteSkillsCache, setSkillsRemoteRegistry }, taskRegistryMaintenance] =
135127
await measureStartup(params.startupTrace, "runtime.early.lazy-runtime-imports", () =>
136128
Promise.all([

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

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ const hoisted = vi.hoisted(() => {
6969
}));
7070
const ensureOpenClawModelsJson = vi.fn(async () => {});
7171
const ensureRuntimePluginsLoaded = vi.fn();
72+
const ensureContextWindowCacheLoaded = vi.fn(async () => {});
7273
const clearCurrentProviderAuthState = vi.fn();
7374
const warmCurrentProviderAuthStateOffMainThread = vi.fn(
7475
async (_cfg?: unknown, _options?: unknown) => {},
@@ -108,6 +109,7 @@ const hoisted = vi.hoisted(() => {
108109
getModelRefStatus,
109110
ensureOpenClawModelsJson,
110111
ensureRuntimePluginsLoaded,
112+
ensureContextWindowCacheLoaded,
111113
clearCurrentProviderAuthState,
112114
warmCurrentProviderAuthStateOffMainThread,
113115
setAuthProfileFailureHook,
@@ -217,6 +219,10 @@ vi.mock("../agents/runtime-plugins.js", () => ({
217219
ensureRuntimePluginsLoaded: hoisted.ensureRuntimePluginsLoaded,
218220
}));
219221

222+
vi.mock("../agents/context.js", () => ({
223+
ensureContextWindowCacheLoaded: hoisted.ensureContextWindowCacheLoaded,
224+
}));
225+
220226
vi.mock("../agents/model-provider-auth.js", () => ({
221227
warmCurrentProviderAuthStateOffMainThread: hoisted.warmCurrentProviderAuthStateOffMainThread,
222228
}));
@@ -249,6 +255,7 @@ vi.mock("./server-tailscale.js", () => ({
249255

250256
const { startGatewayPostAttachRuntime, startGatewaySidecars, testing } =
251257
await import("./server-startup-post-attach.js");
258+
const { scheduleContextCachePrewarm } = await import("./server-startup-context-cache-prewarm.js");
252259
const { STARTUP_UNAVAILABLE_GATEWAY_METHODS } = await import("./methods/core-descriptors.js");
253260
const { createGatewayCloseHandler } = await import("./server-close.js");
254261
const { createChatRunState } = await import("./server-chat-state.js");
@@ -359,6 +366,8 @@ describe("startGatewayPostAttachRuntime", () => {
359366
hoisted.ensureOpenClawModelsJson.mockReset();
360367
hoisted.ensureOpenClawModelsJson.mockResolvedValue(undefined);
361368
hoisted.ensureRuntimePluginsLoaded.mockReset();
369+
hoisted.ensureContextWindowCacheLoaded.mockReset();
370+
hoisted.ensureContextWindowCacheLoaded.mockResolvedValue(undefined);
362371
hoisted.clearCurrentProviderAuthState.mockClear();
363372
hoisted.warmCurrentProviderAuthStateOffMainThread.mockReset();
364373
hoisted.warmCurrentProviderAuthStateOffMainThread.mockResolvedValue(undefined);
@@ -1138,7 +1147,7 @@ describe("startGatewayPostAttachRuntime", () => {
11381147
await vi.advanceTimersToNextTimerAsync();
11391148
expect(postReadyRequestTurn).toHaveBeenCalledTimes(1);
11401149
expect(onPostReadySidecars.mock.calls[0]?.[0]).toHaveLength(0);
1141-
expect(onGatewayLifetimeSidecars.mock.calls[0]?.[0]).toHaveLength(2);
1150+
expect(onGatewayLifetimeSidecars.mock.calls[0]?.[0]).toHaveLength(3);
11421151
await vi.dynamicImportSettled();
11431152
await vi.waitFor(() => {
11441153
expect(hoisted.setAuthProfileFailureHook).toHaveBeenCalledTimes(1);
@@ -1170,7 +1179,7 @@ describe("startGatewayPostAttachRuntime", () => {
11701179
await vi.waitFor(() => {
11711180
expect(hoisted.setAuthProfileFailureHook).toHaveBeenCalledTimes(1);
11721181
});
1173-
expect(onGatewayLifetimeSidecars.mock.calls[0]?.[0]).toHaveLength(2);
1182+
expect(onGatewayLifetimeSidecars.mock.calls[0]?.[0]).toHaveLength(3);
11741183

11751184
await vi.advanceTimersByTimeAsync(10_000);
11761185
expect(hoisted.warmCurrentProviderAuthStateOffMainThread).not.toHaveBeenCalled();
@@ -1220,6 +1229,37 @@ describe("startGatewayPostAttachRuntime", () => {
12201229
expect(testing.agentRuntimePluginPrewarmStartDelayMs).toBe(0);
12211230
});
12221231

1232+
it("defers context-window cache prewarm to a post-ready sidecar", async () => {
1233+
vi.useFakeTimers();
1234+
const cfg = { agents: { defaults: { model: "openai/gpt-5.5" } } } as never;
1235+
const sidecar = scheduleContextCachePrewarm({
1236+
cfgAtStart: cfg,
1237+
log: { warn: vi.fn() },
1238+
});
1239+
1240+
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalled();
1241+
await vi.advanceTimersByTimeAsync(4_999);
1242+
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalled();
1243+
await vi.advanceTimersByTimeAsync(1);
1244+
await vi.dynamicImportSettled();
1245+
await vi.waitFor(() => {
1246+
expect(hoisted.ensureContextWindowCacheLoaded).toHaveBeenCalledWith(cfg);
1247+
});
1248+
await sidecar.stop();
1249+
});
1250+
1251+
it("cancels context-window cache prewarm when the gateway stops first", async () => {
1252+
vi.useFakeTimers();
1253+
const sidecar = scheduleContextCachePrewarm({
1254+
cfgAtStart: {} as never,
1255+
log: { warn: vi.fn() },
1256+
});
1257+
1258+
await sidecar.stop();
1259+
await vi.runAllTimersAsync();
1260+
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalled();
1261+
});
1262+
12231263
it("keeps provider auth prewarm alive when Gmail post-ready sidecars stop", async () => {
12241264
vi.useFakeTimers();
12251265
const onPostReadySidecars = vi.fn();
@@ -1263,7 +1303,7 @@ describe("startGatewayPostAttachRuntime", () => {
12631303
| { stop: () => void }[]
12641304
| undefined;
12651305
expect(gmailSidecars).toHaveLength(1);
1266-
expect(lifetimeSidecars).toHaveLength(2);
1306+
expect(lifetimeSidecars).toHaveLength(3);
12671307

12681308
for (const sidecar of gmailSidecars ?? []) {
12691309
sidecar.stop();
@@ -1325,7 +1365,7 @@ describe("startGatewayPostAttachRuntime", () => {
13251365
| Array<{ stop: () => Promise<void> | void }>
13261366
| undefined;
13271367
expect(gmailSidecars).toHaveLength(1);
1328-
expect(lifetimeSidecars).toHaveLength(2);
1368+
expect(lifetimeSidecars).toHaveLength(3);
13291369

13301370
await vi.waitFor(() => {
13311371
expect(hoisted.transcriptsAutoStartService.start).toHaveBeenCalledTimes(1);
@@ -1820,7 +1860,7 @@ describe("startGatewayPostAttachRuntime", () => {
18201860
name: "sidecars.ready",
18211861
metrics: [
18221862
["loadedPluginCount", 2],
1823-
["postReadySidecarCount", 1],
1863+
["postReadySidecarCount", 2],
18241864
],
18251865
});
18261866
});

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

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
import { STARTUP_UNAVAILABLE_GATEWAY_METHODS } from "./methods/core-descriptors.js";
2727
import type { refreshLatestUpdateRestartSentinel } from "./server-restart-sentinel.js";
2828
import type { GatewaySidecarStartupMode } from "./server-sidecar-startup-mode.js";
29+
import { scheduleContextCachePrewarm } from "./server-startup-context-cache-prewarm.js";
2930
import type { logGatewayStartup } from "./server-startup-log.js";
3031
import {
3132
createGatewayStartupOutcomeRecorder,
@@ -45,7 +46,6 @@ const DEFERRED_SIDECAR_START_DELAY_MS = 100;
4546
const SESSION_LOCK_CLEANUP_CONCURRENCY = 4;
4647
const SKIP_STARTUP_MODEL_PREWARM_ENV = "OPENCLAW_SKIP_STARTUP_MODEL_PREWARM";
4748
const QMD_STARTUP_IDLE_DELAY_MS = 120_000;
48-
4949
type Awaitable<T> = T | Promise<T>;
5050

5151
type GatewayStartupTrace = {
@@ -75,9 +75,7 @@ const loadGatewayRestartSentinelModule = createLazyRuntimeModule(
7575
() => import("./server-restart-sentinel.js"),
7676
);
7777

78-
export type GatewayPostReadySidecarHandle = {
79-
stop: () => Awaitable<void>;
80-
};
78+
export type GatewayPostReadySidecarHandle = { stop: () => Awaitable<void> };
8179

8280
/** Stop sidecars immediately when shutdown has already started before they are reported. */
8381
export function stopPostReadySidecarsAfterCloseStarted(params: {
@@ -1328,7 +1326,7 @@ export async function startGatewayPostAttachRuntime(
13281326
reportPluginServices(result.pluginServices);
13291327
}
13301328
const postReadySidecars = [...result.postReadySidecars];
1331-
const gatewayLifetimeSidecars: GatewayPostReadySidecarHandle[] = [];
1329+
const gatewayLifetimeSidecars = [scheduleContextCachePrewarm(params)];
13321330
if (workerEnvironmentSidecar) {
13331331
gatewayLifetimeSidecars.push(workerEnvironmentSidecar);
13341332
}

0 commit comments

Comments
 (0)