Skip to content

The agent that grows with you

fix(compressor): never commit a compression that grows the transcript (in-place path)

dhruv kejriwalffaa63f887b1
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 45ede85c77c..d069560cd8e 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -71,7 +71,10 @@ from agent.context_engine import (
automatic_compaction_status_message,
sanitize_memory_context,
)
-from agent.model_metadata import estimate_request_tokens_rough
+from agent.model_metadata import (
+ estimate_messages_tokens_rough,
+ estimate_request_tokens_rough,
+)
from agent.session_activity import ActivityProvenance, normalize_activity_provenance
logger = logging.getLogger(__name__)
@@ -3280,6 +3283,51 @@ def compress_context(
# away regardless of whether the id rotates).
agent.commit_memory_session(messages)
+ # Anti-growth guard at the COMMIT SITE: never persist a
+ # compression that makes the transcript larger (observed:
+ # 379K -> 687K when the generated summary plus retained
+ # reasoning exceeded what it replaced). Compare like-for-like
+ # (both rough estimates of the same message shape) so an
+ # "actual vs estimate" measurement mismatch cannot produce a
+ # false verdict. The gateway has a rotation-path-only guard
+ # (#83339), but in-place compaction commits inside this method
+ # via archive_and_compact — before the gateway can inspect the
+ # result — so the guard must live here to protect both paths.
+ # On growth, treat the attempt as a no-op: the original
+ # transcript stays untouched and durable.
+ _rough_in = estimate_messages_tokens_rough(messages)
+ _rough_out = estimate_messages_tokens_rough(compressed)
+ if _rough_out > _rough_in:
+ logger.warning(
+ "Compression refused: compressed transcript would be "
+ "larger than the original (session=%s, ~%s -> ~%s "
+ "tokens); keeping the original transcript unchanged",
+ agent.session_id or "none",
+ f"{_rough_in:,}",
+ f"{_rough_out:,}",
+ )
+ try:
+ agent._emit_warning(
+ "⚠️ Compression refused: the generated summary "
+ "would have GROWN the conversation instead of "
+ "shrinking it. No messages were dropped — "
+ "conversation continues unchanged."
+ )
+ except Exception:
+ pass
+ _existing_sp = getattr(agent, "_cached_system_prompt", None)
+ if not _existing_sp:
+ _existing_sp = agent._build_system_prompt(system_message)
+ _emit_compression_attempt_telemetry(
+ agent,
+ started_at=_attempt_started_at,
+ commit_status="aborted",
+ split_status="aborted",
+ failure_class="would_grow",
+ )
+ _release_lock()
+ return messages, _existing_sp
+
if in_place:
# ── In-place compaction: keep the same session_id ──────────
# No end_session, no new row, no parent_session_id, no title
diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.py
index fb8e111a7e7..f87baa78acf 100644
--- a/tests/agent/test_compression_rotation_state.py
+++ b/tests/agent/test_compression_rotation_state.py
@@ -572,8 +572,18 @@ class TestTodoSnapshotMergedNotDuplicated:
lambda: "## Current Tasks\n- [ ] inspect image"
)
+ # Input transcript must be large enough that the fake compressor's
+ # output is a genuine shrink — the no-growth commit guard refuses
+ # to persist a compression that grows the transcript.
+ input_msgs = [
+ {
+ "role": "user" if i % 2 == 0 else "assistant",
+ "content": f"m{i} " + "x" * 400,
+ }
+ for i in range(20)
+ ]
compressed, _ = agent._compress_context(
- _msgs(), "sys", approx_tokens=120_000
+ input_msgs, "sys", approx_tokens=120_000
)
assert len(compressed) == 3
diff --git a/tests/run_agent/test_compression_boundary_hook.py b/tests/run_agent/test_compression_boundary_hook.py
index 36eacb6c263..2595c0ee646 100644
--- a/tests/run_agent/test_compression_boundary_hook.py
+++ b/tests/run_agent/test_compression_boundary_hook.py
@@ -243,9 +243,11 @@ class TestCompressionBoundaryHook:
original_sid = agent.session_id
- # Must not raise
+ # Must not raise. Input must be large enough that the fake
+ # compressor's one-message summary is a genuine shrink — the
+ # no-growth commit guard refuses to rotate on transcript growth.
compressed, _prompt = agent._compress_context(
- [{"role": "user", "content": "m"}], "sys", approx_tokens=100
+ [{"role": "user", "content": "m" * 400}], "sys", approx_tokens=100
)
assert compressed
assert agent.session_id != original_sid
diff --git a/tests/run_agent/test_compression_persistence.py b/tests/run_agent/test_compression_persistence.py
index 6af2248f862..70568b02aba 100644
--- a/tests/run_agent/test_compression_persistence.py
+++ b/tests/run_agent/test_compression_persistence.py
@@ -296,13 +296,17 @@ class TestFlushAfterCompression:
# for a reason INDEPENDENT of _db_persisted (ephemeral scaffolding,
# synthetic recovery turns). Keep this fixture free of such messages
# or the row count would legitimately differ from len(compressed).
+ # The transcript must also be large enough that the provider-less
+ # static fallback net-shrinks it (middle drops must outweigh the
+ # fixed compaction marker overhead), or the no-growth commit guard
+ # correctly refuses the rotation this test exercises.
messages = [
{
"role": "user" if i % 2 == 0 else "assistant",
- "content": f"message {i}",
+ "content": f"message {i} " + "x" * 200,
"_db_persisted": True,
}
- for i in range(12)
+ for i in range(40)
]
with patch("agent.context_compressor.call_llm", side_effect=RuntimeError("no provider")):
diff --git a/tests/run_agent/test_in_place_compaction.py b/tests/run_agent/test_in_place_compaction.py
index 2149a2d0c84..f354a347aa6 100644
--- a/tests/run_agent/test_in_place_compaction.py
+++ b/tests/run_agent/test_in_place_compaction.py
@@ -245,6 +245,82 @@ class TestInPlaceConfigDefault:
assert DEFAULT_CONFIG["compression"].get("in_place") is True
+class TestInPlaceAntiGrowthGuard:
+ """A compression whose result is LARGER than its input must never be
+ persisted. In-place compaction commits inside compress_context() via
+ archive_and_compact — BEFORE the gateway's rotation-only anti-growth
+ guard (#83339) can inspect the result — so the guard must live at the
+ commit site and cover the in-place path too. Observed failure: session
+ hygiene "compressed" 426 -> 426 msgs, ~379,216 -> ~687,888 tokens and
+ durably persisted the growth."""
+
+ def test_in_place_refuses_growing_compression(self):
+ from hermes_state import SessionDB
+ from agent.conversation_compression import compress_context
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ sid = "20260619_antigrow"
+ _seed(db, sid, "grow")
+ agent = _make_agent(db, sid, in_place=True)
+ agent._last_flushed_db_idx = 5
+
+ def _growing_compress(messages, current_tokens=None, focus_topic=None, force=False):
+ # A "summary" bigger than the entire input transcript.
+ return [
+ {"role": "user", "content": "X" * 200_000},
+ {"role": "assistant", "content": "tiny tail"},
+ ]
+
+ agent.context_compressor.compress = _growing_compress
+ messages = [{"role": "user", "content": f"m{i}"} for i in range(8)]
+ compressed, _sp = compress_context(
+ agent, messages, approx_tokens=100_000, system_message="sys"
+ )
+
+ # Guard refused: the original transcript is returned untouched.
+ assert compressed == messages
+ # No in-place commit signal — nothing was persisted.
+ assert getattr(agent, "_last_compaction_in_place", False) is False
+ # Durable state is byte-for-byte the pre-compression live set:
+ # nothing archived, nothing inserted.
+ reloaded = db.get_messages_as_conversation(sid)
+ assert [m["content"] for m in reloaded] == [f"msg {i}" for i in range(8)]
+ all_rows = db.get_messages(sid, include_inactive=True)
+ assert len(all_rows) == 8
+ assert not any(not m.get("active", 1) for m in all_rows)
+ # Session identity untouched.
+ assert agent.session_id == sid
+ assert db.get_session(sid)["end_reason"] is None
+
+ def test_in_place_still_commits_shrinking_compression(self):
+ """The guard must not block legitimate compressions — a result SMALLER
+ than the input still commits in place (regression net for #83339)."""
+ from hermes_state import SessionDB
+ from agent.conversation_compression import compress_context
+
+ with tempfile.TemporaryDirectory() as tmp:
+ db = SessionDB(db_path=Path(tmp) / "t.db")
+ sid = "20260619_shrink"
+ _seed(db, sid, "shrink")
+ agent = _make_agent(db, sid, in_place=True)
+ agent._last_flushed_db_idx = 5
+
+ messages = [{"role": "user", "content": f"m{i}"} for i in range(8)]
+ compressed, _sp = compress_context(
+ agent, messages, approx_tokens=100_000, system_message="sys"
+ )
+
+ # The fake compressor returns a small summary — commit happens.
+ assert agent._last_compaction_in_place is True
+ reloaded = db.get_messages_as_conversation(sid)
+ assert [m.get("content") for m in reloaded] == [
+ "[CONTEXT COMPACTION] summary of prior turns",
+ "recent reply",
+ ]
+
+
+
class TestCompactedTurnsStaySearchable:
"""Teknium's review hinges on the pre-compaction transcript staying
DISCOVERABLE after in-place compaction. Compaction-archived rows