The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): review fixes for stream 5xx unmask probe
DavidMetcalfe662ace4ef723
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 8c12660bc93..cc0e458b518 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -63,6 +63,11 @@ _PROVIDER_STREAM_ERROR_TEXT_LIMIT = 4096# billing reasons keep their own longer cooldown._FALLBACK_EXHAUSTED_COOLDOWN_S = 5.0+# Streaming 5xx unmask probe: one non-streaming re-issue per this window. Covers the+# outer retry loop (up to ~3 attempts x backoff, well under 60s) so an outage doesn't+# double traffic every attempt, while later turns re-arm automatically.+_STREAM_5XX_PROBE_WINDOW_S = 60.0+def _context_thread_target(callback):"""Bind a no-argument thread target to the caller's ContextVars."""@@ -3536,17 +3541,29 @@ class _StreamingCall(StreamingWaitMonitor):Some gateways validate the request only on their non-streaming path and crashopaquely ("500 something went wrong") when streaming — the real 4xx, with itsactionable message, never reaches the user through stream retries. One- non-streaming probe surfaces it: on success the response is delivered and the- session flips to non-streaming (the _adopt_final_response latch); on a probe 4xx- that error REPLACES the opaque 5xx. Any other probe failure keeps the original- error. True = handled (caller must not overwrite result); False = propagate ``e``.+ non-streaming probe per TURN (latched on the agent: each outer retry builds a+ fresh _StreamingCall, so an instance flag would re-probe every attempt) surfaces+ it: on success the response is delivered for this turn WITHOUT latching+ non-streaming (a transient gateway 500 must not permanently disable streaming);+ on a probe 4xx that error REPLACES the opaque 5xx; any other probe failure keeps+ the original error. Interrupts re-raise (the outer handler routes them). True =+ handled (caller must not overwrite result); False = propagate ``e``."""status = getattr(e, "status_code", None) or getattr(getattr(e, "response", None), "status_code", None)if not isinstance(status, int) or status < 500 or self.deltas_were_sent["yes"]:return False+ if getattr(self.agent, "api_mode", "") not in ("", "chat_completions"):+ return False # adoption replays chat-completions shapes only+ now = time.time()+ last_probe = getattr(self.agent, "_stream_5xx_probe_ts", 0.0) or 0.0+ if now - last_probe < _STREAM_5XX_PROBE_WINDOW_S:+ return False # one probe per outer-retry cycle; later turns re-arm+ self.agent._stream_5xx_probe_ts = nowprobe_kwargs = {k: v for k, v in self.api_kwargs.items() if k not in ("stream", "stream_options")}try:probe = interruptible_api_call(self.agent, probe_kwargs)+ except (KeyboardInterrupt, InterruptedError):+ raise # the outer handler routes user interrupts; never swallow themexcept Exception as probe_err:probe_status = getattr(probe_err, "status_code", None) or getattr(getattr(probe_err, "response", None), "status_code", None)@@ -3557,12 +3574,14 @@ class _StreamingCall(StreamingWaitMonitor):return Truelogger.info("Non-streaming unmask probe failed: %s", probe_err)return False- logger.info("Streaming 5xx re-issued non-streaming successfully; switching %s/%s to non-streaming.",+ logger.info("Streaming 5xx re-issued non-streaming successfully for %s/%s "+ "(not latched: the 5xx may be transient).",self.agent.provider or "unknown", self.agent.model or "unknown")self._quiet(self.agent._buffer_status,- "⚠ Streaming failed with a provider server error; the non-streaming retry succeeded. "- "Disabling streaming for this session.")+ "⚠ Streaming failed with a provider server error; the non-streaming retry succeeded.")+ stream_pref = getattr(self.agent, "_disable_streaming", False)self.result["response"] = self._adopt_final_response(probe)+ self.agent._disable_streaming = stream_pref # one-turn recovery, not a session latchreturn Truedef _call_wire(self, stream_attempt_id: int):diff --git a/tests/agent/test_stream_unmask_5xx.py b/tests/agent/test_stream_unmask_5xx.pyindex 7c7feefe7f2..8ace9a96efd 100644--- a/tests/agent/test_stream_unmask_5xx.py+++ b/tests/agent/test_stream_unmask_5xx.py@@ -5,7 +5,17 @@ only on its non-streaming path returns an opaque ``500 something went wrong`` whstreaming the SAME request. _handle_stream_error must re-issue once non-streaming on apre-delta 5xx so the actionable 4xx (or a successful response) reaches the user insteadof three identical opaque 500s.++Gating invariants (from cross-vendor review):+- never after partial delivery, on non-5xx, or without an HTTP status+- one probe per 60s window on the AGENT (outer retries build fresh _StreamingCall+ instances, so an instance flag would re-probe every attempt)+- chat-completions wire only (adoption replays chat-completions shapes)+- probe success delivers for the turn WITHOUT latching _disable_streaming+ (a transient gateway 500 must not permanently disable streaming)+- user interrupts re-raise; never swallowed"""+import timefrom types import SimpleNamespaceimport pytest@@ -13,10 +23,10 @@ import pytestfrom agent import chat_completion_helpers as h-def _make_call(api_kwargs, *, deltas_sent=False):+def _make_call(api_kwargs, *, deltas_sent=False, api_mode="chat_completions"):call = h._StreamingCall.__new__(h._StreamingCall)call.agent = SimpleNamespace(- provider="custom", model="gpt-5.6-sol",+ provider="custom", model="gpt-5.6-sol", api_mode=api_mode,_interrupt_requested=False,_is_provider_stream_parse_error=lambda e: False,_buffer_status=lambda text: call.buffered.append(text),@@ -48,20 +58,26 @@ def _run_handle_stream_error(call, e):return call._handle_stream_error(e, attempt=2, max_retries=2)-def test_stream_5xx_probe_success_delivers_response(monkeypatch):+def _prime_probe_window(call):+ """Ensure the agent's probe window is open (no probe yet, or an old one)."""+ call.agent._stream_5xx_probe_ts = 0.0+++def test_stream_5xx_probe_success_delivers_response_without_latch(monkeypatch):call = _make_call({"model": "m", "stream": True, "stream_options": {"x": 1}, "messages": []})+ _prime_probe_window(call)seen_kwargs = []def fake_probe(agent, kwargs):seen_kwargs.append(kwargs)- return "completed-response"+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok", reasoning_content=None))])monkeypatch.setattr(h, "interruptible_api_call", fake_probe)adopt_calls = []def fake_adopt(r):adopt_calls.append(r)- call.agent._disable_streaming = True # mirror the real latch+ call.agent._disable_streaming = True # mirror the real latch inside adoptionreturn rmonkeypatch.setattr(call, "_adopt_final_response", fake_adopt)@@ -69,15 +85,17 @@ def test_stream_5xx_probe_success_delivers_response(monkeypatch):handled = not _run_handle_stream_error(call, _StreamErr(500))assert handled- assert call.result["response"] == "completed-response"+ assert call.result["response"] is not Noneassert call.result["error"] is Noneassert seen_kwargs and "stream" not in seen_kwargs[0] and "stream_options" not in seen_kwargs[0]- assert call.agent._disable_streaming is True # latched by _adopt_final_response+ # One-turn recovery: adoption's internal latch is RESTORED, not kept.+ assert call.agent._disable_streaming is Falseassert call.buffered and "non-streaming retry succeeded" in call.buffered[0]def test_stream_5xx_unmasked_by_probe_4xx(monkeypatch):call = _make_call({"model": "m", "messages": []})+ _prime_probe_window(call)real = _ProbeErr(400)def fake_probe(agent, kwargs):@@ -94,6 +112,7 @@ def test_stream_5xx_unmasked_by_probe_4xx(monkeypatch):def test_stream_5xx_probe_5xx_keeps_original_error(monkeypatch):call = _make_call({"model": "m", "messages": []})+ _prime_probe_window(call)original = _StreamErr(500)def fake_probe(agent, kwargs):@@ -146,3 +165,59 @@ def test_no_probe_without_status_code(monkeypatch):handled = _run_handle_stream_error(call, Exception("connection exploded"))assert not handled+++def test_probe_window_blocks_second_probe_within_60s(monkeypatch):+ call = _make_call({"model": "m", "messages": []})+ call.agent._stream_5xx_probe_ts = time.time() # probe just happened (fresh instance = outer retry)++ def fake_probe(agent, kwargs):+ raise AssertionError("second probe within the window must not run")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, _StreamErr(500))++ assert not handled+ assert call.result["error"] is not None # original error propagates+++def test_probe_window_rearms_after_60s(monkeypatch):+ call = _make_call({"model": "m", "messages": []})+ call.agent._stream_5xx_probe_ts = time.time() - 61.0++ def fake_probe(agent, kwargs):+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok", reasoning_content=None))])++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)+ monkeypatch.setattr(call, "_adopt_final_response", lambda r: r)++ handled = not _run_handle_stream_error(call, _StreamErr(500))++ assert handled+++def test_probe_skipped_for_non_chat_completions_wire(monkeypatch):+ call = _make_call({"model": "m", "messages": []}, api_mode="anthropic_messages")++ def fake_probe(agent, kwargs):+ raise AssertionError("probe must not run on the anthropic wire (adoption replays chat shapes)")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, _StreamErr(500))++ assert not handled+++def test_interrupt_during_probe_reraises(monkeypatch):+ call = _make_call({"model": "m", "messages": []})+ _prime_probe_window(call)++ def fake_probe(agent, kwargs):+ raise InterruptedError("Agent interrupted during API call")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ with pytest.raises(InterruptedError):+ _run_handle_stream_error(call, _StreamErr(500))