Skip to content

The agent that grows with you

fix(compression): price the assistant-anchor escape like the tail walk

kshitijk4poorda0bcfca8331
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index cf22d2620da..da00b7efe60 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -12,7 +12,7 @@ import re
import time
import uuid
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional, Sequence, Tuple
+from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from agent.image_eviction_policy import outbound_image_retire_count
from agent.compression_marker import (
@@ -3185,22 +3185,26 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
``cut_at_break``. Only the newest assistant turn's thinking is charged (#73624) unless the route
echoes stale thinking every turn — must agree with the preflight estimate (#84371)."""
n = len(messages)
- newest_asst_idx = _last_assistant_index(messages)
- charge_all_thinking = self._stale_thinking_on_wire()
- native_budget = self._native_anthropic_budget()
+ price = self._tail_row_pricer(messages)
accumulated = 0
cut = n # start from beyond the end
for i in range(n - 1, head_end - 1, -1):
- msg_tokens = (
- native_budget(messages[i]) if native_budget
- else _estimate_msg_budget_tokens(messages[i], charge_all_thinking or i == newest_asst_idx)
- )
+ msg_tokens = price(i)
if accumulated + msg_tokens > ceiling and (n - i) >= min_tail:
return (i if cut_at_break else cut), accumulated
accumulated += msg_tokens
cut = i
return cut, accumulated
+ def _tail_row_pricer(self, messages: List[Dict[str, Any]]) -> Callable[[int], int]:
+ """Per-row tail price ``index -> tokens``: the walk's accounting, shared by every gate that sizes a tail region."""
+ newest_asst_idx = _last_assistant_index(messages)
+ charge_all_thinking = self._stale_thinking_on_wire()
+ native_budget = self._native_anthropic_budget()
+ if native_budget:
+ return lambda i: native_budget(messages[i])
+ return lambda i: _estimate_msg_budget_tokens(messages[i], charge_all_thinking or i == newest_asst_idx)
+
def _prune_boundary(
self, result: List[Dict[str, Any]], protect_tail_count: int, protect_tail_tokens: int | None,
) -> int:
@@ -5192,9 +5196,8 @@ Write only the summary body. Do not include any preamble or prefix."""
asst_anchored_cut < cut_idx
and allow_split_turn
and any(messages[i].get("tool_calls") for i in range(asst_anchored_cut, cut_idx))
- and sum(
- _estimate_msg_budget_tokens(m) for m in messages[asst_anchored_cut:cut_idx]
- ) > soft_ceiling
+ # Priced like the walk (#84371): stale thinking the wire never carries must not trip it.
+ and sum(map(self._tail_row_pricer(messages), range(asst_anchored_cut, cut_idx))) > soft_ceiling
):
if not self.quiet_mode:
logger.debug(
diff --git a/tests/agent/test_split_turn_compaction.py b/tests/agent/test_split_turn_compaction.py
index d8ef9398b46..3b96176306e 100644
--- a/tests/agent/test_split_turn_compaction.py
+++ b/tests/agent/test_split_turn_compaction.py
@@ -456,21 +456,47 @@ def test_assistant_anchor_cannot_retain_a_textless_oversized_turn(
_assert_tool_pairs_are_complete(messages[cut:])
-def test_assistant_anchor_still_binds_when_splitting_is_disabled(
- compressor: ContextCompressor,
+def _reasoning_heavy_small_turn() -> list[dict]:
+ """Under the ceiling on the wire, over it only if stale thinking were charged (BN04 2c)."""
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "older request"},
+ {"role": "assistant", "content": "older turn finished"},
+ ]
+ for index in range(2):
+ group = _tail_group(index)
+ group[0]["reasoning_content"] = "t" * 1200
+ messages.extend(group)
+ messages.append({"role": "user", "content": "keep going"})
+ for index in range(2, 6):
+ messages.extend(_tail_group(index))
+ return messages
+
+
+ ("build", "allow_split_turn"),
+ [
+ # Rolling micro-compaction consumes complete exchanges only (allow_split_turn=False).
+ (_textless_oversized_turn, False),
+ # Stale thinking never reaches the wire on this route, so the escape must price the
+ # region like the walk does (#84371) and not drop a reply that fits (#29824).
+ (_reasoning_heavy_small_turn, True),
+ ],
+)
+def test_assistant_anchor_still_binds(
+ compressor: ContextCompressor, build, allow_split_turn: bool,
) -> None:
- """Rolling micro-compaction consumes complete exchanges only (allow_split_turn=False)."""
- messages = _textless_oversized_turn()
+ """The #131412 escape fires only for a wire-oversized region with splitting allowed."""
+ messages = build()
head_end = compressor._protect_head_size(messages)
cut = compressor._find_tail_cut_by_tokens(
- messages, head_end, token_budget=_TOKEN_BUDGET, allow_split_turn=False,
+ messages, head_end, token_budget=_TOKEN_BUDGET, allow_split_turn=allow_split_turn,
)
older_closer_idx = next(
index for index, message in enumerate(messages)
if message.get("content") == "older turn finished"
)
- # Without the split allowance the anchor pulls the cut back to the older turn's
- # closer, aligned before its preceding tool group; the mid-turn exception never fires.
+ # The anchor pulls the cut back to the older turn's closer, aligned before any tool group.
assert cut == compressor._align_boundary_backward(messages, older_closer_idx)