Skip to content

Commit f7d649b

Browse files
fix(gateway): keep context prewarm cooperative
1 parent 4c94d9f commit f7d649b

14 files changed

Lines changed: 965 additions & 248 deletions
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import { prepareContextWindowCaches } from "./context-cache-projection.js";
3+
import {
4+
lookupCachedContextTokens,
5+
lookupCachedContextWindow,
6+
replaceContextWindowCaches,
7+
} from "./context-cache.js";
8+
import { resetContextWindowCacheForTest } from "./context-runtime-state.js";
9+
10+
function publishConfiguredModel(model: string, contextWindow: number): void {
11+
replaceContextWindowCaches({
12+
configuredTokenCache: new Map([[model, contextWindow]]),
13+
discoveredTokenCache: new Map(),
14+
contextWindowCache: new Map(),
15+
});
16+
}
17+
18+
function createLargeCatalog(prefix: string, count: number) {
19+
return {
20+
entries: Array.from({ length: count }, (_, index) => ({
21+
id: `${prefix}-${index}`,
22+
provider: "synthetic",
23+
contextWindow: 64_000,
24+
})),
25+
staticEntries: [],
26+
};
27+
}
28+
29+
describe("context cache projection", () => {
30+
afterEach(() => {
31+
resetContextWindowCacheForTest();
32+
});
33+
34+
it("keeps the prior generation visible until a cooperative projection is complete", async () => {
35+
publishConfiguredModel("prior-model", 48_000);
36+
37+
const pending = prepareContextWindowCaches({
38+
config: {
39+
models: {
40+
providers: {
41+
synthetic: {
42+
baseUrl: "https://example.invalid",
43+
models: [{ id: "next-model", contextWindow: 96_000 } as never],
44+
},
45+
},
46+
},
47+
},
48+
modelCatalog: createLargeCatalog("discovered", 600),
49+
});
50+
51+
expect(lookupCachedContextTokens("prior-model")).toBe(48_000);
52+
expect(lookupCachedContextTokens("next-model")).toBeUndefined();
53+
54+
replaceContextWindowCaches(await pending);
55+
expect(lookupCachedContextTokens("prior-model")).toBeUndefined();
56+
expect(lookupCachedContextWindow("next-model")).toBe(96_000);
57+
expect(lookupCachedContextTokens("discovered-599")).toBe(64_000);
58+
});
59+
60+
it("does not publish a superseded cooperative projection", async () => {
61+
publishConfiguredModel("prior-model", 48_000);
62+
let current = true;
63+
const pending = prepareContextWindowCaches({
64+
config: {},
65+
modelCatalog: createLargeCatalog("superseded", 1_024),
66+
assertCurrent: () => {
67+
if (!current) {
68+
throw new Error("projection superseded");
69+
}
70+
},
71+
});
72+
current = false;
73+
74+
await expect(pending).rejects.toThrow("projection superseded");
75+
expect(lookupCachedContextTokens("prior-model")).toBe(48_000);
76+
expect(lookupCachedContextTokens("superseded-1023")).toBeUndefined();
77+
});
78+
});
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
2+
import type { OpenClawConfig } from "../config/types.openclaw.js";
3+
import { providerContextTokenCacheKey } from "./context-cache.js";
4+
import { type ModelsConfig, resolveAnthropicFixedContextWindow } from "./context-resolution.js";
5+
import { normalizeProviderId } from "./model-selection.js";
6+
7+
const CONTEXT_PROJECTION_BATCH_SIZE = 512;
8+
9+
type ContextWindowModelEntry = {
10+
id: string;
11+
provider?: string;
12+
contextWindow?: number;
13+
contextTokens?: number;
14+
};
15+
16+
export type ContextWindowCatalog = {
17+
entries: ContextWindowModelEntry[];
18+
staticEntries?: ContextWindowModelEntry[];
19+
};
20+
21+
type PreparedContextWindowCaches = {
22+
configuredTokenCache: Map<string, number>;
23+
discoveredTokenCache: Map<string, number>;
24+
contextWindowCache: Map<string, number>;
25+
};
26+
27+
type ConfiguredProvider = NonNullable<ModelsConfig["providers"]>[string];
28+
type ConfiguredModel = NonNullable<NonNullable<ConfiguredProvider>["models"]>[number];
29+
30+
function cacheMinimum(cache: Map<string, number>, key: string, contextTokens: number): void {
31+
const existing = cache.get(key);
32+
if (existing === undefined || contextTokens < existing) {
33+
cache.set(key, contextTokens);
34+
}
35+
}
36+
37+
function applyDiscoveredContextWindow(
38+
cache: Map<string, number>,
39+
model: ContextWindowModelEntry,
40+
): void {
41+
if (!model?.id) {
42+
return;
43+
}
44+
const discoveredContextTokens =
45+
typeof model.contextTokens === "number"
46+
? Math.trunc(model.contextTokens)
47+
: typeof model.contextWindow === "number"
48+
? Math.trunc(model.contextWindow)
49+
: undefined;
50+
const contextTokens =
51+
resolveDiscoveredAnthropicFixedContextWindow(model) ?? discoveredContextTokens;
52+
if (!contextTokens || contextTokens <= 0) {
53+
return;
54+
}
55+
56+
cacheMinimum(cache, model.id, contextTokens);
57+
if (typeof model.provider !== "string") {
58+
return;
59+
}
60+
const provider = normalizeProviderId(model.provider);
61+
if (!provider) {
62+
return;
63+
}
64+
cacheMinimum(cache, providerContextTokenCacheKey(provider, model.id), contextTokens);
65+
const slash = model.id.indexOf("/");
66+
const prefixedProvider = slash > 0 ? normalizeProviderId(model.id.slice(0, slash)) : "";
67+
const bareModelId = slash > 0 ? model.id.slice(slash + 1).trim() : "";
68+
if (prefixedProvider === provider && bareModelId) {
69+
cacheMinimum(cache, providerContextTokenCacheKey(provider, bareModelId), contextTokens);
70+
}
71+
}
72+
73+
export function applyDiscoveredContextWindows(params: {
74+
cache: Map<string, number>;
75+
models: ContextWindowModelEntry[];
76+
}): void {
77+
for (const model of params.models) {
78+
applyDiscoveredContextWindow(params.cache, model);
79+
}
80+
}
81+
82+
export function applyConfiguredContextWindows(params: {
83+
cache: Map<string, number>;
84+
windowCache: Map<string, number>;
85+
modelsConfig: ModelsConfig | undefined;
86+
}): void {
87+
const providers = params.modelsConfig?.providers;
88+
if (!providers || typeof providers !== "object") {
89+
return;
90+
}
91+
for (const [providerId, provider] of Object.entries(providers)) {
92+
if (!Array.isArray(provider?.models)) {
93+
continue;
94+
}
95+
for (const model of provider.models) {
96+
applyConfiguredContextWindow({
97+
cache: params.cache,
98+
windowCache: params.windowCache,
99+
providerId,
100+
provider,
101+
model,
102+
});
103+
}
104+
}
105+
}
106+
107+
function applyConfiguredContextWindow(params: {
108+
cache: Map<string, number>;
109+
windowCache: Map<string, number>;
110+
providerId: string;
111+
provider: NonNullable<ConfiguredProvider>;
112+
model: ConfiguredModel;
113+
}): void {
114+
const modelId = typeof params.model?.id === "string" ? params.model.id : undefined;
115+
const contextTokens =
116+
typeof params.model?.contextTokens === "number"
117+
? params.model.contextTokens
118+
: typeof params.provider.contextTokens === "number"
119+
? params.provider.contextTokens
120+
: undefined;
121+
const contextWindow =
122+
typeof params.model?.contextWindow === "number"
123+
? params.model.contextWindow
124+
: typeof params.provider.contextWindow === "number"
125+
? params.provider.contextWindow
126+
: undefined;
127+
const configuredValue =
128+
contextTokens && contextTokens > 0
129+
? { cache: params.cache, value: contextTokens }
130+
: contextWindow && contextWindow > 0
131+
? { cache: params.windowCache, value: contextWindow }
132+
: undefined;
133+
if (!modelId || !configuredValue) {
134+
return;
135+
}
136+
const provider = normalizeProviderId(params.providerId);
137+
configuredValue.cache.set(modelId, configuredValue.value);
138+
configuredValue.cache.set(providerContextTokenCacheKey(provider, modelId), configuredValue.value);
139+
const slash = modelId.indexOf("/");
140+
const prefixedProvider = slash > 0 ? normalizeProviderId(modelId.slice(0, slash)) : "";
141+
const bareModelId = slash > 0 ? modelId.slice(slash + 1).trim() : "";
142+
if (provider && prefixedProvider === provider && bareModelId) {
143+
configuredValue.cache.set(
144+
providerContextTokenCacheKey(provider, bareModelId),
145+
configuredValue.value,
146+
);
147+
}
148+
}
149+
150+
function resolveDiscoveredAnthropicFixedContextWindow(
151+
model: ContextWindowModelEntry,
152+
): number | undefined {
153+
const provider =
154+
typeof model.provider === "string" ? normalizeProviderId(model.provider) : undefined;
155+
if (provider) {
156+
return resolveAnthropicFixedContextWindow(provider, model.id);
157+
}
158+
const normalized = normalizeLowercaseStringOrEmpty(model.id);
159+
const slash = normalized.indexOf("/");
160+
if (slash < 0) {
161+
return undefined;
162+
}
163+
const inferredProvider = normalizeProviderId(normalized.slice(0, slash));
164+
const inferredModel = normalized.slice(slash + 1);
165+
return inferredProvider === "claude-cli"
166+
? resolveAnthropicFixedContextWindow(inferredProvider, inferredModel)
167+
: undefined;
168+
}
169+
170+
function yieldToGateway(): Promise<void> {
171+
return new Promise<void>((resolve) => {
172+
setImmediate(resolve);
173+
});
174+
}
175+
176+
async function projectModels(params: {
177+
cache: Map<string, number>;
178+
models: ContextWindowModelEntry[];
179+
processed: { count: number };
180+
assertCurrent?: () => void;
181+
}): Promise<void> {
182+
for (const model of params.models) {
183+
applyDiscoveredContextWindow(params.cache, model);
184+
params.processed.count += 1;
185+
if (params.processed.count % CONTEXT_PROJECTION_BATCH_SIZE === 0) {
186+
await yieldToGateway();
187+
params.assertCurrent?.();
188+
}
189+
}
190+
}
191+
192+
export async function prepareContextWindowCaches(params: {
193+
config: OpenClawConfig;
194+
modelCatalog: ContextWindowCatalog;
195+
assertCurrent?: () => void;
196+
}): Promise<PreparedContextWindowCaches> {
197+
const caches: PreparedContextWindowCaches = {
198+
configuredTokenCache: new Map(),
199+
discoveredTokenCache: new Map(),
200+
contextWindowCache: new Map(),
201+
};
202+
const processed = { count: 0 };
203+
const providers = (params.config.models as ModelsConfig | undefined)?.providers;
204+
if (providers && typeof providers === "object") {
205+
for (const [providerId, provider] of Object.entries(providers)) {
206+
if (!Array.isArray(provider?.models)) {
207+
continue;
208+
}
209+
for (const model of provider.models) {
210+
applyConfiguredContextWindow({
211+
cache: caches.configuredTokenCache,
212+
windowCache: caches.contextWindowCache,
213+
providerId,
214+
provider,
215+
model,
216+
});
217+
processed.count += 1;
218+
if (processed.count % CONTEXT_PROJECTION_BATCH_SIZE === 0) {
219+
await yieldToGateway();
220+
params.assertCurrent?.();
221+
}
222+
}
223+
}
224+
}
225+
await projectModels({
226+
cache: caches.discoveredTokenCache,
227+
models: params.modelCatalog.entries,
228+
processed,
229+
assertCurrent: params.assertCurrent,
230+
});
231+
await projectModels({
232+
cache: caches.discoveredTokenCache,
233+
models: params.modelCatalog.staticEntries ?? [],
234+
processed,
235+
assertCurrent: params.assertCurrent,
236+
});
237+
params.assertCurrent?.();
238+
return caches;
239+
}
240+
241+
export async function prepareDiscoveredContextTokenCache(params: {
242+
modelCatalog: ContextWindowCatalog;
243+
assertCurrent?: () => void;
244+
}): Promise<Map<string, number>> {
245+
const cache = new Map<string, number>();
246+
const processed = { count: 0 };
247+
await projectModels({
248+
cache,
249+
models: params.modelCatalog.entries,
250+
processed,
251+
assertCurrent: params.assertCurrent,
252+
});
253+
await projectModels({
254+
cache,
255+
models: params.modelCatalog.staticEntries ?? [],
256+
processed,
257+
assertCurrent: params.assertCurrent,
258+
});
259+
params.assertCurrent?.();
260+
return cache;
261+
}

0 commit comments

Comments
 (0)