Skip to content

The agent that grows with you

fix(compaction): stop idle compaction re-summarising a transcript that has not grown

joaomarcosa89f6aba44c6
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 691b1de9c06..e0f06338dc2 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -493,6 +493,7 @@ def _should_idle_compact(
tokens: int,
floor_tokens: int,
cooldown_active: bool,
+ last_compaction_tokens: int = 0,
) -> bool:
"""Decide whether an idle-triggered compaction should run this turn.
@@ -508,6 +509,23 @@ def _should_idle_compact(
*to*), so a small idle thread never pays for a summarisation that saves
nothing, and it defers to an active compression-failure cooldown.
+ ``floor_tokens`` alone is a *theoretical* target (``threshold_tokens ×
+ summary_target_ratio``) that a real pass routinely misses: the system
+ prompt, the tool schemas and the protected head/tail are an
+ incompressible floor. A session that compacted to well above that target
+ therefore stays above it forever, so every later idle resume re-runs a
+ full summarisation over a transcript that has not grown — minutes of
+ silently blocked prompt on a slow route, reclaiming nothing (#97239).
+
+ ``last_compaction_tokens`` is what the previous pass on this session
+ actually produced (``ContextCompressor.last_compression_rough_tokens``,
+ the same ``estimate_request_tokens_rough`` shape as ``tokens``). When it
+ is known, require the transcript to have accumulated at least one
+ ``floor_tokens`` worth of *new* content on top of it before paying for
+ another pass. ``0`` — no compaction recorded yet, or the counter reset by
+ a rebind/recalibration — keeps the original floor semantics exactly, so
+ the first idle compaction of any session is unaffected.
+
Pure predicate so the policy is unit-testable without a live agent.
"""
if not enabled or idle_after_seconds <= 0:
@@ -516,7 +534,10 @@ def _should_idle_compact(
return False
if cooldown_active:
return False
- return tokens > floor_tokens
+ effective_floor = floor_tokens
+ if last_compaction_tokens > 0:
+ effective_floor = max(effective_floor, last_compaction_tokens + floor_tokens)
+ return tokens > effective_floor
@dataclass
@@ -960,6 +981,18 @@ def build_turn_context(
_idle_cooldown = getattr(
_compressor, "get_active_compression_failure_cooldown", lambda: None
)()
+ # What the previous pass on this session actually produced — the
+ # honest floor, versus the theoretical ``_idle_floor`` above. Type
+ # pin: minimal compressor doubles (SimpleNamespace / MagicMock)
+ # expose truthy non-ints here, and only a real int may raise the
+ # floor. Anything else falls back to 0 = original semantics.
+ _idle_last_compaction = getattr(
+ _compressor, "last_compression_rough_tokens", 0
+ )
+ if not isinstance(_idle_last_compaction, int) or isinstance(
+ _idle_last_compaction, bool
+ ):
+ _idle_last_compaction = 0
if _should_idle_compact(
enabled=agent.compression_enabled,
idle_after_seconds=_idle_after,
@@ -967,14 +1000,16 @@ def build_turn_context(
tokens=_idle_tokens,
floor_tokens=_idle_floor,
cooldown_active=bool(_idle_cooldown),
+ last_compaction_tokens=_idle_last_compaction,
):
logger.info(
"Idle compaction: %ss idle >= %ss, ~%s tokens > %s floor "
- "(session %s)",
+ "(last compaction produced ~%s) (session %s)",
int(_idle_gap),
_idle_after,
f"{_idle_tokens:,}",
f"{_idle_floor:,}",
+ f"{_idle_last_compaction:,}" if _idle_last_compaction > 0 else "n/a",
agent.session_id or "none",
)
_idle_status = automatic_compaction_status_message(
diff --git a/tests/agent/test_idle_compaction.py b/tests/agent/test_idle_compaction.py
index f4de6c819a7..ba89099cfe4 100644
--- a/tests/agent/test_idle_compaction.py
+++ b/tests/agent/test_idle_compaction.py
@@ -39,3 +39,66 @@ class TestShouldIdleCompact:
def test_fires_just_above_floor(self):
assert _decide(tokens=40_001, floor_tokens=40_000) is True
+
+class TestPostCompactionFloor:
+ """The floor also honours what the previous pass actually produced (#97239).
+
+ ``floor_tokens`` is the theoretical target (threshold × target_ratio); a
+ real pass lands well above it because the system prompt, the tool schemas
+ and the protected head/tail are incompressible. Without this, an already
+ compacted session re-summarises itself on every idle resume forever.
+ """
+
+ def test_unrecorded_last_compaction_keeps_original_floor(self):
+ # 0 = nothing compacted yet (or state reset) — original semantics.
+ assert _decide(tokens=40_001, floor_tokens=40_000,
+ last_compaction_tokens=0) is True
+
+ def test_skips_when_transcript_has_not_grown_since_last_compaction(self):
+ # Previous pass produced 44,000; the transcript is still ~that size.
+ assert _decide(tokens=44_100, floor_tokens=40_000,
+ last_compaction_tokens=44_000) is False
+
+ def test_fires_once_a_full_floor_of_new_content_accumulated(self):
+ assert _decide(tokens=84_001, floor_tokens=40_000,
+ last_compaction_tokens=44_000) is True
+
+ def test_does_not_fire_at_exactly_the_raised_floor(self):
+ assert _decide(tokens=84_000, floor_tokens=40_000,
+ last_compaction_tokens=44_000) is False
+
+ def test_reported_session_stops_recompacting_itself(self):
+ """Exact numbers from issue #97239.
+
+ The 17:01 pass reduced 64,105 -> 44,579 tokens; the 17:36 resume
+ re-fired on that same transcript because 44,579 > the 25,502
+ theoretical floor, blocking the prompt for another 256 s.
+ """
+ common = dict(idle_after_seconds=1, idle_gap_seconds=747.0,
+ floor_tokens=25_502)
+ # Before the fix the second resume fired: 44,579 > 25,502.
+ assert _decide(tokens=44_579, last_compaction_tokens=0, **common) is True
+ # With the previous pass's real output known, it sits the round out.
+ assert _decide(tokens=44_579, last_compaction_tokens=44_579,
+ **common) is False
+
+ def test_an_effective_pass_still_raises_the_floor(self):
+ # 100K -> 10K is a good pass; another one is worth it only once about
+ # a floor's worth of new content has landed on top of the 10K.
+ assert _decide(tokens=30_000, floor_tokens=25_000,
+ last_compaction_tokens=10_000) is False
+ assert _decide(tokens=35_001, floor_tokens=25_000,
+ last_compaction_tokens=10_000) is True
+
+ def test_other_gates_still_win_over_the_raised_floor(self):
+ # Growth alone must not defeat the cooldown / opt-out gates.
+ assert _decide(tokens=200_000, floor_tokens=40_000,
+ last_compaction_tokens=44_000,
+ cooldown_active=True) is False
+ assert _decide(tokens=200_000, floor_tokens=40_000,
+ last_compaction_tokens=44_000,
+ idle_after_seconds=0) is False
+ assert _decide(tokens=200_000, floor_tokens=40_000,
+ last_compaction_tokens=44_000,
+ idle_gap_seconds=0.5) is False
+
diff --git a/tests/agent/test_idle_compaction_lock_and_guards.py b/tests/agent/test_idle_compaction_lock_and_guards.py
index 613488abe4d..d1c30a024a3 100644
--- a/tests/agent/test_idle_compaction_lock_and_guards.py
+++ b/tests/agent/test_idle_compaction_lock_and_guards.py
@@ -53,18 +53,20 @@ def _prep_idle_agent(db: SessionDB, session_id: str, *, idle_after: int = 60,
return agent
-def _run_prologue(agent, history, user_message="hello again"):
+def _run_prologue(agent, history, user_message="hello again",
+ rough_tokens: int = 999_999):
"""Invoke ``build_turn_context`` the way ``conversation_loop`` does.
The token-threshold preflight gate is pinned False so these tests
exercise the IDLE trigger in isolation (the preflight path has its own
- coverage in ``test_turn_context.py``).
+ coverage in ``test_turn_context.py``). ``rough_tokens`` pins the estimate
+ that the idle floor is compared against.
"""
with patch("agent.auxiliary_client.set_runtime_main", lambda *a, **k: None), \
patch("agent.turn_context._should_run_preflight_estimate",
return_value=False), \
patch("agent.turn_context.estimate_request_tokens_rough",
- return_value=999_999):
+ return_value=rough_tokens):
return build_turn_context(
agent=agent,
user_message=user_message,
@@ -145,6 +147,96 @@ def test_idle_compaction_defers_to_held_compression_lock(tmp_path: Path) -> None
assert ctx.messages[ctx.current_turn_user_idx]["content"] == "hello again"
+def _prep_recompaction_agent(db: SessionDB, sid: str):
+ """Idle-eligible agent with the #97239 threshold/floor numbers.
+
+ threshold 127,510 x target_ratio 0.20 => a 25,502 theoretical floor, the
+ same one the reported session kept clearing while never actually
+ shrinking below ~44,579.
+ """
+ agent = _prep_idle_agent(db, sid, idle_after=1, idle_gap=747.0)
+ agent.context_compressor.threshold_tokens = 127_510
+ agent.context_compressor.summary_target_ratio = 0.20
+ agent.context_compressor.emit_automatic_compaction_status = True
+ del agent.context_compressor.get_automatic_compaction_status_message
+ return agent
+
+
+def _pin_compress_seam(agent):
+ """Stub the forwarder so these tests assert the idle DECISION only.
+
+ Whether ``compress_context`` then rotates, locks or aborts is covered by
+ the tests above; here the question is purely whether the idle floor let
+ the turn through. Returning the input list is the documented "skipped"
+ shape, so the caller's re-baseline stays disarmed either way.
+ """
+ seam = MagicMock(side_effect=lambda messages, *a, **k: (messages, "SYSTEM"))
+ agent._compress_context = seam
+ return seam
+
+
+def test_idle_compaction_skips_a_transcript_that_has_not_grown(tmp_path: Path) -> None:
+ """The reported loop: re-compacting a session the last pass just produced.
+
+ ``last_compression_rough_tokens`` records what the previous pass actually
+ emitted (44,579). The theoretical floor (25,502) is far below it, so the
+ old predicate re-fired a full multi-minute summary on every idle resume
+ even though the transcript had not grown at all (#97239).
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid = "IDLE_RECOMPACT"
+ db.create_session(sid, source="cli")
+ agent = _prep_recompaction_agent(db, sid)
+ agent.context_compressor.last_compression_rough_tokens = 44_579
+ seam = _pin_compress_seam(agent)
+
+ ctx = _run_prologue(agent, _history(), rough_tokens=44_579)
+
+ seam.assert_not_called()
+ agent.context_compressor.compress.assert_not_called()
+ assert agent.session_id == sid
+ assert len(ctx.messages) == len(_history()) + 1
+ assert ctx.current_turn_user_idx == len(ctx.messages) - 1
+
+
+def test_idle_compaction_fires_again_once_the_transcript_grows(tmp_path: Path) -> None:
+ """The raised floor is a deferral, not an off switch."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid = "IDLE_REGROWN"
+ db.create_session(sid, source="cli")
+ agent = _prep_recompaction_agent(db, sid)
+ agent.context_compressor.last_compression_rough_tokens = 44_579
+ seam = _pin_compress_seam(agent)
+
+ # 44,579 + 25,502 = 70,081 — one floor's worth of new content on top.
+ _run_prologue(agent, _history(), rough_tokens=70_082)
+
+ seam.assert_called_once()
+
+
+def test_idle_compaction_ignores_a_non_int_last_compaction_reading(
+ tmp_path: Path,
+) -> None:
+ """Compressor doubles expose a Mock here — it must not raise the floor.
+
+ An unset/derived attribute falls back to 0, which restores the original
+ ``tokens > floor_tokens`` semantics exactly.
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid = "IDLE_MOCKREAD"
+ db.create_session(sid, source="cli")
+ agent = _prep_recompaction_agent(db, sid)
+ # Left as the MagicMock auto-attribute (a truthy non-int).
+ assert not isinstance(
+ agent.context_compressor.last_compression_rough_tokens, int
+ )
+ seam = _pin_compress_seam(agent)
+
+ _run_prologue(agent, _history(), rough_tokens=44_579)
+
+ seam.assert_called_once()
+
+
def test_idle_compaction_respects_anti_thrash_breaker(tmp_path: Path) -> None:
"""A tripped ineffective-compression breaker must block the idle trigger.