Skip to content

Commit 83e7fa1

Browse files
authored
perf(plugins): reuse one plugin metadata snapshot per CLI process (#129181)
* perf(plugins): reuse one plugin metadata snapshot per CLI process Built CLI measurements with the same fs shim and isolated state copy:\n- status --json: 174.3k -> 52.8k fs calls; 4.33-4.41s -> 2.63-3.94s\n- agents list --json: 50.7k -> 38.3k fs calls; 2.32-2.93s -> 2.20-2.28s * style(config): use type-only snapshot imports * fix(cli): scope plugin snapshot adoption to inventory reads * test(cli): align snapshot harnesses with adoption
1 parent b9d5227 commit 83e7fa1

15 files changed

Lines changed: 257 additions & 50 deletions

‎src/cli/command-config-snapshot.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// CLI-owned config reads publish one complete metadata generation for later command consumers.
2+
import { readConfigFileSnapshotWithPluginMetadata } from "../config/config.js";
3+
import { adoptCurrentPluginMetadataSnapshotIfAbsent } from "../plugins/current-plugin-metadata-snapshot.js";
4+
import { completePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
5+
6+
/** Reads full command config and adopts its metadata without replacing an existing owner. */
7+
export async function readCommandConfigSnapshot(options?: {
8+
observe?: boolean;
9+
skipPluginValidation?: boolean;
10+
}) {
11+
const read = await readConfigFileSnapshotWithPluginMetadata(options);
12+
const pluginMetadataSnapshot = completePluginMetadataSnapshot({
13+
snapshot: read.pluginMetadataSnapshot,
14+
config: read.snapshot.sourceConfig,
15+
env: process.env,
16+
workspaceDir: read.pluginMetadataSnapshot?.workspaceDir,
17+
});
18+
if (pluginMetadataSnapshot) {
19+
adoptCurrentPluginMetadataSnapshotIfAbsent(pluginMetadataSnapshot, {
20+
config: read.snapshot.sourceConfig,
21+
compatibleConfigs: [read.snapshot.config, read.snapshot.runtimeConfig],
22+
env: process.env,
23+
workspaceDir: pluginMetadataSnapshot.workspaceDir,
24+
});
25+
}
26+
return { ...read, pluginMetadataSnapshot };
27+
}

‎src/commands/agents.commands.list.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ export async function agentsListCommand(
126126
opts: AgentsListOptions,
127127
runtime: RuntimeEnv = defaultRuntime,
128128
) {
129-
const cfg = await requireValidConfig(runtime);
129+
const cfg = await requireValidConfig(runtime, { adoptPluginMetadata: true });
130130
if (!cfg) {
131131
return;
132132
}

‎src/commands/config-validation.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,20 @@ export async function requireValidConfigFileSnapshot(
2121
includeCompatibilityAdvisory?: boolean;
2222
observe?: boolean;
2323
skipPluginValidation?: boolean;
24+
adoptPluginMetadata?: boolean;
2425
},
2526
): Promise<ConfigFileSnapshot | null> {
2627
const readOptions = {
2728
...(opts?.observe === false ? { observe: false } : {}),
2829
...(opts?.skipPluginValidation ? { skipPluginValidation: true } : {}),
2930
};
30-
const snapshot = await readConfigFileSnapshot(
31-
Object.keys(readOptions).length > 0 ? readOptions : undefined,
32-
);
31+
const snapshot = opts?.adoptPluginMetadata
32+
? (
33+
await (
34+
await import("../cli/command-config-snapshot.js")
35+
).readCommandConfigSnapshot(readOptions)
36+
).snapshot
37+
: await readConfigFileSnapshot(Object.keys(readOptions).length > 0 ? readOptions : undefined);
3338
if (snapshot.exists && !snapshot.valid) {
3439
const issues =
3540
snapshot.issues.length > 0
@@ -71,6 +76,7 @@ export async function requireValidConfig(
7176
includeCompatibilityAdvisory?: boolean;
7277
observe?: boolean;
7378
skipPluginValidation?: boolean;
79+
adoptPluginMetadata?: boolean;
7480
},
7581
): Promise<OpenClawConfig | null> {
7682
return (await requireValidConfigFileSnapshot(runtime, opts))?.config ?? null;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import fs from "node:fs";
2+
import { afterEach, expect, it, vi } from "vitest";
3+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
4+
import { createColdPluginFixture } from "../plugins/test-helpers/cold-plugin-fixtures.js";
5+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
6+
7+
const registryLoads = vi.hoisted(() => ({ count: 0 }));
8+
9+
vi.mock("../plugins/plugin-registry-snapshot.js", async (importOriginal) => {
10+
const actual = await importOriginal<typeof import("../plugins/plugin-registry-snapshot.js")>();
11+
return {
12+
...actual,
13+
loadPluginRegistrySnapshotWithMetadata: (
14+
...args: Parameters<typeof actual.loadPluginRegistrySnapshotWithMetadata>
15+
) => {
16+
registryLoads.count += 1;
17+
return actual.loadPluginRegistrySnapshotWithMetadata(...args);
18+
},
19+
};
20+
});
21+
22+
vi.mock("./status.scan.bootstrap-shared.js", () => ({
23+
createStatusScanCoreBootstrap: async () => ({
24+
tailscaleMode: "off",
25+
tailscaleDnsPromise: Promise.resolve(null),
26+
updatePromise: Promise.resolve({ installKind: "unknown" }),
27+
agentStatusPromise: Promise.resolve({
28+
defaultId: "main",
29+
agents: [],
30+
totalSessions: 0,
31+
bootstrapPendingCount: 0,
32+
}),
33+
gatewayProbePromise: Promise.resolve({ gatewayReachable: false }),
34+
resolveTailscaleHttpsUrl: async () => null,
35+
skipColdStartNetworkChecks: false,
36+
}),
37+
}));
38+
39+
vi.mock("../gateway/call.js", () => ({
40+
callGateway: vi.fn(async () => {
41+
throw new Error("gateway unavailable in status snapshot test");
42+
}),
43+
}));
44+
45+
const { collectStatusScanOverview } = await import("./status.scan-overview.js");
46+
47+
afterEach(() => {
48+
clearPluginMetadataLifecycleCaches();
49+
});
50+
51+
it("builds plugin metadata once for a status scan", async () => {
52+
await withOpenClawTestState(
53+
{
54+
prefix: "openclaw-status-plugin-metadata-",
55+
layout: "split",
56+
env: { OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1" },
57+
},
58+
async (state) => {
59+
const pluginDir = state.path("cold-plugin");
60+
fs.mkdirSync(pluginDir, { recursive: true });
61+
createColdPluginFixture({ rootDir: pluginDir, pluginId: "cold-plugin" });
62+
await state.writeConfig({
63+
memory: {
64+
search: {
65+
remote: { apiKey: "${OPENCLAW_STATUS_PLUGIN_METADATA_KEY}" },
66+
},
67+
},
68+
plugins: {
69+
load: { paths: [pluginDir] },
70+
entries: { "cold-plugin": { enabled: true } },
71+
},
72+
});
73+
clearPluginMetadataLifecycleCaches();
74+
registryLoads.count = 0;
75+
76+
const overview = await collectStatusScanOverview({
77+
commandName: "status --json",
78+
opts: {},
79+
showSecrets: false,
80+
includeChannelsData: false,
81+
skipUpdateCheck: true,
82+
resolveHasConfiguredChannels: () => false,
83+
});
84+
85+
expect(overview.cfg.plugins?.entries?.["cold-plugin"]?.enabled).toBe(true);
86+
expect(registryLoads.count).toBe(1);
87+
},
88+
);
89+
});

‎src/commands/status.scan-overview.test.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const mocks = vi.hoisted(() => ({
66
hasConfiguredChannelsForReadOnlyScope: vi.fn(),
77
resolveCommandConfigWithSecrets: vi.fn(),
88
getStatusCommandSecretTargetIds: vi.fn(),
9-
readBestEffortConfigSnapshot: vi.fn(),
9+
readCommandConfigSnapshot: vi.fn(),
1010
resolveGatewayPort: vi.fn(),
1111
resolveOsSummary: vi.fn(),
1212
createStatusScanCoreBootstrap: vi.fn(),
@@ -27,8 +27,11 @@ vi.mock("../cli/command-secret-targets.js", () => ({
2727
getStatusCommandSecretTargetIds: mocks.getStatusCommandSecretTargetIds,
2828
}));
2929

30+
vi.mock("../cli/command-config-snapshot.js", () => ({
31+
readCommandConfigSnapshot: mocks.readCommandConfigSnapshot,
32+
}));
33+
3034
vi.mock("../config/config.js", () => ({
31-
readBestEffortConfigSnapshot: mocks.readBestEffortConfigSnapshot,
3235
resolveGatewayPort: mocks.resolveGatewayPort,
3336
}));
3437

@@ -90,10 +93,12 @@ describe("collectStatusScanOverview", () => {
9093

9194
mocks.hasConfiguredChannelsForReadOnlyScope.mockReturnValue(true);
9295
mocks.getStatusCommandSecretTargetIds.mockReturnValue([]);
93-
mocks.readBestEffortConfigSnapshot.mockResolvedValue({
94-
config: { session: {} },
95-
sourceConfig: { session: { raw: true } },
96-
configDiagnostics: null,
96+
mocks.readCommandConfigSnapshot.mockResolvedValue({
97+
snapshot: {
98+
valid: true,
99+
runtimeConfig: { session: {} },
100+
sourceConfig: { session: { raw: true } },
101+
},
97102
});
98103
mocks.resolveCommandConfigWithSecrets.mockResolvedValue({
99104
resolvedConfig: { session: {} },
@@ -147,10 +152,7 @@ describe("collectStatusScanOverview", () => {
147152
useGatewayCallOverridesForChannelsStatus: true,
148153
});
149154

150-
expect(mocks.readBestEffortConfigSnapshot).toHaveBeenCalledWith({
151-
observe: false,
152-
skipPluginValidation: undefined,
153-
});
155+
expect(mocks.readCommandConfigSnapshot).toHaveBeenCalledOnce();
154156
expect(mocks.callGateway).toHaveBeenCalledTimes(2);
155157
const channelsRequest = gatewayRequest("channels.status");
156158
expect(channelsRequest?.url).toBe("ws://127.0.0.1:18789");

‎src/commands/status.scan-overview.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,6 @@ export async function collectStatusScanOverview(params: {
127127
channelCredentialResolutionSkipped?: boolean;
128128
useGatewayCallOverridesForChannelsStatus?: boolean;
129129
includeChannelSecretTargets?: boolean;
130-
skipConfigPluginValidation?: boolean;
131130
includeAdvertisedControlUiLinks?: boolean;
132131
progress?: {
133132
setLabel(label: string): void;
@@ -157,11 +156,16 @@ export async function collectStatusScanOverview(params: {
157156
env,
158157
commandName: params.commandName,
159158
allowMissingConfigFastPath: params.allowMissingConfigFastPath,
160-
readConfigSnapshot: async () =>
161-
(await configModuleLoader.load()).readBestEffortConfigSnapshot({
162-
observe: false,
163-
skipPluginValidation: params.skipConfigPluginValidation,
164-
}),
159+
readConfigSnapshot: async () => {
160+
const { snapshot } = await (
161+
await import("../cli/command-config-snapshot.js")
162+
).readCommandConfigSnapshot({ observe: false, skipPluginValidation: true });
163+
return {
164+
config: snapshot.runtimeConfig,
165+
sourceConfig: snapshot.sourceConfig,
166+
configDiagnostics: snapshot.valid ? null : { path: snapshot.path, issues: snapshot.issues },
167+
};
168+
},
165169
resolveConfig: async (loadedConfig) =>
166170
await (
167171
await commandConfigResolutionModuleLoader.load()

‎src/commands/status.scan.fast-json.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ export async function scanStatusJsonWithPolicy(
103103
includeChannelsData: false,
104104
// Fast JSON only needs to know whether channels may exist; it does not render channel tables.
105105
includeChannelSecretTargets: false,
106-
skipConfigPluginValidation: true,
107106
fetchGitUpdate: policy.fetchGitUpdate,
108107
includeRegistryUpdate: policy.includeRegistryUpdate,
109108
includeLocalStatusRpcFallback: policy.includeLocalStatusRpcFallback,

‎src/commands/status.scan.test-helpers.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,29 @@ export async function loadStatusScanModuleForTest(
215215
vi.doMock("../config/config.js", () => ({
216216
readBestEffortConfig: mocks.readBestEffortConfig,
217217
readBestEffortConfigSnapshot: mocks.readBestEffortConfigSnapshot,
218+
readConfigFileSnapshotWithPluginMetadata: async (readOptions: unknown) => {
219+
const result = (await mocks.readBestEffortConfigSnapshot(readOptions)) as {
220+
config: OpenClawConfig;
221+
sourceConfig: OpenClawConfig;
222+
configDiagnostics: { path: string; issues: unknown[] } | null;
223+
};
224+
return {
225+
snapshot: {
226+
path: result.configDiagnostics?.path ?? mocks.resolveConfigPath(),
227+
exists: true,
228+
raw: null,
229+
parsed: result.sourceConfig,
230+
sourceConfig: result.sourceConfig,
231+
resolved: result.sourceConfig,
232+
valid: result.configDiagnostics === null,
233+
runtimeConfig: result.config,
234+
config: result.config,
235+
issues: result.configDiagnostics?.issues ?? [],
236+
warnings: [],
237+
legacyIssues: [],
238+
},
239+
};
240+
},
218241
resolveGatewayPort: mocks.resolveGatewayPort,
219242
}));
220243
vi.doMock("../cli/command-secret-targets.js", () => ({

‎src/config/io.context.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,9 @@ export function createConfigIoContext(options: ConfigIoFactoryOptions = {}): Con
139139
env: params.env,
140140
allowCurrent: params.allowCurrentPluginMetadata,
141141
pluginIdScope: resolvePluginIdScope(config),
142+
onSnapshotResolved: (resolved) => {
143+
snapshot = resolved;
144+
},
142145
});
143146
return { manifestRegistry };
144147
},

‎src/config/io.plugin-metadata.ts‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { listAgentWorkspaceDirs } from "../agents/workspace-dirs.js";
22
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
3-
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
3+
import {
4+
resolvePluginMetadataSnapshot,
5+
type PluginMetadataSnapshot,
6+
} from "../plugins/plugin-metadata-snapshot.js";
47
import type { PluginMetadataSnapshotPluginIdScope } from "../plugins/plugin-metadata-snapshot.types.js";
58
import { normalizePluginPolicyId } from "../plugins/plugin-policy-id.js";
69
import type { OpenClawConfig } from "./types.openclaw.js";
@@ -36,29 +39,36 @@ function mergeRegistries(registries: readonly PluginManifestRegistry[]): PluginM
3639
return { plugins, diagnostics };
3740
}
3841

39-
export function resolveConfigWidePluginManifestRegistry(params: {
42+
type ResolveConfigWidePluginMetadataParams = {
4043
config: OpenClawConfig;
4144
env?: NodeJS.ProcessEnv;
4245
stateDir?: string;
4346
allowCurrent?: boolean;
4447
pluginIds?: readonly string[];
4548
pluginIdScope?: PluginMetadataSnapshotPluginIdScope;
46-
}): PluginManifestRegistry {
49+
onSnapshotResolved?: (snapshot: PluginMetadataSnapshot) => void;
50+
};
51+
52+
export function resolveConfigWidePluginManifestRegistry(
53+
params: ResolveConfigWidePluginMetadataParams,
54+
): PluginManifestRegistry {
4755
const env = params.env ?? process.env;
4856
const dirs = listAgentWorkspaceDirs(params.config, env);
49-
return mergeRegistries(
50-
(dirs.length ? dirs : [undefined]).map(
51-
(workspaceDir) =>
52-
resolvePluginMetadataSnapshot({
53-
config: params.config,
54-
...(workspaceDir ? { workspaceDir } : {}),
55-
...(params.stateDir ? { stateDir: params.stateDir } : {}),
56-
env,
57-
allowCurrent: params.allowCurrent,
58-
allowWorkspaceScopedCurrent: true,
59-
...(params.pluginIds !== undefined ? { pluginIds: params.pluginIds } : {}),
60-
...(params.pluginIdScope ? { pluginIdScope: params.pluginIdScope } : {}),
61-
}).manifestRegistry,
62-
),
63-
);
57+
const workspaceDirs: Array<string | undefined> = dirs.length ? dirs : [undefined];
58+
const resolveSnapshot = (workspaceDir: string | undefined) =>
59+
resolvePluginMetadataSnapshot({
60+
config: params.config,
61+
...(workspaceDir ? { workspaceDir } : {}),
62+
...(params.stateDir ? { stateDir: params.stateDir } : {}),
63+
env,
64+
allowCurrent: params.allowCurrent,
65+
allowWorkspaceScopedCurrent: true,
66+
...(params.pluginIds !== undefined ? { pluginIds: params.pluginIds } : {}),
67+
...(params.pluginIdScope ? { pluginIdScope: params.pluginIdScope } : {}),
68+
});
69+
const firstSnapshot = resolveSnapshot(workspaceDirs[0]);
70+
const snapshots = [firstSnapshot, ...workspaceDirs.slice(1).map(resolveSnapshot)];
71+
const manifestRegistry = mergeRegistries(snapshots.map((snapshot) => snapshot.manifestRegistry));
72+
params.onSnapshotResolved?.(firstSnapshot);
73+
return manifestRegistry;
6474
}

0 commit comments

Comments
 (0)