Skip to content

The agent that grows with you

fix(compression): split oversized active turns

embwl0xcc4bb888a474
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 2ac79d2d29a..897c3770a6d 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -4449,10 +4449,13 @@ Write only the summary body. Do not include any preamble or prefix."""
def _find_tail_cut_by_tokens(
self, messages: List[Dict[str, Any]], head_end: int, token_budget: int | None = None,
+ *, allow_split_turn: bool = True,
) -> int:
"""Walk backward accumulating tokens until the budget; return the tail start index.
Optional rows are bounded by a 1.5x soft ceiling. Required last-user/last-assistant (and
- multi-user) anchors and their atomic tool groups may exceed it; tool groups are never split."""
+ multi-user) anchors and their atomic tool groups may exceed it; tool groups are never split.
+ ``allow_split_turn`` is disabled by rolling micro-compaction, which consumes complete
+ exchanges only; batch/manual compaction enables it so an oversized active turn can progress."""
if token_budget is None:
token_budget = self.tail_token_budget
n = len(messages)
@@ -4485,14 +4488,52 @@ Write only the summary body. Do not include any preamble or prefix."""
# Latest user message must stay in the tail (active task). Latest assistant reply must stay too;
# anchors only walk backward, so chaining is monotonic.
# Ensure the most recent user message is always in the tail so the active task is never lost to
- # compression (fixes #10896).
- cut_idx = self._ensure_last_user_message_in_tail(messages, cut_idx, head_end)
- cut_idx = self._ensure_last_assistant_message_in_tail(messages, cut_idx, head_end)
+ # compression (fixes #10896) — EXCEPT when one in-progress turn alone exceeds the soft ceiling:
+ # then the anchor would retain the entire oversized turn and blow the budget by design, so the
+ # clean tool-group boundary above wins and the turn-opening request rides the handoff (#80449).
+ last_user_idx = self._find_last_user_message_idx(messages, head_end)
+ user_anchored_cut = self._ensure_last_user_message_in_tail(messages, cut_idx, head_end)
+ split_oversized_turn = False
+ if (
+ allow_split_turn
+ and last_user_idx >= head_end
+ and last_user_idx < cut_idx
+ and user_anchored_cut < cut_idx
+ # A single oversized user message is indivisible and must stay verbatim in the tail; this
+ # exception is only for aggregate turn growth after a normally sized opening request.
+ and _estimate_msg_budget_tokens(messages[last_user_idx]) <= soft_ceiling
+ and len(_content_text_for_contains(messages[last_user_idx].get("content")).strip())
+ <= _ACTIVE_TASK_MAX_CHARS
+ and sum(
+ _estimate_msg_budget_tokens(message) for message in messages[user_anchored_cut:]
+ ) > soft_ceiling
+ ):
+ split_oversized_turn = True
+ if not self.quiet_mode:
+ logger.info(
+ "Active turn exceeds protected-tail soft ceiling; keeping tool-group-aligned "
+ "mid-turn cut at index %d instead of anchoring user message %d (#80449)",
+ cut_idx, last_user_idx,
+ )
+ else:
+ cut_idx = user_anchored_cut
+ # An older visible assistant reply can precede the active user turn; when the active turn was
+ # deliberately split above, pulling back to it would undo the bounded exception. A latest
+ # assistant already inside the chosen tail is unchanged.
+ assistant_anchored_cut = self._ensure_last_assistant_message_in_tail(messages, cut_idx, head_end)
+ if not split_oversized_turn or assistant_anchored_cut == cut_idx:
+ cut_idx = assistant_anchored_cut
# Optional multi-user anchor; n<=1 is gated here (not delegated): re-running the single-user anchor after
# the assistant anchor could re-trigger its forward turn-pair push. getattr: __new__ doubles skip __init__.
+ # Skipped entirely under the split exception, which would otherwise undo the bounded cut.
_min_tail_users = getattr(self, "min_tail_user_messages", 1)
- if isinstance(_min_tail_users, int) and not isinstance(_min_tail_users, bool) and _min_tail_users > 1:
+ if (
+ not split_oversized_turn
+ and 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
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index 275b77b6a4b..a8f17772ea6 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -282,7 +282,7 @@ class MicroCompactionMixin:
def _next_exchange(self, messages: List[Dict[str, Any]]) -> Optional[tuple[int, int]]:
"""The next un-absorbed exchange inside the compressible window, or None."""
compress_start = self._align_boundary_forward(messages, self._protect_head_size(messages))
- compress_end = self._find_tail_cut_by_tokens(messages, compress_start)
+ compress_end = self._find_tail_cut_by_tokens(messages, compress_start, allow_split_turn=False)
if compress_start >= compress_end:
return None
cursor = self._resolve_compact_cursor(messages, compress_start, compress_end)
diff --git a/tests/agent/test_split_turn_compaction.py b/tests/agent/test_split_turn_compaction.py
new file mode 100644
index 00000000000..e18c04b6af8
--- /dev/null
+++ b/tests/agent/test_split_turn_compaction.py
@@ -0,0 +1,157 @@
+"""Regression for #80449 — an oversized in-progress turn must stay compressible.
+
+When one turn (opening user message + many individually small tool groups) grows past
+the protected-tail soft ceiling, anchoring the cut back to the turn-opening request kept
+the whole turn verbatim: compaction re-fired with an empty summarizable window and the
+session sat over threshold. The cut must instead land on a tool-group-aligned mid-turn
+boundary, and the active request must survive the handoff.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+
+from agent.context_compressor import (
+ COMPRESSED_SUMMARY_METADATA_KEY,
+ ContextCompressor,
+ _estimate_msg_budget_tokens,
+)
+
+
+_ACTIVE_REQUEST = "Inspect every shard and preserve the active request exactly."
+_TOKEN_BUDGET = 250
+
+
+def compressor() -> ContextCompressor:
+ with patch(
+ "agent.context_compressor.get_model_context_length",
+ return_value=100_000,
+ ):
+ instance = ContextCompressor(
+ model="test/model",
+ threshold_percent=0.85,
+ protect_first_n=0,
+ protect_last_n=3,
+ quiet_mode=True,
+ )
+ _ = instance.context_length
+ instance.tail_token_budget = _TOKEN_BUDGET
+ return instance
+
+
+def _tool_group(index: int) -> list[dict]:
+ call_id = f"call_{index}"
+ return [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": "inspect_shard",
+ # Large enough for the complete turn to exceed the
+ # ceiling, but below the phase-1 argument-prune limit.
+ "arguments": "x" * 440,
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": call_id,
+ # Keep each result below the phase-1 result-prune floor. The bug is
+ # aggregate turn size, not one individually oversized result.
+ "content": f"result-{index}:" + "r" * 110,
+ },
+ ]
+
+
+def _oversized_active_turn() -> list[dict]:
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "older request"},
+ {"role": "assistant", "content": "older request completed"},
+ {"role": "user", "content": _ACTIVE_REQUEST},
+ ]
+ for index in range(10):
+ messages.extend(_tool_group(index))
+ return messages
+
+
+def _assert_tool_pairs_are_complete(messages: list[dict]) -> None:
+ call_ids = {
+ call["id"]
+ for message in messages
+ for call in message.get("tool_calls") or []
+ }
+ result_ids = {
+ message["tool_call_id"]
+ for message in messages
+ if message.get("role") == "tool"
+ }
+ assert call_ids == result_ids
+
+
+def test_oversized_active_turn_uses_a_mid_turn_tool_boundary(
+ compressor: ContextCompressor,
+) -> None:
+ messages = _oversized_active_turn()
+ head_end = compressor._protect_head_size(messages)
+
+ cut = compressor._find_tail_cut_by_tokens(
+ messages,
+ head_end,
+ token_budget=_TOKEN_BUDGET,
+ )
+
+ active_user_idx = next(
+ index
+ for index, message in enumerate(messages)
+ if message.get("content") == _ACTIVE_REQUEST
+ )
+ tail_tokens = sum(_estimate_msg_budget_tokens(msg) for msg in messages[cut:])
+
+ assert cut > active_user_idx
+ # Tool-group alignment may retain one additional indivisible group beyond
+ # the scalar ceiling. It must not retain the whole active turn.
+ max_group_tokens = max(
+ sum(_estimate_msg_budget_tokens(msg) for msg in _tool_group(index))
+ for index in range(10)
+ )
+ assert tail_tokens <= int(_TOKEN_BUDGET * 1.5) + max_group_tokens
+ assert tail_tokens < sum(
+ _estimate_msg_budget_tokens(msg) for msg in messages[active_user_idx:]
+ )
+ assert messages[cut]["role"] == "assistant"
+ _assert_tool_pairs_are_complete(messages[head_end:cut])
+ _assert_tool_pairs_are_complete(messages[cut:])
+
+
+def test_full_compaction_preserves_active_request_and_tool_pairs(
+ compressor: ContextCompressor,
+) -> None:
+ messages = _oversized_active_turn()
+
+ # Exercise the deterministic handoff too: even when the summary model is
+ # unavailable, splitting the turn must not lose the opening request.
+ with patch.object(compressor, "_generate_summary", return_value=None):
+ compressed = compressor.compress(messages, current_tokens=90_000)
+
+ summary_rows = [
+ message
+ for message in compressed
+ if message.get(COMPRESSED_SUMMARY_METADATA_KEY)
+ ]
+ assert len(summary_rows) == 1
+ assert _ACTIVE_REQUEST in str(summary_rows[0].get("content"))
+ assert sum(
+ _ACTIVE_REQUEST in str(message.get("content"))
+ for message in compressed
+ ) == 1
+ assert len(compressed) < len(messages)
+ _assert_tool_pairs_are_complete(compressed)
\ No newline at end of file