Skip to content

The agent that grows with you

fix(aux): the chat-stream watchdog cuts only its own unfinished stream

Teknium636b9c608c30
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 1d1a48273b4..9e0cabefe1d 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -2631,7 +2631,9 @@ def _relay_sync_completion(
kwargs = prepare_chat_messages(client, kwargs)
# The progress hook is installed per TASK, so every attempt (retries, recovery rungs, fallbacks)
# must stream through _create_with_progress or the compression watchdog sees silence (#98466).
- callback = create or (lambda request: _create_with_progress(client, request))
+ # Recovery rungs / credential retries keep the task's ``no_progress_timeout`` window.
+ task = (_RELAY_AUX_CALL_CONTEXT.get() or {}).get("task")
+ callback = create or (lambda request: _create_with_progress(client, request, task))
route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode)
# Isolate only the provider callback so the owning thread can unwind its lease/DB
# transaction on hard cancel without touching the shared client.
@@ -7211,60 +7213,24 @@ def _create_with_progress_once(
if hasattr(chunks, "choices"):
_notify_aux_provider_response()
return chunks
+ from agent.auxiliary_stream_watchdog import chat_stream_windows
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:
- """Best-effort ``close()`` (or ``aclose()``); returns a pending awaitable or None."""
- close_fn = getattr(chunks, "close", None) or (
- getattr(chunks, "aclose", None) if allow_aclose else None)
- if not callable(close_fn):
- return None
- try:
- result = close_fn()
- except Exception:
- return None
- return result if inspect.isawaitable(result) else None
+ chunks, model=model, total_ceiling=total_ceiling, no_progress=chat_stream_windows(client, kwargs, task))
def _aggregate_chat_stream(
chunks: Any, *, model: str = "", total_ceiling: Optional[float] = None,
- no_progress: "Optional[Tuple[float, bool]]" = None,
+ no_progress: "Optional[Tuple[float, Optional[float]]]" = None,
) -> Any:
"""Consume a chunk stream into a complete response; TimeoutError (phrased "timed out" so
- ``_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 ChatStreamWatchdog
+ ``_is_timeout_error`` matches) past *total_ceiling* or the *no_progress* windows (#100501)."""
+ from agent.auxiliary_stream_watchdog import _close_chunk_stream, consume_chat_stream
acc = _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 None
try:
- for chunk in chunks:
- 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
- raise
+ consume_chat_stream(chunks, acc, no_progress)
finally:
- 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()
@@ -7408,6 +7374,7 @@ async def _aggregate_chat_stream_async(
async for chunk in chunks:
acc.feed(chunk)
finally:
+ from agent.auxiliary_stream_watchdog import _close_chunk_stream
pending = _close_chunk_stream(chunks, allow_aclose=True)
if pending is not None:
with contextlib.suppress(Exception):
@@ -7935,7 +7902,6 @@ 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).
- # 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,
diff --git a/agent/auxiliary_stream_watchdog.py b/agent/auxiliary_stream_watchdog.py
index 7bbfdd4c6a1..5f5f3a5d815 100644
--- a/agent/auxiliary_stream_watchdog.py
+++ b/agent/auxiliary_stream_watchdog.py
@@ -10,6 +10,7 @@ so the pool drops the dead connection instead of recycling it.
from __future__ import annotations
+import inspect
import threading
import time
from typing import Any, Optional
@@ -22,30 +23,70 @@ def _stream_socket(stream: Any) -> Any:
return _socket_from_response(response) if response is not None else None
+def _close_chunk_stream(chunks: Any, *, allow_aclose: bool = False) -> Any:
+ """Best-effort ``close()`` (or ``aclose()``); returns a pending awaitable or None."""
+ close_fn = getattr(chunks, "close", None) or (
+ getattr(chunks, "aclose", None) if allow_aclose else None)
+ if not callable(close_fn):
+ return None
+ try:
+ result = close_fn()
+ except Exception:
+ return None
+ return result if inspect.isawaitable(result) 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)."""
+ """Re-armed by substantive chunks only. Silence before the first token is bounded by
+ *first_token_window* (the main loop's stale patience: reasoning models think silently for
+ minutes); ``None`` leaves it to the request timeout (a local server's silent prefill)."""
- def __init__(self, stream: Any, window: float, *, first_token: bool = True):
- self._stream = stream
+ def __init__(self, stream: Any, window: float, *, first_token_window: Optional[float] = None):
self.window = window
+ self.first_token_window = first_token_window
self._started = time.monotonic()
self._lock = threading.Lock()
self._deadline: Optional[float] = None
self._timer: Optional[threading.Timer] = None
+ self._generation = 0
self._done = False
self.saw_progress = False
self.fired = False
- if first_token:
- self._rearm()
+ # Pin THIS attempt's socket now and retire the watchdog before the response hands its
+ # connection back to the pool: a timer callback that already woke must never shut down a
+ # pooled connection a later request has acquired (keepalive reuse).
+ self._sock = _stream_socket(stream)
+ self._fence_release(getattr(getattr(stream, "response", None), "stream", None))
+ if first_token_window is not None:
+ self._rearm(first_token_window)
+
+ def _fence_release(self, body: Any) -> None:
+ release = getattr(body, "close", None)
+ if self._sock is None or not callable(release):
+ return
+
+ def fenced_release() -> None:
+ with self._lock:
+ self._done = True
+ release()
+
+ try:
+ body.close = fenced_release
+ except (AttributeError, TypeError):
+ self._sock = None # cannot fence the release: never shut down a socket we may not own
- def _rearm(self) -> None:
- self._deadline = time.monotonic() + self.window
- if self._timer is None:
- self._schedule(self.window)
+ def _rearm(self, window: float) -> None:
+ # A pending timer re-checks the deadline when it fires; replace it only when the new
+ # deadline is earlier (the first token swaps the long first-token window for the short one).
+ previous, self._deadline = self._deadline, time.monotonic() + window
+ if self._timer is None or (previous is not None and self._deadline < previous):
+ if self._timer is not None:
+ self._timer.cancel()
+ self._schedule(window)
def _schedule(self, delay: float) -> None:
- self._timer = threading.Timer(max(delay, 0.0), self._fire)
+ self._generation += 1
+ self._timer = threading.Timer(max(delay, 0.0), self._fire, args=(self._generation,))
self._timer.daemon = True
self._timer.start()
@@ -53,21 +94,22 @@ class ChatStreamWatchdog:
with self._lock:
self.saw_progress = True
if not self._done:
- self._rearm()
+ self._rearm(self.window)
- def _fire(self) -> None:
+ def _fire(self, generation: int) -> None:
+ # Decision and shutdown happen under the lock the fenced release takes, so a retired
+ # attempt (or a timer superseded by ``_rearm`` after it already woke) never acts.
with self._lock:
- if self._done or self._deadline is None:
+ if self._done or self._deadline is None or generation != self._generation:
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)
+ if self._sock is not None:
+ from agent.agent_runtime_helpers import _shutdown_socket
+ _shutdown_socket(self._sock)
def finish(self) -> None:
with self._lock:
@@ -82,8 +124,52 @@ class ChatStreamWatchdog:
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"Auxiliary chat stream produced no output within {self.first_token_window or 0:.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)")
+
+
+def chat_stream_windows(client: Any, kwargs: dict, task: Optional[str]) -> "tuple[float, Optional[float]]":
+ """(inter-chunk window, first-token window) for a streamed chat-completions attempt. Between
+ chunks: the Codex guard's window (``auxiliary.<task>.no_progress_timeout``, 60s default). Before
+ the first token: the main loop's cloud stale patience (context-scaled, reasoning-model floor), so
+ a model thinking silently on a large prompt is not cut; local servers keep their silent prefill
+ on the request timeout (None). Both are capped at the request timeout."""
+ from agent.auxiliary_client import _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS, _get_task_no_progress_timeout
+ from agent.chat_completion_helpers import _cloud_stale_timeout, _stream_env_stale_base
+ from agent.model_metadata import is_local_endpoint
+ window = _get_task_no_progress_timeout(task or "") or _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS
+ first = None
+ if not is_local_endpoint(str(getattr(client, "base_url", "") or "")):
+ first = max(window, _cloud_stale_timeout(_stream_env_stale_base()[0], kwargs))
+ timeout = kwargs.get("timeout")
+ if isinstance(timeout, (int, float)) and timeout > 0:
+ window = min(window, float(timeout))
+ first = min(first, float(timeout)) if first is not None else None
+ return window, first
+
+
+def consume_chat_stream(chunks: Any, acc: Any, no_progress: "Optional[tuple[float, Optional[float]]]") -> None:
+ """Feed *chunks* into the accumulator *acc*. Under a ``(window, first_token_window)`` watchdog a
+ silent stream raises TimeoutError, except after the terminal chunk: with finish_reason (and any
+ usage) in hand a stall is teardown, so the completed response and its billed usage are kept."""
+ if not no_progress:
+ for chunk in chunks:
+ acc.feed(chunk)
+ return
+ watchdog = ChatStreamWatchdog(chunks, no_progress[0], first_token_window=no_progress[1])
+ try:
+ for chunk in chunks:
+ if acc.feed(chunk):
+ watchdog.progress()
+ except Exception as exc:
+ if not watchdog.fired:
+ raise
+ if not acc.finish_reason:
+ raise watchdog.timeout_error() from exc
+ finally:
+ watchdog.finish()
+ if watchdog.fired and not acc.finish_reason:
+ raise watchdog.timeout_error()
diff --git a/tests/agent/test_aux_progress_streaming.py b/tests/agent/test_aux_progress_streaming.py
index a7dcbc9131c..0e796e97879 100644
--- a/tests/agent/test_aux_progress_streaming.py
+++ b/tests/agent/test_aux_progress_streaming.py
@@ -266,53 +266,160 @@ 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."""
+ @staticmethod
+ def _sse_server(gates: dict):
+ """Loopback HTTP/1.1 keepalive SSE endpoint; the request's ``model`` picks the script."""
import http.server
import json
- import openai
-
- from agent.auxiliary_client import _should_skip_same_provider_retry
+ def frame(handler, payload):
+ raw = (payload if isinstance(payload, str) else f"data: {json.dumps(payload)}\n\n").encode()
+ handler.wfile.write(b"%x\r\n%s\r\n" % (len(raw), raw))
+ handler.wfile.flush()
- release = threading.Event()
+ def chunk(content=None, finish=None, usage=None):
+ return {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": "m",
+ "choices": [{"index": 0, "delta": {"content": content} if content else {},
+ "finish_reason": finish}], **({"usage": usage} if usage else {})}
- class _Silent(http.server.BaseHTTPRequestHandler):
- protocol_version = "HTTP/1.0"
+ class _Handler(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def do_POST(self):
- self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ script = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))["model"]
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Transfer-Encoding", "chunked")
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)
+ try:
+ if script == "openai/o3": # silent reasoning before the first token
+ time.sleep(2.0)
+ if script == "b":
+ gates["b_started"].set()
+ frame(self, chunk(content="partial"))
+ if script == "usage": # terminal chunk with billed usage, then a stalled teardown
+ frame(self, chunk(finish="stop", usage={
+ "prompt_tokens": 100, "completion_tokens": 9, "total_tokens": 109}))
+ gates.get(script, gates["release"]).wait(30)
+ if script != "a": # "a" ends its body at EOF (no [DONE]), freeing the keepalive socket
+ frame(self, "data: [DONE]\n\n")
+ self.wfile.write(b"0\r\n\r\n")
+ self.wfile.flush()
+ except OSError:
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
- monkeypatch.setattr("agent.auxiliary_client._AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS", 0.5)
+ return server
+
+ @pytest.fixture
+ def sse(self, monkeypatch):
+ """(gates, call(model, task)) against the real OpenAI SDK + loopback transport. The default
+ window is 3s and ``auxiliary.compression.no_progress_timeout`` is 0.4s."""
+ import openai
+
+ gates = {name: threading.Event() for name in ("release", "a", "b", "b_started", "usage")}
+ server = self._sse_server(gates)
+ monkeypatch.setattr("agent.auxiliary_client._AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS", 3.0)
+ monkeypatch.setattr("agent.auxiliary_client._get_task_no_progress_timeout",
+ lambda task: 0.4 if task == "compression" else None)
# 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()
+
+ def call(model, task, *, via_relay_seam=False):
+ from agent.auxiliary_client import _relay_aux_call_scope, _relay_sync_completion
+
+ request = {"model": model, "messages": [], "timeout": 20.0}
+ with aux_progress_hook(lambda: None):
+ if via_relay_seam: # a recovery rung / credential retry: the default relay callback
+ with _relay_aux_call_scope((task,), {}):
+ return _relay_sync_completion(client, request)
+ return _create_with_progress(client, request, task)
+
try:
- with aux_progress_hook(lambda: None), pytest.raises(TimeoutError) as excinfo:
- _create_with_progress(client, {"model": "m", "messages": [], "timeout": 20.0}, "compression")
+ yield gates, call
finally:
- release.set()
+ for gate in gates.values():
+ gate.set()
server.shutdown()
client.close()
+
+ @pytest.mark.parametrize("via_relay_seam", [False, True], ids=["primary", "recovery_rung"])
+ def test_silent_stream_fails_fast_through_the_real_transport(self, sse, via_relay_seam):
+ """#100501: an endpoint that sends one chunk then goes silent fails at the task's no-progress
+ window as a timeout (so retry/fallback run), not at the request read timeout. Recovery rungs
+ go through the default relay callback and must keep the task's window."""
+ from agent.auxiliary_client import _should_skip_same_provider_retry
+
+ _gates, call = sse
+ started = time.monotonic()
+ with pytest.raises(TimeoutError) as excinfo:
+ call("m", "compression", via_relay_seam=via_relay_seam)
assert time.monotonic() - started < 5.0
- assert "stalled" in str(excinfo.value)
+ assert "stalled: no new output for 0.4s" in str(excinfo.value)
assert _should_skip_same_provider_retry("compression", excinfo.value)
+ @pytest.mark.parametrize("case", ["reasoning_before_first_token", "stall_after_terminal_usage",
+ "late_timer_after_pool_reuse"])
+ def test_watchdog_only_cuts_its_own_unfinished_stream(self, sse, case):
+ """The no-progress watchdog must not cut (a) a reasoning model thinking silently before its
+ first token for 5x the inter-chunk window (main-loop reasoning floor applies), (b) a response
+ whose terminal chunk and billed usage already arrived, nor (c) a later request that reused
+ the keepalive connection after a stalled attempt's timer had already woken."""
+ gates, call = sse
+ if case == "reasoning_before_first_token":
+ gates["release"].set() # the stream ends right after its first chunk
+ assert call("openai/o3", "compression").choices[0].message.content == "partial"
+ return
+ if case == "stall_after_terminal_usage":
+ result = call("usage", "compression")
+ assert result.choices[0].message.content == "partial"
+ assert (result.usage.prompt_tokens, result.usage.completion_tokens) == (100, 9)
+ return
+ # Hold the stalled attempt's timer at the moment it shuts a socket down; meanwhile let
+ # attempt A end at EOF (its connection may return to the pool) and start B on the client.
+ paused, resume, outcome = threading.Event(), threading.Event(), {}
+
+ def tracer(frame, event, _arg):
+ if (event == "call" and frame.f_code.co_name == "_shutdown_socket"
+ and not paused.is_set()):
+ paused.set()
+ resume.wait(3)
+
+ def run(name, model, task):
+ try:
+ outcome[name] = call(model, task)
+ except Exception as exc:
+ outcome[name] = exc
+
+ threading.settrace(tracer)
+ try:
+ attempt_a = threading.Thread(target=run, args=("a", "a", "compression"))
+ attempt_a.start()
+ assert paused.wait(3)
+ gates["a"].set()
+ attempt_a.join(0.3)
+ attempt_b = threading.Thread(target=run, args=("b", "b", None))
+ attempt_b.start()
+ assert gates["b_started"].wait(3)
+ resume.set()
+ time.sleep(0.2)
+ gates["b"].set()
+ attempt_b.join(5)
+ attempt_a.join(5)
+ finally:
+ threading.settrace(None)
+ resume.set()
+ assert isinstance(outcome["a"], TimeoutError)
+ assert getattr(outcome["b"], "choices", None), outcome["b"]
+ assert outcome["b"].choices[0].message.content == "partial"
+
# ---------------------------------------------------------------------------
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 5cff78bf4e0..8517d75731e 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1104,7 +1104,7 @@ Points at a custom OpenAI-compatible endpoint. Uses `OPENAI_API_KEY` for auth.
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 (`... 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.
+- `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 chat-completions stream the window starts at the first token. Before it, a remote endpoint gets the main loop's stale patience (180s, raised for large prompts and to 600s for reasoning models such as o3 or DeepSeek R1, capped at `timeout`), so a model thinking silently is not cut. On a local endpoint (localhost, LAN, Tailscale) a silent prefill is bounded only by `timeout`. The same rule applies to every streamed auxiliary task, including MoA reference calls. 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.