Skip to content

Commit ec8fc16

Browse files
committed
perf(plugins): memoize auto-enable fingerprints
1 parent c43ba8e commit ec8fc16

4 files changed

Lines changed: 172 additions & 47 deletions

File tree

‎src/config/plugin-auto-enable.apply.ts‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { AmbientEnvTriggerPolicy } from "../channels/config-presence.js";
33
import type { PluginDiscoveryResult } from "../plugins/discovery.js";
44
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
5+
import { registerPluginMetadataProcessMemoLifecycleClear } from "../plugins/plugin-metadata-lifecycle.js";
56
import { detectPluginAutoEnableCandidates } from "./plugin-auto-enable.detect.js";
67
import {
78
materializePluginAutoEnableCandidatesInternal,
@@ -29,6 +30,16 @@ type PluginAutoEnableConfigCache = WeakMap<object, PluginAutoEnableEnvCache>;
2930

3031
let sameTurnApplyCache: PluginAutoEnableConfigCache | undefined;
3132
let sameTurnApplyCacheClearScheduled = false;
33+
let stableFingerprintMemo = new WeakMap<object, string>();
34+
let configFingerprintMemo = new WeakMap<object, string>();
35+
36+
// Gateway metadata/config use replacement snapshots, and process.env selection is generation-fixed.
37+
// The plugin metadata lifecycle clear is the freshness boundary for these identity memos.
38+
registerPluginMetadataProcessMemoLifecycleClear(() => {
39+
stableFingerprintMemo = new WeakMap();
40+
configFingerprintMemo = new WeakMap();
41+
sameTurnApplyCache = undefined;
42+
});
3243

3344
function scheduleSameTurnApplyCacheClear(): void {
3445
if (sameTurnApplyCacheClearScheduled) {
@@ -61,22 +72,35 @@ function stableFingerprintValue(value: unknown): string {
6172
if (value === null || typeof value !== "object") {
6273
return JSON.stringify(value) ?? "null";
6374
}
64-
if (Array.isArray(value)) {
65-
return `[${value.map((entry) => stableFingerprintValue(entry)).join(",")}]`;
75+
const cached = stableFingerprintMemo.get(value);
76+
if (cached !== undefined) {
77+
return cached;
6678
}
67-
const record = value as Record<string, unknown>;
68-
return `{${Object.keys(record)
69-
.toSorted((left, right) => left.localeCompare(right))
70-
.map((key) => `${JSON.stringify(key)}:${stableFingerprintValue(record[key])}`)
71-
.join(",")}}`;
79+
const fingerprint = Array.isArray(value)
80+
? `[${value.map((entry) => stableFingerprintValue(entry)).join(",")}]`
81+
: (() => {
82+
const record = value as Record<string, unknown>;
83+
return `{${Object.keys(record)
84+
.toSorted((left, right) => left.localeCompare(right))
85+
.map((key) => `${JSON.stringify(key)}:${stableFingerprintValue(record[key])}`)
86+
.join(",")}}`;
87+
})();
88+
stableFingerprintMemo.set(value, fingerprint);
89+
return fingerprint;
7290
}
7391

74-
/** Fingerprints mutable config inputs used by plugin auto-enable detection. */
92+
/** Fingerprints config snapshots used by plugin auto-enable detection. */
7593
export function fingerprintPluginAutoEnableConfig(config: OpenClawConfig): string {
76-
return hashRuntimeConfigValue(config);
94+
const cached = configFingerprintMemo.get(config);
95+
if (cached !== undefined) {
96+
return cached;
97+
}
98+
const fingerprint = hashRuntimeConfigValue(config);
99+
configFingerprintMemo.set(config, fingerprint);
100+
return fingerprint;
77101
}
78102

79-
/** Fingerprints mutable environment inputs used by plugin auto-enable detection. */
103+
/** Fingerprints environment snapshots used by plugin auto-enable detection. */
80104
export function fingerprintPluginAutoEnableEnv(env: NodeJS.ProcessEnv): string {
81105
return stableFingerprintValue(env);
82106
}

‎src/config/plugin-auto-enable.core.test.ts‎

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from "node:path";
44
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
55
import { setCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
66
import type { PluginCandidate, PluginDiscoveryResult } from "../plugins/discovery.js";
7+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
78
import {
89
applyPluginAutoEnable,
910
detectPluginAutoEnableCandidates,
@@ -1119,6 +1120,68 @@ describe("applyPluginAutoEnable core", () => {
11191120
expect(setupRegistryMock.resolvePluginSetupAutoEnableReasons).toHaveBeenCalledTimes(2);
11201121
});
11211122

1123+
it("fingerprints identical snapshots once per plugin metadata lifecycle", () => {
1124+
const traversals = { candidates: 0, config: 0, env: 0, plugins: 0 };
1125+
const config = new Proxy<OpenClawConfig>(
1126+
{},
1127+
{
1128+
ownKeys: (target) => {
1129+
traversals.config += 1;
1130+
return Reflect.ownKeys(target);
1131+
},
1132+
},
1133+
);
1134+
const envSnapshot = new Proxy(makeIsolatedEnv(), {
1135+
ownKeys: (target) => {
1136+
traversals.env += 1;
1137+
return Reflect.ownKeys(target);
1138+
},
1139+
});
1140+
const discovery: PluginDiscoveryResult = {
1141+
candidates: new Proxy([], {
1142+
get: (target, property, receiver) => {
1143+
if (property === "map") {
1144+
traversals.candidates += 1;
1145+
}
1146+
return Reflect.get(target, property, receiver);
1147+
},
1148+
}),
1149+
diagnostics: [],
1150+
};
1151+
const manifestRegistry = makeRegistry([]);
1152+
manifestRegistry.plugins = new Proxy(manifestRegistry.plugins, {
1153+
get: (target, property, receiver) => {
1154+
if (property === "map") {
1155+
traversals.plugins += 1;
1156+
}
1157+
return Reflect.get(target, property, receiver);
1158+
},
1159+
});
1160+
1161+
const first = applyPluginAutoEnable({
1162+
config,
1163+
discovery,
1164+
env: envSnapshot,
1165+
manifestRegistry,
1166+
});
1167+
const firstTraversalCounts = { ...traversals };
1168+
1169+
for (let index = 0; index < 20; index += 1) {
1170+
expect(applyPluginAutoEnable({ config, discovery, env: envSnapshot, manifestRegistry })).toBe(
1171+
first,
1172+
);
1173+
}
1174+
expect(traversals).toEqual(firstTraversalCounts);
1175+
1176+
clearPluginMetadataLifecycleCaches();
1177+
applyPluginAutoEnable({ config, discovery, env: envSnapshot, manifestRegistry });
1178+
1179+
expect(traversals.config).toBeGreaterThan(firstTraversalCounts.config);
1180+
expect(traversals.env).toBeGreaterThan(firstTraversalCounts.env);
1181+
expect(traversals.candidates).toBeGreaterThan(firstTraversalCounts.candidates);
1182+
expect(traversals.plugins).toBeGreaterThan(firstTraversalCounts.plugins);
1183+
});
1184+
11221185
it("does not reuse same-turn results for omitted metadata after current snapshot replacement", () => {
11231186
const config: OpenClawConfig = {
11241187
channels: { apn: { someKey: "value" } },
@@ -1196,7 +1259,7 @@ describe("applyPluginAutoEnable core", () => {
11961259
expect(setupRegistryMock.resolvePluginSetupAutoEnableReasons).toHaveBeenCalledTimes(2);
11971260
});
11981261

1199-
it("does not reuse same-turn auto-enable results after config mutates in place", () => {
1262+
it("refreshes auto-enable results after config mutates at a lifecycle boundary", () => {
12001263
const config: OpenClawConfig = {};
12011264
const manifestRegistry = makeRegistry([{ id: "apn-channel", channels: ["apn"] }]);
12021265

@@ -1207,6 +1270,7 @@ describe("applyPluginAutoEnable core", () => {
12071270
manifestRegistry,
12081271
});
12091272
config.channels = { apn: { someKey: "value" } };
1273+
clearPluginMetadataLifecycleCaches();
12101274
const second = applyPluginAutoEnable({
12111275
config,
12121276
discovery: emptyDiscovery,
@@ -1219,7 +1283,7 @@ describe("applyPluginAutoEnable core", () => {
12191283
expect(second).not.toBe(first);
12201284
});
12211285

1222-
it("does not reuse same-turn auto-enable results after registry mutates in place", () => {
1286+
it("refreshes auto-enable results after registry mutates at a lifecycle boundary", () => {
12231287
const config: OpenClawConfig = {
12241288
channels: { apn: { someKey: "value" } },
12251289
};
@@ -1236,6 +1300,7 @@ describe("applyPluginAutoEnable core", () => {
12361300
registry.plugins.length,
12371301
...makeRegistry([{ id: "apn-channel", channels: ["apn"] }]).plugins,
12381302
);
1303+
clearPluginMetadataLifecycleCaches();
12391304
const second = applyPluginAutoEnable({
12401305
config,
12411306
discovery: emptyDiscovery,
@@ -1248,7 +1313,7 @@ describe("applyPluginAutoEnable core", () => {
12481313
expect(second).not.toBe(first);
12491314
});
12501315

1251-
it("does not reuse same-turn auto-enable results after discovery mutates in place", () => {
1316+
it("refreshes auto-enable results after discovery mutates at a lifecycle boundary", () => {
12521317
const config: OpenClawConfig = {};
12531318
const mutableDiscovery: PluginDiscoveryResult = { candidates: [], diagnostics: [] };
12541319
const manifestRegistry = makeRegistry([
@@ -1270,6 +1335,7 @@ describe("applyPluginAutoEnable core", () => {
12701335
channelId: "cache-channel",
12711336
}),
12721337
);
1338+
clearPluginMetadataLifecycleCaches();
12731339
const second = applyPluginAutoEnable({
12741340
config,
12751341
discovery: mutableDiscovery,
@@ -1282,7 +1348,7 @@ describe("applyPluginAutoEnable core", () => {
12821348
expect(second).not.toBe(first);
12831349
});
12841350

1285-
it("does not reuse same-turn auto-enable results after env mutates in place", () => {
1351+
it("refreshes auto-enable results after env mutates at a lifecycle boundary", () => {
12861352
const config: OpenClawConfig = {
12871353
plugins: {
12881354
entries: {
@@ -1303,6 +1369,7 @@ describe("applyPluginAutoEnable core", () => {
13031369
manifestRegistry,
13041370
});
13051371
mutableEnv.OPENCLAW_TEST_CACHE_INPUT = "changed";
1372+
clearPluginMetadataLifecycleCaches();
13061373
const second = applyPluginAutoEnable({
13071374
config,
13081375
discovery: emptyDiscovery,

‎src/plugins/runtime/load-context.test.ts‎

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import type { OpenClawConfig } from "../../config/types.openclaw.js";
55
const loadConfigMock = vi.fn<typeof import("../../config/config.js").loadConfig>();
66
const applyPluginAutoEnableMock =
77
vi.fn<typeof import("../../config/plugin-auto-enable.js").applyPluginAutoEnable>();
8+
const fingerprintPluginAutoEnableConfigMock = vi.fn((config: OpenClawConfig) =>
9+
JSON.stringify(config),
10+
);
11+
const fingerprintPluginAutoEnableEnvMock = vi.fn((env: NodeJS.ProcessEnv) => JSON.stringify(env));
812
const resolveAgentWorkspaceDirMock = vi.fn<
913
typeof import("../../agents/agent-scope.js").resolveAgentWorkspaceDir
1014
>(() => "/resolved-workspace");
@@ -31,6 +35,7 @@ let resolvePluginRuntimeLoadContext: typeof import("./load-context.js").resolveP
3135
let buildPluginRuntimeLoadOptions: typeof import("./load-context.js").buildPluginRuntimeLoadOptions;
3236
let clearRuntimeConfigSnapshot: typeof import("../../config/runtime-snapshot.js").clearRuntimeConfigSnapshot;
3337
let setRuntimeConfigSnapshot: typeof import("../../config/runtime-snapshot.js").setRuntimeConfigSnapshot;
38+
let clearPluginMetadataLifecycleCaches: typeof import("../plugin-metadata-lifecycle.js").clearPluginMetadataLifecycleCaches;
3439

3540
vi.mock("../../config/config.js", () => ({
3641
getRuntimeConfig: loadConfigMock,
@@ -41,6 +46,11 @@ vi.mock("../../config/plugin-auto-enable.js", () => ({
4146
applyPluginAutoEnable: applyPluginAutoEnableMock,
4247
}));
4348

49+
vi.mock("../../config/plugin-auto-enable.apply.js", () => ({
50+
fingerprintPluginAutoEnableConfig: fingerprintPluginAutoEnableConfigMock,
51+
fingerprintPluginAutoEnableEnv: fingerprintPluginAutoEnableEnvMock,
52+
}));
53+
4454
vi.mock("../../agents/agent-scope.js", () => ({
4555
resolveAgentWorkspaceDir: resolveAgentWorkspaceDirMock,
4656
resolveDefaultAgentId: resolveDefaultAgentIdMock,
@@ -62,10 +72,13 @@ describe("resolvePluginRuntimeLoadContext", () => {
6272
vi.resetModules();
6373
({ clearRuntimeConfigSnapshot, setRuntimeConfigSnapshot } =
6474
await import("../../config/runtime-snapshot.js"));
75+
({ clearPluginMetadataLifecycleCaches } = await import("../plugin-metadata-lifecycle.js"));
6576
({ resolvePluginRuntimeLoadContext, buildPluginRuntimeLoadOptions } =
6677
await import("./load-context.js"));
6778
loadConfigMock.mockReset();
6879
applyPluginAutoEnableMock.mockReset();
80+
fingerprintPluginAutoEnableConfigMock.mockClear();
81+
fingerprintPluginAutoEnableEnvMock.mockClear();
6982
getCurrentPluginMetadataSnapshotMock.mockReset();
7083
getCurrentPluginMetadataSnapshotMock.mockReturnValue(undefined);
7184
isPluginMetadataSnapshotCompatibleMock.mockReset();
@@ -204,29 +217,34 @@ describe("resolvePluginRuntimeLoadContext", () => {
204217
expect(applyPluginAutoEnableMock).toHaveBeenCalledTimes(3);
205218
});
206219

207-
it("invalidates auto-enable results when config or process env mutates in place", () => {
208-
const rawConfig: OpenClawConfig = { plugins: {} };
220+
it("uses reference fast paths, content fingerprints, and lifecycle invalidation", () => {
221+
const firstConfig: OpenClawConfig = { plugins: {} };
209222
const env = process.env;
210-
const envKey = "OPENCLAW_TEST_PLUGIN_AUTO_ENABLE_FINGERPRINT";
211-
const previousEnvValue = env[envKey];
212-
delete env[envKey];
213-
214-
try {
215-
resolvePluginRuntimeLoadContext({ config: rawConfig, env });
216-
resolvePluginRuntimeLoadContext({ config: rawConfig, env });
217-
rawConfig.plugins = { entries: { demo: { enabled: true } } };
218-
resolvePluginRuntimeLoadContext({ config: rawConfig, env });
219-
env[envKey] = "changed";
220-
resolvePluginRuntimeLoadContext({ config: rawConfig, env });
221-
222-
expect(applyPluginAutoEnableMock).toHaveBeenCalledTimes(3);
223-
} finally {
224-
if (previousEnvValue === undefined) {
225-
delete env[envKey];
226-
} else {
227-
env[envKey] = previousEnvValue;
228-
}
223+
const first = resolvePluginRuntimeLoadContext({ config: firstConfig, env });
224+
225+
for (let index = 0; index < 20; index += 1) {
226+
expect(resolvePluginRuntimeLoadContext({ config: firstConfig, env }).config).toBe(
227+
first.config,
228+
);
229229
}
230+
expect(applyPluginAutoEnableMock).toHaveBeenCalledTimes(1);
231+
expect(fingerprintPluginAutoEnableConfigMock).toHaveBeenCalledTimes(1);
232+
expect(fingerprintPluginAutoEnableEnvMock).toHaveBeenCalledTimes(1);
233+
234+
const replacementConfig: OpenClawConfig = { plugins: {} };
235+
expect(resolvePluginRuntimeLoadContext({ config: replacementConfig, env }).config).toBe(
236+
first.config,
237+
);
238+
expect(applyPluginAutoEnableMock).toHaveBeenCalledTimes(1);
239+
expect(fingerprintPluginAutoEnableConfigMock).toHaveBeenCalledTimes(2);
240+
expect(fingerprintPluginAutoEnableEnvMock).toHaveBeenCalledTimes(1);
241+
242+
clearPluginMetadataLifecycleCaches();
243+
resolvePluginRuntimeLoadContext({ config: replacementConfig, env });
244+
245+
expect(applyPluginAutoEnableMock).toHaveBeenCalledTimes(2);
246+
expect(fingerprintPluginAutoEnableConfigMock).toHaveBeenCalledTimes(3);
247+
expect(fingerprintPluginAutoEnableEnvMock).toHaveBeenCalledTimes(2);
230248
});
231249

232250
it("threads install records from the metadata snapshot into the context and load options", () => {

‎src/plugins/runtime/load-context.ts‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,30 +69,46 @@ function applyCurrentPluginAutoEnable(params: {
6969
discovery: params.snapshot?.discovery,
7070
});
7171
}
72-
// Gateway plugin metadata and config are replacement snapshots. Reuse only while
73-
// mutable config/env content still matches; reload/close lifecycle clears the slot.
7472
const workspaceDir = params.snapshot.workspaceDir ?? params.workspaceDir;
75-
const autoEnableConfigFingerprint = fingerprintPluginAutoEnableConfig(params.config);
76-
const autoEnableEnvFingerprint = fingerprintPluginAutoEnableEnv(params.env);
7773
const cached = currentAutoEnableCache;
78-
if (
79-
cached?.config === params.config &&
80-
cached.env === params.env &&
81-
cached.autoEnableConfigFingerprint === autoEnableConfigFingerprint &&
82-
cached.autoEnableEnvFingerprint === autoEnableEnvFingerprint &&
74+
const metadataMatches =
75+
cached !== undefined &&
8376
cached.metadataConfigFingerprint === params.snapshot.configFingerprint &&
8477
cached.policyHash === params.snapshot.policyHash &&
8578
cached.workspaceDir === workspaceDir &&
86-
samePluginIds(cached.pluginIds, params.snapshot.pluginIds)
87-
) {
88-
return cached.result;
79+
samePluginIds(cached.pluginIds, params.snapshot.pluginIds);
80+
if (metadataMatches) {
81+
if (cached.config === params.config && cached.env === params.env) {
82+
return cached.result;
83+
}
84+
const autoEnableConfigFingerprint =
85+
cached.config === params.config
86+
? cached.autoEnableConfigFingerprint
87+
: fingerprintPluginAutoEnableConfig(params.config);
88+
const autoEnableEnvFingerprint =
89+
cached.env === params.env
90+
? cached.autoEnableEnvFingerprint
91+
: fingerprintPluginAutoEnableEnv(params.env);
92+
if (
93+
cached.autoEnableConfigFingerprint === autoEnableConfigFingerprint &&
94+
cached.autoEnableEnvFingerprint === autoEnableEnvFingerprint
95+
) {
96+
currentAutoEnableCache = {
97+
...cached,
98+
config: params.config,
99+
env: params.env,
100+
};
101+
return cached.result;
102+
}
89103
}
90104
const result = applyPluginAutoEnable({
91105
config: params.config,
92106
env: params.env,
93107
manifestRegistry: params.manifestRegistry,
94108
discovery: params.snapshot.discovery,
95109
});
110+
const autoEnableConfigFingerprint = fingerprintPluginAutoEnableConfig(params.config);
111+
const autoEnableEnvFingerprint = fingerprintPluginAutoEnableEnv(params.env);
96112
currentAutoEnableCache = {
97113
config: params.config,
98114
env: params.env,

0 commit comments

Comments
 (0)