The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: truncated compaction summaries back off 60s/300s/900s across turns
teknium1801e3fa6ddb2
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex ac6de4de4de..0d80fcb3fe7 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -693,14 +693,20 @@ _TERMINAL_SUMMARY_FAILURES = (),)-# Timeouts escalate 60s -> 300s -> 900s: structural repeat offenders back off longer.+# Timeouts escalate 60s -> 300s -> 900s: structural repeat offenders back off longer. Truncated summaries+# (finish_reason=length) walk the same rungs on their own counter: the output cap is deterministic for an+# unchanged route and prompt, so a flat 30s cooldown let every async-completion turn re-issue the same+# capped request after its per-turn attempt budget was refilled (#69637)._TIMEOUT_COOLDOWN_LADDER = (60, 300, 900)-def _next_timeout_cooldown(compressor: Any) -> int:- """Bump ``compressor._consecutive_timeout_failures`` and return the ladder rung for it.- Module-level (not a method) so callers that bind a single real method onto a stub still exercise the ladder."""- n = compressor._consecutive_timeout_failures = getattr(compressor, "_consecutive_timeout_failures", 0) + 1+def _next_timeout_cooldown(compressor: Any, counter: str = "_consecutive_timeout_failures") -> int:+ """Bump ``compressor.<counter>`` and return the ladder rung for it.+ Module-level (not a method) so callers that bind a single real method onto a stub still exercise the ladder.+ ``counter`` stays separate per failure class: the timeout streak also arms the deterministic stall fallback+ (``_prior_timeout_failures``), which a truncation must not trigger."""+ n = getattr(compressor, counter, 0) + 1+ setattr(compressor, counter, n)return _TIMEOUT_COOLDOWN_LADDER[min(n, len(_TIMEOUT_COOLDOWN_LADDER)) - 1]@@ -2086,7 +2092,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin# A handoff may carry role="user" only for alternation, so role alone can't prove a human turn existed.self._previous_summary = self._summary_has_user_turn = self._last_summary_error = Noneself._last_aux_model_failure_error = self._last_aux_model_failure_model = None- self._consecutive_timeout_failures = 0+ self._consecutive_timeout_failures = self._consecutive_truncation_failures = 0# Turns unrecoverably dropped by a static fallback, so callers can warn.self._last_summary_dropped_count = 0self._last_summary_fallback_used = self._last_feasibility_skip = False@@ -2121,7 +2127,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginself._summary_failure_cooldown_until = 0.0self._cooldown_persist_failed = Falseself._last_summary_error = None- self._consecutive_timeout_failures = self._fallback_compression_streak = 0+ self._consecutive_timeout_failures = self._consecutive_truncation_failures = self._fallback_compression_streak = 0self._ineffective_compression_count = self._prellm_skip_count = 0self._anti_thrash_recovery_deadline = self._structural_no_op_backoff_until = 0.0self._reset_proactive_prune_rearm()@@ -2383,7 +2389,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginlogger.info("Skipping compression cooldown clear: host already cancelled this compression attempt")returnself._summary_failure_cooldown_until, self._last_summary_error = 0.0, None- self._consecutive_timeout_failures, self._cooldown_persist_failed = 0, False+ self._consecutive_timeout_failures = self._consecutive_truncation_failures = 0+ self._cooldown_persist_failed = FalseContextCompressor._durable_write(self, "clear_compression_failure_cooldown", "compression failure cooldown clear")def _compression_cancelled(self) -> bool:@@ -3779,12 +3786,15 @@ Write only the summary body. Do not include any preamble or prefix."""# Retry immediately on the main model.return self._generate_summary(turns_to_summarize, focus_topic=focus_topic, memory_context=memory_context)- # Transient errors: short cooldown for JSON-decode/streaming-closed. Timeouts escalate- # 60s→300s→900s (structural repeat offenders) and take precedence over the short rung.+ # Transient errors: short cooldown for JSON-decode/streaming-closed/empty-content. Timeouts escalate+ # 60s→300s→900s (structural repeat offenders) and take precedence over the short rung; truncation+ # escalates on its own counter (see _TIMEOUT_COOLDOWN_LADDER).if kind.timeout:_transient_cooldown = _next_timeout_cooldown(self)+ elif kind.truncated:+ _transient_cooldown = _next_timeout_cooldown(self, "_consecutive_truncation_failures")else:- _transient_cooldown = 30 if (kind.json_decode or kind.streaming_closed or kind.empty_content or kind.truncated) else 60+ _transient_cooldown = 30 if (kind.json_decode or kind.streaming_closed or kind.empty_content) else 60err_text = _short_error_text(e)self._record_compression_failure_cooldown(_transient_cooldown, err_text)self._last_summary_error = err_textdiff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex f282354b355..dd281713266 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -169,7 +169,8 @@ _COMPRESSOR_ATTEMPT_STATE_FIELDS = ("_previous_summary", "_summary_has_user_turn", "compression_count", "_last_compression_savings_pct","_ineffective_compression_count", "_anti_thrash_recovery_deadline", "_fallback_compression_streak","_verify_compaction_cleared_threshold", "_last_compression_made_progress", "_summary_failure_cooldown_until",- "_cooldown_persist_failed", "_last_summary_error", "_consecutive_timeout_failures", "_last_summary_dropped_count",+ "_cooldown_persist_failed", "_last_summary_error", "_consecutive_timeout_failures", "_consecutive_truncation_failures",+ "_last_summary_dropped_count","_last_summary_fallback_used", "_last_compress_aborted", "_last_summary_auth_failure","_last_summary_network_failure", "_last_summary_empty_content_failure", "_last_summary_truncated_failure","_last_aux_model_failure_error", "_last_aux_model_failure_model", "_summary_model_fallen_back", "summary_model",diff --git a/tests/agent/test_compressor_truncated_summary_guard.py b/tests/agent/test_compressor_truncated_summary_guard.pyindex edb326cef02..cd7ae10ce48 100644--- a/tests/agent/test_compressor_truncated_summary_guard.py+++ b/tests/agent/test_compressor_truncated_summary_guard.py@@ -105,6 +105,46 @@ class TestGenerateSummaryTruncationGuard:assert "full summary via main model" in resultassert c._last_summary_truncated_failure is False+ def test_repeated_truncation_escalates_cooldown_across_turns(self):+ """#69637: a later turn (e.g. an async delegation completion arriving after the cooldown lapsed)+ must not re-arm a fresh flat 30s attempt. Consecutive length-stopped summaries walk the durable+ 60s -> 300s -> 900s ladder, one LLM call per turn, and the transcript is preserved every time."""+ with patch("agent.context_compressor.get_model_context_length", return_value=100000):+ c = ContextCompressor(model="test", quiet_mode=True, protect_first_n=2, protect_last_n=2)+ clock = [1000.0]+ recorded = []+ with (+ patch("agent.context_compressor.time.monotonic", side_effect=lambda: clock[0]),+ patch("agent.context_compressor.call_llm", return_value=_mock_response("partial...", "length")) as call,+ ):+ for _turn in range(4):+ msgs = _msgs()+ assert c.compress(msgs, current_tokens=999999) == msgs+ cooldown = c._summary_failure_cooldown_until - clock[0]+ recorded.append(round(cooldown))+ clock[0] += cooldown + 1 # the next turn arrives right after the cooldown lapses+ assert recorded == [60, 300, 900, 900]+ assert call.call_count == 4+ # Truncation keeps its own streak: the timeout ladder (which arms the deterministic stall+ # fallback via _prior_timeout_failures) is untouched.+ assert c._consecutive_timeout_failures == 0+ assert c._consecutive_truncation_failures == 4++ def test_other_transient_failures_keep_short_cooldown(self):+ """Control: empty-content stays on the flat 30s rung and does not bump the truncation streak."""+ with patch("agent.context_compressor.get_model_context_length", return_value=100000):+ c = ContextCompressor(model="test", quiet_mode=True, protect_first_n=2, protect_last_n=2)+ clock = [1000.0]+ with (+ patch("agent.context_compressor.time.monotonic", side_effect=lambda: clock[0]),+ patch("agent.context_compressor.call_llm", side_effect=RuntimeError("LLM returned empty content")),+ ):+ for _turn in range(2):+ c.compress(_msgs(), current_tokens=999999)+ assert round(c._summary_failure_cooldown_until - clock[0]) == 30+ clock[0] += 31+ assert c._consecutive_truncation_failures == 0+def test_stop_finish_reason_still_succeeds(self):"""Control: a normal stop-terminated summary is accepted unchanged."""with patch("agent.context_compressor.get_model_context_length", return_value=100000):diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex 0f2243d7499..f0d3dfd0199 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -175,7 +175,14 @@ A failed or stalled summary attempt arms a per-session **failure cooldown**(escalating 60s → 300s → 900s, never shorter than`compression.context_timeout_seconds`, persisted in `state.db`). While it isarmed, ordinary threshold-triggered compaction is deferred so a broken summary-backend does not re-fire every turn. Three paths run a real attempt anyway:+backend does not re-fire every turn. Timeouts and stalls escalate on one+counter; a summary that ends in `finish_reason=length` (output cap hit, the+transcript is preserved) escalates on its own counter along the same+60s → 300s → 900s rungs, so a later turn — such as an async delegation+completion arriving after the cooldown lapsed — cannot re-issue the same+capped request every 30 seconds (#69637). JSON-decode, closed-stream and+empty-content failures stay on a flat 30 s cooldown. Three paths run a real+attempt anyway:- Manual `/compress` (`force=True`) — clears the cooldown and retries.- The same-turn `fallback_chain` retry after a stalled primary route — the