Skip to content

Commit b537775

Browse files
RileyJJYsteipete
andauthored
fix(agents): cap aggregate pressure warning dedupe cache with LRU eviction (#108667)
* fix(agents): cap aggregate pressure warning dedupe cache with LRU eviction * fix(agents): bound tool-result warning dedupe * fix(agents): keep warning cache limit internal --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 81e626a commit b537775

4 files changed

Lines changed: 68 additions & 7 deletions

File tree

‎src/agents/embedded-agent-runner/run/attempt-prompt-context.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { EmbeddedRunAttemptParams } from "./types.js";
66

77
const hoisted = vi.hoisted(() => ({
88
info: vi.fn(),
9+
promptPressureKeys: new Set<string>(),
910
resolveLiveToolResultAggregateMaxChars: vi.fn(() => 200),
1011
resolveLiveToolResultMaxChars: vi.fn(() => 100),
1112
truncateOversizedToolResultsInMessages: vi.fn(),
@@ -18,6 +19,17 @@ vi.mock("../logger.js", () => ({
1819
vi.mock("../tool-result-truncation.js", () => ({
1920
resolveLiveToolResultAggregateMaxChars: hoisted.resolveLiveToolResultAggregateMaxChars,
2021
resolveLiveToolResultMaxChars: hoisted.resolveLiveToolResultMaxChars,
22+
toolResultWarningDedupe: {
23+
promptPressure: {
24+
check: (key: string) => {
25+
if (hoisted.promptPressureKeys.has(key)) {
26+
return true;
27+
}
28+
hoisted.promptPressureKeys.add(key);
29+
return false;
30+
},
31+
},
32+
},
2133
truncateOversizedToolResultsInMessages: hoisted.truncateOversizedToolResultsInMessages,
2234
}));
2335

@@ -101,6 +113,7 @@ function createInput(options?: {
101113

102114
beforeEach(() => {
103115
vi.clearAllMocks();
116+
hoisted.promptPressureKeys.clear();
104117
hoisted.truncateOversizedToolResultsInMessages.mockImplementation((inputMessages) => ({
105118
messages: inputMessages,
106119
truncatedCount: 0,
@@ -180,6 +193,24 @@ describe("prepareEmbeddedAttemptPromptContext", () => {
180193
);
181194
});
182195

196+
it("deduplicates aggregate pressure warnings per session key", () => {
197+
hoisted.truncateOversizedToolResultsInMessages.mockImplementation((inputMessages) => ({
198+
messages: [...inputMessages],
199+
truncatedCount: 1,
200+
aggregateTruncatedCount: 1,
201+
aggregatePressureEngaged: true,
202+
aggregateBudgetChars: 200,
203+
}));
204+
const attempt = createAttempt({ sessionId: "dup-session", sessionKey: "dup-session" });
205+
206+
prepareEmbeddedAttemptPromptContext(createInput({ attempt }).input);
207+
expect(hoisted.warn).toHaveBeenCalledTimes(1);
208+
hoisted.warn.mockClear();
209+
210+
prepareEmbeddedAttemptPromptContext(createInput({ attempt }).input);
211+
expect(hoisted.warn).not.toHaveBeenCalled();
212+
});
213+
183214
it("moves runtime-only context into the active system prompt", () => {
184215
const fixture = createInput({
185216
attempt: createAttempt({

‎src/agents/embedded-agent-runner/run/attempt-prompt-context.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import {
1515
resolveLiveToolResultAggregateMaxChars,
1616
resolveLiveToolResultMaxChars,
17+
toolResultWarningDedupe,
1718
truncateOversizedToolResultsInMessages,
1819
} from "../tool-result-truncation.js";
1920
import {
@@ -29,8 +30,6 @@ import {
2930
} from "./runtime-context-prompt.js";
3031
import type { EmbeddedRunAttemptParams } from "./types.js";
3132

32-
const aggregateToolResultPressureWarnings = new Set<string>();
33-
3433
type PromptContextAttempt = Pick<
3534
EmbeddedRunAttemptParams,
3635
| "config"
@@ -139,8 +138,7 @@ export function prepareEmbeddedAttemptPromptContext(input: {
139138
`aggregate=${promptToolResultTruncation.aggregateTruncatedCount}) ` +
140139
`sessionKey=${sessionLogKey}`;
141140
if (aggregatePressureEngaged) {
142-
if (!aggregateToolResultPressureWarnings.has(sessionLogKey)) {
143-
aggregateToolResultPressureWarnings.add(sessionLogKey);
141+
if (!toolResultWarningDedupe.promptPressure.check(sessionLogKey)) {
144142
log.warn(
145143
`${truncationLog}; aggregate tool-result pressure detected, compaction has been requested; consider /compact or /new if pressure persists`,
146144
);

‎src/agents/embedded-agent-runner/tool-result-truncation.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ let estimateToolResultReductionPotential: typeof import("./tool-result-truncatio
3737
let DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS: typeof import("./tool-result-truncation.js").DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS;
3838
let resolveLiveToolResultMaxChars: typeof import("./tool-result-truncation.js").resolveLiveToolResultMaxChars;
3939
let resolveLiveToolResultAggregateMaxChars: typeof import("./tool-result-truncation.js").resolveLiveToolResultAggregateMaxChars;
40+
let toolResultWarningDedupe: typeof import("./tool-result-truncation.js").toolResultWarningDedupe;
4041
let tmpDir: string | undefined;
4142

4243
async function loadFreshToolResultTruncationModuleForTest() {
@@ -53,6 +54,7 @@ async function loadFreshToolResultTruncationModuleForTest() {
5354
DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS,
5455
resolveLiveToolResultMaxChars,
5556
resolveLiveToolResultAggregateMaxChars,
57+
toolResultWarningDedupe,
5658
} = await import("./tool-result-truncation.js"));
5759
}
5860

@@ -74,6 +76,8 @@ beforeEach(async () => {
7476
});
7577

7678
afterEach(async () => {
79+
toolResultWarningDedupe.promptPressure.clear();
80+
toolResultWarningDedupe.sessionRecovery.clear();
7781
clearEmbeddedSessionPromptStates(["session-99495", "session-99495-shrink"]);
7882
if (tmpDir) {
7983
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
@@ -95,6 +99,28 @@ function makeToolResult(text: string, toolCallId = "call_1", details?: unknown):
9599
};
96100
}
97101

102+
describe("tool-result warning dedupe", () => {
103+
const warningDedupeLimit = 1_024;
104+
105+
it.each([
106+
["prompt pressure", () => toolResultWarningDedupe.promptPressure],
107+
["session recovery", () => toolResultWarningDedupe.sessionRecovery],
108+
])("bounds and evicts the oldest %s warning keys", (_name, getCache) => {
109+
const cache = getCache();
110+
111+
for (let index = 0; index <= warningDedupeLimit; index += 1) {
112+
expect(cache.check(`session-${index}`)).toBe(false);
113+
}
114+
115+
expect(cache.size()).toBe(warningDedupeLimit);
116+
expect(cache.peek("session-0")).toBe(false);
117+
expect(cache.peek("session-1")).toBe(true);
118+
expect(cache.peek(`session-${warningDedupeLimit}`)).toBe(true);
119+
expect(cache.check("session-0")).toBe(false);
120+
expect(cache.check(`session-${warningDedupeLimit}`)).toBe(true);
121+
});
122+
});
123+
98124
function textWithFullOutputFooter(text: string, fullOutputPath: string): string {
99125
return `${text}\n\n[Showing truncated output. ${formatFullOutputFooter(fullOutputPath)}]`;
100126
}

‎src/agents/embedded-agent-runner/tool-result-truncation.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/
88
import { loadTranscriptEvents } from "../../config/sessions/session-accessor.js";
99
import { parseSqliteSessionFileMarker } from "../../config/sessions/sqlite-marker.js";
1010
import type { OpenClawConfig } from "../../config/types.openclaw.js";
11+
import { createDedupeCache } from "../../infra/dedupe.js";
1112
import { formatErrorMessage } from "../../infra/errors.js";
1213
import type { TextContent } from "../../llm/types.js";
1314
import { emitSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
@@ -68,7 +69,13 @@ const AGGREGATE_TOOL_RESULT_CONTEXT_SHARE = 0.5;
6869
*/
6970
const MIN_KEEP_CHARS = 2_000;
7071
const RECOVERY_MIN_KEEP_CHARS = 0;
71-
const aggregateToolResultRecoveryWarnings = new Set<string>();
72+
const TOOL_RESULT_WARNING_DEDUPE_LIMIT = 1_024;
73+
// Both warning paths live for the process lifetime. Keep their dedupe state
74+
// independently bounded so one hot path cannot evict the other's sessions.
75+
export const toolResultWarningDedupe = {
76+
promptPressure: createDedupeCache({ ttlMs: 0, maxSize: TOOL_RESULT_WARNING_DEDUPE_LIMIT }),
77+
sessionRecovery: createDedupeCache({ ttlMs: 0, maxSize: TOOL_RESULT_WARNING_DEDUPE_LIMIT }),
78+
};
7279

7380
type ToolResultTruncationOptions = {
7481
suffix?: string | ((truncatedChars: number) => string);
@@ -103,11 +110,10 @@ function logToolResultSessionTruncation(params: {
103110
log.info(message);
104111
return;
105112
}
106-
if (aggregateToolResultRecoveryWarnings.has(sessionLogKey)) {
113+
if (toolResultWarningDedupe.sessionRecovery.check(sessionLogKey)) {
107114
log.info(message);
108115
return;
109116
}
110-
aggregateToolResultRecoveryWarnings.add(sessionLogKey);
111117
log.warn(
112118
`${message}; aggregate tool-result pressure detected; consider /compact or /new if pressure persists`,
113119
);

0 commit comments

Comments
 (0)