The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a stale stream attempt advances the cross-turn breaker once, not per timer re-fire
teknium19863980c6116
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 27dce916573..1db9226036a 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2843,6 +2843,7 @@ class _StreamingCall(StreamingWaitMonitor):self._stream_stale_timeout = Noneself.stream_attempt_lock = threading.Lock()self.stream_attempt_state = {"current": 0, "cancelled": set(), "discarded_chunks": 0, "discarded_bytes": 0}+ self._stale_counted_attempts: set[int] = set() # breaker counts each attempt onceself.managed_stream_holder = {"stream": None}# Per-attempt: single-writer token, request-local client, raw HTTP response (chat wire).self._writer_token = self._attempt_request_client = self._attempt_stream_response = None@@ -3825,6 +3826,21 @@ class _StreamingCall(StreamingWaitMonitor):except Exception:logger.debug("Stale stream socket shutdown failed", exc_info=True)+ def _uncounted_stale_attempt(self) -> int:+ """The started attempt the circuit breaker (see ``_stale_streak()``) has not counted+ yet, else 0. Like the non-streaming and inline watchdogs, each attempt counts once:+ the stale timer re-fires every window while the worker has not dispatched yet or is+ still unwinding a kill, and none of those re-kills is another unresponsive attempt."""+ with self.stream_attempt_lock:+ attempt = int(self.stream_attempt_state["current"])+ return 0 if attempt in self._stale_counted_attempts else attempt++ def _count_stale_attempt(self) -> None:+ attempt = self._uncounted_stale_attempt()+ if attempt:+ self._stale_counted_attempts.add(attempt)+ _bump_stale_streak(self.agent)+def _kill_stale_stream(self, elapsed: float) -> None:"""SSE pings but no chunks: cancel the attempt and abort the request-localclient so the retry loop opens a fresh one. The shared client is never@@ -3847,7 +3863,7 @@ class _StreamingCall(StreamingWaitMonitor):self._cancel_current_stream_attempt("stale_stream_kill")self.clients.close_once("stale_stream_kill")self._shutdown_stale_attempt_socket(_killed_response)- _bump_stale_streak(self.agent) # circuit breaker, see ``_stale_streak()``+ self._count_stale_attempt()# Reset the timer so we don't kill repeatedly while the worker unwinds.self.last_chunk_time["t"] = time.time()self.agent._emit_diagnostic_wait(f"⚠ no output from provider for {int(elapsed)}s — reconnecting...")@@ -3856,9 +3872,11 @@ class _StreamingCall(StreamingWaitMonitor):def _abort_for_interrupt(self, stale_elapsed: float) -> None:"""/stop seen by the monitor: mark cancelled, abort the request-localsocket, wait for the worker, flag the interrupt."""- # The stale branch already counted this iteration if its deadline won the race.- if stale_elapsed <= self._stream_stale_timeout:- _record_interrupted_provider_wait(self.agent, stale_elapsed, response_started=self.deltas_were_sent["yes"])+ # Once per attempt: a stale kill that already counted this attempt wins.+ attempt = self._uncounted_stale_attempt()+ if attempt and stale_elapsed <= self._stream_stale_timeout and _record_interrupted_provider_wait(+ self.agent, stale_elapsed, response_started=self.deltas_were_sent["yes"]):+ self._stale_counted_attempts.add(attempt)# Mark cancelled BEFORE force-closing so the worker treats the forced# transport error as a cancel, not a network error (#6600).self._request_cancelled["value"] = Truediff --git a/tests/agent/test_stream_stale_circuit_breaker.py b/tests/agent/test_stream_stale_circuit_breaker.pyindex a9999362323..e8561a1809d 100644--- a/tests/agent/test_stream_stale_circuit_breaker.py+++ b/tests/agent/test_stream_stale_circuit_breaker.py@@ -152,3 +152,51 @@ class TestStreamStaleCircuitBreaker:# At least one stale kill happened; the streak must have advanced.assert agent._consecutive_stale_streams >= 1++ @pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")+ @pytest.mark.parametrize("slow", ["worker_start", "worker_unwind"])+ def test_one_attempt_counts_once_however_often_the_timer_fires(self, monkeypatch, caplog, slow):+ """The stale timer re-fires every window while the worker has not started its+ attempt yet (CPU-starved host) or has not unwound a kill; one attempt must still+ count once, or a single wedged turn trips the breaker for the next one."""+ from agent import chat_completion_helpers as h++ monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "0.1")+ monkeypatch.setenv("HERMES_STREAM_STALE_GIVEUP", "50")+ monkeypatch.setenv("HERMES_STREAM_RETRIES", "0")+ agent = _make_anthropic_agent()+ agent._consecutive_stale_streams = 0+ unblock = threading.Event()++ if slow == "worker_start":+ start = h._StreamingCall._start_stream_attempt++ def _late_start(self):+ threading.Event().wait(1.0)+ return start(self)++ monkeypatch.setattr(h._StreamingCall, "_start_stream_attempt", _late_start)+ agent._abort_request_anthropic_client = lambda *a, **k: unblock.set()+ else:+ agent._abort_request_anthropic_client = lambda *a, **k: None # the kill never wakes the read++ def _blocking_gen():+ unblock.wait(timeout=1.2)+ raise httpx.ConnectError("connection dropped")+ yield++ def _stream_side_effect(*args, **kwargs):+ cm = MagicMock()+ stream = MagicMock()+ stream.__iter__ = MagicMock(return_value=_blocking_gen())+ cm.__enter__ = MagicMock(return_value=stream)+ cm.__exit__ = MagicMock(return_value=False)+ return cm++ agent._anthropic_client.messages.stream.side_effect = _stream_side_effect+ with caplog.at_level("WARNING", logger="agent.chat_completion_helpers"), pytest.raises(Exception):+ agent._interruptible_streaming_api_call({})++ kills = sum("Stream stale for" in r.getMessage() for r in caplog.records)+ assert kills >= 2, f"scenario needs the timer to re-fire; saw {kills} kill(s)"+ assert agent._consecutive_stale_streams == 1