Skip to content

The agent that grows with you

fix(compression): keep the aux ceiling and re-probe feasibility on every main-runtime change

teknium19f5b7ea02e04
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 8b85dc32cc4..69a919d6ae0 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1173,6 +1173,8 @@ def restore_primary_runtime(agent) -> bool:
base_url=rt["compressor_base_url"], api_key=rt["compressor_api_key"],
provider=rt["compressor_provider"], api_mode=rt.get("compressor_api_mode", ""),
)
+ from agent.conversation_compression import revalidate_compression_feasibility
+ revalidate_compression_feasibility(agent)
_rebind_primary_credential_pool(
agent, primary_provider, primary_model, _matches_primary, _load_primary_pool, prefetched_pool, prefetched
)
@@ -2058,16 +2060,13 @@ def _update_switch_compressor(agent, custom_providers, effective_context_length,
provider=agent.provider,
api_mode=agent.api_mode,
)
- # A prior compression attempt may have lowered the live trigger to fit
- # its auxiliary summarizer. update_model() rightly recalibrates from
- # the new main model, so immediately reapply that feasibility guard
- # when it has already been resolved for this session.
- if getattr(agent, "_compression_feasibility_checked", False):
- from agent.conversation_compression import check_compression_model_feasibility
- check_compression_model_feasibility(agent)
except Exception:
_restore_switch_snapshot(agent, snapshot)
raise
+ # Outside the rollback guard: a probe hiccup must not undo a good switch. Eager, so the aux
+ # clamp lands before the first compaction on the new window, not after it (#114707).
+ from agent.conversation_compression import revalidate_compression_feasibility
+ revalidate_compression_feasibility(agent)
def _build_primary_runtime_snapshot(agent, api_mode) -> Dict[str, Any]:
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index a940e631c03..1ca0fdeab0b 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1851,6 +1851,8 @@ def _update_fallback_context_compressor(agent) -> None:
model=agent.model, context_length=fb_context_length, base_url=agent.base_url,
api_key=getattr(agent, "api_key", ""), provider=agent.provider, api_mode=agent.api_mode,
)
+ from agent.conversation_compression import revalidate_compression_feasibility
+ revalidate_compression_feasibility(agent)
def _reresolve_fallback_reasoning_config(agent) -> None:
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index e0788ff3947..4f252fda8fc 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -2321,6 +2321,11 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
# A switch that genuinely changes the output budget passes the new value explicitly. (#43547)
if max_tokens is not None:
self.max_tokens = self._coerce_max_tokens(max_tokens)
+ if runtime_changed:
+ # The aux ceiling was probed against the previous main runtime (an "auto" aux route follows the
+ # main model); the caller re-runs the feasibility probe. A same-runtime recompute (overflow-reported
+ # window, grown local window, tier cap) keeps it: the summariser did not change (#114707).
+ self._aux_context_ceiling = None
self.threshold_tokens = self._compute_threshold_tokens(context_length, self.threshold_percent, self.max_tokens)
self._apply_threshold_tokens_cap()
# Reset to None so the property recomputes via the mode-aware path (not the legacy formula).
@@ -2371,11 +2376,16 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
_coerce_threshold_tokens_cap = _coerce_max_tokens
def _apply_threshold_tokens_cap(self) -> None:
- """Clamp threshold_tokens to the configured cap (itself clamped to the context length)."""
+ """Clamp threshold_tokens to the configured cap (itself clamped to the context length) and to the
+ auxiliary summariser's window when the feasibility probe installed one."""
if self.threshold_tokens_cap is not None and self.threshold_tokens_cap > 0:
_effective_cap = min(self.threshold_tokens_cap, self.context_length)
if _effective_cap < self.threshold_tokens:
self.threshold_tokens = _effective_cap
+ # Durable, so every recomputation honours it rather than a one-time assignment (#114707).
+ _aux_ceiling = getattr(self, "_aux_context_ceiling", None)
+ if isinstance(_aux_ceiling, int) and 0 < _aux_ceiling < self.threshold_tokens:
+ self.threshold_tokens = _aux_ceiling
@staticmethod
def _effective_threshold_percent(context_length: int, threshold_percent: float) -> float:
@@ -2445,6 +2455,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
self.threshold_percent = self._base_threshold_percent
# Effective trigger = min(ratio threshold, cap); re-applied in update_model().
self.threshold_tokens_cap = self._coerce_threshold_tokens_cap(threshold_tokens_cap)
+ # Aux summariser window installed by the feasibility probe; None until it runs.
+ self._aux_context_ceiling: int | None = None
self.protect_first_n, self.protect_last_n = protect_first_n, protect_last_n
# Proactive prune runs independently of the full-compression trigger. 0 = disabled.
self.proactive_prune_tokens = int(proactive_prune_tokens or 0)
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 25e6756f331..b314069b1ef 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1779,6 +1779,16 @@ class _CompressionLockLeaseRefresher:
break
+def _emit_feasibility_notice(agent: Any, msg: str) -> None:
+ """Store + emit a feasibility verdict once per distinct text: every main-runtime change re-probes, and an
+ unchanged verdict must not re-warn on each `/model --once` restore or fallback cycle (#114707)."""
+ if getattr(agent, "_last_feasibility_notice", None) == msg:
+ return
+ agent._last_feasibility_notice = msg
+ agent._compression_warning = msg
+ agent._emit_diagnostic_status(msg)
+
+
def _lower_threshold_to_aux_context(
agent: Any, *, aux_model: str, aux_context: int, aux_provider: str, aux_base_url: str
) -> None:
@@ -1789,6 +1799,9 @@ def _lower_threshold_to_aux_context(
compressor = agent.context_compressor
old_threshold = compressor.threshold_tokens
new_threshold = compressor.threshold_tokens = aux_context
+ # Durable ceiling: update_model() recomputes threshold_tokens from the main model on every window
+ # correction and re-applies this through _apply_threshold_tokens_cap() (#114707).
+ compressor._aux_context_ceiling = aux_context
summary_target_ratio = getattr(compressor, "summary_target_ratio", None)
if getattr(compressor, "tail_mode", None) == "lean":
# Keep the window-relative policy owned by the compressor property.
@@ -1846,8 +1859,7 @@ def _lower_threshold_to_aux_context(
f"Hermes's small-context floor and output reservation would recompute the trigger to "
f"{recomputed_threshold:,} tokens, still above the compression model's {aux_context:,}.)"
)
- agent._compression_warning = msg
- agent._emit_diagnostic_status(msg)
+ _emit_feasibility_notice(agent, msg)
logger.warning(
"Auxiliary compression model %s has %d token context, below the main model's compression threshold of %d "
"tokens — auto-lowered session threshold to %d to keep compression working.", aux_model, aux_context,
@@ -1903,8 +1915,7 @@ def check_compression_model_feasibility(agent: Any) -> None:
"⚠ No auxiliary LLM provider configured: Hermes has no helper model for summarising "
"long chats, so older messages will be cut without a summary. Run `hermes setup` to add one."
)
- agent._compression_warning = msg
- agent._emit_diagnostic_status(msg)
+ _emit_feasibility_notice(agent, msg)
logger.warning("No auxiliary LLM provider for compression — summaries will be unavailable.")
return
aux_base_url = str(getattr(client, "base_url", ""))
@@ -1952,6 +1963,22 @@ def check_compression_model_feasibility(agent: Any) -> None:
logger.debug("Compression feasibility check failed (non-fatal): %s", exc)
+def revalidate_compression_feasibility(agent: Any) -> None:
+ """Re-run the aux feasibility probe after the main runtime changed (model switch, fallback activation,
+ primary restore). ``update_model()`` already voided the previous ceiling; probing now clamps the trigger
+ before the first compaction on the new window rather than after it (#114707). A probe failure leaves the
+ latch unset so the lazy probe at the next compaction re-raises hard rejections."""
+ agent._compression_feasibility_checked = False
+ if not getattr(agent, "context_compressor", None):
+ return
+ try:
+ check_compression_model_feasibility(agent)
+ except Exception as exc:
+ logger.debug("Compression feasibility re-check deferred to the next compaction: %s", exc)
+ return
+ agent._compression_feasibility_checked = True
+
+
def replay_compression_warning(agent: Any) -> None:
"""Re-send the stored compression warning through ``status_callback``.
Called once at the start of the first ``run_conversation()``, when the gateway callback (absent during
@@ -4159,7 +4186,8 @@ def try_shrink_image_parts_in_messages(api_messages: list, *, max_dimension: int
__all__ = [
"COMPACTION_STATUS", "COMPACTION_DONE_STATUS", "COMPACTION_HEARTBEAT_STATUS", "COMPACTION_STATUS_MARKER", "is_compaction_progress_status",
- "check_compression_model_feasibility", "replay_compression_warning", "compress_context",
+ "check_compression_model_feasibility", "revalidate_compression_feasibility", "replay_compression_warning",
+ "compress_context",
"try_shrink_image_parts_in_messages",
]
diff --git a/tests/agent/test_compression_feasibility.py b/tests/agent/test_compression_feasibility.py
index 1e0cdc998b0..e046a02b553 100644
--- a/tests/agent/test_compression_feasibility.py
+++ b/tests/agent/test_compression_feasibility.py
@@ -107,6 +107,47 @@ def test_aux_sync_legacy_tail_follows_lowered_threshold():
assert compressor.tail_token_budget == int(compressor.threshold_tokens * compressor.summary_target_ratio)
+def test_fallback_activation_reprobes_aux_ceiling_and_keeps_it_durable():
+ """Every main-runtime change re-probes the summariser and the clamp survives later window
+ corrections; a failed probe leaves the latch unset for the lazy compaction-time probe (#114707)."""
+ from agent.chat_completion_helpers import _update_fallback_context_compressor
+
+ agent = _make_agent(main_context=200_000)
+ compressor = agent.context_compressor = ContextCompressor(
+ "test-main-model", config_context_length=200_000, threshold_percent=0.50, quiet_mode=True,
+ )
+ notices = 0
+
+ def _count(_message):
+ nonlocal notices
+ notices += 1
+
+ agent._emit_status = _count
+ agent._config_context_length = None
+ agent._compression_feasibility_checked = True # probed on the primary; aux fit there
+ agent.model = "fallback-model"
+ client = MagicMock(base_url="http://localhost/v1", api_key="test-key")
+ with patch("agent.auxiliary_client.get_text_auxiliary_client", return_value=(client, "aux")), \
+ patch("agent.model_metadata.get_model_context_length", side_effect=[1_000_000, 80_000]):
+ _update_fallback_context_compressor(agent)
+ assert compressor.context_length == 1_000_000
+ assert compressor.threshold_tokens == 80_000
+ assert agent._compression_feasibility_checked is True
+ # Same-runtime window correction (provider-reported limit) keeps the ceiling.
+ compressor.update_model(
+ "fallback-model", context_length=800_000, base_url=agent.base_url, api_key=agent.api_key,
+ provider=agent.provider, api_mode=agent.api_mode,
+ )
+ assert compressor.threshold_tokens == 80_000
+ # An unchanged verdict is not re-announced on the next runtime change (fallback/restore cycles).
+ with patch("agent.auxiliary_client.get_text_auxiliary_client", return_value=(client, "aux")), \
+ patch("agent.model_metadata.get_model_context_length", side_effect=[1_000_000, 80_000]):
+ agent.base_url = "https://other-route.example/v1" # runtime change, identical verdict text
+ _update_fallback_context_compressor(agent)
+ assert compressor.threshold_tokens == 80_000
+ assert notices == 1
+
+
# ── Core warning logic ──────────────────────────────────────────────
diff --git a/tests/agent/test_primary_runtime_restore.py b/tests/agent/test_primary_runtime_restore.py
index e66d186bcf1..cf3d46ceab6 100644
--- a/tests/agent/test_primary_runtime_restore.py
+++ b/tests/agent/test_primary_runtime_restore.py
@@ -206,7 +206,8 @@ class TestRestorePrimaryRuntime:
with patch("agent.process_bootstrap.OpenAI", return_value=MagicMock()):
assert agent._restore_primary_runtime() is True
- assert emitted == []
+ # The runtime change re-probes compression feasibility (a diagnostic, not a restore label).
+ assert [m for m in emitted if "restored" in str(m).lower() or "fallback" in str(m).lower()] == []
def test_restore_retry_preserves_fallback_identity_after_partial_failure(self):
agent = _make_agent(
diff --git a/tests/agent/test_switch_model_context.py b/tests/agent/test_switch_model_context.py
index e23652b93a7..b46ddfd6d5e 100644
--- a/tests/agent/test_switch_model_context.py
+++ b/tests/agent/test_switch_model_context.py
@@ -134,10 +134,11 @@ def test_switch_model_without_config_context_length():
def test_switch_model_reapplies_checked_auxiliary_compression_limit():
- """A model switch retains the auxiliary compression model's safe trigger."""
+ """A model switch re-probes the auxiliary summariser eagerly: the trigger is clamped to its window
+ before the first compaction on the new model, and un-clamped again when a later switch fits (#114707)."""
agent = _make_agent_with_compressor(config_context_length=200_000)
agent.compression_enabled = True
- agent._compression_feasibility_checked = True
+ agent._compression_feasibility_checked = False
agent._aux_compression_context_length_config = None
agent._custom_providers = []
agent._compression_warning = None
@@ -173,6 +174,22 @@ def test_switch_model_reapplies_checked_auxiliary_compression_limit():
assert agent.context_compressor.context_length == 400_000
assert agent.context_compressor.threshold_tokens == 80_000
+ assert agent._compression_feasibility_checked is True
+ # A same-runtime window correction (overflow-reported limit) keeps the aux ceiling.
+ agent.context_compressor.update_model(
+ model="larger-main-model", context_length=1_000_000, base_url="https://openrouter.ai/api/v1",
+ api_key="sk-new", provider="openrouter", api_mode="chat_completions",
+ )
+ assert agent.context_compressor.threshold_tokens == 80_000
+ # Switching to a runtime whose aux fits restores the main-model trigger (no one-way ratchet).
+ with (
+ patch("agent.model_metadata.get_model_context_length", side_effect=[400_000, 400_000]),
+ patch("agent.auxiliary_client.get_text_auxiliary_client", return_value=(aux_client, "auxiliary-model")),
+ ):
+ agent.switch_model(
+ "other-main-model", "openrouter", api_key="sk-new", base_url="https://openrouter.ai/api/v1",
+ )
+ assert agent.context_compressor.threshold_tokens == 300_000
def test_switch_model_omitted_base_url_preserves_direct_openai_capability():
diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.md
index 7f237caa4ee..7b395cab68e 100644
--- a/website/docs/developer-guide/context-compression-and-caching.md
+++ b/website/docs/developer-guide/context-compression-and-caching.md
@@ -276,6 +276,13 @@ recomputes `threshold_tokens × target_ratio` (102,400 tokens at 512K × 0.20).
These are tail-selection budgets, not strict limits on the entire compacted context:
protected messages, boundary alignment, summaries, and anchors can add tokens.
+The lowered trigger is a durable ceiling on the compressor, so window corrections for the
+same model (a provider-reported limit, a grown local window) keep it. Whenever the main
+runtime changes — `/model`, fallback activation, or the restore back to the primary — the
+auxiliary model is re-probed immediately: the trigger is clamped again before the first
+compaction on the new window, or restored to the main model's own value when the
+auxiliary model now fits.
+
### Per-model threshold overrides
`compression.model_thresholds` lets you trigger compaction at different points