Skip to content

Commit 9ec0cbe

Browse files
fix: every agent attempt re-hashes unchanged tool descriptions because the report digest cache can never hit (#129145)
* fix(agents): key the per-tool report digest cache on content instead of tool identity toolReportEntryCache is a WeakMap keyed on the AgentTool object, but finalizeAgentTools rebuilds every tool on every attempt (normalizeToolParameters returns a {...tool} copy, then three more wrapper .map passes), so the cache misses 100% of the time and buildSystemPromptReport re-runs one sha256 per tool per attempt over an unchanged description. Add a bounded content-keyed layer for the summary digest, keyed on the exact string hashed, so it survives the tool-object churn. Byte-identical by construction. Schema stats deliberately stay on toolSchemaStatsCache so a tool reusing a name and description with different parameters still reports its own schemaHash. * fix: bound the bytes retained by the tool summary digest cache The 512-entry limit bounded cardinality only. Keys are the summary text, so a sequence of large runtime-generated descriptions could pin megabytes for the process lifetime. Summaries over the length cap still hash, they just never enter the cache. * test(ci): load cancellation identity helpers through tsx Keep plain-Node fixture actors lightweight while resolving the canonical identity helper and its transitive TypeScript imports for cleanup cancellation. Preserve real process ownership and existing deadlines. --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Tran Quang <[email protected]>
1 parent e93f4b3 commit 9ec0cbe

2 files changed

Lines changed: 133 additions & 8 deletions

File tree

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { Type } from "typebox";
2+
import { describe, expect, it, vi } from "vitest";
3+
import { finalizeAgentTools } from "./agent-tools.finalize.js";
4+
import {
5+
createCodeModeExecDescriptionUpdater,
6+
markCodeModeControlTool,
7+
} from "./code-mode-control-tools.js";
8+
import type { AgentTool } from "./runtime/index.js";
9+
10+
const { createHashCalls } = vi.hoisted(() => ({ createHashCalls: { count: 0 } }));
11+
12+
vi.mock("node:crypto", async () => {
13+
const actual = await vi.importActual<typeof import("node:crypto")>("node:crypto");
14+
return {
15+
...actual,
16+
createHash: (...args: Parameters<typeof actual.createHash>) => {
17+
createHashCalls.count += 1;
18+
return actual.createHash(...args);
19+
},
20+
};
21+
});
22+
23+
const { buildSystemPromptReport } = await import("./system-prompt-report.js");
24+
25+
function makeTool(name: string, description: string): AgentTool {
26+
return {
27+
name,
28+
label: name,
29+
description,
30+
parameters: Type.Object({ path: Type.String() }),
31+
execute: async () => ({ content: [], details: {} }),
32+
};
33+
}
34+
35+
function finalize(tools: AgentTool[]) {
36+
return finalizeAgentTools({ tools, hookContext: {}, wrapBeforeToolCallHook: false });
37+
}
38+
39+
function buildReport(tools: AgentTool[]) {
40+
return buildSystemPromptReport({
41+
source: "run",
42+
generatedAt: 0,
43+
bootstrapMaxChars: 20_000,
44+
systemPrompt: "Tool digest cache probe",
45+
injectedWorkspaceFiles: [],
46+
skillsPrompt: "",
47+
tools,
48+
});
49+
}
50+
51+
describe("tool summary digest cache", () => {
52+
it("reuses unchanged digests across real tool finalization without changing the report", () => {
53+
const definitions = ["read", "search", "shell"].map((name) =>
54+
makeTool(`probe_${name}`, `Digest probe: ${name}`),
55+
);
56+
const firstTools = finalize(definitions);
57+
createHashCalls.count = 0;
58+
const first = buildReport(firstTools);
59+
expect(createHashCalls.count).toBe(8);
60+
61+
const secondTools = finalize(definitions);
62+
for (const [index, tool] of secondTools.entries()) {
63+
expect(tool).not.toBe(firstTools[index]);
64+
expect(tool.parameters).toBe(firstTools[index]?.parameters);
65+
}
66+
createHashCalls.count = 0;
67+
const second = buildReport(secondTools);
68+
69+
expect(createHashCalls.count).toBe(2);
70+
expect(second).toEqual(first);
71+
});
72+
73+
it("reports current Code Mode descriptions on retained finalized wrappers", () => {
74+
const definition = markCodeModeControlTool(makeTool("exec", "Initial catalog probe"));
75+
const updater = createCodeModeExecDescriptionUpdater(definition);
76+
try {
77+
const tools = finalize([definition]);
78+
const first = buildReport(tools).tools.entries[0];
79+
updater.update("Updated catalog probe with another capability");
80+
const second = buildReport(tools).tools.entries[0];
81+
82+
expect(second?.summaryChars).toBe(definition.description.length);
83+
expect(second?.summaryHash).not.toBe(first?.summaryHash);
84+
expect(second?.schemaHash).toBe(first?.schemaHash);
85+
expect(second).toEqual(buildReport(finalize([definition])).tools.entries[0]);
86+
} finally {
87+
updater.dispose();
88+
}
89+
});
90+
91+
it("keeps schema statistics independent of identical names and summaries", () => {
92+
const tool = makeTool("schema_probe", "Shared schema probe summary");
93+
const first = buildReport([tool]).tools.entries[0];
94+
tool.parameters = Type.Object({ path: Type.String(), limit: Type.Integer() });
95+
const second = buildReport([tool]).tools.entries[0];
96+
97+
expect(second?.summaryHash).toBe(first?.summaryHash);
98+
expect(second?.schemaHash).not.toBe(first?.schemaHash);
99+
expect(second?.propertiesCount).toBe(2);
100+
});
101+
102+
it("does not retain oversized summary keys", () => {
103+
const definition = makeTool("oversized_probe", `Oversized probe ${"x".repeat(5_000)}`);
104+
const first = buildReport(finalize([definition]));
105+
const tools = finalize([definition]);
106+
createHashCalls.count = 0;
107+
const second = buildReport(tools);
108+
109+
expect(createHashCalls.count).toBe(3);
110+
expect(second).toEqual(first);
111+
});
112+
});

‎src/agents/system-prompt-report.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,17 @@
66
*/
77
import { createHash } from "node:crypto";
88
import type { SessionSystemPromptReport } from "../config/sessions/types.js";
9+
import { pruneMapToMaxSize } from "../infra/map-size.js";
910
import type { BootstrapInjectionStat } from "./bootstrap-budget.types.js";
1011
import type { AgentTool } from "./runtime/index.js";
1112

1213
type ToolReportEntry = SessionSystemPromptReport["tools"]["entries"][number];
1314

14-
const toolReportEntryCache = new WeakMap<AgentTool, ToolReportEntry>();
15+
// Finalization rebuilds tool objects, while Code Mode updates retained descriptions.
16+
// Cache only the summary digest, with bounded key size and entry count.
17+
const toolSummaryHashCache = new Map<string, string>();
18+
const MAX_TOOL_SUMMARY_HASHES = 512;
19+
const MAX_CACHED_TOOL_SUMMARY_CHARS = 4_096;
1520
const toolSchemaStatsCache = new WeakMap<
1621
object,
1722
Pick<ToolReportEntry, "propertiesCount" | "schemaChars" | "schemaHash">
@@ -80,19 +85,27 @@ function buildToolSchemaStats(
8085
return stats;
8186
}
8287

88+
function resolveSummaryHash(summary: string): string {
89+
if (summary.length > MAX_CACHED_TOOL_SUMMARY_CHARS) {
90+
return sha256(summary);
91+
}
92+
const cached = toolSummaryHashCache.get(summary);
93+
if (cached !== undefined) {
94+
return cached;
95+
}
96+
const hash = sha256(summary);
97+
toolSummaryHashCache.set(summary, hash);
98+
pruneMapToMaxSize(toolSummaryHashCache, MAX_TOOL_SUMMARY_HASHES);
99+
return hash;
100+
}
101+
83102
function buildToolsEntries(tools: AgentTool[]): SessionSystemPromptReport["tools"]["entries"] {
84103
return tools.map((tool) => {
85-
const cached = toolReportEntryCache.get(tool);
86-
if (cached) {
87-
return cached;
88-
}
89104
const name = tool.name;
90105
const summary = tool.description?.trim() || tool.label?.trim() || "";
91106
const summaryChars = summary.length;
92107
const schemaStats = buildToolSchemaStats(tool.parameters);
93-
const entry = { name, summaryChars, summaryHash: sha256(summary), ...schemaStats };
94-
toolReportEntryCache.set(tool, entry);
95-
return entry;
108+
return { name, summaryChars, summaryHash: resolveSummaryHash(summary), ...schemaStats };
96109
});
97110
}
98111

0 commit comments

Comments
 (0)