Skip to content

Commit 3cc5558

Browse files
authored
fix(agents): stop silent compaction failures (#125302)
* fix(agents): stop silent compaction failures * fix(agents): preserve aborted compaction outcomes * fix(agents): preserve manual abort outcomes
1 parent 04c9924 commit 3cc5558

21 files changed

Lines changed: 697 additions & 357 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1913,7 +1913,6 @@ src/agents/embedded-agent-runner/tool-result-context-guard.ts 13
19131913
src/agents/embedded-agent-runner/tool-result-truncation.ts 23
19141914
src/agents/embedded-agent-runner/tool-schema-runtime.ts 1
19151915
src/agents/embedded-agent-runner/transcript-rewrite.ts 2
1916-
src/agents/embedded-agent-subscribe.handlers.compaction.ts 1
19171916
src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts 6
19181917
src/agents/embedded-agent-subscribe.handlers.messages.stream.ts 6
19191918
src/agents/embedded-agent-subscribe.handlers.messages.update.ts 6

‎packages/agent-core/src/harness/compaction/compaction.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
CHARS_PER_TOKEN_ESTIMATE,
1111
estimateStringChars,
1212
} from "@openclaw/normalization-core/cjk-chars";
13+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1314
import { resolveAgentReasoningOption } from "../../reasoning.js";
1415
import {
1516
type AgentCoreCompletionRuntimeDeps,
@@ -85,6 +86,22 @@ export interface CompactionResult<T = unknown> {
8586
details?: T;
8687
}
8788

89+
// Persisted summaries replay on every later request, so their owner enforces
90+
// this provider-independent 16K hard bound.
91+
export const MAX_COMPACTION_SUMMARY_CHARS = 16_000;
92+
export const SUMMARY_TRUNCATED_MARKER = "\n\n[Compaction summary truncated to fit budget]";
93+
94+
export function capCompactionSummary(summary: string, maxChars = MAX_COMPACTION_SUMMARY_CHARS) {
95+
if (maxChars <= 0 || summary.length <= maxChars) {
96+
return summary;
97+
}
98+
if (maxChars < SUMMARY_TRUNCATED_MARKER.length) {
99+
return truncateUtf16Safe(summary, maxChars);
100+
}
101+
const budget = maxChars - SUMMARY_TRUNCATED_MARKER.length;
102+
return `${truncateUtf16Safe(summary, budget)}${SUMMARY_TRUNCATED_MARKER}`;
103+
}
104+
88105
/** Compaction thresholds and retention settings. */
89106
export interface CompactionSettings {
90107
/** Enable automatic compaction decisions. */

‎src/agents/agent-hooks/compaction-safeguard.ts‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ import path from "node:path";
66
import { parseDateFirstTimestampMs } from "@openclaw/normalization-core/number-coercion";
77
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
88
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
9+
import {
10+
capCompactionSummary,
11+
MAX_COMPACTION_SUMMARY_CHARS,
12+
SUMMARY_TRUNCATED_MARKER,
13+
} from "../../../packages/agent-core/src/harness/compaction/compaction.js";
914
import {
1015
computeFileLists,
1116
formatFileOperations,
@@ -74,8 +79,6 @@ const TURN_PREFIX_INSTRUCTIONS =
7479
" early progress, and any details needed to understand the retained suffix.";
7580
const MAX_TOOL_FAILURES = 8;
7681
const MAX_TOOL_FAILURE_CHARS = 240;
77-
const MAX_COMPACTION_SUMMARY_CHARS = 16_000;
78-
const SUMMARY_TRUNCATED_MARKER = "\n\n[Compaction summary truncated to fit budget]";
7982
const CONTEXT_TRUNCATED_MARKER = "\n\n[Earlier compaction context truncated to fit budget]\n\n";
8083
// Split-turn context supplements the generated summary and must not claim its
8184
// guaranteed half of the final artifact before common finalization runs.
@@ -561,19 +564,6 @@ function formatToolFailuresSection(failures: ToolFailure[]): string {
561564
return `\n\n## Tool Failures\n${lines.join("\n")}`;
562565
}
563566

564-
function capCompactionSummary(summary: string, maxChars = MAX_COMPACTION_SUMMARY_CHARS): string {
565-
if (maxChars <= 0 || summary.length <= maxChars) {
566-
return summary;
567-
}
568-
const marker = SUMMARY_TRUNCATED_MARKER;
569-
if (maxChars < marker.length) {
570-
// Marker cannot fit; keep body prefix instead of a partial marker fragment.
571-
return truncateUtf16Safe(summary, maxChars);
572-
}
573-
const budget = maxChars - marker.length;
574-
return `${truncateUtf16Safe(summary, budget)}${marker}`;
575-
}
576-
577567
function normalizeCompactionSuffix(suffix: string | CompactionSuffix): CompactionSuffix {
578568
return typeof suffix === "string" ? { text: suffix, contextRanges: [] } : suffix;
579569
}

‎src/agents/embedded-agent-runner/compact-reasons.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ describe("resolveCompactionFailureReason", () => {
3333
});
3434

3535
describe("classifyCompactionReason", () => {
36+
it.each([
37+
'No API key found for "anthropic".',
38+
"Authentication failed for \"anthropic\". Credentials may have expired or network is unavailable. Run '/login anthropic' to re-authenticate.",
39+
])("classifies known authentication guidance as auth_failed: %s", (reason) => {
40+
expect(classifyCompactionReason(reason)).toBe("auth_failed");
41+
});
42+
3643
it('classifies "nothing to compact" as a skip-like reason', () => {
3744
expect(classifyCompactionReason("Nothing to compact (session too small)")).toBe(
3845
"no_compactable_entries",

‎src/agents/embedded-agent-runner/compact-reasons.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ export function classifyCompactionReason(reason?: string): string {
3434
if (!text) {
3535
return "unknown";
3636
}
37+
if (
38+
text.startsWith("no api key found") ||
39+
(text.startsWith("authentication failed for ") && text.includes("credentials may have expired"))
40+
) {
41+
return "auth_failed";
42+
}
3743
if (text.includes("nothing to compact") || text.includes("no real conversation messages")) {
3844
return "no_compactable_entries";
3945
}

‎src/agents/embedded-agent-subscribe.handlers.compaction.test.ts‎

Lines changed: 52 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ function createCompactionContext(params: {
2424
agentId?: string;
2525
initialCount: number;
2626
info?: (message: string, meta?: Record<string, unknown>) => void;
27+
warn?: (message: string, meta?: Record<string, unknown>) => void;
2728
messages?: AgentMessage[];
2829
}): EmbeddedAgentSubscribeContext {
2930
// Minimal context preserves only the compaction counters and callbacks the
@@ -46,7 +47,7 @@ function createCompactionContext(params: {
4647
log: {
4748
debug: vi.fn(),
4849
info: params.info ?? vi.fn(),
49-
warn: vi.fn(),
50+
warn: params.warn ?? vi.fn(),
5051
},
5152
ensureCompactionPromise: vi.fn(),
5253
noteCompactionRetry: vi.fn(),
@@ -102,14 +103,15 @@ function makeCompactionSummaryMessage(timestamp?: number): AgentMessage {
102103
} as AgentMessage;
103104
}
104105

105-
function finishCompaction(ctx: EmbeddedAgentSubscribeContext): void {
106-
handleCompactionEnd(ctx, {
106+
const completedCompactionEnd = () =>
107+
({
107108
type: "compaction_end",
108109
reason: "threshold",
109-
result: { kept: 12 },
110-
willRetry: false,
111-
aborted: false,
112-
});
110+
outcome: { status: "completed", tokensBefore: 100, tokensAfter: 50, willRetry: false },
111+
}) as const;
112+
113+
function finishCompaction(ctx: EmbeddedAgentSubscribeContext): void {
114+
handleCompactionEnd(ctx, completedCompactionEnd());
113115
}
114116

115117
function loggedInfoMetaAt(info: ReturnType<typeof vi.fn>, index: number): Record<string, unknown> {
@@ -199,13 +201,7 @@ describe("compaction lifecycle logging", () => {
199201
type: "compaction_start",
200202
reason: "threshold",
201203
});
202-
handleCompactionEnd(ctx, {
203-
type: "compaction_end",
204-
reason: "threshold",
205-
result: { kept: 12 },
206-
willRetry: false,
207-
aborted: false,
208-
});
204+
handleCompactionEnd(ctx, completedCompactionEnd());
209205

210206
expect(loggedInfoMessageAt(info, 0)).toBe("embedded run auto-compaction start");
211207
const startMeta = loggedInfoMetaAt(info, 0);
@@ -228,7 +224,7 @@ describe("compaction lifecycle logging", () => {
228224
);
229225
});
230226

231-
it("logs manual compaction as incomplete when no result is produced", async () => {
227+
it("logs a benign manual skip at info", async () => {
232228
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-compaction-incomplete-log-"));
233229
const storePath = path.join(tmp, "sessions.json");
234230
const sessionKey = "main";
@@ -252,9 +248,7 @@ describe("compaction lifecycle logging", () => {
252248
handleCompactionEnd(ctx, {
253249
type: "compaction_end",
254250
reason: "manual",
255-
result: undefined,
256-
willRetry: false,
257-
aborted: false,
251+
outcome: { status: "skipped", reason: "Nothing to compact (session too small)" },
258252
});
259253

260254
expect(loggedInfoMessageAt(info, 0)).toBe("embedded run manual compaction start");
@@ -266,19 +260,49 @@ describe("compaction lifecycle logging", () => {
266260
"embedded run manual compaction start: runId=run-test reason=manual",
267261
);
268262

269-
expect(loggedInfoMessageAt(info, 1)).toBe("embedded run manual compaction incomplete");
263+
expect(loggedInfoMessageAt(info, 1)).toBe("embedded run manual compaction skipped");
270264
const endMeta = loggedInfoMetaAt(info, 1);
271265
expect(endMeta.event).toBe("embedded_run_compaction_end");
272266
expect(endMeta.reason).toBe("manual");
267+
expect(endMeta.outcome).toBe("skipped");
273268
expect(endMeta.runId).toBe("run-test");
274269
expect(endMeta.completed).toBe(false);
275-
expect(endMeta.aborted).toBe(false);
270+
expect(endMeta.reasonClass).toBe("no_compactable_entries");
276271
expect(endMeta.consoleMessage).toBe(
277-
"embedded run manual compaction incomplete: runId=run-test reason=manual aborted=false willRetry=false",
272+
"embedded run manual compaction skipped: runId=run-test reason=no_compactable_entries",
278273
);
279274
});
280275

281-
it("defaults legacy synthetic compaction events to threshold logs", async () => {
276+
it("warns with classified, bounded metadata for failed compaction", () => {
277+
const warn = vi.fn();
278+
const ctx = createCompactionContext({
279+
storePath: path.join(os.tmpdir(), "openclaw-compaction-failed-log", "sessions.json"),
280+
sessionKey: "main",
281+
initialCount: 0,
282+
warn,
283+
});
284+
const reason = `Provider unavailable: ${"provider detail ".repeat(100)}`;
285+
286+
handleCompactionEnd(ctx, {
287+
type: "compaction_end",
288+
reason: "overflow",
289+
outcome: { status: "failed", reason },
290+
});
291+
292+
expect(warn).toHaveBeenCalledOnce();
293+
const metadata = loggedInfoMetaAt(warn, 0);
294+
expect(metadata).toMatchObject({
295+
event: "embedded_run_compaction_end",
296+
reason: "overflow",
297+
outcome: "failed",
298+
reasonClass: "unknown",
299+
outcomeReason: reason,
300+
});
301+
expect(String(metadata.reasonDetail)).toHaveLength(100);
302+
expect(String(metadata.consoleMessage)).not.toContain("provider detail provider detail");
303+
});
304+
305+
it("defaults an unknown synthetic compaction start to threshold logs", async () => {
282306
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-compaction-legacy-log-"));
283307
const storePath = path.join(tmp, "sessions.json");
284308
const sessionKey = "main";
@@ -298,12 +322,7 @@ describe("compaction lifecycle logging", () => {
298322
handleCompactionStart(ctx, {
299323
type: "compaction_start",
300324
});
301-
handleCompactionEnd(ctx, {
302-
type: "compaction_end",
303-
result: { kept: 12 },
304-
willRetry: false,
305-
aborted: false,
306-
});
325+
handleCompactionEnd(ctx, completedCompactionEnd());
307326

308327
expect(loggedInfoMessageAt(info, 0)).toBe("embedded run auto-compaction start");
309328
const startMeta = loggedInfoMetaAt(info, 0);
@@ -344,13 +363,7 @@ describe("handleCompactionEnd", () => {
344363
initialCount: 1,
345364
});
346365

347-
handleCompactionEnd(ctx, {
348-
type: "compaction_end",
349-
reason: "threshold",
350-
result: { kept: 12 },
351-
willRetry: false,
352-
aborted: false,
353-
});
366+
handleCompactionEnd(ctx, completedCompactionEnd());
354367

355368
await waitForCompactionCount({
356369
storePath,
@@ -359,7 +372,7 @@ describe("handleCompactionEnd", () => {
359372
});
360373

361374
expect(await readCompactionCount(storePath, sessionKey)).toBe(2);
362-
expect(ctx.noteCompactionTokensAfter).toHaveBeenCalledWith(undefined);
375+
expect(ctx.noteCompactionTokensAfter).toHaveBeenCalledWith(50);
363376
});
364377

365378
it("clears stale assistant usage before compaction and preserves fresh usage after it", async () => {
@@ -401,8 +414,8 @@ describe("handleCompactionEnd", () => {
401414
// A failed/aborted end never rewrote history; zeroing usage here would
402415
// disable the persistent-error compaction trigger for degraded sessions.
403416
const failureEnds = [
404-
{ name: "failed", result: undefined, aborted: false },
405-
{ name: "aborted", result: { kept: 12 }, aborted: true },
417+
{ name: "failed", outcome: { status: "failed", reason: "summary failed" } },
418+
{ name: "aborted", outcome: { status: "aborted" } },
406419
] as const;
407420
for (const failure of failureEnds) {
408421
const liveUsage = makeUsageSnapshot(123_000);
@@ -425,9 +438,7 @@ describe("handleCompactionEnd", () => {
425438
handleCompactionEnd(ctx, {
426439
type: "compaction_end",
427440
reason: "threshold",
428-
result: failure.result,
429-
willRetry: false,
430-
aborted: failure.aborted,
441+
outcome: failure.outcome,
431442
});
432443

433444
const liveAssistant = messages[0] as Extract<AgentMessage, { role: "assistant" }>;

0 commit comments

Comments
 (0)