Skip to content

The agent that grows with you

refactor(compression): one trigger derivation for update_model and the switch-guard preview

kshitijk4pooraf0be164c1d2
diff --git a/agent/agent_init.py b/agent/agent_init.py
index b48037180be..a7b7b64c6a0 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2089,7 +2089,9 @@ def _emit_compression_summary(agent, cs):
# The active engine's own threshold β€” a plugin's differs from cs.threshold.
_pct = getattr(_cc, "threshold_percent", cs.threshold)
_cap = getattr(_cc, "threshold_tokens_cap", None)
- _cap_note = f" (capped at {_cap:,} tokens)" if _cap and _cap > 0 else ""
+ # Name the cap only when it is what set the trigger; on small windows the ratio already sits below it.
+ _cap_binds = bool(_cap) and _cap > 0 and _cc.threshold_tokens == min(_cap, _cc.context_length)
+ _cap_note = f" (capped at {_cap:,} tokens)" if _cap_binds else ""
print(f"πŸ“Š Context limit: {_cc.context_length:,} tokens (compress at {int(_pct*100)}% = {_cc.threshold_tokens:,}{_cap_note})")
else:
print(f"πŸ“Š Context limit: {_cc.context_length:,} tokens (auto-compression disabled)")
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index cfde08c9c10..df0b7b1bb80 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -2312,17 +2312,23 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
logger.debug("compression cancellation check failed", exc_info=True)
return False
- def preview_threshold_tokens(self, model: str, context_length: int, provider: str = "") -> int:
- """The trigger ``update_model`` would install for ``model``/``context_length``, without mutating
- state β€” the model-switch guard quotes it in its preflight-compression warning. Ignores any
- auxiliary-summariser ceiling: the post-switch feasibility probe re-derives that."""
+ def _derive_trigger(self, model: str, context_length: int, provider: str) -> tuple[float, float, int]:
+ """``(base_percent, effective_percent, threshold_tokens)`` for a model/window, from the raw config
+ value so a switch away from an overridden model falls back correctly. Pure: the one place the
+ trigger math lives, shared by ``update_model`` and the switch guard's preview so the number the
+ guard quotes is the number the compressor installs (#83450). Excludes the auxiliary-summariser
+ ceiling, which the feasibility probe re-derives per runtime."""
config_percent = getattr(self, "_config_threshold_percent", self.threshold_percent)
base_percent = resolve_model_threshold(model, self.model_thresholds, config_percent, provider)
- threshold_percent = self._effective_threshold_percent(context_length, base_percent)
- threshold = self._compute_threshold_tokens(context_length, threshold_percent, self.max_tokens)
+ effective_percent = self._effective_threshold_percent(context_length, base_percent)
+ threshold = self._compute_threshold_tokens(context_length, effective_percent, self.max_tokens)
if self.threshold_tokens_cap is not None and self.threshold_tokens_cap > 0:
threshold = min(threshold, self.threshold_tokens_cap, context_length)
- return threshold
+ return base_percent, effective_percent, threshold
+
+ def preview_threshold_tokens(self, model: str, context_length: int, provider: str = "") -> int:
+ """The trigger ``update_model`` would install, without mutating state."""
+ return self._derive_trigger(model, context_length, provider)[2]
def update_model(
self, model: str, context_length: int, base_url: str = "", api_key: Any = "", provider: str = "",
@@ -2332,10 +2338,6 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
runtime_changed = (model, provider, base_url, api_mode) != (self.model, self.provider, self.base_url, self.api_mode)
self.model, self.base_url, self.api_key, self.provider, self.api_mode = model, base_url, api_key, provider, api_mode
self.context_length = context_length
- # Re-resolve from the raw config value so a switch away from an overridden model falls back correctly.
- _config_pct = getattr(self, "_config_threshold_percent", self.threshold_percent)
- self._base_threshold_percent = resolve_model_threshold(model, self.model_thresholds, _config_pct, provider)
- self.threshold_percent = self._effective_threshold_percent(context_length, self._base_threshold_percent)
# max_tokens=None means "unspecified": keep the existing output reservation.
# A switch that genuinely changes the output budget passes the new value explicitly. (#43547)
if max_tokens is not None:
@@ -2345,7 +2347,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
# 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._base_threshold_percent, self.threshold_percent, self.threshold_tokens = self._derive_trigger(
+ model, context_length, provider)
self._apply_threshold_tokens_cap()
# Reset to None so the property recomputes via the mode-aware path (not the legacy formula).
self._tail_token_budget = None
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 62eff906dba..d86af01fcd1 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1278,9 +1278,9 @@ DEFAULT_CONFIG = {
# compression_threshold_tokens: optional absolute cap on a subagent's compaction TRIGGER
# (not the request payload), applied as the lower of this and the child's ratio threshold.
# 0 (default) = no subagent-specific cap; children compact where the parent does β€” the lower
- # of 0.50 x window and compression.threshold_tokens (256K on a 1M model). A replay of a 1,393-agent run showed 200K-400K caps within
- # 5% of each other in cost once cache prefixes are intact, and every compaction is a
- # chance to lose detail, so the default stays off. A token count >= 16000 enables it;
+ # of 0.50 x window and the global compression.threshold_tokens cap. A replay of a 1,393-agent
+ # run showed 200K-400K caps within 5% of each other in cost once cache prefixes are intact,
+ # and every compaction is a chance to lose detail, so the default stays off. A token count >= 16000 enables it;
# other values (true, "200k") are config errors: warned and ignored.
"compression_threshold_tokens": 0,
# When delegate_task narrows child toolsets, keep the parent's enabled MCP toolsets (so
diff --git a/tests/hermes_cli/test_context_switch_guard.py b/tests/hermes_cli/test_context_switch_guard.py
index 1982b78abb6..c1c53ff5539 100644
--- a/tests/hermes_cli/test_context_switch_guard.py
+++ b/tests/hermes_cli/test_context_switch_guard.py
@@ -70,7 +70,10 @@ def test_merge_appends_to_existing_warning(monkeypatch):
assert "preflight compression" in result.warning_message
-def test_default_cap_warns_before_large_window_ratio_threshold(monkeypatch):
+def test_cap_lowers_the_switch_warning_threshold_below_the_ratio(monkeypatch):
+ """The warning quotes the trigger the compressor will install: on a 1M target the ratio alone says
+ 500K (no warning at 300K in-flight), the cap says less β€” the guard must warn with the capped number."""
+ cap = 256_000
monkeypatch.setattr(
"hermes_cli.context_switch_guard._estimate_tokens",
lambda *a, **k: 300_000,
@@ -82,7 +85,7 @@ def test_default_cap_warns_before_large_window_ratio_threshold(monkeypatch):
cc = _compressor(
monkeypatch,
context_length=200_000,
- threshold_tokens_cap=256_000,
+ threshold_tokens_cap=cap,
)
agent = SimpleNamespace(
context_compressor=cc,
@@ -95,9 +98,7 @@ def test_default_cap_warns_before_large_window_ratio_threshold(monkeypatch):
merge_preflight_compression_warning(result, agent=agent)
assert "preflight compression" in result.warning_message
- assert "auto-compress at ~256,000" in result.warning_message
-
-
+ assert f"auto-compress at ~{cap:,}" in result.warning_message
def test_custom_provider_context_avoids_false_shrink_warning(monkeypatch):
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index 2f512c89e37..9cc8fd7f7e7 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -137,7 +137,7 @@ def _child_compression_cap_tokens(raw) -> "int | None":
def _apply_child_compression_cap(child, delegation_cfg: dict) -> None:
"""Optional absolute cap on the child's compaction trigger, ``delegation.compression_threshold_tokens``
(lower of it and any global ``compression.threshold_tokens``). Off by default: a 1M-window child
- compacts where its parent does (the global cap, 256K by default). The compressor applies the cap on first window resolution, which
+ compacts where its parent does. The compressor applies the cap on first window resolution, which
happens after construction, so setting it here is exactly equivalent to config."""
from agent.context_compressor import ContextCompressor