Skip to content

Commit 6d460a4

Browse files
committed
fix(agents): cap compaction budgets for small contexts
1 parent 5ee3e5d commit 6d460a4

9 files changed

Lines changed: 123 additions & 38 deletions
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
f4a00ada9d154a4d3a54e109aa6e9f73f22b09d7df9ab6745e87f88724eec06b config-baseline.json
2-
5ee177382cf32c2816dca0a4e67cd6c01df1045d600b21a6e9c11639ddb10ce8 config-baseline.core.json
3-
0e654bad3f1ef9100f76e512c4453c1f26b6bc1f5ee121ce505d0624a1dad4cd config-baseline.channel.json
4-
e6a1d6f51f0d9c04bd92d51deebfaca8c7917dd28d7998d225c0074e0a095348 config-baseline.plugin.json
1+
8f33d8e21daa30d74977f3e586bc0113eb90bd165629fb8ea7d54484508f35a6 config-baseline.json
2+
18f148db6267582e46fcef54420c62b4e219b2e17ce4bcf964102f80381ca6be config-baseline.core.json
3+
cbf81829dcc8cfd0a16435912da709f8c1d508707385b6493f94cafe211ec67c config-baseline.channel.json
4+
4012b1f8de6f9527c47320a6c7120f30dc30ac1b5524ed63dadef890aad44b20 config-baseline.plugin.json

‎docs/gateway/config-agents.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,9 @@ Periodic heartbeat runs.
662662
- `mode`: `default` or `safeguard` (chunked summarization for long histories). See [Compaction](/concepts/compaction).
663663
- `provider`: id of a registered compaction provider plugin. When set, the provider's `summarize()` is called instead of built-in LLM summarization. Falls back to built-in on failure. Setting a provider forces `mode: "safeguard"`. See [Compaction](/concepts/compaction).
664664
- `timeoutSeconds`: maximum seconds allowed for a single compaction operation before OpenClaw aborts it. Default: `900`.
665-
- `keepRecentTokens`: agent cut-point budget for keeping the most recent transcript tail verbatim. Manual `/compact` honors this when explicitly set; otherwise manual compaction is a hard checkpoint.
665+
- `reserveTokens`: token headroom kept available for the model response and future tool output after compaction. When the active model context window is known, OpenClaw caps impossible reserve values so smaller local models still keep usable prompt budget.
666+
- `reserveTokensFloor`: minimum reserve enforced by the embedded runtime. Set `0` to disable the floor. The floor is also capped against the active model context window when that window is known.
667+
- `keepRecentTokens`: agent cut-point budget for keeping the most recent transcript tail verbatim. Manual `/compact` honors this when explicitly set; otherwise manual compaction is a hard checkpoint. When the active model context window is known, OpenClaw caps impossible values to the prompt budget left after reserve tokens and summary overhead.
666668
- `identifierPolicy`: `strict` (default), `off`, or `custom`. `strict` prepends built-in opaque identifier retention guidance during compaction summarization.
667669
- `identifierInstructions`: optional custom identifier-preservation text used when `identifierPolicy=custom`.
668670
- `qualityGuard`: retry-on-malformed-output checks for safeguard summaries. Enabled by default in safeguard mode; set `enabled: false` to skip the audit.

‎docs/reference/session-management-compaction.md‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -340,11 +340,19 @@ OpenClaw also enforces a safety floor for embedded runs:
340340
- If `compaction.reserveTokens < reserveTokensFloor`, OpenClaw bumps it.
341341
- Default floor is `20000` tokens.
342342
- Set `agents.defaults.compaction.reserveTokensFloor: 0` to disable the floor.
343-
- If it's already higher, OpenClaw leaves it alone.
343+
- When the active model context window is known, OpenClaw first caps that floor
344+
so `reserveTokens` cannot consume the whole context window. This keeps
345+
smaller local models with 16K-32K windows from entering an immediate
346+
compaction loop.
347+
- Explicit or existing `reserveTokens` values can also be capped to the same
348+
context-aware maximum. Without a known context window, OpenClaw keeps the old
349+
uncapped floor behavior.
344350
- Manual `/compact` honors an explicit `agents.defaults.compaction.keepRecentTokens`
345351
and keeps OpenClaw runtime's recent-tail cut point. Without an explicit keep budget,
346352
manual compaction remains a hard checkpoint and rebuilt context starts from
347353
the new summary.
354+
- When the active model context window is known, OpenClaw caps `keepRecentTokens`
355+
to the prompt budget left after `reserveTokens` and summary overhead.
348356
- Set `agents.defaults.compaction.midTurnPrecheck.enabled: true` to run the
349357
optional tool-loop precheck after new tool results and before the next model
350358
call. This is a trigger only; summary generation still uses the configured
@@ -362,8 +370,12 @@ OpenClaw also enforces a safety floor for embedded runs:
362370

363371
Why: leave enough headroom for multi-turn "housekeeping" (like memory writes) before compaction becomes unavoidable.
364372

365-
Implementation: `ensureAgentCompactionReserveTokens()` in `src/agents/agent-settings.ts`
366-
(called from `src/agents/embedded-agent-runner.ts`).
373+
Implementation: `applyAgentCompactionSettingsFromConfig()` in
374+
`src/agents/agent-settings.ts` applies config, reserve floors, context-window
375+
caps, and keep-recent caps for embedded runs. The older
376+
`ensureAgentCompactionReserveTokens()` helper is not context-aware and should
377+
not be used for small-context model setup unless the caller has already chosen
378+
a safe floor.
367379

368380
---
369381

‎src/agents/agent-compaction-constants.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,9 @@ export const MIN_PROMPT_BUDGET_TOKENS = 8_000;
1010
* content after reserve tokens are subtracted.
1111
*/
1212
export const MIN_PROMPT_BUDGET_RATIO = 0.5;
13+
14+
/**
15+
* Overhead reserved for summarization prompt, system prompt, previous summary,
16+
* and serialization wrappers (<conversation> tags, instructions, etc.).
17+
*/
18+
export const COMPACTION_SUMMARY_OVERHEAD_TOKENS = 4_096;

‎src/agents/agent-settings.test.ts‎

Lines changed: 56 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { describe, expect, it, vi } from "vitest";
2-
import { MIN_PROMPT_BUDGET_RATIO, MIN_PROMPT_BUDGET_TOKENS } from "./agent-compaction-constants.js";
2+
import {
3+
COMPACTION_SUMMARY_OVERHEAD_TOKENS,
4+
MIN_PROMPT_BUDGET_RATIO,
5+
MIN_PROMPT_BUDGET_TOKENS,
6+
} from "./agent-compaction-constants.js";
37
import {
48
applyAgentAutoCompactionGuard,
59
applyAgentCompactionSettingsFromConfig,
@@ -163,12 +167,11 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
163167
expect(settingsManager.applyOverrides).not.toHaveBeenCalled();
164168
});
165169

166-
it("caps floor to context window ratio for small-context models", () => {
170+
it("caps reserve tokens to keep usable prompt budget for small-context models", () => {
167171
// Embedded runner default reserveTokens is 16 384. With a 16 384 context window
168172
// the default floor (20 000) exceeds the window. The aligned cap
169173
// computes: minPromptBudget = min(8_000, floor(16_384 * 0.5)) = 8_000,
170-
// maxReserve = 16_384 - 8_000 = 8_384. Since current (16_384) > capped
171-
// floor (8_384), no override is needed.
174+
// maxReserve = 16_384 - 8_000 = 8_384.
172175
const settingsManager = {
173176
getCompactionReserveTokens: () => 16_384,
174177
getCompactionKeepRecentTokens: () => 20_000,
@@ -180,14 +183,12 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
180183
contextTokenBudget: 16_384,
181184
});
182185

183-
// Without the cap, reserveTokens would be bumped to 20_000.
184-
// With the cap, it stays at 16_384 (the current value).
185-
expect(result.compaction.reserveTokens).toBe(16_384);
186-
expect(result.compaction.reserveTokens).toBeLessThan(
187-
DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR,
188-
);
189-
expect(result.didOverride).toBe(false);
190-
expect(settingsManager.applyOverrides).not.toHaveBeenCalled();
186+
expect(result.compaction.reserveTokens).toBe(8_384);
187+
expect(result.compaction.keepRecentTokens).toBe(4_000);
188+
expect(result.didOverride).toBe(true);
189+
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
190+
compaction: { reserveTokens: 8_384, keepRecentTokens: 4_000 },
191+
});
191192
});
192193

193194
it("applies capped floor over user-configured reserveTokens when default floor exceeds context window", () => {
@@ -215,7 +216,7 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
215216
expect(result.didOverride).toBe(true);
216217
expect(result.compaction.reserveTokens).toBe(8_384); // capped floor wins over user's 2_048
217218
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
218-
compaction: { reserveTokens: 8_384 },
219+
compaction: { reserveTokens: 8_384, keepRecentTokens: 4_000 },
219220
});
220221
});
221222

@@ -244,7 +245,7 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
244245
expect(result.didOverride).toBe(true);
245246
expect(result.compaction.reserveTokens).toBe(expectedReserve);
246247
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
247-
compaction: { reserveTokens: expectedReserve },
248+
compaction: { reserveTokens: expectedReserve, keepRecentTokens: 4_000 },
248249
});
249250
});
250251

@@ -271,12 +272,43 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
271272
});
272273

273274
expect(result.compaction.reserveTokens).toBe(2_048);
275+
expect(result.compaction.keepRecentTokens).toBe(10_240);
276+
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
277+
compaction: { reserveTokens: 2_048, keepRecentTokens: 10_240 },
278+
});
279+
});
280+
281+
it("caps explicit reserve and keep-recent settings that exceed a small context window", () => {
282+
const settingsManager = {
283+
getCompactionReserveTokens: () => 16_384,
284+
getCompactionKeepRecentTokens: () => 20_000,
285+
applyOverrides: vi.fn(),
286+
};
287+
288+
const result = applyAgentCompactionSettingsFromConfig({
289+
settingsManager,
290+
cfg: {
291+
agents: {
292+
defaults: {
293+
compaction: {
294+
reserveTokens: 20_000,
295+
reserveTokensFloor: 0,
296+
keepRecentTokens: 15_000,
297+
},
298+
},
299+
},
300+
},
301+
contextTokenBudget: 16_000,
302+
});
303+
304+
expect(result.compaction.reserveTokens).toBe(8_000);
305+
expect(result.compaction.keepRecentTokens).toBe(4_000);
274306
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
275-
compaction: { reserveTokens: 2_048 },
307+
compaction: { reserveTokens: 8_000, keepRecentTokens: 4_000 },
276308
});
277309
});
278310

279-
it("does not cap floor for mid-size models when maxReserve exceeds default floor", () => {
311+
it("keeps the reserve floor but caps keep-recent when it exceeds remaining prompt budget", () => {
280312
const settingsManager = {
281313
getCompactionReserveTokens: () => 16_384,
282314
getCompactionKeepRecentTokens: () => 20_000,
@@ -285,15 +317,21 @@ describe("applyAgentCompactionSettingsFromConfig", () => {
285317

286318
// 32 768 context window → minPromptBudget = min(8_000, floor(32_768 * 0.5)) = 8_000.
287319
// maxReserve = 32_768 - 8_000 = 24_768.
288-
// Since 24_768 > 20_000 (DEFAULT_FLOOR), the floor is NOT capped and stays at 20_000.
320+
// Since 24_768 > 20_000 (DEFAULT_FLOOR), the reserve stays at 20_000.
321+
// keepRecentTokens still cannot consume the whole remaining prompt budget:
322+
// the compacted transcript needs room for the summary and prompt wrapper.
289323
const result = applyAgentCompactionSettingsFromConfig({
290324
settingsManager,
291325
contextTokenBudget: 32_768,
292326
});
293327

294328
expect(result.compaction.reserveTokens).toBe(DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR);
329+
expect(result.compaction.keepRecentTokens).toBe(12_768 - COMPACTION_SUMMARY_OVERHEAD_TOKENS);
295330
expect(settingsManager.applyOverrides).toHaveBeenCalledWith({
296-
compaction: { reserveTokens: DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR },
331+
compaction: {
332+
reserveTokens: DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR,
333+
keepRecentTokens: 12_768 - COMPACTION_SUMMARY_OVERHEAD_TOKENS,
334+
},
297335
});
298336
});
299337

‎src/agents/agent-settings.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
22
import type { AgentCompactionMode } from "../config/types.agent-defaults.js";
33
import type { OpenClawConfig } from "../config/types.openclaw.js";
44
import type { ContextEngineInfo } from "../context-engine/types.js";
5-
import { MIN_PROMPT_BUDGET_RATIO, MIN_PROMPT_BUDGET_TOKENS } from "./agent-compaction-constants.js";
5+
import {
6+
COMPACTION_SUMMARY_OVERHEAD_TOKENS,
7+
MIN_PROMPT_BUDGET_RATIO,
8+
MIN_PROMPT_BUDGET_TOKENS,
9+
} from "./agent-compaction-constants.js";
610
import { resolveProviderEndpoint } from "./provider-attribution.js";
711

812
export const DEFAULT_AGENT_COMPACTION_RESERVE_TOKENS_FLOOR = 20_000;
@@ -65,6 +69,13 @@ function toPositiveInt(value: unknown): number | undefined {
6569
return Math.floor(value);
6670
}
6771

72+
function resolveKeepRecentOverheadTokens(promptBudgetAfterReserve: number): number {
73+
return Math.min(
74+
COMPACTION_SUMMARY_OVERHEAD_TOKENS,
75+
Math.max(1, Math.floor(promptBudgetAfterReserve / 2)),
76+
);
77+
}
78+
6879
export function applyAgentCompactionSettingsFromConfig(params: {
6980
settingsManager: AgentSettingsManagerLike;
7081
cfg?: OpenClawConfig;
@@ -81,6 +92,7 @@ export function applyAgentCompactionSettingsFromConfig(params: {
8192
const configuredReserveTokens = toNonNegativeInt(compactionCfg?.reserveTokens);
8293
const configuredKeepRecentTokens = toPositiveInt(compactionCfg?.keepRecentTokens);
8394
let reserveTokensFloor = resolveCompactionReserveTokensFloor(params.cfg);
95+
let maxReserveTokens: number | undefined;
8496

8597
// Cap the floor to a safe fraction of the context window so that
8698
// small-context models (e.g. Ollama with 16 K tokens) are not starved of
@@ -93,15 +105,31 @@ export function applyAgentCompactionSettingsFromConfig(params: {
93105
MIN_PROMPT_BUDGET_TOKENS,
94106
Math.max(1, Math.floor(ctxBudget * MIN_PROMPT_BUDGET_RATIO)),
95107
);
96-
const maxReserve = Math.max(0, ctxBudget - minPromptBudget);
97-
reserveTokensFloor = Math.min(reserveTokensFloor, maxReserve);
108+
maxReserveTokens = Math.max(0, ctxBudget - minPromptBudget);
109+
reserveTokensFloor = Math.min(reserveTokensFloor, maxReserveTokens);
98110
}
99111

100-
const targetReserveTokens = Math.max(
112+
let targetReserveTokens = Math.max(
101113
configuredReserveTokens ?? currentReserveTokens,
102114
reserveTokensFloor,
103115
);
104-
const targetKeepRecentTokens = configuredKeepRecentTokens ?? currentKeepRecentTokens;
116+
if (maxReserveTokens !== undefined) {
117+
targetReserveTokens = Math.min(targetReserveTokens, maxReserveTokens);
118+
}
119+
let targetKeepRecentTokens = configuredKeepRecentTokens ?? currentKeepRecentTokens;
120+
if (
121+
typeof ctxBudget === "number" &&
122+
Number.isFinite(ctxBudget) &&
123+
ctxBudget > 0 &&
124+
targetKeepRecentTokens > 0
125+
) {
126+
const promptBudgetAfterReserve = Math.max(1, Math.floor(ctxBudget) - targetReserveTokens);
127+
const keepRecentOverheadTokens = resolveKeepRecentOverheadTokens(promptBudgetAfterReserve);
128+
targetKeepRecentTokens = Math.min(
129+
targetKeepRecentTokens,
130+
Math.max(1, promptBudgetAfterReserve - keepRecentOverheadTokens),
131+
);
132+
}
105133

106134
const overrides: { reserveTokens?: number; keepRecentTokens?: number } = {};
107135
if (targetReserveTokens !== currentReserveTokens) {

‎src/agents/compaction-planning.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { COMPACTION_SUMMARY_OVERHEAD_TOKENS } from "./agent-compaction-constants.js";
12
import { stripRuntimeContextCustomMessages } from "./internal-runtime-context.js";
23
import type { AgentMessage } from "./runtime/index.js";
34
import { repairToolUseResultPairing, stripToolResultDetails } from "./session-transcript-repair.js";
@@ -9,10 +10,8 @@ export const MIN_CHUNK_RATIO = 0.15;
910
export const SAFETY_MARGIN = 1.2; // 20% buffer for estimateTokens() inaccuracy
1011
const DEFAULT_PARTS = 2;
1112

12-
// Overhead reserved for summarization prompt, system prompt, previous summary,
13-
// and serialization wrappers (<conversation> tags, instructions, etc.).
1413
// generateSummary uses reasoning: "high" which also consumes context budget.
15-
export const SUMMARIZATION_OVERHEAD_TOKENS = 4096;
14+
export const SUMMARIZATION_OVERHEAD_TOKENS = COMPACTION_SUMMARY_OVERHEAD_TOKENS;
1615

1716
export type StageSplitPlan =
1817
| {

‎src/config/schema.help.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1458,9 +1458,9 @@ export const FIELD_HELP: Record<string, string> = {
14581458
"agents.defaults.compaction.provider":
14591459
"Id of a registered compaction provider plugin used for summarization. When set and the provider is registered, its summarize() method is called instead of the built-in summarizeInStages pipeline. Falls back to built-in on provider failure. Leave unset to use the default built-in summarization.",
14601460
"agents.defaults.compaction.reserveTokens":
1461-
"Token headroom reserved for reply generation and tool output after compaction runs. Use higher reserves for verbose/tool-heavy sessions, and lower reserves when maximizing retained history matters more.",
1461+
"Token headroom reserved for reply generation and tool output after compaction runs. Use higher reserves for verbose/tool-heavy sessions, and lower reserves when maximizing retained history matters more. When the active model context window is known, impossible reserves are capped so prompt content still has usable budget.",
14621462
"agents.defaults.compaction.keepRecentTokens":
1463-
"Minimum token budget preserved from the most recent conversation window during compaction. Use higher values to protect immediate context continuity and lower values to keep more long-tail history.",
1463+
"Minimum token budget preserved from the most recent conversation window during compaction. Use higher values to protect immediate context continuity and lower values to keep more long-tail history. When the active model context window is known, impossible keep-recent budgets are capped to leave room for reserve headroom and summary overhead.",
14641464
"agents.defaults.compaction.reserveTokensFloor":
14651465
"Minimum floor enforced for reserveTokens in embedded OpenClaw compaction paths (0 disables the floor guard). Use a non-zero floor to avoid over-aggressive compression under fluctuating token estimates.",
14661466
"agents.defaults.compaction.maxHistoryShare":

‎src/config/types.agent-defaults.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -486,9 +486,9 @@ export type AgentCompactionMidTurnPrecheckConfig = {
486486
export type AgentCompactionConfig = {
487487
/** Compaction summarization mode. */
488488
mode?: AgentCompactionMode;
489-
/** Embedded OpenClaw reserve tokens target before floor enforcement. */
489+
/** Embedded OpenClaw reserve tokens target before floor and context-window caps. */
490490
reserveTokens?: number;
491-
/** Embedded OpenClaw keepRecentTokens budget used for cut-point selection. */
491+
/** Embedded OpenClaw keepRecentTokens budget, capped by context and summary overhead. */
492492
keepRecentTokens?: number;
493493
/** Minimum reserve tokens enforced for embedded OpenClaw compaction (0 disables the floor). */
494494
reserveTokensFloor?: number;

0 commit comments

Comments
 (0)