The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): structural no-ops defer retries instead of striking the breaker
Aniruddha Adakf778c0d94109
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex cbd5e4478a4..79cf10a6214 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -2099,6 +2099,7 @@ class ContextCompressor(ContextEngine):self._last_compression_savings_pct = 100.0self._ineffective_compression_count = 0self._anti_thrash_recovery_deadline = 0.0+ self._structural_no_op_backoff_until = 0.0self._prellm_skip_count = 0self._fallback_compression_streak = 0self._verify_compaction_cleared_threshold = False@@ -2383,6 +2384,7 @@ class ContextCompressor(ContextEngine):self._last_compression_savings_pct = 100.0self._ineffective_compression_count = 0self._anti_thrash_recovery_deadline = 0.0+ self._structural_no_op_backoff_until = 0.0self._prellm_skip_count = 0self._fallback_compression_streak = 0self._verify_compaction_cleared_threshold = False@@ -2415,6 +2417,7 @@ class ContextCompressor(ContextEngine):self._ineffective_compression_count = 0self._prellm_skip_count = 0self._anti_thrash_recovery_deadline = 0.0+ self._structural_no_op_backoff_until = 0.0self._proactive_prune_rearm_tokens = 0self.get_active_compression_failure_cooldown()self._load_fallback_compression_streak()@@ -2595,6 +2598,31 @@ class ContextCompressor(ContextEngine):self._ineffective_compression_count = countself._persist_ineffective_compression_count()+ def _record_structural_no_op(self, reason: str) -> None:+ """Defer retries after a structural no-op WITHOUT striking the breaker.++ A structural no-op (too few messages / no compressible window /+ empty post-handoff window) means the protection window left nothing+ eligible to compress *right now* — compression was never really+ attempted, so there is nothing "ineffective" to score (#93022).+ Counting these as strikes permanently disarms auto-compaction on+ short sessions even after they later grow real compressible+ material. The transient backoff preserves #40803's guarantee (a+ transcript that can never shrink does not re-fire the scan every+ turn) while auto-compaction resumes on its own once the backoff+ lapses or the transcript outgrows the window.+ """+ self._structural_no_op_backoff_until = (+ time.monotonic() + self._STRUCTURAL_NO_OP_BACKOFF_SECONDS+ )+ if not self.quiet_mode:+ logger.warning(+ "Compression skipped (%s): retrying in %.0fs "+ "(structural no-op backoff)",+ reason,+ self._STRUCTURAL_NO_OP_BACKOFF_SECONDS,+ )+def record_rejected_compaction(self) -> None:"""Record one compaction whose result was REJECTED before committing.@@ -2633,6 +2661,10 @@ class ContextCompressor(ContextEngine):exactly the incompressible-transcript case the ineffective-strikebreaker exists for, and its recovery probe bounds the block."""+ # A completed boundary is proof the transcript was compressible, so+ # lift any pending structural no-op backoff (#93022) alongside the+ # usual bookkeeping.+ self._structural_no_op_backoff_until = 0.0self._verify_compaction_cleared_threshold = Trueif feasibility_skip:# A deliberate pre-LLM feasibility skip (#60451) is not a@@ -2949,6 +2981,17 @@ class ContextCompressor(ContextEngine):# before it rides into the provider's hard context limit._ANTI_THRASH_RECOVERY_SECONDS = 300.0+ # Structural no-op backoff (#93022): when a compression attempt finds+ # nothing eligible inside the protection window (too few messages, empty+ # window, post-handoff residue), that is "nothing to compress right now"+ # — not an ineffective attempt — so it must not strike the anti-thrash+ # breaker (a short session would otherwise permanently disarm+ # auto-compaction). Instead, defer retries for this long so a transcript+ # that can never shrink doesn't re-fire the scan every turn (#40803's+ # frozen-CLI loop). Compaction resumes automatically once the backoff+ # lapses or the transcript outgrows the window.+ _STRUCTURAL_NO_OP_BACKOFF_SECONDS = 300.0+@staticmethoddef _coerce_max_tokens(value: Any) -> int | None:"""Normalize a max_tokens value to a positive int or None.@@ -3244,6 +3287,9 @@ class ContextCompressor(ContextEngine):# no-op/abort without inferring progress from message-list length.self._last_compression_made_progress: bool = Falseself._summary_failure_cooldown_until: float = 0.0+ # Transient deferral after a structural no-op (#93022) — see the+ # _STRUCTURAL_NO_OP_BACKOFF_SECONDS class constant.+ self._structural_no_op_backoff_until: float = 0.0# True while the live local cooldown failed to persist to the DB;# a refresh must then treat an empty durable row as unknown, not# cleared (see get_active_compression_failure_cooldown).@@ -3508,6 +3554,10 @@ class ContextCompressor(ContextEngine):* ``"cooldown:<seconds>"`` — the summary LLM is recovering from arecent 429/transient failure; compression is deferred to avoid thefreeze loop described in #11529.+ * ``"structural_backoff:<seconds>"`` — a recent attempt found nothing+ eligible inside the protection window (#93022); retries are+ deferred transiently and compaction resumes when the backoff+ lapses or the transcript outgrows the window.* ``"ineffective"`` — anti-thrashing has backed off (the last twocompressions each saved <10%, or the fallback streak tripped).* ``None`` — no block active.@@ -3515,6 +3565,11 @@ class ContextCompressor(ContextEngine):_cooldown_remaining = self._summary_failure_cooldown_until - time.monotonic()if _cooldown_remaining > 0:return f"cooldown:{_cooldown_remaining:.0f}"+ _structural_remaining = (+ self._structural_no_op_backoff_until - time.monotonic()+ )+ if _structural_remaining > 0:+ return f"structural_backoff:{_structural_remaining:.0f}"if (self._ineffective_compression_count >= 2or self._fallback_compression_streak >= 2@@ -3579,6 +3634,23 @@ class ContextCompressor(ContextEngine):_cooldown_remaining,)return True+ # Structural no-op backoff (#93022): a recent attempt found nothing+ # eligible inside the protection window. Unlike the ineffective+ # breaker below this is inherently transient (in-memory only, no+ # strikes accumulate), so a short session that tripped it can still+ # auto-compact normally once the backoff lapses or the transcript+ # outgrows the protection window.+ _structural_remaining = (+ self._structural_no_op_backoff_until - time.monotonic()+ )+ if _structural_remaining > 0:+ if not self.quiet_mode:+ logger.debug(+ "Compression deferred — structural no-op backoff for "+ "%.0fs more",+ _structural_remaining,+ )+ return True# Anti-thrashing: back off if recent compressions were ineffective.# The back-off must not be permanent (#14694): the tripped state was# judged against the transcript as it existed THEN (e.g. a middle@@ -7229,29 +7301,25 @@ This compaction should PRIORITISE preserving all information related to the focu# this, /compress would silently no-op for 30-60s after a failure.if force:self._clear_compression_failure_cooldown()+ # Manual /compress also overrides a structural no-op backoff+ # (#93022): an explicit user request must always get a real try.+ self._structural_no_op_backoff_until = 0.0n_messages = len(messages)# Only need head + 3 tail messages minimum (token budget decides the real tail size)_min_for_compress = self._protect_head_size(messages) + 3 + 1if n_messages <= _min_for_compress:- # Record the no-op, exactly as the sibling "no compressable window"- # branch below does (#40803). Returning without touching the- # anti-thrashing counter leaves should_compress() saying True on a- # transcript that can never shrink: when the prompt sits above the- # threshold because of the incompressible floor (system prompt +- # tool schemas), every subsequent turn re-fires a compaction that- # returns here unchanged, and the CLI appears frozen.- self._record_ineffective_compression_verdict(- self._ineffective_compression_count + 1,- )+ # Structural no-op, not an ineffective attempt (#93022): with this+ # few messages there is nothing eligible to compress yet. Defer+ # retries via the transient backoff instead of striking the+ # anti-thrashing breaker — striking it here permanently disarmed+ # auto-compaction on short sessions even after they grew real+ # compressible material. The backoff still prevents #40803's+ # per-turn re-fire loop on a transcript that cannot shrink.self._last_compression_savings_pct = 0.0telemetry["failure_class"] = "insufficient_messages"- if not self.quiet_mode:- logger.warning(- "Cannot compress: only %d messages (need > %d). "- "ineffective_compression_count=%d",- n_messages, _min_for_compress,- self._ineffective_compression_count,- )+ self._record_structural_no_op(+ f"only {n_messages} messages (need > {_min_for_compress})"+ )return messagesdisplay_tokens = current_tokens if current_tokens else self.last_prompt_tokens or estimate_messages_tokens_rough(messages)@@ -7319,22 +7387,17 @@ This compaction should PRIORITISE preserving all information related to the focu)telemetry["failure_class"] = "no_compressible_window"# No compressable window — the entire transcript fits within- # the tail budget (soft_ceiling). Without recording this as- # an ineffective compression the anti-thrashing guard in- # should_compress() never fires and every subsequent turn- # re-triggers a no-op compression loop. (#40803)- self._record_ineffective_compression_verdict(- self._ineffective_compression_count + 1,- )+ # the tail budget (soft_ceiling): nothing was eligible to+ # compress. This is a structural no-op, not an ineffective+ # attempt (#93022), so defer retries via the transient backoff+ # instead of striking the anti-thrashing breaker; the backoff+ # still prevents #40803's per-turn no-op compression loop on a+ # transcript that cannot shrink.self._last_compression_savings_pct = 0.0- if not self.quiet_mode:- logger.warning(- "Compression skipped: compress_start (%d) >= compress_end (%d) "- "— transcript fits within tail budget, nothing to compress. "- "ineffective_compression_count=%d",- compress_start, compress_end,- self._ineffective_compression_count,- )+ self._record_structural_no_op(+ f"compress_start ({compress_start}) >= compress_end "+ f"({compress_end}) - transcript fits within tail budget"+ )return messagesturns_to_summarize = messages[compress_start:compress_end]@@ -7458,30 +7521,21 @@ This compaction should PRIORITISE preserving all information related to the focu# is nothing new to summarize. Skip the summary call entirely:# without this guard the empty window still reached# _generate_summary, wasting an aux LLM call that aborts- # noisily on empty input (#59496). Mirrors the sibling- # "no compressable window" guard above (#40803): record an- # ineffective strike through the durable write-through helper- # so the anti-thrash breaker in should_compress() can stop the- # loop — this shape cannot shrink, so every subsequent turn- # would otherwise re-fire the same no-op. The rehydrated- # _previous_summary is deliberately KEPT (not rolled back as- # the summary-abort path does for #57835): it came from a- # handoff genuinely present in this transcript, which is- # returned unchanged.+ # noisily on empty input (#59496). Like the sibling "no+ # compressable window" guard above, this is a structural no-op,+ # not an ineffective attempt (#93022): defer retries via the+ # transient backoff instead of striking the anti-thrash breaker,+ # while still stopping #40803's per-turn re-fire of the same+ # no-op. The rehydrated _previous_summary is deliberately KEPT+ # (not rolled back as the summary-abort path does for #57835):+ # it came from a handoff genuinely present in this transcript,+ # which is returned unchanged.telemetry["failure_class"] = "empty_post_handoff_window"- self._record_ineffective_compression_verdict(- self._ineffective_compression_count + 1,- )self._last_compression_savings_pct = 0.0- if not self.quiet_mode:- logger.warning(- "Compression skipped: latest context summary leaves no "- "new turns to summarize in window %d-%d. "- "ineffective_compression_count=%d",- compress_start,- compress_end,- self._ineffective_compression_count,- )+ self._record_structural_no_op(+ f"window {compress_start}-{compress_end} holds only "+ "already-summarized handoffs"+ )return messagesif not self.quiet_mode:diff --git a/tests/agent/test_compression_anti_thrash_persistence.py b/tests/agent/test_compression_anti_thrash_persistence.pyindex 5faf9e4840b..ac4ad920e05 100644--- a/tests/agent/test_compression_anti_thrash_persistence.py+++ b/tests/agent/test_compression_anti_thrash_persistence.py@@ -144,13 +144,19 @@ class TestResetSemanticsPreserved:class TestStrikesPersistFromEveryVerdictSite:- def test_no_op_compaction_branches_write_through(self, tmp_path):- """The insufficient-messages no-op branch records its strike durably."""+ def test_no_op_compaction_branch_does_not_strike(self, tmp_path):+ """The insufficient-messages branch is a structural no-op (#93022).++ Nothing was eligible to compress, so no ineffective strike is+ recorded — durable or in-memory. The transient structural backoff+ arms instead; the breaker must stay untouched so a short session+ can still auto-compact once it grows real compressible material.+ """db = _db(tmp_path)db.create_session("s1", source="cli")cc = _compressor(db, "s1")- # 3 tiny messages < minimum window → the #40803 no-op branch.+ # 3 tiny messages < minimum window → the #40803/#93022 no-op branch.msgs = [{"role": "system", "content": "sys"},{"role": "user", "content": "hi"},@@ -158,8 +164,9 @@ class TestStrikesPersistFromEveryVerdictSite:]out = cc.compress(msgs, current_tokens=10**9)assert out == msgs- assert cc._ineffective_compression_count == 1- assert db.get_compression_ineffective_count("s1") == 1+ assert cc._ineffective_compression_count == 0+ assert db.get_compression_ineffective_count("s1") == 0+ assert cc._structural_no_op_backoff_until > 0.0def test_persist_failure_is_swallowed_and_memory_still_advances(self, tmp_path):"""A DB write failure must not break the in-memory guard."""diff --git a/tests/agent/test_context_compressor_structural_backoff.py b/tests/agent/test_context_compressor_structural_backoff.pynew file mode 100644index 00000000000..fab297d6369--- /dev/null+++ b/tests/agent/test_context_compressor_structural_backoff.py@@ -0,0 +1,161 @@+"""Structural no-op backoff (#93022).++A compression attempt that finds nothing eligible inside the protection+window (too few messages / empty window / post-handoff residue) is "nothing+to compress right now", not an ineffective attempt: it must defer retries+transiently instead of arming the permanent anti-thrash breaker, so a short+session can still auto-compact after it grows real compressible material.+"""++import time+from unittest.mock import MagicMock, patch++from agent.context_compressor import ContextCompressor+++def _compressor(protect_first_n: int = 1) -> ContextCompressor:+ with patch("agent.context_compressor.get_model_context_length", return_value=100000):+ return ContextCompressor(+ model="test/model",+ threshold_percent=0.85,+ protect_first_n=protect_first_n,+ protect_last_n=1,+ quiet_mode=True,+ )+++def _response(content: str):+ mock_response = MagicMock()+ mock_response.choices = [MagicMock()]+ mock_response.choices[0].message.content = content+ return mock_response+++def test_insufficient_messages_backs_off_without_strike():+ """Too few messages -> structural backoff, breaker stays untouched."""+ compressor = _compressor()+ messages = [+ {"role": "system", "content": "system prompt"},+ {"role": "user", "content": "hello"},+ ]++ result = compressor.compress(messages, current_tokens=90_000)++ assert result == messages+ assert compressor._ineffective_compression_count == 0+ assert compressor._structural_no_op_backoff_until > 0.0+ telemetry = compressor._last_compression_telemetry or {}+ assert telemetry.get("failure_class") == "insufficient_messages"+++def test_no_compressible_window_backs_off_without_strike():+ """Transcript inside the tail budget -> backoff, breaker untouched."""+ compressor = _compressor()+ messages = [+ {"role": "system", "content": "system prompt"},+ {"role": "user", "content": "turn one"},+ {"role": "assistant", "content": "answer one"},+ {"role": "user", "content": "turn two"},+ {"role": "assistant", "content": "answer two"},+ {"role": "user", "content": "turn three"},+ {"role": "assistant", "content": "answer three"},+ {"role": "user", "content": "latest request in protected tail"},+ ]++ with patch.object(compressor, "_find_tail_cut_by_tokens", return_value=2):+ result = compressor.compress(messages, current_tokens=90_000)++ assert result == messages+ assert compressor._ineffective_compression_count == 0+ assert compressor._structural_no_op_backoff_until > 0.0+ telemetry = compressor._last_compression_telemetry or {}+ assert telemetry.get("failure_class") == "no_compressible_window"+++def test_gate_blocked_during_backoff_then_resumes():+ """should_compress defers during the backoff and recovers after it lapses.++ The transcript sits over the compression threshold the whole time; only+ the clock changes, proving the block is transient rather than a latched+ breaker state.+ """+ compressor = _compressor()++ # While the structural backoff is live the gate must say blocked.+ compressor._structural_no_op_backoff_until = time.monotonic() + 300.0+ with patch.object(+ compressor, "_automatic_compression_blocked", return_value=True+ ):+ should, reason = compressor.should_compress_info(prompt_tokens=300_000)+ assert should is False+ assert reason is not None+ assert reason.startswith("structural_backoff:")+ assert compressor._compression_block_reason().startswith(+ "structural_backoff:"+ )++ # After the backoff lapses nothing blocks: same over-threshold+ # transcript compresses again (real gate, real state).+ compressor._structural_no_op_backoff_until = (+ time.monotonic() - 1.0+ )+ should, reason = compressor.should_compress_info(prompt_tokens=300_000)+ assert should is True+ assert reason is None+++SUMMARY_RESPONSE = "fresh replacement summary body"+++def _messages_with_old_handoff():+ return [+ {"role": "system", "content": "system prompt"},+ {"role": "user", "content": (+ "CONTEXT SUMMARY (from previous session):\nold summary body"+ )},+ {"role": "assistant", "content": "handoff acknowledged after resume"},+ {"role": "user", "content": "new user turn after resume"},+ {"role": "assistant", "content": "new assistant work after resume"},+ {"role": "user", "content": "more new work after resume"},+ {"role": "assistant", "content": "latest tail response"},+ {"role": "user", "content": "final active request stays in protected tail"},+ ]+++def test_forced_attempt_and_success_lift_the_backoff():+ """Manual /compress clears an active backoff; a completed boundary lifts it.++ Both are proof the transcript is being actively worked on — neither may+ leave auto-compaction deferred by a stale structural no-op.+ """+ compressor = _compressor()+ compressor._structural_no_op_backoff_until = time.monotonic() + 300.0++ with patch(+ "agent.context_compressor.call_llm",+ return_value=_response(SUMMARY_RESPONSE),+ ):+ compressed = compressor.compress(+ _messages_with_old_handoff(), force=True+ )++ assert compressor._structural_no_op_backoff_until == 0.0+ # The forced attempt actually committed a boundary.+ assert len(compressed) < len(_messages_with_old_handoff())+++def test_real_attempt_underperformance_still_strikes_breaker():+ """Only genuine attempted-but-underperformed compressions strike.++ A real summary pass that saves <10% goes through the ineffective+ verdict (persisted); structural no-ops must not touch that counter —+ that distinction IS this fix.+ """+ compressor = _compressor()+ before = compressor._ineffective_compression_count+ compressor._record_ineffective_compression_verdict(before + 1)+ assert compressor._ineffective_compression_count == before + 1++ compressor._record_structural_no_op("test reason")+ assert compressor._structural_no_op_backoff_until > 0.0+ assert compressor._ineffective_compression_count == before + 1diff --git a/tests/agent/test_context_compressor_summary_continuity.py b/tests/agent/test_context_compressor_summary_continuity.pyindex 8d14ff11e6a..5f93d7a11c6 100644--- a/tests/agent/test_context_compressor_summary_continuity.py+++ b/tests/agent/test_context_compressor_summary_continuity.py@@ -442,10 +442,12 @@ def test_empty_post_handoff_window_noops_without_summary_call():# genuinely present in the returned (unchanged) transcript.assert compressor._previous_summary == old_summaryassert compressor.compression_count == 0- # Mirrors the sibling no-compressible-window guard (#40803): the shape- # cannot shrink, so it counts as an ineffective strike (routed through- # the durable write-through helper) to arm the anti-thrash breaker.- assert compressor._ineffective_compression_count == 1+ # Mirrors the sibling no-compressible-window guard, but as a structural+ # no-op (#93022): the window holds nothing eligible to compress, so the+ # compressor defers retries transiently instead of arming the permanent+ # anti-thrash breaker.+ assert compressor._ineffective_compression_count == 0+ assert compressor._structural_no_op_backoff_until > 0.0assert compressor._last_compression_savings_pct == 0.0assert compressor._last_summary_dropped_count == 0assert compressor._last_summary_fallback_used is False