Skip to content

Commit 2babe03

Browse files
committed
perf(gateway): cache stable plugin index fingerprints
1 parent 1d4537a commit 2babe03

8 files changed

Lines changed: 296 additions & 121 deletions

‎extensions/codex/src/app-server/sandbox-exec-server.http.test.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
execServerUrlFromClient,
1111
openSocket,
1212
rpc,
13-
shellQuote,
1413
waitForHttpBodyDeltas,
1514
} from "./sandbox-exec-server.test-helpers.js";
1615

@@ -19,6 +18,12 @@ afterEach(async () => {
1918
await closeCodexSandboxExecServersForTests();
2019
});
2120

21+
function testExecEnv(): NodeJS.ProcessEnv {
22+
return {
23+
PATH: process.env.PATH,
24+
};
25+
}
26+
2227
describe("OpenClaw Codex sandbox exec-server HTTP", () => {
2328
it("routes HTTP requests through the sandbox backend", async () => {
2429
const runShellCommand = vi.fn(async () => ({
@@ -84,13 +89,13 @@ describe("OpenClaw Codex sandbox exec-server HTTP", () => {
8489
});
8590
const buildExecSpec = vi.fn(async () => ({
8691
argv: [
87-
"/bin/sh",
88-
"-lc",
92+
process.execPath,
93+
"-e",
8994
[headerLine, bodyLine, doneLine]
90-
.map((line) => `printf '%s\\n' ${shellQuote(line)}`)
91-
.join("; "),
95+
.map((line) => `process.stdout.write(${JSON.stringify(`${line}\n`)});`)
96+
.join(""),
9297
],
93-
env: process.env,
98+
env: testExecEnv(),
9499
stdinMode: "pipe-closed" as const,
95100
}));
96101
const runShellCommand = vi.fn(async () => ({
@@ -167,7 +172,7 @@ describe("OpenClaw Codex sandbox exec-server HTTP", () => {
167172
"setInterval(() => {}, 1000);",
168173
].join(""),
169174
],
170-
env: process.env,
175+
env: testExecEnv(),
171176
finalizeToken: "stream-token",
172177
stdinMode: "pipe-closed",
173178
}),

‎extensions/codex/src/app-server/sandbox-exec-server.test-helpers.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ export function createSandboxContext(overrides: {
4040
buildExecSpec:
4141
overrides.buildExecSpec ??
4242
(async () => ({
43-
argv: ["/bin/sh", "-lc", "true"],
44-
env: process.env,
43+
argv: [process.execPath, "-e", ""],
44+
env: { PATH: process.env.PATH },
4545
stdinMode: "pipe-closed",
4646
})),
4747
finalizeExec: overrides.finalizeExec,

‎extensions/codex/src/app-server/sandbox-exec-server.test.ts‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,26 @@ afterEach(async () => {
2020
await closeCodexSandboxExecServersForTests();
2121
});
2222

23+
function testExecEnv(): NodeJS.ProcessEnv {
24+
return {
25+
PATH: process.env.PATH,
26+
};
27+
}
28+
29+
function echoFirstInputLineScript(prefix: string): string {
30+
return [
31+
"let data = '';",
32+
"process.stdin.setEncoding('utf8');",
33+
"process.stdin.on('data', (chunk) => {",
34+
"data += chunk;",
35+
"if (data.includes('\\n')) {",
36+
`process.stdout.write(${JSON.stringify(prefix)} + data);`,
37+
"process.exit(0);",
38+
"}",
39+
"});",
40+
].join(" ");
41+
}
42+
2343
describe("OpenClaw Codex sandbox exec-server", () => {
2444
it("reports unavailable app-server remote environment support without exposing an environment", async () => {
2545
const sandbox = createSandboxContext({});
@@ -95,8 +115,8 @@ describe("OpenClaw Codex sandbox exec-server", () => {
95115

96116
it("registers a sandbox-backed Codex environment and routes process execution through it", async () => {
97117
const buildExecSpec = vi.fn(async () => ({
98-
argv: ["/bin/sh", "-lc", "printf 'sandbox-process-ok\\n'"],
99-
env: process.env,
118+
argv: [process.execPath, "-e", "process.stdout.write('sandbox-process-ok\\n')"],
119+
env: testExecEnv(),
100120
stdinMode: "pipe-closed" as const,
101121
}));
102122
const sandbox = createSandboxContext({ buildExecSpec });
@@ -172,8 +192,8 @@ describe("OpenClaw Codex sandbox exec-server", () => {
172192

173193
it("rejects unsupported arg0 overrides instead of dropping them", async () => {
174194
const buildExecSpec = vi.fn(async () => ({
175-
argv: ["/bin/sh", "-lc", "true"],
176-
env: process.env,
195+
argv: [process.execPath, "-e", ""],
196+
env: testExecEnv(),
177197
stdinMode: "pipe-closed" as const,
178198
}));
179199
const sandbox = createSandboxContext({ buildExecSpec });
@@ -204,8 +224,8 @@ describe("OpenClaw Codex sandbox exec-server", () => {
204224
it("accepts stdin writes for pipe-backed processes", async () => {
205225
const sandbox = createSandboxContext({
206226
buildExecSpec: async () => ({
207-
argv: ["/bin/sh", "-lc", 'read line; printf "echo:%s\\n" "$line"'],
208-
env: process.env,
227+
argv: [process.execPath, "-e", echoFirstInputLineScript("echo:")],
228+
env: testExecEnv(),
209229
stdinMode: "pipe-open",
210230
}),
211231
});
@@ -242,8 +262,8 @@ describe("OpenClaw Codex sandbox exec-server", () => {
242262

243263
it("keeps tty process starts pipe-backed for sandbox backends", async () => {
244264
const buildExecSpec = vi.fn(async () => ({
245-
argv: ["/bin/sh", "-lc", 'read line; printf "tty:%s\\n" "$line"'],
246-
env: process.env,
265+
argv: [process.execPath, "-e", echoFirstInputLineScript("tty:")],
266+
env: testExecEnv(),
247267
stdinMode: "pipe-open" as const,
248268
}));
249269
const sandbox = createSandboxContext({ buildExecSpec });
@@ -289,7 +309,7 @@ describe("OpenClaw Codex sandbox exec-server", () => {
289309
vi.stubEnv("OPENCLAW_TEST_DATABASE_PASSWORD", "host-password");
290310
vi.stubEnv("OPENCLAW_TEST_PRIVATE_KEY", "host-private-key");
291311
const buildExecSpec = vi.fn(async () => ({
292-
argv: ["/bin/sh", "-lc", "true"],
312+
argv: [process.execPath, "-e", ""],
293313
env: {},
294314
stdinMode: "pipe-closed" as const,
295315
}));
@@ -336,7 +356,7 @@ describe("OpenClaw Codex sandbox exec-server", () => {
336356
"-e",
337357
"process.stdout.write('aaaa'); process.stderr.write('bbbb');",
338358
],
339-
env: process.env,
359+
env: testExecEnv(),
340360
stdinMode: "pipe-closed",
341361
}),
342362
});

‎src/plugins/installed-plugin-index-record-reader.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import crypto from "node:crypto";
12
import fs from "node:fs";
23
import path from "node:path";
34
import type { PluginInstallRecord } from "../config/types.plugins.js";
@@ -239,8 +240,9 @@ const installRecordsCache = new Map<string, InstallRecordsCacheEntry>();
239240

240241
function readFileSignature(filePath: string): string {
241242
try {
242-
const stat = fs.statSync(filePath);
243-
return `${stat.mtimeMs}:${stat.size}`;
243+
const stat = fs.statSync(filePath, { bigint: true });
244+
const hash = crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("base64url");
245+
return `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${hash}`;
244246
} catch {
245247
return "missing";
246248
}

‎src/plugins/manifest-registry-installed.test.ts‎

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import {
66
writePersistedInstalledPluginIndex,
77
} from "./installed-plugin-index-store.js";
88
import type { InstalledPluginIndex } from "./installed-plugin-index.js";
9-
import { loadPluginManifestRegistryForInstalledIndex } from "./manifest-registry-installed.js";
9+
import {
10+
loadPluginManifestRegistryForInstalledIndex,
11+
resolveInstalledManifestRegistryIndexFingerprint,
12+
} from "./manifest-registry-installed.js";
1013
import { cleanupTrackedTempDirs, makeTrackedTempDir } from "./test-helpers/fs-fixtures.js";
1114

1215
const tempDirs: string[] = [];
@@ -70,7 +73,106 @@ function createIndex(rootDir: string): InstalledPluginIndex {
7073
};
7174
}
7275

76+
function fileSignature(filePath: string) {
77+
const stat = fs.statSync(filePath);
78+
return {
79+
size: stat.size,
80+
mtimeMs: stat.mtimeMs,
81+
ctimeMs: stat.ctimeMs,
82+
};
83+
}
84+
85+
function createIndexWithFileSignatures(rootDir: string): InstalledPluginIndex {
86+
const index = createIndex(rootDir);
87+
return {
88+
...index,
89+
plugins: index.plugins.map((record) => ({
90+
...record,
91+
manifestFile: fileSignature(record.manifestPath),
92+
})),
93+
};
94+
}
95+
96+
function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {
97+
if (!value || typeof value !== "object") {
98+
return value;
99+
}
100+
const object = value as object;
101+
if (seen.has(object)) {
102+
return value;
103+
}
104+
seen.add(object);
105+
for (const child of Object.values(value)) {
106+
deepFreeze(child, seen);
107+
}
108+
return Object.freeze(value);
109+
}
110+
73111
describe("loadPluginManifestRegistryForInstalledIndex", () => {
112+
it("reuses frozen installed-index fingerprints when file signatures are persisted", () => {
113+
const rootDir = makeTempDir();
114+
writePlugin(rootDir, "installed", "installed-");
115+
const index = deepFreeze(createIndexWithFileSignatures(rootDir));
116+
const first = resolveInstalledManifestRegistryIndexFingerprint(index);
117+
const manifestPath = path.join(rootDir, "openclaw.plugin.json");
118+
const nextMtime = new Date(Date.now() + 5000);
119+
fs.utimesSync(manifestPath, nextMtime, nextMtime);
120+
const second = resolveInstalledManifestRegistryIndexFingerprint(index);
121+
122+
expect(second).toBe(first);
123+
});
124+
125+
it("recomputes installed-index fingerprints for mutable index objects", () => {
126+
const rootDir = makeTempDir();
127+
writePlugin(rootDir, "installed", "installed-");
128+
const index = createIndexWithFileSignatures(rootDir);
129+
const first = resolveInstalledManifestRegistryIndexFingerprint(index);
130+
const record = index.plugins[0];
131+
if (!record) {
132+
throw new Error("expected index record");
133+
}
134+
record.manifestHash = "changed";
135+
const second = resolveInstalledManifestRegistryIndexFingerprint(index);
136+
137+
expect(second).not.toBe(first);
138+
});
139+
140+
it("does not cache shallow-frozen installed-index fingerprints with mutable nested records", () => {
141+
const rootDir = makeTempDir();
142+
writePlugin(rootDir, "installed", "installed-");
143+
const index = createIndexWithFileSignatures(rootDir);
144+
const record = index.plugins[0];
145+
if (!record) {
146+
throw new Error("expected index record");
147+
}
148+
Object.freeze(index.installRecords);
149+
Object.freeze(index.diagnostics);
150+
Object.freeze(record);
151+
Object.freeze(index.plugins);
152+
Object.freeze(index);
153+
const first = resolveInstalledManifestRegistryIndexFingerprint(index);
154+
155+
const agentHarnesses = record.startup.agentHarnesses as string[];
156+
agentHarnesses.push("changed");
157+
const second = resolveInstalledManifestRegistryIndexFingerprint(index);
158+
159+
expect(second).not.toBe(first);
160+
});
161+
162+
it("does not cache frozen installed-index fingerprints that depend on live file state", () => {
163+
const rootDir = makeTempDir();
164+
writePlugin(rootDir, "installed", "installed-");
165+
const index = deepFreeze(createIndex(rootDir));
166+
const first = resolveInstalledManifestRegistryIndexFingerprint(index);
167+
168+
const manifestPath = path.join(rootDir, "openclaw.plugin.json");
169+
const nextMtime = new Date(Date.now() + 5000);
170+
fs.utimesSync(manifestPath, nextMtime, nextMtime);
171+
const second = resolveInstalledManifestRegistryIndexFingerprint(index);
172+
173+
expect(second).not.toBe(first);
174+
});
175+
74176
it("reconstructs installed-index manifest registries when manifest files change", () => {
75177
const rootDir = makeTempDir();
76178
const manifestPath = path.join(rootDir, "openclaw.plugin.json");

‎src/plugins/manifest-registry-installed.ts‎

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { normalizeOptionalString } from "../shared/string-coerce.js";
77
import { normalizeOptionalTrimmedStringList } from "../shared/string-normalization.js";
88
import type { PluginCandidate } from "./discovery.js";
99
import { hashJson } from "./installed-plugin-index-hash.js";
10+
import type { InstalledPluginFileSignature } from "./installed-plugin-index-hash.js";
1011
import type { InstalledPluginIndex, InstalledPluginIndexRecord } from "./installed-plugin-index.js";
1112
import { extractPluginInstallRecordsFromInstalledPluginIndex } from "./installed-plugin-index.js";
1213
import { loadPluginManifestRegistry, type PluginManifestRegistry } from "./manifest-registry.js";
@@ -25,6 +26,37 @@ import {
2526
type PluginDependencySpecMap,
2627
} from "./status-dependencies.js";
2728

29+
const installedManifestRegistryIndexFingerprintCache = new WeakMap<InstalledPluginIndex, string>();
30+
31+
function isDeepFrozenJsonLike(value: unknown, seen = new WeakSet<object>()): boolean {
32+
if (!value || typeof value !== "object") {
33+
return true;
34+
}
35+
const object = value as object;
36+
if (seen.has(object)) {
37+
return true;
38+
}
39+
if (!Object.isFrozen(object)) {
40+
return false;
41+
}
42+
seen.add(object);
43+
return Object.values(value).every((entry) => isDeepFrozenJsonLike(entry, seen));
44+
}
45+
46+
function hasPersistedFileSignatures(index: InstalledPluginIndex): boolean {
47+
return index.plugins.every(
48+
(record) =>
49+
record.manifestFile !== undefined &&
50+
(record.packageJson === undefined || record.packageJson.fileSignature !== undefined),
51+
);
52+
}
53+
54+
function isInstalledManifestRegistryIndexFingerprintCacheable(
55+
index: InstalledPluginIndex,
56+
): boolean {
57+
return hasPersistedFileSignatures(index) && isDeepFrozenJsonLike(index);
58+
}
59+
2860
function isRelativePathInsideOrEqual(relativePath: string): boolean {
2961
return (
3062
relativePath === "" ||
@@ -61,12 +93,19 @@ function safeFileSignature(filePath: string | undefined): string | undefined {
6193
}
6294
try {
6395
const stat = fs.statSync(filePath);
64-
return `${filePath}:${stat.size}:${stat.mtimeMs}`;
96+
return formatFileSignature(filePath, stat);
6597
} catch {
6698
return `${filePath}:missing`;
6799
}
68100
}
69101

102+
function formatFileSignature(
103+
filePath: string,
104+
signature: Pick<InstalledPluginFileSignature, "size" | "mtimeMs">,
105+
): string {
106+
return `${filePath}:${signature.size}:${signature.mtimeMs}`;
107+
}
108+
70109
function buildInstalledManifestRegistryIndexKey(index: InstalledPluginIndex) {
71110
const realpathCache = new Map<string, string>();
72111
return {
@@ -78,9 +117,12 @@ function buildInstalledManifestRegistryIndexKey(index: InstalledPluginIndex) {
78117
installRecords: index.installRecords,
79118
diagnostics: index.diagnostics,
80119
plugins: index.plugins.map((record) => {
81-
const packageJsonFile =
82-
record.packageJson?.fileSignature ??
83-
safeFileSignature(resolvePackageJsonPath(record, realpathCache));
120+
const packageJsonPath = resolvePackageJsonPath(record, realpathCache);
121+
const packageJsonFile = record.packageJson?.fileSignature
122+
? packageJsonPath
123+
? formatFileSignature(packageJsonPath, record.packageJson.fileSignature)
124+
: undefined
125+
: safeFileSignature(packageJsonPath);
84126
return {
85127
pluginId: record.pluginId,
86128
packageName: record.packageName,
@@ -91,7 +133,9 @@ function buildInstalledManifestRegistryIndexKey(index: InstalledPluginIndex) {
91133
packageChannel: record.packageChannel,
92134
manifestPath: record.manifestPath,
93135
manifestHash: record.manifestHash,
94-
manifestFile: safeFileSignature(record.manifestPath),
136+
manifestFile: record.manifestFile
137+
? formatFileSignature(record.manifestPath, record.manifestFile)
138+
: safeFileSignature(record.manifestPath),
95139
format: record.format,
96140
bundleFormat: record.bundleFormat,
97141
source: record.source,
@@ -116,7 +160,15 @@ function buildInstalledManifestRegistryIndexKey(index: InstalledPluginIndex) {
116160
export function resolveInstalledManifestRegistryIndexFingerprint(
117161
index: InstalledPluginIndex,
118162
): string {
119-
return hashJson(buildInstalledManifestRegistryIndexKey(index));
163+
const cached = installedManifestRegistryIndexFingerprintCache.get(index);
164+
if (cached) {
165+
return cached;
166+
}
167+
const fingerprint = hashJson(buildInstalledManifestRegistryIndexKey(index));
168+
if (isInstalledManifestRegistryIndexFingerprintCacheable(index)) {
169+
installedManifestRegistryIndexFingerprintCache.set(index, fingerprint);
170+
}
171+
return fingerprint;
120172
}
121173

122174
function resolveInstalledPluginRootDir(record: InstalledPluginIndexRecord): string {

0 commit comments

Comments
 (0)