The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): retry a stalled summary on the fallback chain (#78981)
Shaun Eccles2c6938dc3a3a
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex cd873b20e37..b9cca84c76b 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -16,6 +16,8 @@ Improvements over v2:- Richer tool call/result detail in summarizer input"""+import contextlib+import contextvarsimport copyimport hashlibimport json@@ -56,6 +58,78 @@ def _safe_int(value: Any) -> int | None:return None+# ── Pinned summary route ─────────────────────────────────────────────────+# The summary call normally resolves its provider/model from+# ``auxiliary.compression``. One caller needs to override that for a single+# attempt: after the host's progress-aware timeout aborts a stalled summary+# (#78981), ``agent.conversation_compression`` re-runs compression with the+# route pinned to a configured ``fallback_chain`` entry. Nothing raised out+# of the stalled call, so the auxiliary client's own fallback handling — which+# only runs from its exception path — never saw that failure.+#+# A ContextVar, not an attribute on the compressor: the aborted worker is+# detached and still alive on the pool, and the compressor object is shared+# with it. Context is copied per worker (``propagate_context_to_thread``), so+# the pin reaches the retry's whole synchronous call chain and cannot leak+# into the stalled attempt or any unrelated auxiliary call.+_SUMMARY_ROUTE_PIN: contextvars.ContextVar[Optional[Dict[str, Any]]] = (+ contextvars.ContextVar("hermes_summary_route_pin", default=None)+)++# call_llm kwargs a pinned route may set. ``timeout`` lets a fallback entry+# keep its own deadline instead of inheriting one the primary already burned+# (same per-entry semantics the aux client applies to chain candidates).+_PINNED_ROUTE_FIELDS: tuple[str, ...] = (+ "provider",+ "model",+ "base_url",+ "api_key",+ "api_mode",+ "timeout",+)+++def pin_summary_route(route: Optional[Dict[str, Any]]):+ """Pin the next summary LLM call in this context to an explicit route.++ ``route`` is a mapping of :data:`_PINNED_ROUTE_FIELDS`; ``None`` is a+ no-op passthrough so callers can wire it unconditionally. Re-entrant-safe:+ restores the previous pin on exit.+ """+ token = _SUMMARY_ROUTE_PIN.set(route if isinstance(route, dict) else None)+ try:+ yield+ finally:+ _SUMMARY_ROUTE_PIN.reset(token)+++def take_pinned_summary_route() -> Optional[Dict[str, Any]]:+ """Read and consume the pinned summary route, if one is installed.++ Single use by design. ``_generate_summary`` retries itself on the main+ model when the summary route fails; re-issuing the pinned route there+ would spend a second full deadline on the backend that just failed.+ """+ route = _SUMMARY_ROUTE_PIN.get()+ if route is None:+ return None+ _SUMMARY_ROUTE_PIN.set(None)+ return route+++def _pinned_summary_call_kwargs() -> Dict[str, Any]:+ """Consume the pinned route as explicit ``call_llm`` keyword arguments."""+ route = take_pinned_summary_route()+ if not route:+ return {}+ return {+ field: route[field]+ for field in _PINNED_ROUTE_FIELDS+ if route.get(field) not in (None, "")+ }++_SUMMARY_PERMANENT_QUOTA_MARKERS: tuple[str, ...] = ("insufficient_quota","quota exceeded",@@ -5010,6 +5084,16 @@ This compaction should PRIORITISE preserving all information related to the focu_aux_context = self.context_lengthexcept Exception:pass+ # A pinned route (stall fallback, #78981) is an explicit override:+ # it replaces the task-config route for this one call so the retry+ # actually leaves the backend that just stalled, and it re-points+ # the aux telemetry at where the request really went.+ _pinned_route = _pinned_summary_call_kwargs()+ if _pinned_route:+ call_kwargs.update(_pinned_route)+ _aux_provider = str(_pinned_route.get("provider") or _aux_provider)+ _aux_model = str(_pinned_route.get("model") or _aux_model)+ _aux_context = None# Compression is atomic: protect the in-flight summary call from a# mid-turn gateway interrupt. Without this, an incoming user message# aborts the summary and compression falls back to a degraded staticdiff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 5a0d191069f..e7c032d7521 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -843,6 +843,170 @@ def resolve_context_compression_timeouts(return idle, ceiling+def resolve_compression_fallback_route() -> Optional[dict]:+ """Return the first usable ``auxiliary.compression.fallback_chain`` entry.++ The chain is the user's declared answer to "the configured compression+ route is unhealthy". The auxiliary client applies it from its exception+ handler, so a route that *stalls* — connection open, no tokens, aborted by+ the host's progress-aware timeout — never reaches it (#78981). This+ resolves the same config into explicit ``call_llm`` route arguments the+ stall path can pin onto one retry.++ Only the first structurally complete entry is returned: one extra bounded+ attempt is the budget for a stall, and if that entry cannot build a client+ (or errors) the auxiliary client's own exception path still walks the rest+ of the chain from there. Returns ``None`` when no entry is usable, which+ keeps the historical continue-without-compression behaviour.+ """+ try:+ from agent.auxiliary_client import (+ _fallback_entry_api_key,+ _get_auxiliary_task_config,+ )++ chain = _get_auxiliary_task_config("compression").get("fallback_chain")+ except Exception:+ logger.debug("compression fallback_chain lookup failed", exc_info=True)+ return None+ if not isinstance(chain, list):+ return None++ for index, entry in enumerate(chain):+ if not isinstance(entry, dict):+ continue+ provider = str(entry.get("provider") or "").strip()+ model = str(entry.get("model") or "").strip()+ # Both are required to name a route. _resolve_fallback_entry applies+ # the same rule when the aux client walks this chain itself.+ if not provider or not model:+ continue+ try:+ api_key = _fallback_entry_api_key(entry)+ except Exception:+ logger.debug(+ "compression fallback_chain[%d] api key resolution failed",+ index,+ exc_info=True,+ )+ api_key = None+ raw_timeout = entry.get("timeout")+ timeout = None+ if isinstance(raw_timeout, (int, float)) and not isinstance(+ raw_timeout, bool+ ) and raw_timeout > 0:+ timeout = float(raw_timeout)+ return {+ "label": f"fallback_chain[{index}]({provider})",+ "provider": provider,+ "model": model,+ "base_url": str(entry.get("base_url") or "").strip() or None,+ "api_key": api_key or None,+ "api_mode": str(+ entry.get("api_mode") or entry.get("transport") or ""+ ).strip() or None,+ "timeout": timeout,+ }+ return None+++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,+ on_commit_overrun: Optional[Callable[[float, float], None]] = None,+ telemetry_agent: Any = None,+ new_fence: Optional[Callable[[], CompressionCommitFence]] = None,+) -> Optional[Tuple[list, str]]:+ """Re-run an aborted compression once with the summary route pinned.++ Returns the fallback attempt's ``(messages, system_prompt)`` when it+ actually compressed, or ``None`` when there was nothing to fall back to,+ the attempt raised, or it produced no compression either — the caller then+ degrades exactly as it did before.++ The retry is bounded the same way the primary was: silence for one idle+ window ends it, while a fallback that is streaming keeps its ceiling. The+ entry's own ``timeout`` (when declared) sets that idle window, so a+ fallback tuned for a slower-but-healthy backend is not held to a deadline+ the stalled primary defined (#62452 semantics, applied to the stall path).+ """+ # An explicit stop is not a stalled route. The retry worker would abort on+ # the same event anyway, but starting one at all makes /stop look ignored.+ hard_cancel = getattr(telemetry_agent, "_hard_interrupt_requested", None)+ if callable(getattr(hard_cancel, "is_set", None)) and hard_cancel.is_set():+ return None++ route = resolve_compression_fallback_route()+ if route is None:+ return None++ # The aborted fence refuses every future commit, so the retry needs a+ # fresh one. Mint it through the host's factory when it has one: hosts+ # publish the active fence for hard-interrupt admission, and a /stop+ # during the retry must serialize against THIS attempt's commit boundary.+ retry_fence = None+ if new_fence is not None:+ try:+ retry_fence = new_fence()+ except Exception:+ logger.debug(+ "compression stall-fallback fence factory failed",+ exc_info=True,+ )+ if not isinstance(retry_fence, CompressionCommitFence):+ retry_fence = CompressionCommitFence()+ idle = float(route.get("timeout") or idle_timeout_seconds)+ ceiling = max(float(total_ceiling_seconds), idle)+ logger.warning(+ "Context compression stalled on the configured summary route — "+ "retrying once on %s (%s) before continuing without compression",+ route["label"],+ route["model"],+ )+ try:+ from agent.context_compressor import pin_summary_route++ with pin_summary_route(route):+ result_msgs, result_prompt = run_compress_context_with_progress_timeout(+ worker=worker,+ messages=messages,+ system_prompt_fallback=system_prompt_fallback,+ idle_timeout_seconds=idle,+ total_ceiling_seconds=ceiling,+ on_commit_overrun=on_commit_overrun,+ fence=retry_fence,+ telemetry_agent=telemetry_agent,+ stall_fallback=False,+ )+ except Exception:+ # The primary already failed; a failing fallback must degrade, never+ # turn "continue without compression" into a raised turn.+ logger.warning(+ "Context compression fallback attempt on %s failed",+ route["label"],+ exc_info=True,+ )+ return None+ if result_msgs is messages:+ # Aborted or no-op: the worker hands back the caller's own list.+ logger.warning(+ "Context compression fallback attempt on %s produced no "+ "compression; continuing without compression",+ route["label"],+ )+ return None+ logger.info(+ "Context compression recovered on %s after the primary summary route "+ "stalled",+ route["label"],+ )+ return result_msgs, result_prompt++def run_compress_context_with_progress_timeout(*,worker: Callable[[CompressionCommitFence], Tuple[list, str]],@@ -854,6 +1018,8 @@ def run_compress_context_with_progress_timeout(on_commit_overrun: Optional[Callable[[float, float], None]] = None,fence: Optional[CompressionCommitFence] = None,telemetry_agent: Any = None,+ stall_fallback: bool = True,+ new_fence: Optional[Callable[[], CompressionCommitFence]] = None,) -> Tuple[list, str]:"""Run ``worker(fence)`` under a sync progress-aware timeout.@@ -884,6 +1050,19 @@ def run_compress_context_with_progress_timeout(``system_prompt_fallback`` may be a string or a zero-arg callable resolvedonly on the timeout path, so successful compression never pays for (orfails on) an eager prompt rebuild.++ ``stall_fallback`` (default on) makes an aborted stall attempt the+ configured ``auxiliary.compression.fallback_chain`` once — pinned onto a+ fresh fence — before degrading to "continue without compression". Nothing+ raises out of a silent stall, so the auxiliary client's own fallback+ handling (exception-path only) never sees it (#78981). ``on_timeout``+ therefore fires only after that attempt has also failed, which keeps its+ cooldown bookkeeping from suppressing the retry it precedes.++ ``new_fence`` mints that retry's fence. Hosts that publish the active+ fence for hard-interrupt admission pass a factory that publishes the new+ one too, so a ``/stop`` during the retry serializes against the retry's+ commit boundary rather than the aborted attempt's."""if idle_timeout_seconds <= 0:raise ValueError(@@ -1086,6 +1265,23 @@ def run_compress_context_with_progress_timeout(fence.release_cancelled_compression_lock()waited = time.monotonic() - wait_startedsince_progress = fence.seconds_since_progress()+ # The durable lease is free again (above), so a fallback attempt can+ # acquire it immediately. Run it BEFORE on_timeout: that callback+ # records the summary-failure cooldown, which would make the retry's+ # own summary call a no-op.+ if stall_fallback:+ recovered = _retry_compression_on_fallback_chain(+ worker=worker,+ messages=messages,+ system_prompt_fallback=system_prompt_fallback,+ idle_timeout_seconds=idle,+ total_ceiling_seconds=ceiling,+ on_commit_overrun=on_commit_overrun,+ telemetry_agent=telemetry_agent,+ new_fence=new_fence,+ )+ if recovered is not None:+ return recoveredif on_timeout is not None:try:on_timeout(idle, waited, since_progress)diff --git a/run_agent.py b/run_agent.pyindex c6638b6cacd..9c38ced8eb0 100644--- a/run_agent.py+++ b/run_agent.py@@ -8196,6 +8196,17 @@ class AIAgent:"check SessionDB health (disk / lock contention).")+ def _publish_new_fence():+ # The stall-fallback retry (#78981) needs a fence the aborted+ # attempt cannot veto. Publish it on the same serialized slot+ # hard_interrupt() reads, so a /stop during the retry admits+ # against the attempt that is actually running. The finally+ # below restores whatever the caller had either way.+ retry_fence = CompressionCommitFence()+ with fence_registration_lock:+ self._active_compression_commit_fence = retry_fence+ return retry_fence+result = run_compress_context_with_progress_timeout(worker=_snapshot_worker,messages=messages,@@ -8206,6 +8217,7 @@ class AIAgent:on_commit_overrun=_on_commit_overrun,fence=active_fence,telemetry_agent=self,+ new_fence=_publish_new_fence,)# compress_context ran on a daemon pool worker thread; the session# id rotation updated hermes_logging._session_context (adiff --git a/tests/agent/test_compression_stall_fallback_78981.py b/tests/agent/test_compression_stall_fallback_78981.pynew file mode 100644index 00000000000..398cbd4b2af--- /dev/null+++ b/tests/agent/test_compression_stall_fallback_78981.py@@ -0,0 +1,360 @@+"""Compression falls back after an aborted (stalled) summary — #78981.++A summariser that keeps the connection open but never emits a real token+produces no fence progress, so the host's progress-aware timeout aborts the+worker and returns "continue without compression". Nothing raises out of the+auxiliary client on that path, so its configured ``fallback_chain`` — the+user's declared answer to "this route is unhealthy" — was never consulted for+the one failure mode that most needs it.++These tests pin the contract:++* an aborted stall re-attempts compression once with the summary route pinned+ to the configured ``auxiliary.compression.fallback_chain``;+* the pinned route reaches the summary ``call_llm`` (provider/model/base_url/+ api_key/timeout), and is single-use so the compressor's own main-model retry+ does not re-issue the same failed route;+* the historical "continue without compression" degrade survives when no chain+ is configured or the fallback attempt also stalls.+"""++from __future__ import annotations++import threading+from types import SimpleNamespace+from unittest.mock import patch++from agent.context_compressor import (+ ContextCompressor,+ pin_summary_route,+ take_pinned_summary_route,+)+from agent.conversation_compression import (+ CompressionCommitFence,+ resolve_compression_fallback_route,+ run_compress_context_with_progress_timeout,+)++CHAIN_ENTRY = {+ "provider": "custom",+ "model": "backup-summarizer",+ "base_url": "https://fallback.invalid/v1",+ "api_key": "sk-fallback",+ "timeout": 45,+}+++def _patch_chain(chain):+ """Pin auxiliary.compression config without touching the real config.yaml."""+ return patch(+ "agent.auxiliary_client._get_auxiliary_task_config",+ return_value={"fallback_chain": chain},+ )+++class _StalledSummaryWorker:+ """A compression worker whose first attempt streams nothing at all.++ Mirrors the reported shape: the provider holds the connection open, so the+ worker never calls ``fence.touch_progress()`` and the host's idle budget+ lapses. ``stall_attempts`` controls how many attempts hang; any later+ attempt commits a real summary.+ """++ def __init__(self, compressed, *, stall_attempts=1):+ self.compressed = compressed+ self.stall_attempts = stall_attempts+ self.routes = []+ self.fences = []+ self._lock = threading.Lock()+ self.release = threading.Event()++ @property+ def attempts(self):+ return len(self.routes)++ def __call__(self, fence: CompressionCommitFence):+ with self._lock:+ self.routes.append(take_pinned_summary_route())+ self.fences.append(fence)+ attempt = len(self.routes)+ if attempt <= self.stall_attempts:+ # Connection open, zero tokens, zero fence progress.+ self.release.wait(timeout=10)+ return ([{"role": "assistant", "content": "late"}], "late-prompt")+ if not fence.begin_commit():+ return ([{"role": "assistant", "content": "cancelled"}], "cancelled")+ try:+ return (self.compressed, "summarized-prompt")+ finally:+ fence.finish_commit()+++def _run(worker, *, chain, timeouts, messages, idle=0.05, ceiling=0.2):+ with _patch_chain(chain):+ return run_compress_context_with_progress_timeout(+ worker=worker,+ messages=messages,+ system_prompt_fallback="degraded-prompt",+ idle_timeout_seconds=idle,+ total_ceiling_seconds=ceiling,+ on_timeout=lambda *args: timeouts.append(args),+ )+++# ---------------------------------------------------------------------------+# Fence-level contract: an aborted stall consults the configured chain+# ---------------------------------------------------------------------------+++def test_stalled_summary_attempts_configured_fallback_chain():+ original = [{"role": "user", "content": "keep-me"}]+ compressed = [{"role": "user", "content": "summary of earlier turns"}]+ worker = _StalledSummaryWorker(compressed)+ timeouts = []++ try:+ msgs, prompt = _run(+ worker, chain=[CHAIN_ENTRY], timeouts=timeouts, messages=original+ )+ finally:+ worker.release.set()++ assert worker.attempts == 2, "the aborted stall must be retried once"+ assert worker.routes[0] is None, "the primary attempt is never pinned"+ pinned = worker.routes[1]+ assert pinned is not None, "the retry must carry the configured fallback route"+ assert pinned["provider"] == "custom"+ assert pinned["model"] == "backup-summarizer"+ assert msgs == compressed, "the fallback attempt's compression must be published"+ assert prompt == "summarized-prompt"+ assert not timeouts, "no continue-without-compression degrade after a recovery"+++def test_retry_runs_on_a_host_published_fence():+ """The aborted fence vetoes every future commit, so the retry needs a new+ one — minted through the host so ``/stop`` admits against the attempt that+ is actually running."""+ original = [{"role": "user", "content": "keep-me"}]+ compressed = [{"role": "user", "content": "summary"}]+ worker = _StalledSummaryWorker(compressed)+ minted = []++ def _new_fence():+ fence = CompressionCommitFence()+ minted.append(fence)+ return fence++ try:+ with _patch_chain([CHAIN_ENTRY]):+ msgs, _prompt = run_compress_context_with_progress_timeout(+ worker=worker,+ messages=original,+ system_prompt_fallback="degraded-prompt",+ idle_timeout_seconds=0.05,+ total_ceiling_seconds=0.2,+ new_fence=_new_fence,+ )+ finally:+ worker.release.set()++ assert msgs == compressed+ assert len(minted) == 1, "exactly one fence is minted for the one retry"+ assert worker.fences[1] is minted[0]+ assert worker.fences[1] is not worker.fences[0]+ assert worker.fences[0].is_cancelled, "the aborted attempt stays cancelled"+++def test_hard_interrupt_suppresses_the_fallback_attempt():+ """An explicit stop is not an unhealthy route — don't start another+ summary on the user's behalf after they asked for the turn to end."""+ original = [{"role": "user", "content": "keep-me"}]+ worker = _StalledSummaryWorker([{"role": "user", "content": "unused"}])+ stopped = threading.Event()+ stopped.set()+ agent = SimpleNamespace(_hard_interrupt_requested=stopped)+ timeouts = []++ try:+ with _patch_chain([CHAIN_ENTRY]):+ msgs, prompt = run_compress_context_with_progress_timeout(+ worker=worker,+ messages=original,+ system_prompt_fallback="degraded-prompt",+ idle_timeout_seconds=0.05,+ total_ceiling_seconds=0.2,+ on_timeout=lambda *args: timeouts.append(args),+ telemetry_agent=agent,+ )+ finally:+ worker.release.set()++ assert worker.attempts == 1+ assert msgs is original+ assert prompt == "degraded-prompt"+ assert len(timeouts) == 1+++def test_no_fallback_chain_configured_degrades_without_retry():+ original = [{"role": "user", "content": "keep-me"}]+ worker = _StalledSummaryWorker([{"role": "user", "content": "unused"}])+ timeouts = []++ try:+ msgs, prompt = _run(worker, chain=[], timeouts=timeouts, messages=original)+ finally:+ worker.release.set()++ assert worker.attempts == 1, "nothing to fall back to — do not burn a retry"+ assert msgs is original+ assert prompt == "degraded-prompt"+ assert len(timeouts) == 1+++def test_fallback_that_also_stalls_degrades_after_one_attempt():+ original = [{"role": "user", "content": "keep-me"}]+ worker = _StalledSummaryWorker(+ [{"role": "user", "content": "unused"}], stall_attempts=2+ )+ timeouts = []+ entry = dict(CHAIN_ENTRY, timeout=0.05)++ try:+ msgs, prompt = _run(worker, chain=[entry], timeouts=timeouts, messages=original)+ finally:+ worker.release.set()++ assert worker.attempts == 2, "the fallback is attempted once, not in a loop"+ assert msgs is original, "no messages may be dropped when both routes stall"+ assert prompt == "degraded-prompt"+ assert len(timeouts) == 1, "the degrade must be reported exactly once"+++# ---------------------------------------------------------------------------+# Route resolution: a chain entry becomes an explicit summary route+# ---------------------------------------------------------------------------+++def test_resolved_route_carries_entry_credentials_and_timeout():+ with _patch_chain([CHAIN_ENTRY]):+ route = resolve_compression_fallback_route()++ assert route is not None+ assert route["provider"] == "custom"+ assert route["model"] == "backup-summarizer"+ assert route["base_url"] == "https://fallback.invalid/v1"+ assert route["api_key"] == "sk-fallback"+ # Per-entry timeouts already govern aux-client fallback candidates+ # (#62452); the stall retry honours the same declaration.+ assert route["timeout"] == 45.0+++def test_incomplete_chain_entries_are_skipped():+ chain = [+ "not-a-mapping",+ {"model": "orphan-model"}, # no provider+ {"provider": "custom"}, # no model+ CHAIN_ENTRY,+ ]+ with _patch_chain(chain):+ route = resolve_compression_fallback_route()++ assert route is not None+ assert route["model"] == "backup-summarizer"+++def test_no_chain_resolves_to_no_route():+ with _patch_chain([]):+ assert resolve_compression_fallback_route() is None+++# ---------------------------------------------------------------------------+# Injection point: the pinned route reaches the summary call+# ---------------------------------------------------------------------------+++def _make_compressor(summary_model="aux-summarizer"):+ with patch(+ "agent.context_compressor.get_model_context_length", return_value=100000+ ):+ return ContextCompressor(+ model="main-model",+ quiet_mode=True,+ summary_model_override=summary_model,+ )+++def _msgs():+ return [+ {"role": "user", "content": "u1 " + "x" * 200},+ {"role": "assistant", "content": "a1 " + "y" * 200},+ {"role": "user", "content": "u2 " + "z" * 200},+ ]+++def _ok_response(content="SUMMARY BODY"):+ return SimpleNamespace(+ choices=[SimpleNamespace(message=SimpleNamespace(content=content))]+ )+++def test_pinned_route_overrides_the_summary_call_route():+ compressor = _make_compressor()+ calls = []++ def _fake_call_llm(**kwargs):+ calls.append(kwargs)+ return _ok_response()++ with patch("agent.context_compressor.call_llm", side_effect=_fake_call_llm):+ with pin_summary_route(dict(CHAIN_ENTRY)):+ summary = compressor._generate_summary(_msgs())++ assert summary and "SUMMARY BODY" in summary+ assert len(calls) == 1+ call = calls[0]+ assert call["task"] == "compression"+ assert call["provider"] == "custom"+ assert call["model"] == "backup-summarizer"+ assert call["base_url"] == "https://fallback.invalid/v1"+ assert call["api_key"] == "sk-fallback"+ assert call["timeout"] == 45+++def test_pinned_route_is_not_reissued_by_the_main_model_retry():+ """The compressor's own main-model retry must not re-run the failed route."""+ compressor = _make_compressor()+ calls = []++ def _fake_call_llm(**kwargs):+ calls.append(kwargs)+ if len(calls) == 1:+ raise TimeoutError("Request timed out.")+ return _ok_response()++ with patch("agent.context_compressor.call_llm", side_effect=_fake_call_llm):+ with pin_summary_route(dict(CHAIN_ENTRY)):+ summary = compressor._generate_summary(_msgs())++ assert summary and "SUMMARY BODY" in summary+ assert len(calls) == 2+ assert calls[0]["provider"] == "custom"+ assert "provider" not in calls[1], (+ "the retry must route normally, not repeat the stalled fallback route"+ )+++def test_unpinned_summary_call_keeps_task_routing():+ compressor = _make_compressor()+ calls = []++ def _fake_call_llm(**kwargs):+ calls.append(kwargs)+ return _ok_response()++ with patch("agent.context_compressor.call_llm", side_effect=_fake_call_llm):+ summary = compressor._generate_summary(_msgs())++ assert summary+ assert calls and "provider" not in calls[0]+ assert calls[0]["model"] == "aux-summarizer"diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 86f66931341..c9dee244d32 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -898,7 +898,7 @@ Older configs with `compression.summary_model`, `compression.summary_provider`,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 skips compaction, keeps the existing messages, and warns 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. 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_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.