Skip to content

The agent that grows with you

fix(compression): a timed-out preflight compaction sends a fitting request and prune-commits an over-window one

teknium1303bcd804af4
diff --git a/agent/compression_facade.py b/agent/compression_facade.py
index 52ef5ff5dee..576b54d194d 100644
--- a/agent/compression_facade.py
+++ b/agent/compression_facade.py
@@ -106,13 +106,16 @@ def _sync_persisted_markers(target_messages, source_messages) -> None:
def _run_under_progress_timeout(
- agent, run, messages, system_message, *, active_fence, fence_registration_lock, idle_timeout, total_ceiling
+ agent, run, messages, system_message, *, active_fence, fence_registration_lock, idle_timeout, total_ceiling,
+ approx_tokens=None,
):
"""Run ``run(fence, target_messages=snapshot)`` on the pool under the progress-aware timeout.
The pooled worker must NEVER share the caller's live transcript — a late engine after a host timeout could
rewrite it. It deep-snapshots on the worker and publishes only via an ADMITTED commit; a no-op/abort
returns the snapshot unchanged, so the ORIGINAL list is handed back to keep identity semantics."""
- from agent.conversation_compression import CompressionCommitFence, run_compress_context_with_progress_timeout
+ from agent.conversation_compression import (
+ CompressionCommitFence, request_exceeds_model_window, run_compress_context_with_progress_timeout,
+ )
def _snapshot_worker(fence=None, *, same_turn_fallback_recovery=False):
# #76354 review F3: the pooled worker must NEVER share the caller's live transcript. Plugin/legacy
@@ -160,6 +163,7 @@ def _run_under_progress_timeout(
on_timeout_cause=_on_timeout_cause,
on_commit_overrun=lambda waited, ceiling: _warn_commit_overrun(agent, waited, ceiling), fence=active_fence,
telemetry_agent=agent, new_fence=_publish_new_fence, fallback_worker=_same_turn_fallback_worker,
+ request_exceeds_window=request_exceeds_model_window(agent, approx_tokens) is True,
)
@@ -271,7 +275,7 @@ class CompressionFacadeMixin:
result = _run_under_progress_timeout(
self, _run, messages, system_message,
active_fence=active_fence, fence_registration_lock=fence_registration_lock,
- idle_timeout=idle_timeout, total_ceiling=total_ceiling,
+ idle_timeout=idle_timeout, total_ceiling=total_ceiling, approx_tokens=approx_tokens,
)
_mirror_result_onto_live_lists(self, result, messages, direct_path=direct_path)
_rebind_caller_session_context(self)
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 4f252fda8fc..5b0d6a2392a 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -3384,6 +3384,12 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
_aux_call_start = time.monotonic()
_latency_info: Dict[str, int] = {"prompt_build_ms": max(0, int((_aux_call_start - prompt_started_at) * 1000))}
call_kwargs["latency_info"] = _latency_info
+ # Per-attempt observable (#114594): with this line a stalled attempt is distinguishable from a slow
+ # one — silence before it is prompt build, silence after it is the summary provider.
+ logger.info(
+ "Compression summary call dispatched: model=%s prompt_chars=%s prompt_build_ms=%s",
+ self.summary_model or self.model, f"{len(prompt):,}", _latency_info["prompt_build_ms"],
+ )
try:
# Compression is atomic: shield the summary call from gateway interrupts. Re-entrant.
with aux_interrupt_protection():
diff --git a/agent/context_compressor_summary.py b/agent/context_compressor_summary.py
index fcffc0b8977..6c50875a4d3 100644
--- a/agent/context_compressor_summary.py
+++ b/agent/context_compressor_summary.py
@@ -38,7 +38,7 @@ class SummaryDispatchMixin:
if take_deterministic_summary_pin():
# Surfaces through the fallback summary's reason line and the host's one-shot user warning.
self._last_summary_error = (
- "summary model stalled again after a stall backoff; deterministic fallback summary inserted"
+ "summary model stalled on every route; deterministic fallback summary inserted"
)
telemetry = getattr(self, "_active_compression_telemetry", None)
if isinstance(telemetry, dict):
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index ef752bf696b..a0b2f9ac5d4 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -869,6 +869,18 @@ def _prior_timeout_failures(agent: Any) -> int:
return count if isinstance(count, int) and not isinstance(count, bool) else 0
+def request_exceeds_model_window(agent: Any, request_tokens: Any) -> Optional[bool]:
+ """Whether a ~``request_tokens`` request cannot be sent at all (above the model's context window).
+ ``None`` when either side is unknown (no compressor / unresolvable window / no estimate), so callers
+ keep their conservative default instead of treating "unknown" as "fits"."""
+ window = getattr(getattr(agent, "context_compressor", None), "context_length", None)
+ if isinstance(window, bool) or not isinstance(window, int) or window <= 0:
+ return None
+ if isinstance(request_tokens, bool) or not isinstance(request_tokens, int):
+ return None
+ return request_tokens > window
+
+
def _retry_compression_on_fallback_chain(
*, worker: Callable[[CompressionCommitFence], Tuple[list, str]], messages: list,
system_prompt_fallback: Any, idle_timeout_seconds: float, total_ceiling_seconds: float,
@@ -939,7 +951,7 @@ def _run_pinned_compression_retry(
deterministic = route.get("deterministic") is True
if deterministic:
logger.warning(
- "Context compression stalled again after a stall backoff — committing the %s (no summary model) "
+ "Context compression stalled on every summary route — committing the %s (no summary model) "
"before continuing without compression", route["label"],
)
else:
@@ -1090,11 +1102,15 @@ def run_compress_context_with_progress_timeout(
fence: Optional[CompressionCommitFence] = None, telemetry_agent: Any = None, stall_fallback: bool = True,
new_fence: Optional[Callable[[], CompressionCommitFence]] = None,
fallback_worker: Optional[Callable[[CompressionCommitFence], Tuple[list, str]]] = None,
+ request_exceeds_window: bool = False,
) -> Tuple[list, str]:
"""Run ``worker(fence)`` under a sync progress-aware (idle + ceiling) timeout.
Budgets bound the PRE-commit phase only: an admitted commit always completes (overrun logged, surfaced
once via ``on_commit_overrun``). A pre-commit cancel returns ``(messages, system_prompt_fallback)`` (lazy
- callable), detaching the worker; a stall first retries the chain once on ``new_fence``, then on_timeout"""
+ callable), detaching the worker; a stall first retries the chain once on ``new_fence``, then on_timeout.
+ ``request_exceeds_window``: the request this compaction must shrink is above the model's context
+ window, so "continue without compression" is not an option — a stall escalates to the deterministic
+ fallback summary on the FIRST timeout instead of waiting for a prior stall in the session (#114594)."""
if idle_timeout_seconds <= 0:
raise ValueError(
"run_compress_context_with_progress_timeout requires "
@@ -1110,8 +1126,11 @@ def run_compress_context_with_progress_timeout(
fence.set_total_ceiling_seconds(ceiling)
# Read BEFORE this attempt runs: the host's ``stalled`` record and the cancelled worker's
# ``stall_interrupted`` record both land during the unwind below, and this stall must not count as
- # its own prior. One prior timeout-class failure = the route already burned a full idle window.
- escalate_deterministic = stall_fallback and _prior_timeout_failures(telemetry_agent) >= 1
+ # One prior timeout-class failure = the route already burned a full idle window. An over-window request
+ # cannot be sent unchanged, so it earns the deterministic fallback on its first stall (#114594).
+ escalate_deterministic = stall_fallback and (
+ request_exceeds_window or _prior_timeout_failures(telemetry_agent) >= 1
+ )
# Sync mirror of gateway hygiene's run_in_executor + wait_for loop: offload,
# poll idle budget + ceiling, fence-cancel on timeout so no late commit lands.
from tools.thread_context import propagate_context_to_thread
diff --git a/agent/turn_context.py b/agent/turn_context.py
index fd671e52d52..b3f5e7f7338 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -309,11 +309,22 @@ class PreflightCompressionTimedOut(RuntimeError):
def _fail_closed_after_preflight_timeout(agent, request_tokens: int) -> None:
- """Stop an oversized turn instead of sending its unchanged provider payload."""
- from agent.conversation_compression import context_compression_timed_out
+ """Stop an oversized turn instead of sending its unchanged provider payload.
+ Only a request the model cannot accept (above its context window, or of unknown fit) is stopped: a
+ request that merely sits above the compression threshold is sent unchanged, exactly as the
+ cooldown-blocked path sends it every turn — otherwise a slow summariser turns a session that still
+ fits its window into a turn that can never run (#113646, #114594)."""
+ from agent.conversation_compression import context_compression_timed_out, request_exceeds_model_window
if not context_compression_timed_out(agent):
return
+ if request_exceeds_model_window(agent, request_tokens) is False:
+ logger.warning(
+ "Preflight compression timed out but the request (~%s tokens) fits the model window (%s); "
+ "sending it uncompressed this turn",
+ f"{request_tokens:,}", f"{agent.context_compressor.context_length:,}",
+ )
+ return
raise PreflightCompressionTimedOut(
"Context compression timed out before it could commit while the request "
f"was still approximately {request_tokens:,} tokens. The provider call "
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 950bc388da8..94a1e465bf7 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -595,7 +595,9 @@ DEFAULT_CONFIG = {
"hygiene_max_turn_hold_seconds": 10,
# Inactivity budget for in-agent compress_context (loop, /compress, preflight); same
# progress-aware semantics as hygiene_timeout_seconds. 0 = disable the owned wrapper
- # (callers passing commit_fence, e.g. gateway hygiene, never use it).
+ # (callers passing commit_fence, e.g. gateway hygiene, never use it). Floored at the auxiliary
+ # compression request timeout (auxiliary.compression.timeout, min 300s): the host never judges
+ # silence before the summary request itself would time out.
"context_timeout_seconds": 120,
# Absolute cap on the *pre-commit* compress_context wait (summary/stream phase) even while
# tokens move. Clamped >= context_timeout_seconds when that is > 0. A started SessionDB
diff --git a/tests/agent/test_compress_context_progress_timeout.py b/tests/agent/test_compress_context_progress_timeout.py
index 3a5ed5b06c9..2989a7efab9 100644
--- a/tests/agent/test_compress_context_progress_timeout.py
+++ b/tests/agent/test_compress_context_progress_timeout.py
@@ -124,11 +124,29 @@ class TestContextCompressionTimeoutState:
class TestResolveContextCompressionTimeouts:
+ @pytest.fixture(autouse=True)
+ def _no_aux_floor(self, monkeypatch):
+ # The aux compression request budget floors the idle window (#114594); pin it off so the legacy
+ # clamps below are judged on their own, and on in the dedicated test.
+ import agent.auxiliary_client as aux
+ monkeypatch.setattr(aux, "_effective_aux_timeout", lambda task, timeout: 0.0)
+
def test_defaults_when_empty_cfg(self):
idle, ceiling = resolve_context_compression_timeouts({})
assert idle == 120.0
assert ceiling == 600.0
+ def test_idle_is_floored_at_the_aux_compression_request_budget(self, monkeypatch):
+ """The host must never judge silence before the summary request itself would time out; a budget
+ above the ceiling raises the ceiling too, and a larger explicit idle is kept."""
+ import agent.auxiliary_client as aux
+ monkeypatch.setattr(aux, "_effective_aux_timeout", lambda task, timeout: 300.0)
+ assert resolve_context_compression_timeouts({}) == (300.0, 600.0)
+ assert resolve_context_compression_timeouts({"context_timeout_seconds": 900}) == (900.0, 900.0)
+ monkeypatch.setattr(aux, "_effective_aux_timeout", lambda task, timeout: 900.0)
+ assert resolve_context_compression_timeouts({}) == (900.0, 900.0)
+ assert resolve_context_compression_timeouts({"context_timeout_seconds": 0}) == (0.0, 600.0)
+
def test_zero_idle_disables_wrapper(self):
idle, ceiling = resolve_context_compression_timeouts(
{"context_timeout_seconds": 0}
diff --git a/tests/agent/test_compression_stall_deterministic_fallback.py b/tests/agent/test_compression_stall_deterministic_fallback.py
index 83994e64b41..732f3cfad94 100644
--- a/tests/agent/test_compression_stall_deterministic_fallback.py
+++ b/tests/agent/test_compression_stall_deterministic_fallback.py
@@ -4,7 +4,8 @@ After one stall the host records a stall-class backoff (``_consecutive_timeout_f
next attempt stalls again, "continuing without compression" would re-enter the same silent route every
turn, so the stall retry ladder ends with a deterministic rung: the worker is re-run with the summary LLM
skipped and compress() commits its static fallback summary through the ordinary lease/fence pipeline.
-A first stall keeps today's behaviour (backoff, LLM retry after it lapses). A pinned fallback route whose
+A first stall keeps today's behaviour (backoff, LLM retry after it lapses) unless the request is already
+above the model's context window — then nothing can be sent unchanged and the rung runs at once (#114594). A pinned fallback route whose
summary call fails still commits under the default ``abort_on_summary_failure=false`` — that must not be
logged as a recovery (#112387 review caveat).
"""
@@ -174,3 +175,22 @@ def test_fence_level_retry_ladder_is_unchanged_without_a_prior_timeout():
)
assert msgs is original and prompt == "degraded-prompt"
assert len(attempts) == 1
+
+
+def test_over_window_request_commits_the_deterministic_fallback_on_the_first_stall(tmp_path, fast_timeouts):
+ """A request above the model's context window cannot be sent unchanged, so waiting for a SECOND stall
+ (which on the messaging gateway never comes — the first one auto-reset the session) is a dead end:
+ the deterministic rung runs on the first stall and the transcript is committed (#114594)."""
+ agent = _make_agent(tmp_path, "C")
+ compressor = agent.context_compressor
+ compressor.context_length = 64_000
+ calls = []
+ live = _transcript()
+ with patch("agent.context_compressor.call_llm", side_effect=_stalling_call_llm(compressor, calls)), \
+ patch("agent.auxiliary_client._get_auxiliary_task_config", return_value={"fallback_chain": []}):
+ out, _ = agent._compress_context(live, "sys", approx_tokens=70_000)
+
+ assert calls == ["primary"], "the deterministic rung makes no second summary LLM call"
+ assert out is not live and len(out) < len(live)
+ assert len(_summary_rows(out)) == 1, "the over-window request got a committed deterministic handoff"
+ assert getattr(agent, "_last_compression_timed_out", None) is not True
diff --git a/tests/agent/test_compression_timeout_terminal.py b/tests/agent/test_compression_timeout_terminal.py
index f0dc8056d4d..2693c35c6a8 100644
--- a/tests/agent/test_compression_timeout_terminal.py
+++ b/tests/agent/test_compression_timeout_terminal.py
@@ -123,6 +123,8 @@ def test_pre_api_compression_timeout_is_typed_terminal():
agent.context_compressor.protect_first_n = 0
agent.context_compressor.protect_last_n = 0
agent.context_compressor._threshold_tokens = 1
+ # The typed terminal is the over-window outcome; a request that fits its window is sent uncompressed.
+ agent.context_compressor._resolved_context_length = 1
agent.context_compressor.should_compress = MagicMock(return_value=True)
agent.context_compressor.should_compress_info = MagicMock(
return_value=(True, None)
diff --git a/tests/agent/test_preflight_compression_timeout_fail_closed.py b/tests/agent/test_preflight_compression_timeout_fail_closed.py
index 05b9eabc0a9..00834b6da8f 100644
--- a/tests/agent/test_preflight_compression_timeout_fail_closed.py
+++ b/tests/agent/test_preflight_compression_timeout_fail_closed.py
@@ -11,6 +11,7 @@ from agent.turn_context import (
def test_preflight_timeout_blocks_unchanged_provider_payload():
+ """Unknown window (no compressor): the conservative #98424 default — never send blind."""
agent = SimpleNamespace(_last_compression_timed_out=True)
with pytest.raises(PreflightCompressionTimedOut, match="provider call was not sent"):
@@ -21,3 +22,18 @@ def test_structural_noop_keeps_existing_preflight_behavior():
agent = SimpleNamespace(_last_compression_timed_out=False)
_fail_closed_after_preflight_timeout(agent, 190_035)
+
+
+def test_preflight_timeout_sends_a_request_that_fits_the_model_window():
+ """Over the compression threshold but under the window (#113646): the turn runs uncompressed, exactly
+ like the cooldown-blocked path sends it; above the window it still fails closed."""
+ fits = SimpleNamespace(
+ _last_compression_timed_out=True, context_compressor=SimpleNamespace(context_length=120_000),
+ )
+ _fail_closed_after_preflight_timeout(fits, 99_347)
+
+ over = SimpleNamespace(
+ _last_compression_timed_out=True, context_compressor=SimpleNamespace(context_length=1_000_000),
+ )
+ with pytest.raises(PreflightCompressionTimedOut):
+ _fail_closed_after_preflight_timeout(over, 1_313_423)
diff --git a/tests/agent/test_preflight_timeout_typed_result.py b/tests/agent/test_preflight_timeout_typed_result.py
index 94541a2850c..1b08f668837 100644
--- a/tests/agent/test_preflight_timeout_typed_result.py
+++ b/tests/agent/test_preflight_timeout_typed_result.py
@@ -40,6 +40,8 @@ def test_turn_start_preflight_timeout_returns_typed_result_not_exception():
agent.context_compressor.protect_first_n = 0
agent.context_compressor.protect_last_n = 0
agent.context_compressor.threshold_tokens = 1
+ # The typed result is the over-window outcome; a request that fits its window is sent uncompressed.
+ agent.context_compressor._resolved_context_length = 1
agent.context_compressor.should_compress = MagicMock(return_value=True)
agent.context_compressor.should_defer_preflight_to_real_usage = MagicMock(
return_value=False
diff --git a/tests/agent/test_turn_context.py b/tests/agent/test_turn_context.py
index a08d6665e2b..d285390277c 100644
--- a/tests/agent/test_turn_context.py
+++ b/tests/agent/test_turn_context.py
@@ -215,7 +215,8 @@ def test_returns_turn_context_with_user_message_appended():
def test_preflight_timeout_stops_turn_before_provider_boundary():
- """An unchanged oversized payload must not escape turn construction."""
+ """An unchanged payload above the model window must not escape turn construction (a request that
+ still fits its window is sent uncompressed instead — see test_preflight_compression_timeout_fail_closed)."""
agent = _FakeAgent()
agent.compression_enabled = True
agent.max_compression_attempts = 3
@@ -223,7 +224,7 @@ def test_preflight_timeout_stops_turn_before_provider_boundary():
protect_first_n=2,
protect_last_n=2,
threshold_tokens=1_000,
- context_length=4_000,
+ context_length=1_500,
summary_target_ratio=0.3,
last_prompt_tokens=0,
should_compress=lambda tokens=None: True,
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 9798b799746..cd5b073aa5f 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1015,7 +1015,7 @@ The same limit is also a **fail-closed bound on what the model is sent** wheneve
The value is the **first rung** of an escalating ladder, not a fixed interval: consecutive failures for the same session wait `1x`, `3x`, then `9x` this value, capped at one hour. A session whose summary model is permanently broken therefore backs off instead of retrying forever on a fixed interval, and a run that actually shrinks the transcript resets it to the first rung. Escalation is per-session and process-local — a gateway restart resets it to the first rung while the cooldown deadline itself survives.
-`context_timeout_seconds` (default `120`) is the same **inactivity budget** for in-agent `compress_context` — the conversation loop, preflight compaction, and manual `/compress` — so a hung summary model cannot stall a session indefinitely. Streamed summary tokens extend the wait; only a silent worker is cut off. On timeout Hermes retries the summary once against the first entry of `auxiliary.compression.fallback_chain` (using that entry's own `timeout` when it declares one) — a stalled route never raises, so the auxiliary client's own fallback handling cannot see it. Only if that attempt also fails, or no fallback chain is configured, does Hermes skip compaction, keep the existing messages, and warn the user. Set to `0` to disable. Gateway session hygiene keeps its own `hygiene_timeout_seconds` path and is not double-wrapped.
+`context_timeout_seconds` (default `120`) is the same **inactivity budget** for in-agent `compress_context` — the conversation loop, preflight compaction, and manual `/compress` — so a hung summary model cannot stall a session indefinitely. Streamed summary tokens extend the wait; only a silent worker is cut off. The budget is floored at the auxiliary compression request's own timeout (`auxiliary.compression.timeout`, minimum 300s), so the host never gives up on a silent summariser before the request itself would — a reasoning summariser thinking before its first token, or a route that cannot stream, gets the same budget the provider call has. On timeout Hermes retries the summary once against the first entry of `auxiliary.compression.fallback_chain` (using that entry's own `timeout` when it declares one) — a stalled route never raises, so the auxiliary client's own fallback handling cannot see it. If that attempt also fails, or no fallback chain is configured, what happens next depends on whether the request still fits the model's context window: a request that fits is sent uncompressed this turn (the summary-failure cooldown stops the retry from repeating every turn); a request above the window cannot be sent at all, so Hermes commits its deterministic fallback summary (old tool results pruned, a static handoff in place of the summarised middle) instead of ending the turn — ending the turn with the "compression timed out" recovery result (and, on the messaging gateway, the automatic session reset) is the last resort, reached only when even the deterministic pass cannot shrink the transcript. Set to `0` to disable. Gateway session hygiene keeps its own `hygiene_timeout_seconds` path and is not double-wrapped.
`context_total_ceiling_seconds` (default `600`) bounds the in-agent **pre-commit** wait (summary / stream phase) even while tokens are still moving. It is clamped to at least `context_timeout_seconds`. The exact guarantee: **the summary phase is bounded by this ceiling; the commit phase is logged and surfaced if it exceeds it.** Once the worker has entered the compression commit fence and SessionDB mutation is in flight, the commit is never abandoned mid-flight — that would risk transcript divergence — but the wait is no longer silent: if the commit runs past the ceiling, Hermes logs the overrun (WARNING, escalating to ERROR on repeat), sends a one-shot warning through the user-visible warning channel, and keeps waiting in bounded increments until the commit completes. When the ceiling expires during the summary phase, the summary model's stream is closed at that same instant on every auxiliary wire (chat.completions, Codex Responses, Anthropic Messages) — an abandoned summary is not billed to completion on a connection nobody is waiting for, and its session lease is freed for the next attempt.