Skip to content

The agent that grows with you

fix(compression): an over-window session that cannot shrink ends the turn with /new guidance and waits one idle budget, not the ceiling

teknium1d03d6c2b3973
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 479da2bde90..c41cce6b5f2 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1123,6 +1123,13 @@ def run_compress_context_with_progress_timeout(
ceiling = max(float(total_ceiling_seconds), float(idle_timeout_seconds))
idle = float(idle_timeout_seconds)
+ # An over-window request cannot be sent uncompressed, so a summary that keeps streaming while
+ # reclaiming nothing must not hold the host (and the Desktop UI) to the full ceiling: bound the
+ # pre-commit wait to one inactivity budget (``compression.context_timeout_seconds``) and let the
+ # first-stall deterministic fallback below carry the compaction (#116472: a 600s trickle froze
+ # the Desktop for 10 minutes per turn).
+ if request_exceeds_window:
+ ceiling = idle
fence = fence if fence is not None else CompressionCommitFence()
fence.set_total_ceiling_seconds(ceiling)
# Read BEFORE this attempt runs: the host's ``stalled`` record and the cancelled worker's
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 15b4f772c50..616edceba64 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -337,6 +337,32 @@ def _fail_closed_after_preflight_timeout(agent, request_tokens: int) -> None:
)
+def _fail_closed_on_insufficient_progress(agent, request_tokens: int) -> None:
+ """Stop an over-window turn the moment preflight proves it cannot shrink the session, with
+ "start a new session" guidance, instead of sending a request the model cannot accept.
+
+ ``_fail_closed_after_preflight_timeout`` only stops a turn whose compression wait timed out. A
+ pass that ran and reclaimed nothing (or under 5%) on a request still above the model window used
+ to fall through to the provider call: the provider rejected it, the overflow handler forced
+ another compression pass, and each pass re-waited its budget while the UI sat blocked (#116472:
+ ~356k tokens on a 131k window). Only a ``True`` verdict fails closed — an unknown window or a
+ fitting request keeps the send-as-is behaviour — and a pass skipped by the summary-failure
+ cooldown is a defer, not proof of incompressibility, so it keeps its typed cooldown result.
+ """
+ from agent.conversation_compression import compression_blocked_transiently, request_exceeds_model_window
+
+ if request_exceeds_model_window(agent, request_tokens) is not True:
+ return
+ if compression_blocked_transiently(agent):
+ return
+ window = agent.context_compressor.context_length
+ raise PreflightCompressionTimedOut(
+ "Context compression could not bring this session under the model's context window "
+ f"(~{request_tokens:,} tokens vs {window:,}). The provider call was not "
+ "sent. Start a new session with /new; this session is too large to compress further."
+ )
+
+
def _review_fork_first_request_pending(agent: Any) -> bool:
"""Whether a detached review fork has yet to send its first provider request: it
replays the parent's FULL snapshot as a warm cache read, so compaction must wait
diff --git a/agent/turn_context_compaction.py b/agent/turn_context_compaction.py
index 590946c6b99..939ecaa92df 100644
--- a/agent/turn_context_compaction.py
+++ b/agent/turn_context_compaction.py
@@ -404,6 +404,7 @@ def _run_preflight_passes(
_orig_len, len(out.messages), _orig_tokens, _preflight_tokens
):
_tc._fail_closed_after_preflight_timeout(agent, _preflight_tokens)
+ _tc._fail_closed_on_insufficient_progress(agent, _preflight_tokens)
out.blocked = True
break # Cannot compress further: neither rows nor tokens moved
out.conversation_history = conversation_history_after_compression(
@@ -421,6 +422,8 @@ def _run_preflight_passes(
"~%s -> ~%s request tokens; skipping additional passes",
f"{_orig_tokens:,}", f"{_preflight_tokens:,}",
)
+ # Sub-5% progress on a request still above the window: no further pass will get under it.
+ _tc._fail_closed_on_insufficient_progress(agent, _preflight_tokens)
break
diff --git a/tests/agent/test_over_window_compression_fail_closed.py b/tests/agent/test_over_window_compression_fail_closed.py
new file mode 100644
index 00000000000..3e3f61bdfe5
--- /dev/null
+++ b/tests/agent/test_over_window_compression_fail_closed.py
@@ -0,0 +1,81 @@
+"""An over-window session that compression cannot shrink must not block the host toward the
+compression ceiling or send a request the model cannot accept (#116472).
+
+Two invariants: turn-start preflight ends the turn at once with ``/new`` guidance when a pass made
+no progress on a request still above the model window (a fitting or unknown-window request keeps
+the send-as-is behaviour); and the pre-commit wait for an over-window request is bounded by ONE
+inactivity budget (``compression.context_timeout_seconds``) instead of the generic ceiling, so a
+summary that keeps streaming while reclaiming nothing cannot hold the session for minutes.
+"""
+
+import time
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from agent.conversation_compression import run_compress_context_with_progress_timeout
+from agent.turn_context import PreflightCompressionTimedOut
+from agent.turn_context_compaction import CompactionOutcome, _run_preflight_passes
+
+
+def _agent(*, context_length):
+ compressor = SimpleNamespace(
+ protect_first_n=3, protect_last_n=3, threshold_tokens=65_536, context_length=context_length,
+ summary_target_ratio=0.5, should_compress=lambda tokens: tokens >= 65_536,
+ )
+ agent = SimpleNamespace(
+ context_compressor=compressor, session_id="s1", model="m", max_compression_attempts=3,
+ _emit_status=MagicMock(), _compression_blocked_transient=None,
+ )
+ agent._compress_context = lambda msgs, system, **kw: (msgs, system) # a pass that reclaims nothing
+ return agent
+
+
+def _preflight(agent, request_tokens):
+ out = CompactionOutcome(
+ messages=[{"role": "user", "content": "hi"}], active_system_prompt="sys",
+ conversation_history=None, current_turn_user_idx=0,
+ )
+ with patch("agent.turn_context._preflight_request_tokens", return_value=request_tokens), patch(
+ "agent.turn_context_compaction.automatic_compaction_status_message", return_value=""
+ ):
+ _run_preflight_passes(agent, out, agent.context_compressor, request_tokens, "sys", "t")
+ return out
+
+
+def test_no_progress_preflight_fails_closed_only_when_the_request_exceeds_the_window():
+ with pytest.raises(PreflightCompressionTimedOut, match="Start a new session with /new"):
+ _preflight(_agent(context_length=131_072), 356_113)
+
+ # Over threshold but inside the window: sent as-is (blocked so the loop does not retry).
+ assert _preflight(_agent(context_length=1_000_000), 356_113).blocked is True
+ # Window unresolvable (0): never guess — the previous behaviour stands.
+ assert _preflight(_agent(context_length=0), 356_113).blocked is True
+ # The pass no-op'd on a transient guard (summary-failure cooldown): a defer, not proof.
+ cooling = _agent(context_length=131_072)
+ cooling._compression_blocked_transient = "cooldown:42"
+ assert _preflight(cooling, 356_113).blocked is True
+
+
+def test_over_window_wait_is_bounded_by_one_inactivity_budget():
+ msgs = [{"role": "user", "content": "x"}]
+
+ def trickle(fence):
+ end = time.monotonic() + 5
+ while time.monotonic() < end and not (fence.is_cancelled or fence.deadline_exceeded):
+ fence.touch_progress() # a token every 50ms: never idle, never committing
+ time.sleep(0.05)
+ return msgs, ""
+
+ def waited(*, request_exceeds_window):
+ started = time.monotonic()
+ result = run_compress_context_with_progress_timeout(
+ worker=trickle, messages=msgs, system_prompt_fallback="sys", idle_timeout_seconds=0.4,
+ total_ceiling_seconds=2.0, request_exceeds_window=request_exceeds_window, stall_fallback=False,
+ )
+ assert result[0] is msgs
+ return time.monotonic() - started
+
+ assert waited(request_exceeds_window=True) < 1.5 # one idle budget (0.4s), not the 2s ceiling
+ assert waited(request_exceeds_window=False) >= 1.9 # a fitting request keeps the full ceiling
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index cc96dc0285f..2ffa4109ed5 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1025,9 +1025,9 @@ 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. 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_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. A preflight pass that reclaims nothing on a request still above the window ends the turn immediately with guidance to start a new session (`/new`) instead of sending a request the model cannot accept. 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.
+`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`. For a request already above the model's context window the pre-commit wait is bounded by one `context_timeout_seconds` budget instead of this ceiling: such a request cannot be sent uncompressed anyway, and a summary that keeps streaming while reclaiming nothing would otherwise hold the session (and the Desktop UI) for the full ceiling on every turn — the deterministic fallback summary then carries the compaction. Raise `context_timeout_seconds` if your summariser legitimately needs longer. 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.
`protect_first_n` controls how many **non-system** head messages are pinned across every compaction. Default `3` — the opening user/assistant exchange survives every summarizer pass so the original goal stays visible. On long-running rolling-compaction sessions where the opening turn is no longer relevant, set `protect_first_n: 0` to pin nothing but the system prompt + summary + tail. The system prompt itself is always preserved regardless of this setting.