The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compaction): bench a failing summary model instead of blocking compaction
Elisa Martinez Abadbdba7042a9b5
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex f1e07b34872..e8a27e30a81 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -2398,6 +2398,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginself._prellm_skip_count = 0# Only a healthy completed summary resets this; ordinary fitting responses do not.self._fallback_compression_streak = 0+ # Monotonic time of the next summary-model probe while the fallback streak benches it; 0.0 = unarmed.+ self._fallback_probe_at = 0.0# Armed at a completed boundary; consumed by the next real prompt count in update_from_response().self._verify_compaction_cleared_threshold = False# Lets the boundary wrapper tell a completed rewrite from a no-op without inferring from length.@@ -2614,8 +2616,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginif feasibility_skip:# A pre-LLM feasibility skip is not a summary-quality verdict: it must neither extend nor reset the streak.# A deliberate pre-LLM feasibility skip (#60451) is not a summary-quality verdict: it must- # neither extend a fallback streak (two skips would otherwise latch the >= 2 breaker and disable- # compression entirely — including the cheap deterministic dropping the skip exists to reach)+ # neither extend a fallback streak (the streak decides whether the summary model is called)# nor reset one (a skip proves nothing about the summary model's health).if not self.quiet_mode:logger.info(@@ -2812,8 +2813,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin_MIN_CTX_TRIGGER_RATIO = 0.85# Anti-thrash recovery: after this long blocked, allow ONE probe (counters drop to 1 strike).- # Anti-thrash recovery window (#14694): once the ineffective/fallback breaker trips, automatic- # compaction stays blocked for this long, then ONE probe attempt is allowed (counters drop to 1 strike,+ # Anti-thrash recovery window (#14694): once the ineffective breaker trips, automatic+ # compaction stays blocked for this long, then ONE probe attempt is allowed (the count drops to 1 strike,# so another ineffective pass re-trips immediately). Long enough that a genuinely incompressible session# isn't compacting in a loop; short enough that a session which has since grown real compressible# material recovers well before it rides into the provider's hard context limit.@@ -3111,14 +3112,18 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginreturn "ineffective" if self._tripped() else Nonedef _tripped(self) -> bool:- """Anti-thrash breaker state: two ineffective compactions or two fallback summaries in a row."""- return self._ineffective_compression_count >= 2 or self._fallback_compression_streak >= 2+ """Only provider-confirmed ineffective compactions trip the breaker.++ A static fallback still reclaims the window, so blocking on it lets the prompt run into the+ provider's hard limit. The fallback streak instead benches the failing summary model+ (``_fallback_streak_skip``), which is what stops a paid fallback loop (#63008).+ """+ return self._ineffective_compression_count >= 2def _refresh_durable_guards(self) -> None:"""Re-read durable cooldown + breaker state; called only when a gate is about to block."""for label, refresh in (("cooldown", lambda: self.get_active_compression_failure_cooldown(refresh=True)),- ("fallback-streak", self._load_fallback_compression_streak),("ineffective-count", self._load_ineffective_compression_count),):try:@@ -3170,7 +3175,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin# accumulate plenty of compressible material later. Without a recovery path the session# never auto-compacts again and rides into the provider's hard context limit. Recovery is a# probation probe: after _ANTI_THRASH_RECOVERY_SECONDS of continuous block, allow ONE- # attempt by dropping the tripped counter(s) to 1 strike (persisted, so sibling agents on+ # attempt by dropping the ineffective counter to 1 strike (persisted, so sibling agents on# the same session row unblock too). If the probe is ineffective again the very next verdict# re-trips the guard, so the worst case in the truly-incompressible state is one compaction# attempt per recovery window — bounded, not thrash. The clock is armed lazily on the first@@ -3180,9 +3185,6 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin# already-armed deadline resumes that window instead of restarting it.if self._ineffective_compression_count >= 2:self._record_ineffective_compression_verdict(1)- if self._fallback_compression_streak >= 2:- self._fallback_compression_streak = 1- self._persist_fallback_compression_streak()if not self.quiet_mode:logger.info("Anti-thrashing recovery: %.0fs elapsed since the guard tripped — allowing one "@@ -5415,6 +5417,34 @@ Write only the summary body. Do not include any preamble or prefix."""compress_start + 1, compress_end, n_turns, compress_start, tail_msgs,)+ def _fallback_streak_skip(self, telemetry: Dict[str, Any]) -> bool:+ """Pre-LLM skip while two summaries in a row fell back: compact deterministically instead of+ paying for a summary model that keeps failing (#63008). One probe per recovery window; a+ healthy summary resets the streak, another fallback benches it again."""+ if self._fallback_compression_streak < 2:+ self._fallback_probe_at = 0.0+ return False+ now = time.monotonic()+ if self._fallback_probe_at and now >= self._fallback_probe_at:+ self._fallback_probe_at = 0.0+ if not self.quiet_mode:+ logger.info(+ "Compression: probing the summary model again after %d fallback summaries in a row",+ self._fallback_compression_streak,+ )+ return False+ if not self._fallback_probe_at:+ self._fallback_probe_at = now + self._ANTI_THRASH_RECOVERY_SECONDS+ self._last_feasibility_skip = True+ telemetry["failure_class"] = "summary_model_benched"+ if not self.quiet_mode:+ logger.warning(+ "Compression: %d fallback summaries in a row — skipping LLM summarization, proceeding with "+ "deterministic message dropping. Next summary-model probe in %.0fs.",+ self._fallback_compression_streak, max(0.0, self._fallback_probe_at - now),+ )+ return True+def _feasibility_skip(self, telemetry: Dict[str, Any], turns_to_summarize: List[Dict[str, Any]],compress_start: int, compress_end: int,@@ -5738,7 +5768,10 @@ Write only the summary body. Do not include any preamble or prefix."""from agent.conversation_compression import _raise_if_stale_attempt_raise_if_stale_attempt(self)- feasibility_skip = not force and self._feasibility_skip(telemetry, turns_to_summarize, compress_start, compress_end)+ feasibility_skip = not force and (+ self._fallback_streak_skip(telemetry)+ or self._feasibility_skip(telemetry, turns_to_summarize, compress_start, compress_end)+ )summary = None # feasibility skip: no LLM call; Phase 4 inserts the deterministic fallbackif not feasibility_skip:summary = self._summarize_window(diff --git a/tests/agent/test_compression_anti_thrash_recovery.py b/tests/agent/test_compression_anti_thrash_recovery.pyindex cf245ac9a55..d29e074ff02 100644--- a/tests/agent/test_compression_anti_thrash_recovery.py+++ b/tests/agent/test_compression_anti_thrash_recovery.py@@ -3,7 +3,7 @@When two consecutive compactions each fail to clear the threshold, theanti-thrashing breaker blocks automatic compaction. Before this fix the blockwas permanent for the life of the session: nothing ever decremented-``_ineffective_compression_count`` (or ``_fallback_compression_streak``)+``_ineffective_compression_count``while blocked, so a session whose middle region was briefly too small tocompact never auto-compacted again — it grew unbounded until the provider'shard context limit, and only ``/new`` or ``/reset`` recovered it.@@ -11,12 +11,12 @@ hard context limit, and only ``/new`` or ``/reset`` recovered it.The recovery contract pinned here:* After ``_ANTI_THRASH_RECOVERY_SECONDS`` of continuous block, the gate- grants exactly ONE probation probe: tripped counters drop to 1 strike+ grants exactly ONE probation probe: the tripped count drops to 1 strike(persisted) and the gate reports unblocked once.* An ineffective probe re-trips the guard on the very next verdict, and thenext recovery waits a FULL fresh window (no immediate re-probe loop).* An effective probe (or any fitting real-usage reading) fully clears the- counters through the existing ``update_from_response`` path.+ count through the existing ``update_from_response`` path.* The recovery clock is armed lazily on the first blocked evaluation andpersisted on the session row as a wall-clock deadline (#100185): a freshcompressor that loads a durable tripped counter (#69872) with NO stored@@ -72,18 +72,26 @@ class TestRecoveryWindow:assert cc._ineffective_compression_count == 0assert cc._anti_thrash_recovery_deadline == 0.0- def test_fallback_streak_breaker_recovers_too(self):+ def test_fallback_streak_alone_does_not_block_compaction(self):cc = _compressor()cc._fallback_compression_streak = 2- base = 1000.0- with patch("agent.context_compressor.time.time", return_value=base):- assert cc.should_compress(cc.threshold_tokens + 1) is False- with patch(- "agent.context_compressor.time.time",- return_value=base + cc._ANTI_THRASH_RECOVERY_SECONDS + 1,- ):+ assert cc.should_compress(cc.threshold_tokens + 1) is True+ assert cc._fallback_compression_streak == 2++ def test_fallback_boundaries_wait_for_real_effectiveness_verdict(self):+ cc = _compressor()+ for prompt_tokens in (4_000, 5_000):+ cc.record_completed_compaction(used_fallback=True)+ cc.update_from_response({"prompt_tokens": prompt_tokens})assert cc.should_compress(cc.threshold_tokens + 1) is True- assert cc._fallback_compression_streak == 1+ assert cc._fallback_compression_streak == 2+ assert cc._ineffective_compression_count == 0++ for _ in range(2):+ cc.record_completed_compaction(used_fallback=True)+ cc.update_from_response({"prompt_tokens": cc.threshold_tokens + 1})+ assert cc.should_compress(cc.threshold_tokens + 1) is False+ assert cc._ineffective_compression_count == 2diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.pyindex 3a9643a6553..cd813336d7f 100644--- a/tests/agent/test_compression_rotation_state.py+++ b/tests/agent/test_compression_rotation_state.py@@ -1177,14 +1177,7 @@ class TestAutomaticCompressionStateRefreshAfterLock:class TestGateLevelGuardRefresh:- """The unblock direction must work from the should_compress() pre-gates.-- compress_context refreshes durable guards internally, but the automatic- paths (preflight/turn gates) consult should_compress() first — if a stale- in-memory fallback streak (which has no expiry timer) blocks there, the- refresh inside compress_context is never reached and the agent stays- blocked forever.- """+ """The pre-gate uses the measured ineffective count, not summary type."""def test_should_compress_unblocks_after_another_agent_clears_streak(self,@@ -1197,9 +1190,11 @@ class TestGateLevelGuardRefresh:compressor = _bound_context_compressor(db, session_id)assert compressor._fallback_compression_streak == 2- # Another agent's healthy boundary clears the durable breaker.+ # A previous run's fallback streak is diagnostic, so it never blocks.+ assert compressor.should_compress(10**9) is True+ # Another agent's healthy boundary clears the durable diagnostic count.db.set_compression_fallback_streak(session_id, 0)-+ compressor._load_fallback_compression_streak()assert compressor.should_compress(10**9) is Trueassert compressor._fallback_compression_streak == 0diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex 9bf28b1c225..60c625c26d6 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -3685,7 +3685,87 @@ class TestPreLlmFeasibilityCheck:mock_gen.assert_called_once()assert compressor._prellm_skip_count == 0+ def test_fallback_streak_benches_summary_model_but_keeps_compacting(self, compressor):+ """Two fallbacks in a row stop the summary calls (#63008), not the compaction itself:+ the window is still dropped, and one probe per recovery window can heal the streak."""+ compressor._fallback_compression_streak = 2+ msgs = self._make_messages()++ with patch.object(compressor, "_generate_summary", return_value="LLM summary") as mock_gen:+ benched = compressor.compress(msgs, force=False)+ mock_gen.assert_not_called()+ assert len(benched) < len(msgs)+ assert compressor._last_feasibility_skip is True # recorded streak-neutral++ compressor._fallback_probe_at = time.monotonic() - 1 # recovery window elapsed+ compressor.compress(self._make_messages(), force=False)+ mock_gen.assert_called_once()++ @staticmethod+ def _record_boundary(compressor):+ """Mirror the boundary wrapper's bookkeeping (agent/conversation_compression.py)."""+ compressor.record_completed_compaction(+ used_fallback=compressor._last_summary_fallback_used,+ feasibility_skip=compressor._last_feasibility_skip,+ )++ def test_fresh_compressor_with_a_streak_benches_and_arms_a_full_window(self, compressor):+ """A compressor that comes up with a persisted streak (restart, session rotation) has no+ probe clock: it benches the summary model and starts a full window, it does not probe at once."""+ compressor._fallback_compression_streak = 2+ assert compressor._fallback_probe_at == 0.0+ before = time.monotonic()++ with patch.object(compressor, "_generate_summary", return_value="LLM summary") as mock_gen:+ compressor.compress(self._make_messages(), force=False)++ mock_gen.assert_not_called()+ assert compressor._fallback_probe_at >= before + compressor._ANTI_THRASH_RECOVERY_SECONDS+ def test_healthy_probe_resets_the_streak(self, compressor):+ """A bench leaves the streak alone; the probe after the recovery window is a normal summary+ attempt, so a healthy summary resets it."""+ compressor._fallback_compression_streak = 2++ with patch.object(compressor, "_generate_summary", return_value="LLM summary") as mock_gen:+ compressor.compress(self._make_messages(), force=False) # benched+ self._record_boundary(compressor)+ assert compressor._fallback_compression_streak == 2 # a bench is streak-neutral++ compressor._fallback_probe_at = time.monotonic() - 1 # recovery window elapsed+ compressor.compress(self._make_messages(), force=False) # probe+ self._record_boundary(compressor)++ mock_gen.assert_called_once()+ assert compressor._fallback_compression_streak == 0++ def test_failed_probe_benches_again_for_another_window(self, compressor):+ """One probe per recovery window: a probe whose summary fails again counts as a fallback+ and benches the summary model for another full window."""+ compressor._fallback_compression_streak = 2+ compressor._fallback_probe_at = time.monotonic() - 1 # recovery window elapsed++ with patch.object(compressor, "_generate_summary", return_value=None) as mock_gen:+ compressor.compress(self._make_messages(), force=False) # probe, summary fails+ self._record_boundary(compressor)+ assert mock_gen.call_count == 1+ assert compressor._fallback_compression_streak == 3++ before = time.monotonic()+ compressor.compress(self._make_messages(), force=False) # benched again++ assert mock_gen.call_count == 1+ assert compressor._fallback_probe_at >= before + compressor._ANTI_THRASH_RECOVERY_SECONDS++ def test_skip_count_resets_on_session_reset(self, compressor):+ """_prellm_skip_count must reset alongside _ineffective_compression_count."""+ compressor._prellm_skip_count = 5+ compressor._ineffective_compression_count = 2++ compressor.bind_session_state() # a new session row++ assert compressor._prellm_skip_count == 0+ assert compressor._ineffective_compression_count == 0def test_skip_fires_on_fat_tail_small_middle(self, compressor):"""The target scenario from #60451: a tool-heavy transcript whose@@ -3725,9 +3805,8 @@ class TestPreLlmFeasibilityCheck:skip path sets _last_summary_fallback_used, which the boundarywrapper (conversation_compression.py) records viarecord_completed_compaction(used_fallback=True) — incrementing- _fallback_compression_streak, whose second occurrence blocks- automatic compression. Two deliberate skips must NOT trip that- breaker."""+ _fallback_compression_streak. A deliberate skip must not count as+ a failed summary-model attempt."""compressor._ineffective_compression_count = 1msgs = self._make_messages()@@ -3746,10 +3825,7 @@ class TestPreLlmFeasibilityCheck:assert compressor._prellm_skip_count == 2assert compressor._fallback_compression_streak == 0- assert not compressor._automatic_compression_blocked_locally(), (- "two deliberate feasibility skips must not disable automatic "- "compression via the fallback-streak breaker"- )+ assert not compressor._automatic_compression_blocked_locally()def test_boundary_accounting_skip_does_not_reset_fallback_streak(self, compressor):"""A skip proves nothing about the summary model's health: andiff --git a/tests/agent/test_context_compressor_cross_session_guard.py b/tests/agent/test_context_compressor_cross_session_guard.pyindex e76adf1335a..abbeccd339c 100644--- a/tests/agent/test_context_compressor_cross_session_guard.py+++ b/tests/agent/test_context_compressor_cross_session_guard.py@@ -54,6 +54,8 @@ def _make_compressor():c._context_probed = Falsec._last_compression_savings_pct = 100.0c._ineffective_compression_count = 0+ c._fallback_compression_streak = 0+ c._fallback_probe_at = 0.0c._last_summary_error = Nonec._last_summary_dropped_count = 0c._last_summary_fallback_used = False