Skip to content

Commit 2d3612d

Browse files
authored
fix(gateway): preserve prepared plugin metadata under load (#124844)
* fix(gateway): preserve prepared plugin metadata under load * fix(gateway): project metadata before catalog preparation * test(agents): assert projected startup metadata * test(gateway): bind load probes to each finalization wave
1 parent 6c66f48 commit 2d3612d

11 files changed

Lines changed: 199 additions & 74 deletions

‎src/agents/openclaw-tools.media-factory-plan.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ describe("optional media tool factory planning", () => {
637637

638638
it("defers PDF model resolution from the tool-prep hot path", async () => {
639639
const config: OpenClawConfig = {};
640-
installSnapshot(config, []);
640+
installSnapshot(config, createImageAndPdfPlugins());
641641
const resolveSpy = vi.spyOn(pdfModelConfigModule, "resolvePdfModelConfigForTool");
642642

643643
const tools = await createOpenClawToolsForTest({

‎src/agents/prepared-model-runtime.build.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
createPreparedInboundRegistryLoader,
3535
preparedModelRuntimeWorkspaceFactsKey,
3636
} from "./prepared-model-runtime.inbound-registry.js";
37+
import { projectPreparedPluginGeneration } from "./prepared-model-runtime.plugin-generation.js";
3738
import type {
3839
PreparedModelRuntimeBuildStats,
3940
PreparedModelRuntimeCatalogMode,
@@ -355,7 +356,13 @@ async function buildSnapshotBatch(
355356
configuredProjectionMs += prepared.buildStats.configuredProjectionMs;
356357
for (const agentFacts of prepared.agentFacts) {
357358
preparedInputs.set(agentFacts.input, agentFacts);
358-
pluginGenerations.set(agentFacts.input, prepared.pluginGeneration);
359+
pluginGenerations.set(
360+
agentFacts.input,
361+
projectPreparedPluginGeneration({
362+
input: agentFacts.input,
363+
pluginGeneration: prepared.pluginGeneration,
364+
}),
365+
);
359366
}
360367
}
361368
const workspaceFactsMs = performance.now() - workspaceFactsStartedAt;

‎src/agents/prepared-model-runtime.inbound-registry.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,28 @@ describe("prepared reply dispatch runtime", () => {
138138
expect(mocks.loadAgentRuntimePluginRegistryHandle).toHaveBeenCalledTimes(publicationLoadCount);
139139
});
140140

141+
it("projects shared plugin metadata into each configured runtime workspace", async () => {
142+
mocks.configuredAgentIds = ["default"];
143+
const workspaceDir = "/tmp/configured-metadata-workspace";
144+
const config = retainLegacyDefaultAgentId({ agents: { entries: { default: {} } } }, "default");
145+
await refreshPreparedModelRuntimeSnapshots(config, {
146+
gatewayLifecycle: true,
147+
catalogMode: "static",
148+
defaultWorkspaceDir: workspaceDir,
149+
});
150+
151+
const snapshot = getPreparedModelRuntimeSnapshot({
152+
agentId: "default",
153+
agentDir: "/tmp/unused-agent",
154+
inheritedAuthDir: "/tmp/unused-agent",
155+
config,
156+
workspaceDir,
157+
});
158+
159+
expect(snapshot?.metadataSnapshot.workspaceDir).toBe(workspaceDir);
160+
expect(snapshot?.metadataSnapshot.index.workspaceDir).toBe(workspaceDir);
161+
});
162+
141163
it("reuses configured and retained dynamic plugin generations during auth refresh", async () => {
142164
mocks.configuredAgentIds = ["default"];
143165
const workspaceDir = "/tmp/dynamic-auth-workspace";

‎src/agents/prepared-model-runtime.plugin-context.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import type { PluginDiscoveryResult } from "../plugins/discovery.js";
22
import { extractPluginInstallRecordsFromInstalledPluginIndex } from "../plugins/installed-plugin-index-install-records.js";
3-
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
3+
import {
4+
projectPluginMetadataSnapshotWorkspace,
5+
resolvePluginMetadataSnapshot,
6+
} from "../plugins/plugin-metadata-snapshot.js";
47
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
58
import type { PluginRegistry } from "../plugins/registry-types.js";
69
import {
@@ -59,14 +62,22 @@ export function prepareOwnedPluginLoadContext(
5962
env: NodeJS.ProcessEnv,
6063
registry: PluginRegistry | undefined,
6164
): PluginMetadataSnapshot {
62-
const metadataSnapshot = resolvePluginMetadataSnapshot({
65+
const resolvedMetadataSnapshot = resolvePluginMetadataSnapshot({
6366
config: input.config,
6467
env,
6568
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
6669
...(input.workspacePluginRootPresent === undefined
6770
? {}
6871
: { workspacePluginRootPresent: input.workspacePluginRootPresent }),
6972
});
73+
const metadataSnapshot = input.workspaceDir
74+
? projectPluginMetadataSnapshotWorkspace({
75+
snapshot: resolvedMetadataSnapshot,
76+
config: input.config,
77+
env,
78+
workspaceDir: input.workspaceDir,
79+
})
80+
: resolvedMetadataSnapshot;
7081
preparePluginLoadContext(input, env, registry, metadataSnapshot);
7182
return metadataSnapshot;
7283
}

‎src/agents/prepared-model-runtime.plugin-generation.ts‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,25 @@ export function createPreparedPluginGeneration(params: {
4747
});
4848
}
4949

50+
export function projectPreparedPluginGeneration(params: {
51+
input: PreparedModelRuntimeInput;
52+
pluginGeneration: PreparedModelRuntimePluginGeneration;
53+
}): PreparedModelRuntimePluginGeneration {
54+
const { input, pluginGeneration } = params;
55+
if (!input.workspaceDir) {
56+
return pluginGeneration;
57+
}
58+
const pluginMetadataSnapshot = projectPluginMetadataSnapshotWorkspace({
59+
snapshot: pluginGeneration.pluginMetadataSnapshot,
60+
config: input.config,
61+
env: input.env ?? process.env,
62+
workspaceDir: input.workspaceDir,
63+
});
64+
return pluginMetadataSnapshot === pluginGeneration.pluginMetadataSnapshot
65+
? pluginGeneration
66+
: Object.freeze({ ...pluginGeneration, pluginMetadataSnapshot });
67+
}
68+
5069
export async function buildPreparedPluginModelCatalog(params: {
5170
agentFacts: {
5271
credentials: Parameters<typeof buildPreparedModelCatalogSnapshot>[0]["authCredentials"];
@@ -59,13 +78,13 @@ export async function buildPreparedPluginModelCatalog(params: {
5978
const { credentials, input } = params.agentFacts;
6079
return await withPreparedPluginGenerationScope(
6180
{ input, pluginGeneration: params.pluginGeneration },
62-
() =>
81+
(metadataSnapshot) =>
6382
buildPreparedModelCatalogSnapshot({
6483
agentDir: input.agentDir,
6584
authCredentials: credentials,
6685
config: input.config,
6786
modelRegistry: params.modelRegistry,
68-
metadataSnapshot: params.pluginGeneration.pluginMetadataSnapshot,
87+
metadataSnapshot,
6988
includeProviderPluginAugmentation: params.catalogMode === "live",
7089
...(input.env ? { env: input.env } : {}),
7190
...(input.readOnly ? { readOnly: true } : {}),
@@ -82,15 +101,9 @@ export function withPreparedPluginGenerationScope<T>(
82101
},
83102
run: (metadataSnapshot: PreparedModelRuntimePluginGeneration["pluginMetadataSnapshot"]) => T,
84103
): T {
85-
const { input, pluginGeneration } = params;
86-
const metadataSnapshot = input.workspaceDir
87-
? projectPluginMetadataSnapshotWorkspace({
88-
snapshot: pluginGeneration.pluginMetadataSnapshot,
89-
config: input.config,
90-
env: input.env ?? process.env,
91-
workspaceDir: input.workspaceDir,
92-
})
93-
: pluginGeneration.pluginMetadataSnapshot;
104+
const { input } = params;
105+
const pluginGeneration = projectPreparedPluginGeneration(params);
106+
const metadataSnapshot = pluginGeneration.pluginMetadataSnapshot;
94107
return withPluginRuntimeGenerationScope(
95108
{
96109
config: input.config,

‎src/agents/prepared-model-runtime.startup-static.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,14 @@ describe("prepared model runtime Gateway catalog mode", () => {
398398
includePluginCatalogs: true,
399399
modelsJsonContents: null,
400400
pluginCatalogs: [],
401-
pluginMetadataSnapshot: mocks.metadataSnapshot,
401+
pluginMetadataSnapshot: expect.objectContaining({
402+
...mocks.metadataSnapshot,
403+
index: expect.objectContaining({
404+
...mocks.metadataSnapshot.index,
405+
workspaceDir: "/tmp/prepared-static-workspace",
406+
}),
407+
workspaceDir: "/tmp/prepared-static-workspace",
408+
}),
402409
workspaceDir: "/tmp/prepared-static-workspace",
403410
}),
404411
);

‎src/plugins/current-plugin-metadata-snapshot.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,23 @@ describe("current plugin metadata snapshot", () => {
393393
);
394394
});
395395

396+
it("trusts the config identity explicitly paired with an owner-prepared scope", () => {
397+
const sourceConfig = { plugins: { allow: ["source"] } };
398+
const runtimeConfig = { plugins: { allow: ["runtime"] } };
399+
const workspaceDir = "/workspace";
400+
const snapshot = createSnapshot({ config: sourceConfig, workspaceDir });
401+
402+
withPluginMetadataSnapshotScope(
403+
snapshot,
404+
() => {
405+
expect(getCurrentPluginMetadataSnapshot({ config: runtimeConfig, workspaceDir })).toBe(
406+
snapshot,
407+
);
408+
},
409+
{ config: runtimeConfig },
410+
);
411+
});
412+
396413
it("rejects a workspace-scoped snapshot when the caller does not provide workspace scope", () => {
397414
const config = { plugins: { allow: ["demo"] } };
398415
const snapshot = createSnapshot({ config, workspaceDir: "/workspace/a" });

‎src/plugins/current-plugin-metadata-snapshot.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -279,10 +279,9 @@ export function withPluginMetadataSnapshotScope<T>(
279279
: snapshot.configFingerprint;
280280
const configIdentities = new WeakSet<OpenClawConfig>();
281281
if (options.config) {
282-
const policyHash = resolveInstalledPluginIndexPolicyHash(options.config);
283-
if (policyHash === snapshot.policyHash || compatiblePolicyHashes?.includes(policyHash)) {
284-
configIdentities.add(options.config);
285-
}
282+
// The closure owner already paired this exact config with its immutable generation.
283+
// Recomputing policy compatibility here makes nested hot paths discard prepared facts.
284+
configIdentities.add(options.config);
286285
}
287286
for (const config of options.compatibleConfigs ?? []) {
288287
configIdentities.add(config);

‎src/plugins/plugin-metadata-snapshot.test.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
// Verifies lifecycle snapshot loading, ownership facts, and immutable boundaries.
2+
import fs from "node:fs";
3+
import os from "node:os";
4+
import path from "node:path";
25
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
36
import { setCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot.js";
4-
import { clearCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-state.js";
57
import type { PluginDiscoveryResult } from "./discovery.js";
68
import { resolveInstalledPluginIndexPolicyHash } from "./installed-plugin-index-policy.js";
79
import type { InstalledPluginIndex } from "./installed-plugin-index.js";
810
import type { PluginManifestRecord, PluginManifestRegistry } from "./manifest-registry.js";
11+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
912
import {
1013
completePluginMetadataSnapshot,
1114
loadPluginMetadataSnapshot,
@@ -96,7 +99,7 @@ describe("plugin metadata snapshot", () => {
9699
});
97100

98101
afterEach(() => {
99-
clearCurrentPluginMetadataSnapshot();
102+
clearPluginMetadataLifecycleCaches();
100103
});
101104

102105
it("keeps explicit control-plane loads fresh", () => {
@@ -187,7 +190,6 @@ describe("plugin metadata snapshot", () => {
187190
config,
188191
env: {},
189192
workspaceDir: targetWorkspace,
190-
workspacePluginRootPresent: false,
191193
});
192194

193195
expect(resolved).not.toBe(source);
@@ -204,6 +206,15 @@ describe("plugin metadata snapshot", () => {
204206
workspacePluginRootPresent: true,
205207
});
206208
expect(loadPluginRegistrySnapshotWithMetadata).toHaveBeenCalledOnce();
209+
210+
const pluginWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-plugin-workspace-"));
211+
try {
212+
fs.mkdirSync(path.join(pluginWorkspace, ".openclaw", "extensions"), { recursive: true });
213+
resolvePluginMetadataSnapshot({ config, env: {}, workspaceDir: pluginWorkspace });
214+
expect(loadPluginRegistrySnapshotWithMetadata).toHaveBeenCalledTimes(2);
215+
} finally {
216+
fs.rmSync(pluginWorkspace, { force: true, recursive: true });
217+
}
207218
});
208219

209220
it("rewalks collection-bearing manifest graphs after prototype mutation", () => {

‎src/plugins/plugin-metadata-snapshot.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
13
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
24
import type { OpenClawConfig } from "../config/types.openclaw.js";
35
import {
@@ -14,7 +16,9 @@ import {
1416
resolveInstalledManifestRegistryIndexFingerprint,
1517
} from "./manifest-registry-installed.js";
1618
import type { PluginManifestRecord, PluginManifestRegistry } from "./manifest-registry.js";
19+
import { PluginLruCache } from "./plugin-cache-primitives.js";
1720
import { resolvePluginControlPlaneFingerprint } from "./plugin-control-plane-context.js";
21+
import { registerPluginMetadataProcessMemoLifecycleClear } from "./plugin-metadata-lifecycle.js";
1822
import { buildPluginMetadataProviderFacts } from "./plugin-metadata-provider-facts.js";
1923
import { registerPluginMetadataSnapshotReaders } from "./plugin-metadata-snapshot.runtime.js";
2024
import type {
@@ -41,6 +45,8 @@ const PLUGIN_METADATA_ENV_KEYS = [
4145
"USERPROFILE",
4246
"XDG_CONFIG_HOME",
4347
] as const;
48+
const workspacePluginRootPresence = new PluginLruCache<boolean>(128);
49+
registerPluginMetadataProcessMemoLifecycleClear(() => workspacePluginRootPresence.clear());
4450
export type {
4551
PluginMetadataSnapshot,
4652
PluginMetadataSnapshotOwnerMaps,
@@ -62,6 +68,18 @@ export function resolvePluginMetadataEnvFingerprint(env: NodeJS.ProcessEnv): str
6268
});
6369
}
6470

71+
function hasWorkspacePluginRoot(workspaceDir: string): boolean {
72+
const cached = workspacePluginRootPresence.getResult(workspaceDir);
73+
if (cached.hit) {
74+
return cached.value;
75+
}
76+
// Plugin metadata is lifecycle-stable. Resolve this admission fact once per workspace so
77+
// configless nested readers can reuse the prepared graph without freshness-polling the disk.
78+
const present = fs.existsSync(path.join(workspaceDir, ".openclaw", "extensions"));
79+
workspacePluginRootPresence.set(workspaceDir, present);
80+
return present;
81+
}
82+
6583
function throwReadonlyPluginMetadataMutation(): never {
6684
throw new TypeError("Plugin metadata snapshots are immutable");
6785
}
@@ -396,14 +414,17 @@ export function resolvePluginMetadataSnapshot(
396414
const hasWorkspacePlugin = lifecycleSnapshot?.index.plugins.some(
397415
(plugin) => plugin.origin === "workspace",
398416
);
417+
const workspacePluginRootPresent =
418+
params.workspacePluginRootPresent ??
419+
(targetWorkspace ? hasWorkspacePluginRoot(targetWorkspace) : undefined);
399420
// Gateway metadata is lifecycle-stable. A workspace with no plugin root can reuse the
400421
// published graph without polling every bundled/global artifact on its first turn.
401422
if (
402423
lifecycleSnapshot &&
403424
targetWorkspace &&
404425
targetWorkspace !== lifecycleSnapshot.workspaceDir &&
405426
!hasWorkspacePlugin &&
406-
params.workspacePluginRootPresent === false
427+
workspacePluginRootPresent === false
407428
) {
408429
return projectPluginMetadataSnapshotWorkspace({
409430
snapshot: lifecycleSnapshot,

0 commit comments

Comments
 (0)