Skip to content

The agent that grows with you

refactor(compaction): move pre-LLM summary skips into context_compressor_prellm

kshitijk4poord6daf4bdd221
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index e9755225ab6..07c77f5f814 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -32,6 +32,7 @@ from agent.auxiliary_client import (
extract_content_or_reasoning,
)
from agent.context_engine import ContextEngine, sanitize_memory_context
+from agent.context_compressor_prellm import FALLBACK_PROBE_AT_MODEL_CONFIG_KEY, PreLlmSkipMixin
from agent.context_compressor_summary import SummaryDispatchMixin
from agent.error_classifier import FailoverReason, classify_api_error
from agent.micro_compaction import MicroCompactionMixin
@@ -328,7 +329,6 @@ _DB_PERSISTED_MARKER = "_db_persisted"
# they don't duplicate live copies in recall; never persisted (unknown column).
_COMPACTION_TAIL_MARKER = "_compaction_tail"
PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY = "_proactive_prune_rearm_tokens"
-FALLBACK_PROBE_AT_MODEL_CONFIG_KEY = "_fallback_probe_at"
_NO_USER_TASK_SENTINEL = "None. This session contains no user-authored turns."
COMPRESSION_CONTINUATION_USER_CONTENT = (
@@ -1161,10 +1161,6 @@ _ACTIVE_TASK_MAX_CHARS = 1400
# full protect_last_n would recreate the nothing-compactable large-tool-output case.
_MAX_TAIL_MESSAGE_FLOOR = 8
-# Skip the LLM call when the compressible middle is below this fraction of the
-# threshold (and a prior ineffectiveness strike exists); dropping alone suffices.
-# See #60451.
-_FEASIBILITY_SKIP_MIDDLE_FRACTION = 0.10
# Under pressure, demote large tool outputs even inside the protected region but
# keep this many trailing messages verbatim.
_PRESSURE_KEEP_RECENT_MESSAGES = 3
@@ -2178,7 +2174,7 @@ Describe agent/tool work only as completed actions, state, or historical work.]"
}
-class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngine):
+class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMixin, ContextEngine):
"""Default context engine: prune tool results, protect head/tail, summarize the middle
with an LLM, and iteratively update the previous summary on later compactions."""
@@ -2586,16 +2582,6 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
self._anti_thrash_recovery_deadline = deadline
self._durable_write("set_compression_recovery_deadline", "compression recovery deadline", deadline)
- def _set_fallback_probe_at(self, at: float) -> None:
- """Set the summary-model probe deadline, persisting on change only (0 = unarmed) so a rebuilt
- compressor resumes the bench window instead of restarting it (same contract as #100185)."""
- if at == self._fallback_probe_at:
- return
- self._fallback_probe_at = at
- self._durable_write(
- "patch_session_model_config", "summary-model probe deadline", {FALLBACK_PROBE_AT_MODEL_CONFIG_KEY: at or None},
- )
-
def _record_ineffective_compression_verdict(self, count: int) -> None:
"""Set the anti-thrash strike counter; persists only on change."""
if count == self._ineffective_compression_count:
@@ -5432,61 +5418,6 @@ 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._set_fallback_probe_at(0.0)
- return False
- # Wall clock: the deadline is persisted on the session row so a gateway rebuild resumes the window.
- now = time.time()
- if self._fallback_probe_at and now >= self._fallback_probe_at:
- self._set_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 or self._fallback_probe_at - now > self._ANTI_THRASH_RECOVERY_SECONDS:
- self._set_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,
- ) -> bool:
- """Pre-LLM skip after a real-usage ineffectiveness strike (reads the counter, never writes)."""
- if self._ineffective_compression_count < 1:
- return False
- # Reuse the telemetry estimate so log and telemetry agree; None means the regions helper
- # no-op'd (0 is valid).
- middle_tokens = telemetry.get("middle_window_tokens")
- middle_tokens = estimate_messages_tokens_rough(turns_to_summarize) if middle_tokens is None else middle_tokens
- if middle_tokens >= int(self.threshold_tokens * _FEASIBILITY_SKIP_MIDDLE_FRACTION):
- return False
- self._last_feasibility_skip = True
- self._prellm_skip_count += 1
- telemetry["prellm_skip_count"] = self._prellm_skip_count
- if not self.quiet_mode:
- logger.warning(
- "Compression: middle section (%d tokens at indices %d-%d) is below %.0f%% of threshold (%d tokens) — "
- "skipping LLM summarization, proceeding with deterministic message dropping. prellm_skip_count=%d",
- middle_tokens, compress_start, compress_end,
- _FEASIBILITY_SKIP_MIDDLE_FRACTION * 100,
- self.threshold_tokens, self._prellm_skip_count,
- )
- return True
-
def _abort_on_summary_failure(
self, telemetry: Dict[str, Any], n_skipped: int, previous_summary_before_scan: Optional[str],
) -> bool:
diff --git a/agent/context_compressor_prellm.py b/agent/context_compressor_prellm.py
new file mode 100644
index 00000000000..e3487b8605d
--- /dev/null
+++ b/agent/context_compressor_prellm.py
@@ -0,0 +1,86 @@
+"""Pre-LLM summary skips for ContextCompressor: compact deterministically without calling a summary model."""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any, Dict, List
+
+from agent.model_metadata import estimate_messages_tokens_rough
+
+logger = logging.getLogger(__name__)
+
+# Skip the LLM call when the compressible middle is below this fraction of the
+# threshold (and a prior ineffectiveness strike exists); dropping alone suffices.
+# See #60451.
+_FEASIBILITY_SKIP_MIDDLE_FRACTION = 0.10
+FALLBACK_PROBE_AT_MODEL_CONFIG_KEY = "_fallback_probe_at"
+
+
+class PreLlmSkipMixin:
+ """Decides, before the summary call, whether compress() should skip the summary model."""
+
+ def _set_fallback_probe_at(self, at: float) -> None:
+ """Set the summary-model probe deadline, persisting on change only (0 = unarmed) so a rebuilt
+ compressor resumes the bench window instead of restarting it (same contract as #100185)."""
+ if at == self._fallback_probe_at:
+ return
+ self._fallback_probe_at = at
+ self._durable_write(
+ "patch_session_model_config", "summary-model probe deadline", {FALLBACK_PROBE_AT_MODEL_CONFIG_KEY: at or None},
+ )
+
+ 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._set_fallback_probe_at(0.0)
+ return False
+ # Wall clock: the deadline is persisted on the session row so a gateway rebuild resumes the window.
+ now = time.time()
+ if self._fallback_probe_at and now >= self._fallback_probe_at:
+ self._set_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 or self._fallback_probe_at - now > self._ANTI_THRASH_RECOVERY_SECONDS:
+ self._set_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,
+ ) -> bool:
+ """Pre-LLM skip after a real-usage ineffectiveness strike (reads the counter, never writes)."""
+ if self._ineffective_compression_count < 1:
+ return False
+ # Reuse the telemetry estimate so log and telemetry agree; None means the regions helper
+ # no-op'd (0 is valid).
+ middle_tokens = telemetry.get("middle_window_tokens")
+ middle_tokens = estimate_messages_tokens_rough(turns_to_summarize) if middle_tokens is None else middle_tokens
+ if middle_tokens >= int(self.threshold_tokens * _FEASIBILITY_SKIP_MIDDLE_FRACTION):
+ return False
+ self._last_feasibility_skip = True
+ self._prellm_skip_count += 1
+ telemetry["prellm_skip_count"] = self._prellm_skip_count
+ if not self.quiet_mode:
+ logger.warning(
+ "Compression: middle section (%d tokens at indices %d-%d) is below %.0f%% of threshold (%d tokens) — "
+ "skipping LLM summarization, proceeding with deterministic message dropping. prellm_skip_count=%d",
+ middle_tokens, compress_start, compress_end,
+ _FEASIBILITY_SKIP_MIDDLE_FRACTION * 100,
+ self.threshold_tokens, self._prellm_skip_count,
+ )
+ return True