The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): bound tail message floor by token budget
KoNit-Kfdbcdef91466
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 6c03642e49a..519ea15b43d 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -4396,8 +4396,8 @@ Write only the summary body. Do not include any preamble or prefix."""self, messages: List[Dict[str, Any]], head_end: int, token_budget: int | None = None,) -> int:"""Walk backward accumulating tokens until the budget; return the tail start index.- May exceed the budget by up to 1.5x to avoid cutting inside an oversized message; never splits a- tool group; keeps the last user message in the tail."""+ Optional rows are bounded by a 1.5x soft ceiling. Required last-user/last-assistant anchors and+ their atomic tool groups may exceed it; tool groups are never split."""if token_budget is None:token_budget = self.tail_token_budgetn = len(messages)@@ -4410,13 +4410,26 @@ Write only the summary body. Do not include any preamble or prefix."""min_tail = min(min_tail_floor, compressible_tail_cap, available_tail) if available_tail > 1 else 0soft_ceiling = int(token_budget * 1.5)cut_idx, accumulated = self._walk_tail_budget(messages, head_end, soft_ceiling, min_tail, cut_at_break=False)+ # Preserve the continuity floor when the configured ceiling cannot fit even the fixed wire+ # overhead of that many empty rows; no token-respecting count floor exists in that case.+ floor_can_fit_ceiling = soft_ceiling >= min_tail * _estimate_msg_budget_tokens({})+ fallback_cut = n - min_tail+ bounded_cut, bounded_accumulated = self._walk_tail_budget(+ messages, head_end, soft_ceiling, 0, cut_at_break=False,+ )+ floor_exceeds_ceiling = floor_can_fit_ceiling and fallback_cut < bounded_cut+ if floor_exceeds_ceiling:+ # The count floor is opportunistic: oversized optional rows must not make it an+ # unbounded override of the token ceiling. Required user/assistant anchors and+ # atomic tool groups are applied below and may still necessarily exceed it.+ cut_idx, accumulated = bounded_cut, bounded_accumulated# Whole transcript fits soft_ceiling: re-cut with the raw budget so a worthwhile middle# exists (else #40803 loop).if cut_idx <= head_end and 0 < accumulated <= soft_ceiling:cut_idx, _ = self._walk_tail_budget(messages, head_end, token_budget, min_tail, cut_at_break=True)- fallback_cut = n - min_tail- cut_idx = min(cut_idx, fallback_cut)+ if not floor_exceeds_ceiling:+ cut_idx = min(cut_idx, fallback_cut)# Small conversations: force a cut after the head so compression still removes something.if cut_idx <= head_end:cut_idx = max(fallback_cut, head_end + 1)diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex 1665ea008dd..91ba9748ab4 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -3443,6 +3443,63 @@ class TestMinTailUserMessages:assert accumulated > c.tail_token_budget+class TestTailTokenBudgetCeiling:+ def test_message_floor_does_not_unboundedly_override_soft_ceiling(self):+ """Oversized optional rows must not ride the count floor past 1.5x budget."""+ with patch("agent.context_compressor.get_model_context_length", return_value=200_000):+ c = ContextCompressor(+ model="test/model",+ protect_first_n=1,+ protect_last_n=20,+ quiet_mode=True,+ tail_mode="lean",+ )+ c.tail_token_budget = 10_000+ oversized = "x" * 24_000+ messages = [+ {"role": "system", "content": "system"},+ {"role": "user", "content": oversized},+ {"role": "assistant", "content": oversized},+ {"role": "user", "content": oversized},+ {"role": "assistant", "content": oversized},+ {"role": "user", "content": oversized},+ {"role": "assistant", "content": oversized},+ {"role": "user", "content": "latest request"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call-latest", "function": {"name": "read_file", "arguments": "{}"}}],+ },+ {"role": "tool", "tool_call_id": "call-latest", "content": "result " + ("r" * 20_000)},+ {"role": "assistant", "content": "latest answer"},+ ]++ cut = c._find_tail_cut_by_tokens(messages, head_end=1)+ tail = messages[cut:]++ from agent.context_compressor import _estimate_msg_budget_tokens+ tail_tokens = sum(_estimate_msg_budget_tokens(message) for message in tail)+ assert tail_tokens <= int(c.tail_token_budget * 1.5)+ assert any(message.get("content") == "latest request" for message in tail)+ assert tail[-1]["content"] == "latest answer"+ assert [message.get("role") for message in tail if message.get("tool_call_id") == "call-latest"] == ["tool"]+ assert any(+ call.get("id") == "call-latest"+ for message in tail+ for call in message.get("tool_calls", [])+ )++ # The ceiling remains soft when required continuity is itself oversized:+ # keep the active user's whole tool group and final assistant response.+ messages[9]["content"] = "result " + ("r" * 80_000)+ oversized_cut = c._find_tail_cut_by_tokens(messages, head_end=1)+ oversized_tail = messages[oversized_cut:]+ assert sum(_estimate_msg_budget_tokens(message) for message in oversized_tail) > int(+ c.tail_token_budget * 1.5+ )+ assert messages[7:] == oversized_tail++class TestContextLengthSetterCoherence:"""The context_length setter must (a) not wipe runtime corrections on