Skip to content

Commit c45b0a1

Browse files
fix(gateway): reuse published owner for context prewarm (#119562)
1 parent c02e393 commit c45b0a1

4 files changed

Lines changed: 168 additions & 35 deletions

File tree

‎src/agents/context.lookup.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ const contextTestState = vi.hoisted(() => {
2727
staticEntries: state.staticCatalogModels,
2828
},
2929
})),
30+
loadPublishedModelCatalogOwnerSnapshot: vi.fn(async (_params: unknown) => ({
31+
config: state.loadConfigImpl() as OpenClawConfig,
32+
modelCatalog: {
33+
entries: state.discoveredModels,
34+
routeVariants: [],
35+
staticEntries: state.staticCatalogModels,
36+
},
37+
})),
3038
};
3139
return state;
3240
});
@@ -44,6 +52,8 @@ vi.mock("../config/runtime-source-projection.js", () => ({
4452

4553
vi.mock("./prepared-model-catalog.js", () => ({
4654
loadPreparedModelCatalogOwnerSnapshot: contextTestState.loadModelCatalogOwnerSnapshot,
55+
loadPublishedPreparedModelCatalogOwnerSnapshot:
56+
contextTestState.loadPublishedModelCatalogOwnerSnapshot,
4757
}));
4858

4959
function mockContextDeps(params: {
@@ -140,6 +150,15 @@ describe("lookupContextTokens", () => {
140150
staticEntries: contextTestState.staticCatalogModels,
141151
},
142152
}));
153+
contextTestState.loadPublishedModelCatalogOwnerSnapshot.mockClear();
154+
contextTestState.loadPublishedModelCatalogOwnerSnapshot.mockImplementation(async () => ({
155+
config: contextTestState.loadConfigImpl() as OpenClawConfig,
156+
modelCatalog: {
157+
entries: contextTestState.discoveredModels,
158+
routeVariants: [],
159+
staticEntries: contextTestState.staticCatalogModels,
160+
},
161+
}));
143162
contextModule.resetContextWindowCacheForTest();
144163
});
145164

@@ -358,7 +377,7 @@ describe("lookupContextTokens", () => {
358377
);
359378
});
360379

361-
it("uses caller config when gateway startup starts cache warming", async () => {
380+
it("keeps ordinary cache loading on the exact owner path", async () => {
362381
const config = createContextOverrideConfig("anthropic", "claude-opus-4.7-20260219", 200_000);
363382
mockDiscoveryDeps([
364383
{
@@ -374,11 +393,56 @@ describe("lookupContextTokens", () => {
374393
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledWith(
375394
expect.objectContaining({ config, readOnly: true }),
376395
);
396+
expect(contextTestState.loadPublishedModelCatalogOwnerSnapshot).not.toHaveBeenCalled();
377397
expect(
378398
lookupContextTokens("anthropic/claude-opus-4.7-20260219", { allowAsyncLoad: false }),
379399
).toBe(ANTHROPIC_CONTEXT_1M_TOKENS);
380400
});
381401

402+
it("warms from the current Gateway-published owner without hashing a fallback owner key", async () => {
403+
const requestedConfig = createContextOverrideConfig("synthetic", "stale-model", 111_000);
404+
const publishedConfig = createContextOverrideConfig("synthetic", "current-model", 222_000);
405+
contextTestState.loadPublishedModelCatalogOwnerSnapshot.mockResolvedValueOnce({
406+
config: publishedConfig,
407+
modelCatalog: {
408+
entries: [{ id: "discovered-model", provider: "synthetic", contextWindow: 64_000 }],
409+
routeVariants: [],
410+
staticEntries: [],
411+
},
412+
});
413+
414+
const { lookupContextTokens, prewarmContextWindowCacheAfterReady } =
415+
await importContextModule();
416+
await prewarmContextWindowCacheAfterReady({ config: requestedConfig });
417+
418+
expect(contextTestState.loadPublishedModelCatalogOwnerSnapshot).toHaveBeenCalledWith(
419+
expect.objectContaining({
420+
config: requestedConfig,
421+
allowGatewaySubagentBinding: true,
422+
readOnly: true,
423+
}),
424+
);
425+
expect(contextTestState.loadModelCatalogOwnerSnapshot).not.toHaveBeenCalled();
426+
expect(
427+
lookupContextTokens("current-model", {
428+
allowAsyncLoad: false,
429+
skipRuntimeConfigLoad: true,
430+
}),
431+
).toBe(222_000);
432+
expect(
433+
lookupContextTokens("discovered-model", {
434+
allowAsyncLoad: false,
435+
skipRuntimeConfigLoad: true,
436+
}),
437+
).toBe(64_000);
438+
expect(
439+
lookupContextTokens("stale-model", {
440+
allowAsyncLoad: false,
441+
skipRuntimeConfigLoad: true,
442+
}),
443+
).toBeUndefined();
444+
});
445+
382446
it("warms fresh caches instead of reusing a pre-generation load promise", async () => {
383447
const legacyLoadPromise = Promise.resolve();
384448
CONTEXT_WINDOW_RUNTIME_STATE.loadPromise = legacyLoadPromise;

‎src/agents/context.ts‎

Lines changed: 79 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ type ModelEntry = {
4444
contextWindow?: number;
4545
contextTokens?: number;
4646
};
47+
type ContextWindowCatalogOwner = {
48+
config: OpenClawConfig;
49+
modelCatalog: {
50+
entries: ModelEntry[];
51+
staticEntries?: ModelEntry[];
52+
};
53+
};
4754
const CONFIG_LOAD_RETRY_POLICY: BackoffPolicy = {
4855
initialMs: 1_000,
4956
maxMs: 60_000,
@@ -186,7 +193,10 @@ function primeConfiguredContextWindows(): OpenClawConfig | undefined {
186193
}
187194
}
188195

189-
export function ensureContextWindowCacheLoaded(cfgOverride?: OpenClawConfig): Promise<void> {
196+
function ensureContextWindowCacheLoadedFromOwner(params: {
197+
cfgOverride?: OpenClawConfig;
198+
catalogOwner?: ContextWindowCatalogOwner;
199+
}): Promise<void> {
190200
const generation = CONTEXT_WINDOW_RUNTIME_STATE.generation;
191201
if (
192202
CONTEXT_WINDOW_RUNTIME_STATE.loadPromise &&
@@ -195,9 +205,11 @@ export function ensureContextWindowCacheLoaded(cfgOverride?: OpenClawConfig): Pr
195205
return CONTEXT_WINDOW_RUNTIME_STATE.loadPromise;
196206
}
197207

198-
const cfg = cfgOverride
199-
? primeConfiguredContextWindowsFromConfig(cfgOverride)
200-
: primeConfiguredContextWindows();
208+
const cfg = params.catalogOwner
209+
? primeConfiguredContextWindowsFromConfig(params.catalogOwner.config)
210+
: params.cfgOverride
211+
? primeConfiguredContextWindowsFromConfig(params.cfgOverride)
212+
: primeConfiguredContextWindows();
201213
if (!cfg) {
202214
return Promise.resolve();
203215
}
@@ -209,17 +221,22 @@ export function ensureContextWindowCacheLoaded(cfgOverride?: OpenClawConfig): Pr
209221
return;
210222
}
211223
try {
212-
const { loadPreparedModelCatalogOwnerSnapshot } = await loadPreparedModelCatalogRuntime();
213-
const defaultAgentId = resolveDefaultAgentId(cfg);
214-
const catalogResult = await loadPreparedModelCatalogOwnerSnapshot({
215-
config: cfg,
216-
agentId: defaultAgentId,
217-
agentDir: resolveAgentDir(cfg, defaultAgentId),
218-
readOnly: true,
219-
}).then(
220-
(value) => ({ status: "fulfilled" as const, value }),
221-
(reason: unknown) => ({ status: "rejected" as const, reason }),
222-
);
224+
const catalogResult = params.catalogOwner
225+
? ({ status: "fulfilled" as const, value: params.catalogOwner } as const)
226+
: await (async () => {
227+
const { loadPreparedModelCatalogOwnerSnapshot } =
228+
await loadPreparedModelCatalogRuntime();
229+
const defaultAgentId = resolveDefaultAgentId(cfg);
230+
return await loadPreparedModelCatalogOwnerSnapshot({
231+
config: cfg,
232+
agentId: defaultAgentId,
233+
agentDir: resolveAgentDir(cfg, defaultAgentId),
234+
readOnly: true,
235+
}).then(
236+
(value) => ({ status: "fulfilled" as const, value }),
237+
(reason: unknown) => ({ status: "rejected" as const, reason }),
238+
);
239+
})();
223240
if (CONTEXT_WINDOW_RUNTIME_STATE.generation !== generation) {
224241
return;
225242
}
@@ -253,6 +270,53 @@ export function ensureContextWindowCacheLoaded(cfgOverride?: OpenClawConfig): Pr
253270
return CONTEXT_WINDOW_RUNTIME_STATE.loadPromise;
254271
}
255272

273+
export function ensureContextWindowCacheLoaded(cfgOverride?: OpenClawConfig): Promise<void> {
274+
return ensureContextWindowCacheLoadedFromOwner({ cfgOverride });
275+
}
276+
277+
/**
278+
* Reuse the Gateway's published catalog generation. Omitting the Gateway binding
279+
* falls through to a read-only owner whose key hashes the full model config.
280+
*/
281+
export async function prewarmContextWindowCacheAfterReady(params: {
282+
config: OpenClawConfig;
283+
isCancelled?: () => boolean;
284+
}): Promise<void> {
285+
const generation = CONTEXT_WINDOW_RUNTIME_STATE.generation;
286+
if (
287+
CONTEXT_WINDOW_RUNTIME_STATE.loadPromise &&
288+
CONTEXT_WINDOW_RUNTIME_STATE.loadGeneration === generation
289+
) {
290+
return CONTEXT_WINDOW_RUNTIME_STATE.loadPromise;
291+
}
292+
const shouldStop = () =>
293+
CONTEXT_WINDOW_RUNTIME_STATE.generation !== generation || params.isCancelled?.() === true;
294+
if (shouldStop()) {
295+
return;
296+
}
297+
try {
298+
const { loadPublishedPreparedModelCatalogOwnerSnapshot } =
299+
await loadPreparedModelCatalogRuntime();
300+
if (shouldStop()) {
301+
return;
302+
}
303+
const defaultAgentId = resolveDefaultAgentId(params.config);
304+
const owner = await loadPublishedPreparedModelCatalogOwnerSnapshot({
305+
config: params.config,
306+
agentId: defaultAgentId,
307+
agentDir: resolveAgentDir(params.config, defaultAgentId),
308+
allowGatewaySubagentBinding: true,
309+
readOnly: true,
310+
});
311+
if (shouldStop()) {
312+
return;
313+
}
314+
await ensureContextWindowCacheLoadedFromOwner({ catalogOwner: owner });
315+
} catch {
316+
// Optional Gateway warmup is best-effort; request-time loading remains exact.
317+
}
318+
}
319+
256320
export async function waitForContextWindowCacheLoad(options?: {
257321
timeoutMs?: number;
258322
}): Promise<"idle" | "loaded" | "timeout"> {

‎src/gateway/server-startup-context-cache-prewarm.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ type ContextCachePrewarmHandle = {
1414
};
1515

1616
export function scheduleContextCachePrewarm(params: {
17-
cfgAtStart: OpenClawConfig;
17+
getConfig: () => OpenClawConfig;
1818
startupTrace?: StartupTrace;
1919
log: { warn: (msg: string) => void };
2020
}): ContextCachePrewarmHandle {
@@ -23,9 +23,12 @@ export function scheduleContextCachePrewarm(params: {
2323
if (stopped) {
2424
return;
2525
}
26-
const { ensureContextWindowCacheLoaded } = await import("../agents/context.js");
26+
const { prewarmContextWindowCacheAfterReady } = await import("../agents/context.js");
2727
if (!stopped) {
28-
await ensureContextWindowCacheLoaded(params.cfgAtStart);
28+
await prewarmContextWindowCacheAfterReady({
29+
config: params.getConfig(),
30+
isCancelled: () => stopped,
31+
});
2932
}
3033
};
3134

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

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ const hoisted = vi.hoisted(() => {
6767
async (_cfg?: unknown, _options?: unknown) => {},
6868
);
6969
const loadAgentRuntimePluginRegistryHandle = vi.fn();
70-
const ensureContextWindowCacheLoaded = vi.fn(async () => {});
70+
const prewarmContextWindowCacheAfterReady = vi.fn(async () => {});
7171
const scheduleGatewayHandlerPrewarm = vi.fn(() => ({ stop: vi.fn() }));
7272
const clearCurrentProviderAuthState = vi.fn();
7373
const warmCurrentProviderAuthStateOffMainThread = vi.fn(
@@ -107,7 +107,7 @@ const hoisted = vi.hoisted(() => {
107107
prepareModelRuntimeSnapshot,
108108
refreshPreparedModelRuntimeSnapshots,
109109
loadAgentRuntimePluginRegistryHandle,
110-
ensureContextWindowCacheLoaded,
110+
prewarmContextWindowCacheAfterReady,
111111
scheduleGatewayHandlerPrewarm,
112112
clearCurrentProviderAuthState,
113113
warmCurrentProviderAuthStateOffMainThread,
@@ -217,7 +217,7 @@ vi.mock("../agents/runtime-plugins.js", () => ({
217217
}));
218218

219219
vi.mock("../agents/context.js", () => ({
220-
ensureContextWindowCacheLoaded: hoisted.ensureContextWindowCacheLoaded,
220+
prewarmContextWindowCacheAfterReady: hoisted.prewarmContextWindowCacheAfterReady,
221221
}));
222222

223223
vi.mock("./server-startup-handler-prewarm.js", () => ({
@@ -368,8 +368,8 @@ describe("startGatewayPostAttachRuntime", () => {
368368
hoisted.refreshPreparedModelRuntimeSnapshots.mockReset();
369369
hoisted.refreshPreparedModelRuntimeSnapshots.mockResolvedValue(undefined);
370370
hoisted.loadAgentRuntimePluginRegistryHandle.mockReset();
371-
hoisted.ensureContextWindowCacheLoaded.mockReset();
372-
hoisted.ensureContextWindowCacheLoaded.mockResolvedValue(undefined);
371+
hoisted.prewarmContextWindowCacheAfterReady.mockReset();
372+
hoisted.prewarmContextWindowCacheAfterReady.mockResolvedValue(undefined);
373373
hoisted.scheduleGatewayHandlerPrewarm.mockClear();
374374
hoisted.clearCurrentProviderAuthState.mockClear();
375375
hoisted.warmCurrentProviderAuthStateOffMainThread.mockReset();
@@ -1258,32 +1258,34 @@ describe("startGatewayPostAttachRuntime", () => {
12581258

12591259
it("defers context-window cache prewarm to a post-ready sidecar", async () => {
12601260
vi.useFakeTimers();
1261-
const cfg = { agents: { defaults: { model: "openai/gpt-5.5" } } } as never;
1261+
const startupConfig = { agents: { defaults: { model: "openai/gpt-5.5" } } };
1262+
const currentConfig = { ...startupConfig };
12621263
const admission = tryBeginGatewayRootWorkAdmission();
12631264
if (!admission) {
12641265
throw new Error("Expected request work admission");
12651266
}
12661267
const sidecar = scheduleContextCachePrewarm({
1267-
cfgAtStart: cfg,
1268+
getConfig: () => currentConfig,
12681269
log: { warn: vi.fn() },
12691270
});
12701271

12711272
try {
1272-
// Earlier gateway lifetimes may finish during the fake-clock window;
1273-
// this sidecar's captured config identifies its own prewarm precisely.
1274-
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalledWith(cfg);
1273+
expect(hoisted.prewarmContextWindowCacheAfterReady).not.toHaveBeenCalled();
12751274
await vi.advanceTimersByTimeAsync(4_999);
1276-
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalledWith(cfg);
1275+
expect(hoisted.prewarmContextWindowCacheAfterReady).not.toHaveBeenCalled();
12771276
await vi.advanceTimersByTimeAsync(1);
1278-
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalledWith(cfg);
1277+
expect(hoisted.prewarmContextWindowCacheAfterReady).not.toHaveBeenCalled();
12791278

12801279
admission.release();
12811280
await vi.advanceTimersByTimeAsync(249);
1282-
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalledWith(cfg);
1281+
expect(hoisted.prewarmContextWindowCacheAfterReady).not.toHaveBeenCalled();
12831282
await vi.advanceTimersByTimeAsync(1);
12841283
await vi.dynamicImportSettled();
12851284
await waitForGatewayTestState(() => {
1286-
expect(hoisted.ensureContextWindowCacheLoaded).toHaveBeenCalledWith(cfg);
1285+
expect(hoisted.prewarmContextWindowCacheAfterReady).toHaveBeenCalledWith({
1286+
config: currentConfig,
1287+
isCancelled: expect.any(Function),
1288+
});
12871289
});
12881290
} finally {
12891291
admission.release();
@@ -1294,13 +1296,13 @@ describe("startGatewayPostAttachRuntime", () => {
12941296
it("cancels context-window cache prewarm when the gateway stops first", async () => {
12951297
vi.useFakeTimers();
12961298
const sidecar = scheduleContextCachePrewarm({
1297-
cfgAtStart: {} as never,
1299+
getConfig: () => ({}) as never,
12981300
log: { warn: vi.fn() },
12991301
});
13001302

13011303
await sidecar.stop();
13021304
await vi.runAllTimersAsync();
1303-
expect(hoisted.ensureContextWindowCacheLoaded).not.toHaveBeenCalled();
1305+
expect(hoisted.prewarmContextWindowCacheAfterReady).not.toHaveBeenCalled();
13041306
});
13051307

13061308
it("keeps provider auth prewarm alive when Gmail post-ready sidecars stop", async () => {

0 commit comments

Comments
 (0)