Skip to content

Commit b7db637

Browse files
committed
perf(agents): cache subagent registry reads
1 parent 34d11d5 commit b7db637

3 files changed

Lines changed: 161 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Docs: https://docs.openclaw.ai
2525
- CLI/tools: keep the Gateway `tools.*` RPC namespace out of plugin command discovery and managed proxy startup, so stray commands like `openclaw tools effective` fail quickly instead of cold-loading plugin metadata. Refs #73477. Thanks @oromeis.
2626
- CLI/status: keep default text `openclaw status --usage` on metadata-only channel scans unless `--deep` or `--all` is set, and send stray `openclaw tools --help` through the precomputed root-help fast path so latency-triage commands avoid plugin/runtime cold loads before printing. Refs #73477 and #74220. Thanks @oromeis and @NianJiuZst.
2727
- Agents/diagnostics: trace embedded-run startup and preparation stage timings before model I/O, and warn only on severe slow stages, so Docker/VPS latency reports can identify whether plugin loading, auth/model resolution, tool inventory, bootstrap, MCP/LSP, resource loading, or stream setup is dominating pre-run latency without noisy normal logs. Refs #73428. Thanks @Dimaoggg, @quangtran88, and @Heyvhuang.
28+
- Agents/subagents: cache persisted subagent run registry reads by file signature while preserving fresh-parse isolation, so busy gateways stop reparsing unchanged `subagents/runs.json` on controller/list/status hot paths. Refs #72338. Thanks @argus-as.
2829
- Gateway/clients: wait for the event loop to become responsive before opening Gateway WebSocket RPC/probe/client connections while charging that readiness wait to caller timeouts, so Windows deferred module-evaluation stalls no longer turn healthy loopback gateways into false handshake timeouts across status, TUI, ACP, MCP, node-host, and plugin client paths. Refs #74279 and #48270. Thanks @wongcode and @joost-heijden.
2930
- Gateway/Windows: read listener command lines via PowerShell before falling back to `wmic`, so restart health can recognize OpenClaw listeners on modern Windows installs and avoid long anonymous-port waits. Refs #74280. Thanks @zym951223.
3031
- Plugins/runtime-deps: memoize packaged bundled runtime dist-mirror preparation after the first successful pass while keeping source-checkout mirrors refreshable, so constrained Docker/VPS installs avoid repeated root scans before chat turns. Refs #73428, #73421, #73532, and #73477. Thanks @Dimaoggg, @oromeis, @oadiazp, @jmfraga, @bstanbury, @antoniusfelix, and @jkobject.

‎src/agents/subagent-registry.persistence.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,96 @@ describe("subagent registry persistence", () => {
328328
expect(after.version).toBe(2);
329329
});
330330

331+
it("reuses unchanged persisted registry snapshots without reparsing runs.json", async () => {
332+
const registryPath = await writePersistedRegistry(
333+
{
334+
version: 2,
335+
runs: {
336+
"run-cached": {
337+
runId: "run-cached",
338+
childSessionKey: "agent:main:subagent:cached",
339+
requesterSessionKey: "agent:main:main",
340+
requesterOrigin: { channel: "telegram", accountId: "cached-account" },
341+
requesterDisplayKey: "main",
342+
task: "cached persisted run",
343+
cleanup: "keep",
344+
createdAt: 1,
345+
startedAt: 1,
346+
outcome: { status: "ok" },
347+
},
348+
},
349+
},
350+
{ seedChildSessions: false },
351+
);
352+
const readSpy = vi.spyOn(fsSync, "readFileSync");
353+
354+
const first = loadSubagentRegistryFromDisk();
355+
first.clear();
356+
const cachedEntry = loadSubagentRegistryFromDisk().get("run-cached");
357+
if (!cachedEntry) {
358+
throw new Error("expected cached run");
359+
}
360+
cachedEntry.endedAt = 999;
361+
cachedEntry.cleanupHandled = true;
362+
if (cachedEntry.requesterOrigin) {
363+
cachedEntry.requesterOrigin.accountId = "mutated-account";
364+
}
365+
if (cachedEntry.outcome) {
366+
cachedEntry.outcome.status = "error";
367+
}
368+
const second = loadSubagentRegistryFromDisk();
369+
370+
expect(second.get("run-cached")).toMatchObject({
371+
requesterOrigin: { accountId: "cached-account" },
372+
outcome: { status: "ok" },
373+
});
374+
expect(second.get("run-cached")?.endedAt).toBeUndefined();
375+
expect(second.get("run-cached")?.cleanupHandled).toBeUndefined();
376+
expect(
377+
readSpy.mock.calls.filter(([pathname]) => String(pathname) === registryPath),
378+
).toHaveLength(1);
379+
380+
await fs.writeFile(
381+
registryPath,
382+
`${JSON.stringify({
383+
version: 2,
384+
runs: {
385+
"run-updated": {
386+
runId: "run-updated",
387+
childSessionKey: "agent:main:subagent:updated",
388+
requesterSessionKey: "agent:main:main",
389+
requesterDisplayKey: "main",
390+
task: "updated persisted run with a longer payload",
391+
cleanup: "keep",
392+
createdAt: 2,
393+
startedAt: 2,
394+
},
395+
},
396+
})}\n`,
397+
"utf8",
398+
);
399+
400+
expect(loadSubagentRegistryFromDisk().has("run-updated")).toBe(true);
401+
expect(
402+
readSpy.mock.calls.filter(([pathname]) => String(pathname) === registryPath),
403+
).toHaveLength(2);
404+
});
405+
406+
it("reuses unchanged invalid persisted registry snapshots as empty", async () => {
407+
tempStateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-subagent-"));
408+
process.env.OPENCLAW_STATE_DIR = tempStateDir;
409+
const registryPath = path.join(tempStateDir, "subagents", "runs.json");
410+
await fs.mkdir(path.dirname(registryPath), { recursive: true });
411+
await fs.writeFile(registryPath, "{invalid", "utf8");
412+
const readSpy = vi.spyOn(fsSync, "readFileSync");
413+
414+
expect(loadSubagentRegistryFromDisk()).toEqual(new Map());
415+
expect(loadSubagentRegistryFromDisk()).toEqual(new Map());
416+
expect(
417+
readSpy.mock.calls.filter(([pathname]) => String(pathname) === registryPath),
418+
).toHaveLength(1);
419+
});
420+
331421
it("normalizes persisted and newly registered session keys to canonical trimmed values", async () => {
332422
const persisted = {
333423
version: 2,

‎src/agents/subagent-registry.store.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fs from "node:fs";
12
import os from "node:os";
23
import path from "node:path";
34
import { resolveStateDir } from "../config/paths.js";
@@ -21,16 +22,48 @@ type PersistedSubagentRegistryV2 = {
2122
type PersistedSubagentRegistry = PersistedSubagentRegistryV1 | PersistedSubagentRegistryV2;
2223

2324
const REGISTRY_VERSION = 2 as const;
25+
const MAX_SUBAGENT_REGISTRY_READ_CACHE_ENTRIES = 32;
2426

2527
type PersistedSubagentRunRecord = SubagentRunRecord;
2628

29+
type RegistryCacheEntry = {
30+
signature: string;
31+
runs: Map<string, SubagentRunRecord>;
32+
};
33+
2734
type LegacySubagentRunRecord = PersistedSubagentRunRecord & {
2835
announceCompletedAt?: unknown;
2936
announceHandled?: unknown;
3037
requesterChannel?: unknown;
3138
requesterAccountId?: unknown;
3239
};
3340

41+
const registryReadCache = new Map<string, RegistryCacheEntry>();
42+
43+
function cloneSubagentRunRecord(entry: SubagentRunRecord): SubagentRunRecord {
44+
return structuredClone(entry);
45+
}
46+
47+
function cloneSubagentRunMap(runs: Map<string, SubagentRunRecord>): Map<string, SubagentRunRecord> {
48+
return new Map([...runs].map(([runId, entry]) => [runId, cloneSubagentRunRecord(entry)]));
49+
}
50+
51+
function setCachedRegistryRead(
52+
pathname: string,
53+
signature: string,
54+
runs: Map<string, SubagentRunRecord>,
55+
): void {
56+
registryReadCache.delete(pathname);
57+
registryReadCache.set(pathname, { signature, runs: cloneSubagentRunMap(runs) });
58+
if (registryReadCache.size <= MAX_SUBAGENT_REGISTRY_READ_CACHE_ENTRIES) {
59+
return;
60+
}
61+
const oldestKey = registryReadCache.keys().next().value;
62+
if (typeof oldestKey === "string") {
63+
registryReadCache.delete(oldestKey);
64+
}
65+
}
66+
3467
function resolveSubagentStateDir(env: NodeJS.ProcessEnv = process.env): string {
3568
const explicit = env.OPENCLAW_STATE_DIR?.trim();
3669
if (explicit) {
@@ -48,16 +81,30 @@ export function resolveSubagentRegistryPath(): string {
4881

4982
export function loadSubagentRegistryFromDisk(): Map<string, SubagentRunRecord> {
5083
const pathname = resolveSubagentRegistryPath();
84+
const signature = statRegistryFileSignature(pathname);
85+
if (signature === null) {
86+
registryReadCache.delete(pathname);
87+
return new Map();
88+
}
89+
const cached = registryReadCache.get(pathname);
90+
if (cached?.signature === signature) {
91+
registryReadCache.delete(pathname);
92+
registryReadCache.set(pathname, cached);
93+
return cloneSubagentRunMap(cached.runs);
94+
}
5195
const raw = loadJsonFile(pathname);
5296
if (!raw || typeof raw !== "object") {
97+
setCachedRegistryRead(pathname, signature, new Map());
5398
return new Map();
5499
}
55100
const record = raw as Partial<PersistedSubagentRegistry>;
56101
if (record.version !== 1 && record.version !== 2) {
102+
setCachedRegistryRead(pathname, signature, new Map());
57103
return new Map();
58104
}
59105
const runsRaw = record.runs;
60106
if (!runsRaw || typeof runsRaw !== "object") {
107+
setCachedRegistryRead(pathname, signature, new Map());
61108
return new Map();
62109
}
63110
const out = new Map<string, SubagentRunRecord>();
@@ -123,6 +170,8 @@ export function loadSubagentRegistryFromDisk(): Map<string, SubagentRunRecord> {
123170
} catch {
124171
// ignore migration write failures
125172
}
173+
} else {
174+
setCachedRegistryRead(pathname, signature, out);
126175
}
127176
return out;
128177
}
@@ -138,4 +187,25 @@ export function saveSubagentRegistryToDisk(runs: Map<string, SubagentRunRecord>)
138187
runs: serialized,
139188
};
140189
saveJsonFile(pathname, out);
190+
const signature = statRegistryFileSignature(pathname);
191+
if (signature === null) {
192+
registryReadCache.delete(pathname);
193+
} else {
194+
setCachedRegistryRead(pathname, signature, runs);
195+
}
196+
}
197+
198+
function statRegistryFileSignature(pathname: string): string | null {
199+
try {
200+
const stat = fs.statSync(pathname, { bigint: true });
201+
if (!stat.isFile()) {
202+
return null;
203+
}
204+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
205+
} catch (error) {
206+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
207+
return null;
208+
}
209+
throw error;
210+
}
141211
}

0 commit comments

Comments
 (0)