The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): fail a silent chat-completions summary stream at the no-progress window
Teknium1259068415b1
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex a140ee5f3c8..1d1a48273b4 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -6354,7 +6354,7 @@ def _compression_fast_lane_controls(def _get_task_no_progress_timeout(task: str) -> Optional[float]:"""``auxiliary.<task>.no_progress_timeout`` from config, or None when unset/invalid- (the Codex stream guard then keeps its built-in ``_AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS``+ (the Codex and chat-stream watchdogs then keep the built-in ``_AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS``default). Lets an operator widen the substantive-progress window independently of theoverall request timeout — see #108104."""if not task:@@ -7211,7 +7211,20 @@ def _create_with_progress_once(if hasattr(chunks, "choices"):_notify_aux_provider_response()return chunks- return _aggregate_chat_stream(chunks, model=model, total_ceiling=total_ceiling)+ return _aggregate_chat_stream(+ chunks, model=model, total_ceiling=total_ceiling, no_progress=_chat_stream_no_progress(client, kwargs, task))+++def _chat_stream_no_progress(client: Any, kwargs: Dict[str, Any], task: Optional[str]) -> "Tuple[float, bool]":+ """(window, enforce before the first token) for a streamed chat-completions attempt: the Codex+ guard's window (``auxiliary.<task>.no_progress_timeout``, 60s default, capped at the request+ timeout). Local servers keep their silent prefill on the request timeout, as the main loop does."""+ window = _get_task_no_progress_timeout(task or "") or _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS+ timeout = kwargs.get("timeout")+ if isinstance(timeout, (int, float)) and timeout > 0:+ window = min(window, float(timeout))+ from agent.model_metadata import is_local_endpoint+ return window, not is_local_endpoint(str(getattr(client, "base_url", "") or ""))def _close_chunk_stream(chunks: Any, *, allow_aclose: bool = False) -> Any:@@ -7228,17 +7241,30 @@ def _close_chunk_stream(chunks: Any, *, allow_aclose: bool = False) -> Any:def _aggregate_chat_stream(- chunks: Any, *, model: str = "", total_ceiling: Optional[float] = None+ chunks: Any, *, model: str = "", total_ceiling: Optional[float] = None,+ no_progress: "Optional[Tuple[float, bool]]" = None,) -> Any:"""Consume a chunk stream into a complete response; TimeoutError (phrased "timed out" so- ``_is_timeout_error`` matches) when *total_ceiling* elapses."""+ ``_is_timeout_error`` matches) when *total_ceiling* elapses, or when the stream is silent for+ the *no_progress* ``(window, first_token)`` window (#100501)."""+ from agent.auxiliary_stream_watchdog import ChatStreamWatchdogacc = _ChatStreamAccumulator(model=model, total_ceiling=total_ceiling, host_deadline=_current_aux_stream_deadline())+ watchdog = ChatStreamWatchdog(chunks, no_progress[0], first_token=no_progress[1]) if no_progress else Nonetry:for chunk in chunks:- acc.feed(chunk)+ if acc.feed(chunk) and watchdog is not None:+ watchdog.progress()+ except Exception as exc:+ if watchdog is not None and watchdog.fired:+ raise watchdog.timeout_error() from exc+ raisefinally:+ if watchdog is not None:+ watchdog.finish()_close_chunk_stream(chunks)+ if watchdog is not None and watchdog.fired:+ raise watchdog.timeout_error()return acc.finish()@@ -7316,9 +7342,9 @@ class _ChatStreamAccumulator:made_progress = Truereturn made_progress- def feed(self, chunk: Any) -> None:+ def feed(self, chunk: Any) -> bool:# Every frame records transport timing (TTFP); only a substantive payload ticks the- # forward-progress hook that keeps compression alive.+ # forward-progress hook that keeps compression alive (and is reported as True)._notify_aux_timing_response()self._check_deadlines()self.resp_id = getattr(chunk, "id", None) or self.resp_id@@ -7328,12 +7354,12 @@ class _ChatStreamAccumulator:self.usage = chunk_usagechoices = getattr(chunk, "choices", None) or []if not choices:- return+ return Falsechoice = choices[0]self.finish_reason = getattr(choice, "finish_reason", None) or self.finish_reasondelta = getattr(choice, "delta", None)if delta is None:- return+ return Falsemade_progress = Falsefrom agent.message_content import flatten_message_text@@ -7353,6 +7379,7 @@ class _ChatStreamAccumulator:made_progress |= self._feed_tool_calls(delta)if made_progress:_notify_aux_progress()+ return made_progressdef finish(self) -> Any:tool_calls = None@@ -7908,10 +7935,12 @@ def _ladder_provider_fallback(first_err: Exception, route: _LadderRoute):if reason == "request timed out":# WARNING, naming the endpoint, the budget and the knob: the only other trace of a slow# local model is the fallback provider's complaint about a model it never had (#89445).- logger.warning("Auxiliary %s%s: request to %s timed out after %ss (raise auxiliary.%s.timeout "- "for slow or reasoning models) on %s, trying fallback",- task or "call", tag, route.base_info or resolved_provider, route.timeout,- task or "call", resolved_provider)+ # A no-progress stall names its own window; the request budget is the wrong knob for it.+ stalled = "Auxiliary chat stream" in str(first_err)+ logger.warning("Auxiliary %s%s: request to %s %s (raise auxiliary.%s.%s for slow or reasoning "+ "models) on %s, trying fallback", task or "call", tag, route.base_info or resolved_provider,+ first_err if stalled else f"timed out after {route.timeout}s", task or "call",+ "no_progress_timeout" if stalled else "timeout", resolved_provider)else:logger.info("Auxiliary %s%s: %s on %s (%s), trying fallback",task or "call", tag, reason, resolved_provider, first_err)diff --git a/agent/auxiliary_stream_watchdog.py b/agent/auxiliary_stream_watchdog.pynew file mode 100644index 00000000000..7bbfdd4c6a1--- /dev/null+++ b/agent/auxiliary_stream_watchdog.py@@ -0,0 +1,89 @@+"""No-progress watchdog for streamed chat-completions auxiliary calls (#100501).++The consumer blocks inside the SDK's chunk iterator, so a silent stream is only noticed when the+httpx read timeout (the full auxiliary request budget, >= 300s for compression) expires; the host+compression wait gives up first and the attempt dies with no fallback. The window is enforced from a+Timer that only ``shutdown()``s this attempt's socket: that is FD-safe from a stranger thread+(#70773), wakes the owner's blocked read, and the owner still closes the stream in its ``finally``+so the pool drops the dead connection instead of recycling it.+"""++from __future__ import annotations++import threading+import time+from typing import Any, Optional+++def _stream_socket(stream: Any) -> Any:+ """The raw socket under an SDK chunk stream (``stream.response`` is the ``httpx.Response``)."""+ from agent.agent_runtime_helpers import _socket_from_response+ response = getattr(stream, "response", None)+ return _socket_from_response(response) if response is not None else None+++class ChatStreamWatchdog:+ """Re-armed by substantive chunks only; ``first_token=False`` leaves time-to-first-token to the+ request timeout (a local server's prefill of a large prompt is silent but alive)."""++ def __init__(self, stream: Any, window: float, *, first_token: bool = True):+ self._stream = stream+ self.window = window+ self._started = time.monotonic()+ self._lock = threading.Lock()+ self._deadline: Optional[float] = None+ self._timer: Optional[threading.Timer] = None+ self._done = False+ self.saw_progress = False+ self.fired = False+ if first_token:+ self._rearm()++ def _rearm(self) -> None:+ self._deadline = time.monotonic() + self.window+ if self._timer is None:+ self._schedule(self.window)++ def _schedule(self, delay: float) -> None:+ self._timer = threading.Timer(max(delay, 0.0), self._fire)+ self._timer.daemon = True+ self._timer.start()++ def progress(self) -> None:+ with self._lock:+ self.saw_progress = True+ if not self._done:+ self._rearm()++ def _fire(self) -> None:+ with self._lock:+ if self._done or self._deadline is None:+ return+ remaining = self._deadline - time.monotonic()+ if remaining > 0:+ self._schedule(remaining)+ return+ self.fired = True+ sock = _stream_socket(self._stream)+ if sock is not None:+ from agent.agent_runtime_helpers import _shutdown_socket+ _shutdown_socket(sock)++ def finish(self) -> None:+ with self._lock:+ self._done = True+ timer = self._timer+ if timer is not None:+ timer.cancel()++ def timeout_error(self) -> TimeoutError:+ """Zero-output stalls say "no-progress timeout" (same-provider retry stays allowed, see+ ``_should_skip_same_provider_retry``); a mid-stream stall goes straight to fallback."""+ elapsed = time.monotonic() - self._started+ if not self.saw_progress:+ return TimeoutError(+ f"Auxiliary chat stream produced no output within {self.window:.1f}s "+ f"(no-progress timeout, {elapsed:.1f}s elapsed)")+ return TimeoutError(+ f"Auxiliary chat stream stalled: no new output for {self.window:.1f}s "+ f"({elapsed:.1f}s elapsed, timed out)")diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex c15e3888089..a25bcc9ee12 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -758,9 +758,9 @@ DEFAULT_CONFIG = {# OpenAI-compatible request fields. Vision: download_timeout = image HTTP download (s)."vision": _aux(120, download_timeout=30),# web_extract and session_search no longer use an aux LLM; leftover blocks in user config- # are ignored. Compression: raise timeout for local models. no_progress_timeout- # (Codex/Responses streams only): seconds without a substantive event before the stream- # fails fast; None = built-in 60s default. Independent of "timeout" (the overall request+ # are ignored. Compression: raise timeout for local models. no_progress_timeout:+ # seconds a streamed call goes without a substantive chunk before it fails fast into+ # retry/fallback; None = built-in 60s default. Independent of "timeout" (the overall request# budget) — raising "timeout" alone does not widen this window. See #108104."compression": _aux(120, no_progress_timeout=None),"skills_hub": _aux(30),diff --git a/tests/agent/test_aux_progress_streaming.py b/tests/agent/test_aux_progress_streaming.pyindex 394865d348d..a7dcbc9131c 100644--- a/tests/agent/test_aux_progress_streaming.py+++ b/tests/agent/test_aux_progress_streaming.py@@ -8,6 +8,7 @@ liveness. Without a hook, behavior is byte-for-byte the old non-streaming call."""import threading+import timefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -265,6 +266,53 @@ class TestAggregateChatStream:assert result.choices[0].message.content == "ok"assert closed == [True]+ def test_silent_stream_fails_fast_through_the_real_transport(self, monkeypatch):+ """#100501: an endpoint that sends one chunk then goes silent must fail at the no-progress+ window as a timeout (so retry/fallback run), not block until the request read timeout."""+ import http.server+ import json++ import openai++ from agent.auxiliary_client import _should_skip_same_provider_retry++ release = threading.Event()++ class _Silent(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.0"++ def log_message(self, *args):+ pass++ def do_POST(self):+ self.rfile.read(int(self.headers.get("Content-Length") or 0))+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.end_headers()+ chunk = {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": "m",+ "choices": [{"index": 0, "delta": {"content": "partial"}, "finish_reason": None}]}+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())+ self.wfile.flush()+ release.wait(30)++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Silent)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ monkeypatch.setattr("agent.auxiliary_client._AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS", 0.5)+ # Loopback stands in for a remote endpoint: the first-token window applies to non-local ones.+ monkeypatch.setattr("agent.model_metadata.is_local_endpoint", lambda _url: False)+ client = openai.OpenAI(api_key="k", base_url=f"http://127.0.0.1:{server.server_port}/v1", max_retries=0)+ started = time.monotonic()+ try:+ with aux_progress_hook(lambda: None), pytest.raises(TimeoutError) as excinfo:+ _create_with_progress(client, {"model": "m", "messages": [], "timeout": 20.0}, "compression")+ finally:+ release.set()+ server.shutdown()+ client.close()+ assert time.monotonic() - started < 5.0+ assert "stalled" in str(excinfo.value)+ assert _should_skip_same_provider_retry("compression", excinfo.value)+# ---------------------------------------------------------------------------diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex c0a238e5731..5cff78bf4e0 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1099,12 +1099,12 @@ Points at a custom OpenAI-compatible endpoint. Uses `OPENAI_API_KEY` for auth.| `nous` / `openrouter` / etc. | not set | Force that provider, use its auth || any | set | Use the custom endpoint directly (provider ignored) |-### Stream progress timeout (Responses routes)+### Stream progress timeout-When the summary runs over a Responses stream (the `openai-codex` provider, or any route the auxiliary client drives through the Responses API), two timeouts apply, and they are independent:+When the summary streams (compression always streams over chat-completions and Responses routes, e.g. `openai-codex` or a custom OpenAI-compatible endpoint), two timeouts apply, and they are independent:- `auxiliary.compression.timeout` — the overall request budget (default 120s).-- `auxiliary.compression.no_progress_timeout` — how long the stream may go without a **substantive** event (a text/reasoning delta or a completed output item) before the attempt aborts with `Codex auxiliary Responses stream stalled: no new output for Ns`. Default **60s** when unset. Keepalive and lifecycle frames (`response.in_progress`, pings) do not count as progress; every substantive event re-arms the window, so a slow but progressing summary is never cut off by it.+- `auxiliary.compression.no_progress_timeout` — how long the stream may go without a **substantive** event (a text/reasoning delta or a completed output item) before the attempt aborts (`... stream stalled: no new output for Ns`) and the normal retry / fallback chain takes over. Default **60s** when unset. On a local endpoint (localhost, LAN, Tailscale) the window starts at the first token, so a silent prefill of a large prompt is bounded only by `timeout`. Keepalive and lifecycle frames (`response.in_progress`, pings) do not count as progress; every substantive event re-arms the window, so a slow but progressing summary is never cut off by it.Raising `timeout` alone does **not** widen the progress window — a request configured for 600s still aborts after a 60s gap. Set `no_progress_timeout` to change that gap; the effective window is capped at `timeout`, and the host's hard deadline / cancellation still win. The host's own inactivity budget is the outer cap here: in-agent compaction gives up on a silent summariser after `compression.context_timeout_seconds` (default 120s, floored at the effective `auxiliary.compression.timeout`, itself at least 300s) and gateway hygiene after `compression.hygiene_timeout_seconds` (default 30s), so a `no_progress_timeout` larger than the applicable host budget is silently cut short by it. The key is per task (`auxiliary.<task>.no_progress_timeout`), so widening it for compression does not change other auxiliary tasks. A value that is not a positive number is ignored with a warning in the log and the 60s default applies.@@ -1565,8 +1565,8 @@ auxiliary:# Context compression timeout (separate from compression.* config)compression:timeout: 120 # seconds — compression summarizes long conversations, needs more time- # no_progress_timeout: 60 # Responses-stream routes (openai-codex) only: seconds a summary stream- # # may go without a substantive event before the attempt fails fast+ # no_progress_timeout: 60 # seconds a streamed summary may go without a substantive chunk+ # # before the attempt fails fast into retry/fallback# fallback_chain: # Optional — providers to try on rate-limit / connectivity failure# - provider: nous# model: deepseek/deepseek-chat