Skip to content

The agent that grows with you

fix(compression): measure the authored request, not the reply quote, before splitting an oversized turn

Anthony Ruiz5b3db284bed8
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 176f636dd46..0e16ac20da5 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1396,6 +1396,31 @@ def _content_text_for_contains(content: Any) -> str:
return "" if content is None else content if isinstance(content, str) else str(content)
+# Gateway reply pointer prepended to a user turn (gateway/run_inbound.py
+# ``_prepend_inbound_reply_context``), optionally behind the Discord triggering note.
+# Non-greedy: a quote that itself contains the closing delimiter is only partly
+# stripped, which over-counts the request and keeps the conservative anchor.
+_GATEWAY_REPLY_POINTER_RE = re.compile(
+ r'\A(?:\[Triggering message id: [^\n]*\]\n\n)?'
+ r'\[Replying to(?: your previous message)?: ".*?"\]\n\n',
+ re.DOTALL,
+)
+
+
+def _authored_request_text(content: Any) -> str:
+ """Text the user wrote in a turn, without the gateway's reply-to pointer.
+
+ The pointer quotes another message verbatim; it disambiguates which message is being
+ answered but is not part of the request, so it must not count toward request size. A
+ request restated after an earlier compaction carries the replay header first: measure
+ the restated text after it, as ``_reappend_inflight_user_task`` does.
+ """
+ text = _content_text_for_contains(content).strip()
+ if _INFLIGHT_TASK_REPLAY_HEADER in text:
+ text = text.rsplit(_INFLIGHT_TASK_REPLAY_HEADER, 1)[1].strip()
+ return _GATEWAY_REPLY_POINTER_RE.sub("", text, count=1).strip()
+
+
def _is_text_only_content(content: Any) -> bool:
"""Whether the active request can be restated without losing a content part."""
if isinstance(content, str):
@@ -4427,9 +4452,13 @@ Write only the summary body. Do not include any preamble or prefix."""
text = _redact_compaction_text(_content_text_for_contains(msg.get("content")).strip())
if not text:
continue
+ if len(text) > _ACTIVE_TASK_MAX_CHARS:
+ # Past the cap, drop a gateway reply quote first so elision cannot keep the quote
+ # and cut the request; the split-turn gate measures the same authored text.
+ text = _redact_compaction_text(_authored_request_text(msg.get("content"))) or text
text = re.sub(r"\s+", " ", text)
# Elide AFTER repr: repr would escape the marker's "Hermes's" and hide a copy from the
- # guard. Text within the cap stays whole (the split-turn path relies on that).
+ # guard. Authored text within the cap stays whole (the split-turn path relies on that).
text = repr(text) if len(text) <= _ACTIVE_TASK_MAX_CHARS else elide(repr(text), _ACTIVE_TASK_MAX_CHARS)
return (
f"User asked (deterministic, from compacted turns): {text}\n"
@@ -5060,8 +5089,9 @@ Write only the summary body. Do not include any preamble or prefix."""
# 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
+ # Measure what the user wrote: a gateway reply pointer quotes another message and
+ # would otherwise disable the split for a short reply to a long answer.
+ and len(_authored_request_text(messages[last_user_idx].get("content"))) <= _ACTIVE_TASK_MAX_CHARS
# Only split when there is real turn body to summarize: if the oversized weight is the
# active turn's own newest group, the pre-anchor cut retains it anyway, so taking the
# active request out of the tail buys no reclaim and loses the #10896 anchor.
diff --git a/tests/agent/test_split_turn_compaction.py b/tests/agent/test_split_turn_compaction.py
index ec07a7fece4..92849bb5e6e 100644
--- a/tests/agent/test_split_turn_compaction.py
+++ b/tests/agent/test_split_turn_compaction.py
@@ -9,6 +9,7 @@ boundary, and the active request must survive the handoff.
from __future__ import annotations
+from typing import Any
from unittest.mock import patch
import pytest
@@ -16,6 +17,10 @@ import pytest
from agent.context_compressor import (
COMPRESSED_SUMMARY_METADATA_KEY,
ContextCompressor,
+ _ACTIVE_TASK_MAX_CHARS,
+ _INFLIGHT_TASK_REPLAY_HEADER,
+ _SUMMARY_END_MARKER,
+ _authored_request_text,
_estimate_msg_budget_tokens,
)
@@ -221,7 +226,6 @@ def test_a_tail_that_fits_the_budget_still_anchors_the_active_request() -> None:
def test_active_request_survives_repeated_compaction_and_restart(tmp_path) -> None:
# Fallback compaction (no LLM summary) + SQLite reload between cycles:
# the active request must be recognized from persisted content alone.
- from agent.context_compressor import _INFLIGHT_TASK_REPLAY_HEADER, _SUMMARY_END_MARKER
from agent.conversation_compression import _ensure_compressed_has_user_turn
from hermes_state import SessionDB
@@ -277,6 +281,118 @@ def test_active_request_survives_repeated_compaction_and_restart(tmp_path) -> No
assert not detect({"role": "user", "content": "hi", "_inflight_replay_merged": True})
+_LONG_QUOTE = "Earlier assistant answer. " * 80
+
+
+def _gateway_reply(text: str, *, own: bool = False, discord_id: str | None = None) -> str:
+ """Build the row exactly as the gateway does, so a pointer format change fails here."""
+ from gateway.config import Platform
+ from gateway.platforms.event import MessageEvent
+ from gateway.run import GatewayRunner
+ from gateway.session import SessionSource
+
+ platform = Platform.DISCORD if discord_id else Platform.TELEGRAM
+ source = SessionSource(platform=platform, chat_id="1", chat_type="dm")
+ event = MessageEvent(
+ text=text, source=source, message_id=discord_id,
+ reply_to_message_id="7", reply_to_text=_LONG_QUOTE, reply_to_is_own_message=own,
+ )
+ with patch("gateway.session._discord_tools_loaded", return_value=True):
+ return GatewayRunner._prepend_inbound_reply_context(event, source, text)
+
+
+def _reply_turn(request: str, groups: int = 30) -> list[dict[str, Any]]:
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "older request"},
+ {"role": "assistant", "content": "older request completed"},
+ {"role": "user", "content": request},
+ ]
+ for index in range(groups):
+ messages.extend(_tool_group(index))
+ return messages
+
+
+ "gateway_kwargs",
+ [{}, {"own": True}, {"discord_id": "42"}],
+ ids=["reply", "own-reply", "discord-note"],
+)
+def test_reply_pointer_does_not_count_toward_the_request_size(gateway_kwargs: dict[str, Any]) -> None:
+ """A short reply to a long answer must still split: the quote is not the request.
+
+ The gateway prepends ``[Replying to: "<quoted message>"]``; measured whole, a reply to a
+ long assistant answer exceeded the active-task cap, the split never fired, and every
+ automatic pass hit an empty window (structural backoff) while the turn kept growing.
+ """
+ request = _gateway_reply(_ACTIVE_REQUEST, **gateway_kwargs)
+ assert len(request) > _ACTIVE_TASK_MAX_CHARS
+ assert _authored_request_text(request) == _ACTIVE_REQUEST
+ compressor = _make_compressor()
+ compressor.tail_token_budget = 1_000
+ messages = _reply_turn(request)
+ active_user_idx = 3
+
+ cut = compressor._find_tail_cut_by_tokens(messages, compressor._protect_head_size(messages))
+ assert cut > active_user_idx
+
+ with patch.object(compressor, "_generate_summary", return_value=None):
+ compressed = compressor.compress(messages, current_tokens=90_000)
+ assert len(compressed) < len(messages)
+ _assert_tool_pairs_are_complete(compressed)
+ actionable = "\n".join(
+ str(m.get("content")).rsplit(_SUMMARY_END_MARKER, 1)[-1]
+ for m in compressed if m["role"] == "user"
+ )
+ assert actionable.count(_ACTIVE_REQUEST) == 1
+
+
+def test_restated_reply_keeps_splitting_on_later_compactions() -> None:
+ """After the first split the request is restated behind the replay header; the next
+ passes must still measure the authored text, not the header plus the quote.
+
+ ``protect_first_n=3`` (the default) keeps the restated row standalone, so the second
+ pass anchors on it instead of on the summary carrier.
+ """
+ compressor = _make_compressor(protect_first_n=3)
+ compressor.tail_token_budget = 1_000
+ messages = _reply_turn(_gateway_reply(_ACTIVE_REQUEST))
+ for cycle in range(3):
+ with patch.object(compressor, "_generate_summary", return_value=None):
+ compressed = compressor.compress(messages, current_tokens=90_000)
+ # One cycle adds 30 tool groups (60 rows); a refused split reclaims only a handful.
+ assert len(messages) - len(compressed) >= 30, f"cycle {cycle}: split refused"
+ _assert_tool_pairs_are_complete(compressed)
+ messages = list(compressed)
+ for index in range(30):
+ messages.extend(_tool_group(100 * (cycle + 1) + index))
+
+
+def test_task_snapshot_keeps_the_request_not_the_reply_quote() -> None:
+ """Head elision of a long reply row used to keep only the quote and drop the request."""
+ snapshot = ContextCompressor._latest_user_task_snapshot(
+ [{"role": "user", "content": _gateway_reply("please fix the parser")}]
+ )
+ assert snapshot is not None
+ assert "please fix the parser" in snapshot
+ assert "Earlier assistant answer" not in snapshot
+
+
+ "content, expected",
+ [
+ (_ACTIVE_REQUEST, _ACTIVE_REQUEST),
+ ('[Replying to: "a"]\n\n', '[Replying to: "a"]'),
+ ('[Replying to: "q"]\n\nsays "x"]\n\n in code"]\n\ngo', 'says "x"]\n\n in code"]\n\ngo'),
+ (f'{_INFLIGHT_TASK_REPLAY_HEADER}\n[Replying to: "q"]\n\ngo', "go"),
+ (f'I quoted it:\n[Replying to: "q"]\n\ngo', 'I quoted it:\n[Replying to: "q"]\n\ngo'),
+ ],
+ ids=["no-pointer", "pointer-only", "quote-with-delimiter", "after-replay-header", "not-leading"],
+)
+def test_authored_request_text_never_strips_user_text(content: str, expected: str) -> None:
+ assert _authored_request_text(content) == expected
+
+
@pytest.mark.parametrize(
"payload, can_split",
[