Skip to content

The agent that grows with you

fix(compression): a tail cut inside the first post-handoff tool group still compacts

Tekniumf6a84fd6d91f
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 16721abb9f9..6732e1af81b 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -38,7 +38,7 @@ from agent.context_compressor_summary import SummaryDispatchMixin
from agent.context_compressor_retry import retryable_user_text
from agent.context_compressor_tail import (
demote_stale_tail_tools, lean_tail_budget, is_demoted_stub, skill_view_names_by_call_id, tail_cut_pricer,
- elide_keeping_skill_safety_rule, with_skill_safety_rule, without_skill_safety_rule,
+ elide_keeping_skill_safety_rule, with_skill_safety_rule, without_skill_safety_rule, tail_cut_progress_floor,
)
from agent.context_compressor_telemetry import CompressionTelemetryMixin
from agent.error_classifier import FailoverReason, classify_api_error
@@ -5102,9 +5102,9 @@ Write only the summary body. Do not include any preamble or prefix."""
if isinstance(_min_tail_users, int) and not isinstance(_min_tail_users, bool) and _min_tail_users > 1:
cut_idx = self._ensure_last_n_user_messages_in_tail(messages, cut_idx, head_end, _min_tail_users)
- # Floor guarantees progress (>= 1 message claimed); re-align FORWARD only so a raised cut
+ # Floor guarantees progress (>= 1 non-handoff message claimed); re-align FORWARD only so a raised cut
# can't split a tool group (backward would give the floor's message back).
- return min(n, self._align_boundary_forward(messages, max(cut_idx, head_end + 1)))
+ return min(n, self._align_boundary_forward(messages, max(cut_idx, tail_cut_progress_floor(self, messages, head_end, cut_idx))))
def has_content_to_compress(self, messages: list[dict[str, Any]]) -> bool:
"""True if a non-empty middle region exists (lets the gateway ``/compress`` guard skip the LLM call)."""
diff --git a/agent/context_compressor_tail.py b/agent/context_compressor_tail.py
index 96cc270090e..af35d5ed1c2 100644
--- a/agent/context_compressor_tail.py
+++ b/agent/context_compressor_tail.py
@@ -132,6 +132,25 @@ def tail_cut_pricer(compressor: Any, messages: list[dict[str, Any]], head_end: i
return price if newest < 0 else (lambda i: 0 if i <= newest else price(i))
+def tail_cut_progress_floor(compressor: Any, messages: list[dict[str, Any]], head_end: int, cut_idx: int) -> int:
+ """Lowest tail cut that leaves the summary window a row the handoff scan keeps.
+
+ The scan drops standalone handoff rows from the window, so when every row before the cut (and up to the newest
+ handoff) is a handoff, the planned window is empty and compress() no-ops with ``empty_post_handoff_window``. That
+ happens when the cut lands inside the tool group right after the handoff and is aligned back onto the group's
+ assistant. The floor then moves past that group, unless doing so would take the newest row or the active user
+ request out of the tail; those cases keep the old ``head_end + 1`` floor."""
+ floor = head_end + 1
+ newest = next(
+ (i for i in range(len(messages) - 1, head_end - 1, -1) if compressor._is_context_summary_message(messages[i])), -1,
+ )
+ if newest < 0 or not all(map(compressor._is_context_summary_message, messages[head_end:max(cut_idx, newest + 1)])):
+ return floor
+ raised = compressor._align_boundary_forward(messages, newest + 2)
+ last_user = compressor._find_last_user_message_idx(messages, newest + 1)
+ return floor if raised >= len(messages) or 0 <= last_user < raised else raised
+
+
def with_skill_safety_rule(
summary: str, head: list[dict[str, Any]], tail: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]]]:
diff --git a/tests/agent/test_compressor_handoff_tool_group_floor.py b/tests/agent/test_compressor_handoff_tool_group_floor.py
new file mode 100644
index 00000000000..ccec8795c64
--- /dev/null
+++ b/tests/agent/test_compressor_handoff_tool_group_floor.py
@@ -0,0 +1,60 @@
+"""A tail cut that lands inside the tool group right after a handoff must not collapse the window onto the handoff.
+
+After one compaction the transcript is ``[handoff, assistant(tool_calls) + results, ...]``. When the raw tail budget
+breaks inside that first tool group, aligning the cut backward to the group's assistant leaves a window holding only
+the handoff, which the handoff scan drops: compress() returned the ``empty_post_handoff_window`` no-op and the session
+stayed over the trigger with no warning (C4 e2e ``test_good_summarizer_compacts_and_keeps_every_invariant[11]``).
+"""
+
+from unittest.mock import patch
+
+from agent.context_compressor import COMPRESSED_SUMMARY_METADATA_KEY, SUMMARY_PREFIX, ContextCompressor
+
+
+def _compressor() -> ContextCompressor:
+ with patch("agent.context_compressor.get_model_context_length", return_value=64_000):
+ cc = ContextCompressor(
+ model="test-model", quiet_mode=True, config_context_length=64_000, protect_first_n=3,
+ protect_last_n=4, summary_target_ratio=0.20, threshold_percent=0.50, tail_mode="lean",
+ )
+ cc.tail_token_budget = 6_000
+ return cc
+
+
+def _calls(*ids: str) -> dict:
+ return {"role": "assistant", "content": "", "tool_calls": [
+ {"id": i, "type": "function", "function": {"name": "read_file", "arguments": '{"path": "f.txt"}'}} for i in ids
+ ]}
+
+
+def _result(call_id: str, tokens: int) -> dict:
+ return {"role": "tool", "tool_call_id": call_id, "content": "w " * (tokens * 2)}
+
+
+def _transcript() -> list[dict]:
+ handoff = {"role": "user", "content": f"{SUMMARY_PREFIX}\n## Goal\n" + "earlier " * 380,
+ COMPRESSED_SUMMARY_METADATA_KEY: True}
+ return [
+ handoff,
+ _calls("a", "b", "c"), _result("a", 50), _result("b", 1_160), _result("c", 420),
+ _calls("d", "e"), _result("d", 1_340), _result("e", 340),
+ {"role": "assistant", "content": "answer for the previous ask"},
+ {"role": "user", "content": "please read the next file and report"},
+ _calls("f"), _result("f", 1_770),
+ _calls("g"), _result("g", 1_670),
+ ]
+
+
+def test_cut_inside_the_first_tool_group_still_compacts_past_the_handoff():
+ cc = _compressor()
+ messages = _transcript()
+ with patch.object(cc, "_generate_summary", return_value="NEW SUMMARY BODY"):
+ result = cc.compress(messages, current_tokens=12_800)
+
+ assert (cc._last_compression_telemetry or {}).get("failure_class") is None
+ assert cc._last_compression_made_progress is True
+ assert len(result) < len(messages)
+ assert sum(1 for m in result if cc._is_context_summary_message(m)) == 1
+ # The active ask and everything after it stay verbatim in the tail.
+ assert [m.get("content") for m in result[-5:]] == [m.get("content") for m in messages[-5:]]
+