Skip to content

Commit f77d2ec

Browse files
authored
fix: stop repeated static catalog manifest scans (#125090)
1 parent 35695cb commit f77d2ec

9 files changed

Lines changed: 254 additions & 55 deletions

‎src/agents/embedded-agent-runner/model.static-catalog.snapshot-cache.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { clearPluginMetadataLifecycleCaches } from "../../plugins/plugin-metadata-lifecycle.js";
23
import type { PluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.types.js";
34

45
const manifestMocks = vi.hoisted(() => ({
@@ -108,6 +109,7 @@ function setManifestPlugins(plugins: unknown[]) {
108109
}
109110

110111
beforeEach(() => {
112+
clearPluginMetadataLifecycleCaches();
111113
for (const mock of Object.values(manifestMocks)) {
112114
mock.mockReset();
113115
}
@@ -284,6 +286,56 @@ describe("bundled static model catalog snapshot cache", () => {
284286
expect(manifestMocks.loadPluginManifest).toHaveBeenCalledTimes(1);
285287
});
286288

289+
it("refreshes the no-snapshot memo only at the plugin metadata lifecycle boundary", () => {
290+
const env = { HOME: "/custom-home" };
291+
const plugin = createMistralManifestPlugin();
292+
setManifestPlugins([
293+
{ ...plugin, modelCatalog: { ...plugin.modelCatalog, runtimeAugment: true } },
294+
]);
295+
296+
expect(bundledStaticCatalogProviderUsesRuntimeAugment({ provider: "mistral", env })).toBe(true);
297+
expect(bundledStaticCatalogProviderUsesRuntimeAugment({ provider: "mistral", env })).toBe(true);
298+
expect(manifestMocks.listOpenClawPluginManifestMetadata).toHaveBeenCalledTimes(1);
299+
300+
setManifestPlugins([
301+
{ ...plugin, modelCatalog: { ...plugin.modelCatalog, runtimeAugment: false } },
302+
]);
303+
expect(bundledStaticCatalogProviderUsesRuntimeAugment({ provider: "mistral", env })).toBe(true);
304+
305+
clearPluginMetadataLifecycleCaches();
306+
expect(bundledStaticCatalogProviderUsesRuntimeAugment({ provider: "mistral", env })).toBe(
307+
false,
308+
);
309+
expect(manifestMocks.listOpenClawPluginManifestMetadata).toHaveBeenCalledTimes(2);
310+
});
311+
312+
it("refreshes a retained no-snapshot resolver at the plugin metadata lifecycle boundary", () => {
313+
const env = { HOME: "/custom-home" };
314+
const firstPlugin = createMistralManifestPlugin();
315+
setManifestPlugins([firstPlugin]);
316+
const resolveModel = createBundledStaticCatalogModelResolver({ env });
317+
318+
expect(resolveModel({ provider: "mistral", modelId: "mistral-medium-3-5" })?.id).toBe(
319+
"mistral-medium-3-5",
320+
);
321+
322+
const replacementPlugin = createMistralManifestPlugin();
323+
replacementPlugin.modelCatalog.providers.mistral.models =
324+
replacementPlugin.modelCatalog.providers.mistral.models.map((model) => ({
325+
...model,
326+
id: "mistral-medium-next",
327+
name: "Mistral Medium Next",
328+
}));
329+
setManifestPlugins([replacementPlugin]);
330+
clearPluginMetadataLifecycleCaches();
331+
332+
expect(resolveModel({ provider: "mistral", modelId: "mistral-medium-3-5" })).toBeUndefined();
333+
expect(resolveModel({ provider: "mistral", modelId: "mistral-medium-next" })?.name).toBe(
334+
"Mistral Medium Next",
335+
);
336+
expect(manifestMocks.listOpenClawPluginManifestMetadata).toHaveBeenCalledTimes(2);
337+
});
338+
287339
it("preserves plugin enablement policy for current snapshot catalog rows", () => {
288340
setCurrentManifestPlugins([createMistralManifestPlugin()]);
289341

‎src/agents/embedded-agent-runner/model.static-catalog.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ vi.mock("../../plugins/provider-discovery.js", async (importOriginal) => ({
4848
runProviderStaticCatalog: providerMocks.runProviderStaticCatalog,
4949
}));
5050

51+
import { clearPluginMetadataLifecycleCaches } from "../../plugins/plugin-metadata-lifecycle.js";
5152
import { getModelProviderRequestTransport } from "../provider-request-config.js";
5253
import {
5354
createBundledProviderStaticCatalogContextResolver,
@@ -192,6 +193,7 @@ function expectManifestAliasResolution(
192193
}
193194

194195
beforeEach(() => {
196+
clearPluginMetadataLifecycleCaches();
195197
manifestMocks.getCurrentPluginMetadataSnapshot.mockReset();
196198
manifestMocks.listOpenClawPluginManifestMetadata.mockReset();
197199
manifestMocks.loadPluginManifest.mockReset();

‎src/agents/embedded-agent-runner/model.static-catalog.ts‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { listOpenClawPluginManifestMetadata } from "../../plugins/manifest-metad
1212
import { passesManifestOwnerBasePolicy } from "../../plugins/manifest-owner-policy.js";
1313
import { loadPluginManifestRegistryCore } from "../../plugins/manifest-registry.js";
1414
import { loadPluginManifest } from "../../plugins/manifest.js";
15+
import { registerPluginMetadataProcessMemoLifecycleClear } from "../../plugins/plugin-metadata-lifecycle.js";
1516
import type { PluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.types.js";
1617
import {
1718
normalizePluginDiscoveryResult,
@@ -145,14 +146,20 @@ type BundledStaticCatalogState = {
145146
plans: Map<string, ReturnType<typeof planEffectiveModelCatalogRows>>;
146147
};
147148

148-
// Snapshot identity changes at the Gateway reload commit, so old provider plans
149-
// cannot survive into a replacement plugin generation.
150-
const bundledStaticCatalogStatesBySnapshot = new WeakMap<
151-
PluginMetadataSnapshot,
149+
let bundledStaticCatalogStatesByOwner = new WeakMap<
150+
object,
152151
WeakMap<OpenClawConfig, BundledStaticCatalogState>
153152
>();
154153
const defaultBundledStaticCatalogConfig: OpenClawConfig = {};
155154

155+
function clearBundledStaticCatalogStates(): void {
156+
bundledStaticCatalogStatesByOwner = new WeakMap();
157+
}
158+
159+
// Snapshot or environment identity pins one plugin generation; install/reload
160+
// owners replace this map so retained resolvers cannot keep stale provider plans.
161+
registerPluginMetadataProcessMemoLifecycleClear(clearBundledStaticCatalogStates);
162+
156163
function resolveBundledStaticCatalogMetadataSnapshot(
157164
params: BundledStaticCatalogParams,
158165
): PluginMetadataSnapshot | undefined {
@@ -203,14 +210,15 @@ function listBundledStaticCatalogPlugins(
203210
);
204211
}
205212

206-
function resolveSnapshotBundledStaticCatalogState(
213+
function resolveBundledStaticCatalogState(
207214
params: BundledStaticCatalogParams,
208-
metadataSnapshot: PluginMetadataSnapshot,
215+
metadataSnapshot?: PluginMetadataSnapshot,
209216
): BundledStaticCatalogState {
210-
let states = bundledStaticCatalogStatesBySnapshot.get(metadataSnapshot);
217+
const owner = metadataSnapshot ?? params.env;
218+
let states = bundledStaticCatalogStatesByOwner.get(owner);
211219
if (!states) {
212220
states = new WeakMap();
213-
bundledStaticCatalogStatesBySnapshot.set(metadataSnapshot, states);
221+
bundledStaticCatalogStatesByOwner.set(owner, states);
214222
}
215223
const config = params.cfg ?? defaultBundledStaticCatalogConfig;
216224
const cached = states.get(config);
@@ -230,6 +238,7 @@ export function bundledStaticCatalogProviderUsesRuntimeAugment(params: {
230238
provider: string;
231239
cfg?: OpenClawConfig;
232240
env?: NodeJS.ProcessEnv;
241+
metadataSnapshot?: PluginMetadataSnapshot;
233242
workspaceDir?: string;
234243
}): boolean {
235244
const provider = normalizeProviderId(params.provider);
@@ -239,12 +248,11 @@ export function bundledStaticCatalogProviderUsesRuntimeAugment(params: {
239248
const catalogParams = {
240249
cfg: params.cfg,
241250
env: params.env ?? process.env,
251+
...(params.metadataSnapshot ? { metadataSnapshot: params.metadataSnapshot } : {}),
242252
workspaceDir: params.workspaceDir,
243253
};
244254
const metadataSnapshot = resolveBundledStaticCatalogMetadataSnapshot(catalogParams);
245-
const plugins = metadataSnapshot
246-
? resolveSnapshotBundledStaticCatalogState(catalogParams, metadataSnapshot).plugins
247-
: listBundledStaticCatalogPlugins(catalogParams);
255+
const plugins = resolveBundledStaticCatalogState(catalogParams, metadataSnapshot).plugins;
248256
return plugins.some((plugin) => {
249257
const catalog = plugin.modelCatalog;
250258
if (catalog?.runtimeAugment !== true) {
@@ -305,19 +313,13 @@ export function createBundledStaticCatalogModelResolver(params?: {
305313
const matchesStaticModelId = params?.metadataSnapshot
306314
? createStaticModelIdMatcher({ manifestPlugins: params.metadataSnapshot.plugins })
307315
: staticModelIdMatches;
308-
let standaloneState: BundledStaticCatalogState | undefined;
309316
return (lookup) => {
310317
const provider = normalizeProviderId(lookup.provider);
311318
if (!provider || !lookup.modelId.trim()) {
312319
return undefined;
313320
}
314321
const metadataSnapshot = resolveBundledStaticCatalogMetadataSnapshot(catalogParams);
315-
const state = metadataSnapshot
316-
? resolveSnapshotBundledStaticCatalogState(catalogParams, metadataSnapshot)
317-
: (standaloneState ??= {
318-
plugins: listBundledStaticCatalogPlugins(catalogParams),
319-
plans: new Map(),
320-
});
322+
const state = resolveBundledStaticCatalogState(catalogParams, metadataSnapshot);
321323
if (state.plugins.length === 0) {
322324
return undefined;
323325
}

‎src/agents/tools/image-tool.test-support.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
describeImagesWithModel,
1414
MediaUnderstandingProvider,
1515
} from "../../plugin-sdk/media-understanding.js";
16+
import type { PluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.types.js";
1617
import type { AuthProfileStore } from "../auth-profiles/types.js";
1718
import type { resolveBundledStaticCatalogModel } from "../embedded-agent-runner/model.static-catalog.js";
1819
import type { PreparedModelRuntimeSnapshot } from "../prepared-model-runtime.js";
@@ -51,6 +52,7 @@ type ResolveImageCompressionPolicy = (params: {
5152
imageCount: number;
5253
agentDir?: string;
5354
workspaceDir?: string;
55+
metadataSnapshot?: PluginMetadataSnapshot;
5456
}) => Promise<ImageCompressionPolicy>;
5557

5658
type ImageToolProviderDeps = {

‎src/agents/tools/image-tool.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@ import { isInboundPathAllowed } from "@openclaw/media-core/inbound-path-policy";
88
import { expectDefined } from "@openclaw/normalization-core";
99
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1010
import type { OpenClawConfig } from "../../config/config.js";
11+
import { createPluginMetadataSnapshot } from "../../config/plugin-auto-enable.test-helpers.js";
1112
import type { ModelDefinitionConfig } from "../../config/types.models.js";
1213
import { encodePngRgba, fillPixel } from "../../media/png-encode.js";
1314
import type {
1415
ImageDescriptionRequest,
1516
ImagesDescriptionRequest,
1617
MediaUnderstandingProvider,
1718
} from "../../plugin-sdk/media-understanding.js";
19+
import { installTemporaryCurrentPluginMetadataSnapshot } from "../../plugins/current-plugin-metadata-snapshot.js";
20+
import type { PluginManifestRecord } from "../../plugins/manifest-registry.js";
1821
import { withEnvAsync } from "../../test-utils/env.js";
1922
import { withFetchPreconnect } from "../../test-utils/fetch-mock.js";
2023
import type { AuthProfileCredential, AuthProfileStore } from "../auth-profiles/types.js";
@@ -3149,6 +3152,103 @@ describe("image compression policy", () => {
31493152
testing.setProviderDepsForTest();
31503153
});
31513154

3155+
it("keeps runtime augmentation pinned to the prepared plugin generation", async () => {
3156+
const provider = "prepared-image-provider";
3157+
const model = "prepared-image-model";
3158+
const cfg = {
3159+
models: {
3160+
providers: {
3161+
[provider]: {
3162+
baseUrl: "https://prepared-image.example.test/v1",
3163+
api: "openai-completions",
3164+
models: [
3165+
{
3166+
id: model,
3167+
name: "Prepared image model",
3168+
reasoning: false,
3169+
input: ["text", "image"],
3170+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
3171+
contextWindow: 128_000,
3172+
maxTokens: 8_192,
3173+
},
3174+
],
3175+
},
3176+
},
3177+
},
3178+
} satisfies OpenClawConfig;
3179+
const createSnapshot = (runtimeAugment: boolean) => {
3180+
const plugin = {
3181+
id: "prepared-image-plugin",
3182+
enabledByDefault: true,
3183+
channels: [],
3184+
providers: [provider],
3185+
cliBackends: [],
3186+
skills: [],
3187+
hooks: [],
3188+
origin: "bundled",
3189+
rootDir: "/fake/prepared-image-plugin",
3190+
source: "/fake/prepared-image-plugin/index.js",
3191+
manifestPath: "/fake/prepared-image-plugin/openclaw.plugin.json",
3192+
modelCatalog: {
3193+
runtimeAugment,
3194+
providers: {
3195+
[provider]: {
3196+
baseUrl: "https://prepared-image.example.test/v1",
3197+
api: "openai-completions",
3198+
models: [{ id: model, name: "Prepared image model" }],
3199+
},
3200+
},
3201+
},
3202+
} satisfies PluginManifestRecord;
3203+
return createPluginMetadataSnapshot({
3204+
config: cfg,
3205+
manifestRegistry: { plugins: [plugin], diagnostics: [] },
3206+
});
3207+
};
3208+
const preparedSnapshot = createSnapshot(false);
3209+
const currentSnapshot = createSnapshot(true);
3210+
const hookModes: Array<boolean | undefined> = [];
3211+
installImageUnderstandingProviderDeps([], {
3212+
resolveModelAsync: async (resolvedProvider, resolvedModel, _agentDir, _cfg, options) => {
3213+
hookModes.push(options?.skipProviderRuntimeHooks);
3214+
return {
3215+
model: {
3216+
id: resolvedModel,
3217+
provider: resolvedProvider,
3218+
input: ["text", "image"],
3219+
mediaInput: {
3220+
image: options?.skipProviderRuntimeHooks
3221+
? { maxBytes: 1_000_000 }
3222+
: { maxSidePx: 4096 },
3223+
},
3224+
} as never,
3225+
authStorage: {} as never,
3226+
modelRegistry: {} as never,
3227+
};
3228+
},
3229+
});
3230+
const currentLease = installTemporaryCurrentPluginMetadataSnapshot(currentSnapshot, {
3231+
config: cfg,
3232+
});
3233+
3234+
try {
3235+
await expect(
3236+
testing.resolveImageCompressionPolicy({
3237+
cfg,
3238+
imageModelConfig: { primary: `${provider}/${model}` },
3239+
imageCount: 1,
3240+
metadataSnapshot: preparedSnapshot,
3241+
}),
3242+
).resolves.toEqual({
3243+
imageCount: 1,
3244+
models: [{ maxBytes: 1_000_000 }],
3245+
});
3246+
expect(hookModes).toEqual([true]);
3247+
} finally {
3248+
currentLease.release();
3249+
}
3250+
});
3251+
31523252
it("derives model metadata, quality preference, and image count from config", async () => {
31533253
const cfg = {
31543254
...cfgWithImageModelMetadata,

‎src/agents/tools/image-tool.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -496,9 +496,6 @@ function providerUsesRuntimeModelAugment(params: {
496496
if (!provider) {
497497
return false;
498498
}
499-
if (bundledStaticCatalogProviderUsesRuntimeAugment({ provider })) {
500-
return true;
501-
}
502499
const config = params.cfg ?? {};
503500
const preparedSnapshot =
504501
params.metadataSnapshot &&
@@ -518,6 +515,16 @@ function providerUsesRuntimeModelAugment(params: {
518515
env: process.env,
519516
...(params.workspaceDir !== undefined ? { workspaceDir: params.workspaceDir } : {}),
520517
});
518+
if (
519+
bundledStaticCatalogProviderUsesRuntimeAugment({
520+
provider,
521+
cfg: params.cfg,
522+
...(snapshot ? { metadataSnapshot: snapshot } : {}),
523+
workspaceDir: params.workspaceDir,
524+
})
525+
) {
526+
return true;
527+
}
521528
if (!snapshot) {
522529
return false;
523530
}

0 commit comments

Comments
 (0)