The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(streaming): back off between stream reconnects; treat Anthropic connection errors as transient
kshitijk4poor0b5673364dba
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex ad2156422fb..dfd9c71b3c7 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2405,6 +2405,36 @@ def _rejects_stream_options(exc: BaseException) -> bool:k in body for k in ("extra", "not supported", "unrecognized", "unexpected", "unknown"))+_STREAM_RETRY_BACKOFF_BASE_S = 1.0+_STREAM_RETRY_BACKOFF_CAP_S = 4.0+++def _stream_retry_backoff_seconds(attempt: int) -> float:+ """Delay before stream-level reconnect ``attempt`` (0-based): 1s, 2s, 4s, capped."""+ return min(_STREAM_RETRY_BACKOFF_BASE_S * (2 ** max(0, attempt)), _STREAM_RETRY_BACKOFF_CAP_S)+++def _wait_stream_retry_backoff(agent, delay: float) -> bool:+ """Sleep ``delay`` seconds in 0.1s steps, returning False as soon as the+ agent is interrupted (so /stop is never held hostage by a backoff)."""+ deadline = time.monotonic() + max(0.0, delay)+ while True:+ if getattr(agent, "_interrupt_requested", False):+ return False+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return True+ time.sleep(min(0.1, remaining))+++def _anthropic_connection_error_types() -> tuple:+ try:+ from anthropic import APIConnectionError as _AnthropicConnErr+ except Exception:+ return ()+ return (_AnthropicConnErr,)++def _is_sse_connection_error(exc: BaseException) -> bool:from openai import APIError as _APIErrorif not isinstance(exc, _APIError) or getattr(exc, "status_code", None):@@ -3370,6 +3400,9 @@ class _StreamingCall(StreamingWaitMonitor):buffer_anthropic_tool_input(self.api_kwargs, getattr(self.agent, "_anthropic_base_url", None))self._cancel_current_stream_attempt(reason)self.clients.close_once(reason)+ # Exponential backoff between stream-level reconnects (back-to-back retries+ # hammer a provider that just dropped us). Interruptible: /stop exits at once.+ _wait_stream_retry_backoff(self.agent, _stream_retry_backoff_seconds(attempt))def _maybe_disable_streaming(self, e) -> None:"""Flip to non-streaming for failures streaming itself cannot survive, or that@@ -3421,7 +3454,10 @@ class _StreamingCall(StreamingWaitMonitor):_is_timeout = isinstance(e, (_httpx.ReadTimeout, _httpx.ConnectTimeout, _httpx.PoolTimeout))# ReadError: abort/reset mid-body (stale-kill shutdown under a parked reader,# ECONNRESET) — the retry loop owns recovery.- _is_conn_err = isinstance(e, (_httpx.ConnectError, _httpx.ReadError, _httpx.RemoteProtocolError, ConnectionError))+ # anthropic.APIConnectionError: the Anthropic SDK wraps connect/read drops+ # (incl. stale-kill aborts) in its own type, not httpx's.+ _is_conn_err = isinstance(e, (_httpx.ConnectError, _httpx.ReadError, _httpx.RemoteProtocolError, ConnectionError,+ *_anthropic_connection_error_types()))_is_stream_parse_err = self.agent._is_provider_stream_parse_error(e)_is_empty_stream = isinstance(e, EmptyStreamError)_is_sse_conn_err = not _is_timeout and not _is_conn_err and _is_sse_connection_error(e)diff --git a/tests/agent/test_stream_retry_backoff.py b/tests/agent/test_stream_retry_backoff.pynew file mode 100644index 00000000000..8e6c6d134ec--- /dev/null+++ b/tests/agent/test_stream_retry_backoff.py@@ -0,0 +1,67 @@+"""Stream-level reconnects back off exponentially and stay interruptible (#60029)."""+import threading+import time+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import httpx++from agent import chat_completion_helpers as cch+++def _bare_call(agent):+ call = object.__new__(cch._StreamingCall)+ call.agent = agent+ call.api_kwargs = {}+ call.result = {}+ call.clients = SimpleNamespace(diag={}, close_once=MagicMock())+ call._request_cancelled = {"value": False}+ call.deltas_were_sent = {"yes": False}+ call.first_delta_fired = {"done": False}+ call.provider_tool_in_flight = {"yes": False}+ call._cancel_current_stream_attempt = MagicMock()+ return call+++def _agent(**kw):+ return SimpleNamespace(+ _interrupt_requested=False,+ _stream_options_unsupported=False,+ _emit_stream_drop=MagicMock(),+ _is_provider_stream_parse_error=lambda e: False,+ **kw,+ )+++def test_transient_drops_retry_with_capped_exponential_backoff():+ """Each reconnect waits 1s, 2s, 4s, 4s — including Anthropic SDK connection errors."""+ import anthropic++ slept = []+ clock = [0.0]++ def fake_sleep(s):+ slept.append(s)+ clock[0] += s++ call = _bare_call(_agent())+ req = httpx.Request("POST", "https://api.anthropic.com/v1/messages")+ errors = [anthropic.APIConnectionError(request=req), httpx.ConnectError("reset"),+ httpx.ReadError("reset"), httpx.RemoteProtocolError("closed")]+ per_attempt = []+ with patch.object(cch.time, "sleep", fake_sleep), patch.object(cch.time, "monotonic", lambda: clock[0]):+ for attempt, err in enumerate(errors):+ before = clock[0]+ assert call._handle_stream_error(err, attempt, max_retries=10) is True+ per_attempt.append(round(clock[0] - before, 6))+ assert per_attempt == [1.0, 2.0, 4.0, 4.0]+ assert "error" not in call.result+++def test_backoff_wait_returns_immediately_on_interrupt():+ agent = _agent()+ call = _bare_call(agent)+ threading.Timer(0.2, lambda: setattr(agent, "_interrupt_requested", True)).start()+ start = time.monotonic()+ call._retry_after_drop(httpx.ConnectError("x"), 5, 10, mid_tool_call=False, reason="t")+ assert time.monotonic() - start < 1.0