The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): cap the protected tail at 20% of the context window
teknium1b7803a176355
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex ae0edde2c08..f337eb65d8a 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -840,6 +840,10 @@ def _reinject_pruned_skill_markers(summary: str, skill_names: list[str]) -> str:# 2.5% of the context window, clamped; floor keeps small models workable.LEAN_TAIL_FLOOR_TOKENS = 10_000LEAN_TAIL_CAP_TOKENS = 25_000+# Hard share of the window the verbatim tail may occupy, applied after either formula. The lean+# floor alone is 61% of a 16K window and 122% of an 8K one, so on a local 27B the "protected"+# tail WAS the whole request and every compaction pass summarised six rows and reclaimed nothing.+TAIL_MAX_CONTEXT_FRACTION = 0.20# Newest-first budget, straddler truncated; lives inside the single summary message._LEAN_USER_MESSAGES_BUDGET_CHARS = 24_000 # ~6K tokens_LEAN_USER_MESSAGE_MAX_CHARS = 4_000@@ -2057,9 +2061,12 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginif self._tail_token_budget is None:if getattr(self, "tail_mode", "lean") == "lean":# Lean mode: tail is a small clamped recency window; the summary carries continuity.- self._tail_token_budget = max(LEAN_TAIL_FLOOR_TOKENS, min(LEAN_TAIL_CAP_TOKENS, int(self.context_length * 0.025)))+ budget = max(LEAN_TAIL_FLOOR_TOKENS, min(LEAN_TAIL_CAP_TOKENS, int(self.context_length * 0.025)))else:- self._tail_token_budget = int(self.threshold_tokens * self.summary_target_ratio)+ budget = int(self.threshold_tokens * self.summary_target_ratio)+ if self.context_length > 0:+ budget = min(budget, int(self.context_length * TAIL_MAX_CONTEXT_FRACTION))+ self._tail_token_budget = max(1, budget)return self._tail_token_budget@tail_token_budget.setter@@ -2975,6 +2982,16 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginresult[idx] = {**msg, "content": _summarize_tool_result(tool_name, tool_args, content)}return True+ def _tail_soft_ceiling(self, token_budget: int) -> int:+ """Optional tail rows may overrun the budget by 1.5x so whole rows are kept, but never past+ ``TAIL_MAX_CONTEXT_FRACTION`` of the window — on a small window the overrun alone was a third+ of the request. Required anchors and atomic tool groups may still exceed it."""+ ceiling = int(token_budget * 1.5)+ ctx = getattr(self, "context_length", 0) or 0+ if ctx > 0:+ ceiling = min(ceiling, int(ctx * TAIL_MAX_CONTEXT_FRACTION))+ return max(ceiling, token_budget)+def _pressure_demote_tail(self, result: List[Dict[str, Any]], prune_boundary: int, protect_tail_tokens: int,call_id_to_tool: Dict[str, tuple[str, str]], min_prune_chars: int,@@ -2982,7 +2999,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin"""Pass 4: demote inside the protected tail when it alone exceeds the soft budget (#61932).Keeps a short recent floor verbatim; overrides the skill guard (else the dead-end recurs).Returns the number of tool results demoted (arg truncations are logged but not counted)."""- soft_ceiling = int(protect_tail_tokens * 1.5)+ soft_ceiling = self._tail_soft_ceiling(protect_tail_tokens)demote_end = len(result) - min(_PRESSURE_KEEP_RECENT_MESSAGES, len(result))start = max(0, prune_boundary)@@ -4585,7 +4602,7 @@ Write only the summary body. Do not include any preamble or prefix."""# Keep >= 2 non-head messages summarizable so a tiny middle still saves messages.compressible_tail_cap = max(3, available_tail - 2)min_tail = min(min_tail_floor, compressible_tail_cap, available_tail) if available_tail > 1 else 0- soft_ceiling = int(token_budget * 1.5)+ soft_ceiling = self._tail_soft_ceiling(token_budget)# The count floor is opportunistic: oversized optional rows must not ride it past the token# ceiling (#108647), so the walk runs floorless whenever the ceiling can hold at least the wire# overhead of that many empty rows. Only when it cannot does the continuity floor win — nodiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 2fad56b30c2..9199805c952 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -570,7 +570,9 @@ DEFAULT_CONFIG = {# (~3x fewer retained tokens; a few extra summarizer calls at the boundary). "legacy" =# 0.20×threshold verbatim tail (100-240K tokens on big windows)."tail_mode": "lean",- "protect_last_n": 20, # minimum recent messages kept uncompressed+ # protect_last_n: minimum recent messages kept uncompressed, honoured up to a small count+ # floor; the verbatim tail is otherwise token-bounded and never above 20% of the window.+ "protect_last_n": 20,# min_tail_user_messages: REAL (actionable) user messages guaranteed to survive in the tail.# 1 = single last-user anchor; raise (e.g. 3) when bulky tool outputs fill the tail budget."min_tail_user_messages": 1,diff --git a/tests/agent/test_compression_small_ctx_threshold_floor.py b/tests/agent/test_compression_small_ctx_threshold_floor.pyindex abaf2407070..8b3fbb33e65 100644--- a/tests/agent/test_compression_small_ctx_threshold_floor.py+++ b/tests/agent/test_compression_small_ctx_threshold_floor.py@@ -159,3 +159,39 @@ class TestTailBudgetProportionality:comp = _make(128_000)assert comp.tail_mode == "lean"assert LEAN_TAIL_FLOOR_TOKENS <= comp.tail_token_budget <= LEAN_TAIL_CAP_TOKENS++ def test_tail_budget_never_exceeds_window_share(self):+ """The lean 10K floor is 61% of a 16K window and 122% of an 8K one: on a local 27B the+ "protected" tail was the whole request and compaction reclaimed nothing. Whatever the+ formula, the verbatim tail stays within ``TAIL_MAX_CONTEXT_FRACTION`` of the window."""+ from agent.context_compressor import LEAN_TAIL_FLOOR_TOKENS, TAIL_MAX_CONTEXT_FRACTION++ for ctx in (8_192, 16_384, 32_768):+ comp = _make(ctx)+ assert comp.tail_token_budget <= ctx * TAIL_MAX_CONTEXT_FRACTION, ctx+ assert comp.tail_token_budget > 0, ctx+ # Big windows are untouched: the lean clamp still binds.+ assert _make(131_072).tail_token_budget == LEAN_TAIL_FLOOR_TOKENS++ def test_small_window_compress_leaves_a_real_middle(self):+ """End to end through the boundary walk: on an 8K window a tool-heavy transcript must yield a+ compressible middle that is most of the transcript, and the retained tail must stay near the+ window share (one atomic tool group of overrun is allowed for the required anchors)."""+ from agent.context_compressor import TAIL_MAX_CONTEXT_FRACTION, _estimate_msg_budget_tokens++ ctx = 8_192+ comp = _make(ctx)+ msgs: list = [{"role": "system", "content": "sys"}]+ for i in range(12):+ msgs.append({"role": "user", "content": f"step {i}"})+ msgs.append({+ "role": "assistant", "content": "",+ "tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}],+ })+ msgs.append({"role": "tool", "tool_call_id": f"c{i}", "content": "x" * 4_000})+ msgs.append({"role": "assistant", "content": f"done {i}"})+ start, end = comp._compress_window(msgs)+ tail_tokens = sum(_estimate_msg_budget_tokens(m) for m in msgs[end:])+ one_turn = sum(_estimate_msg_budget_tokens(m) for m in msgs[-4:])+ assert tail_tokens <= ctx * TAIL_MAX_CONTEXT_FRACTION + one_turn+ assert end - start >= (len(msgs) - start) // 2, (start, end, len(msgs))diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex f4507f53f7d..f083ee20be1 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -285,7 +285,9 @@ Set `in_place: false` to restore the legacy rotating path, where each compactionA smaller auxiliary compression model can lower the live compression trigger withoutchanging the selected tail policy. In `lean` mode the selection budget remains based-on the **main model's context window**: 2.5%, clamped to 10K–25K tokens. For example,+on the **main model's context window**: 2.5%, clamped to 10K–25K tokens, and never more+than 20% of that window (the 10K floor alone is 61% of a 16K local window, so without the cap a+small model's "protected" tail was the whole request and compaction reclaimed nothing). For example,a 1M main model (`threshold_tokens: null`) with a 512K auxiliary model retains a 25Kselection budget even when feasibility lowers its trigger from 850K to 512K. Explicit `legacy` mode insteadrecomputes `threshold_tokens × target_ratio` (102,400 tokens at 512K × 0.20).@@ -508,8 +510,11 @@ outputs (file contents, terminal output, search results).```Tail protection is **token-budget based**: walks backward from the end,-accumulating tokens until the budget is exhausted. Falls back to the fixed-`protect_last_n` count if the budget would protect fewer messages.+accumulating tokens until the budget is exhausted. The budget — and the 1.5× soft+ceiling whole rows may overrun it by — is capped at 20% of the context window on every+model, so `protect_last_n` is a *minimum* only up to a small count floor (8 rows) and never+forces a tail that cannot leave room to compact; only the required last-user / last-assistant+anchors and atomic tool groups may exceed the cap.Boundaries are aligned to avoid splitting tool_call/tool_result groups.The `_align_boundary_backward()` method walks past consecutive tool resultsdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 8cf9694a665..932334fa30d 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -982,7 +982,7 @@ compression:threshold: 0.50 # Compress at this % of context limitthreshold_tokens: 256000 # Absolute token cap — takes lower of ratio vs absolutetarget_ratio: 0.20 # Fraction of threshold to preserve as recent tail- tail_mode: lean # Tail retention: "lean" (default — clamped 2.5% tail, 10K-25K, with a detailed session log + anchor index + session_search recovery pointers in the summary, all from ONE auxiliary summarizer call; ~3x fewer retained tokens after compaction) or "legacy" (0.20×threshold verbatim tail)+ tail_mode: lean # Tail retention: "lean" (default — clamped 2.5% tail, 10K-25K, never above 20% of the window, with a detailed session log + anchor index + session_search recovery pointers in the summary, all from ONE auxiliary summarizer call; ~3x fewer retained tokens after compaction) or "legacy" (0.20×threshold verbatim tail)protect_last_n: 20 # Min recent messages to keep uncompressedprotect_first_n: 3 # Non-system head messages pinned across compactions (0 = pin nothing)in_place: true # Compact on the same session id (no rotation) — see below