The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): unmask opaque streaming 5xx with one non-streaming retry
DavidMetcalfe1965ea81ce8a
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex a62e4d9220d..8c12660bc93 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3524,10 +3524,47 @@ class _StreamingCall(StreamingWaitMonitor):else:self._maybe_disable_streaming(e)logger.exception("Streaming failed before delivery: %s", e)+ if self._unmask_server_error_with_nonstreaming(e):+ return False# Propagate to the main retry loop (credential rotation, fallback, backoff).self.result["error"] = ereturn False+ def _unmask_server_error_with_nonstreaming(self, e: Exception) -> bool:+ """One non-streaming re-issue when a 5xx killed the stream before any delta.++ Some gateways validate the request only on their non-streaming path and crash+ opaquely ("500 something went wrong") when streaming — the real 4xx, with its+ actionable 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``.+ """+ 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+ probe_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 Exception as probe_err:+ probe_status = getattr(probe_err, "status_code", None) or getattr(+ getattr(probe_err, "response", None), "status_code", None)+ if isinstance(probe_status, int) and probe_status < 500:+ # The provider's REAL validation error beats the opaque 5xx.+ logger.info("Non-streaming unmask probe surfaced the underlying error: %s", probe_err)+ self.result["error"] = probe_err+ return True+ logger.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.",+ 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.")+ self.result["response"] = self._adopt_final_response(probe)+ return True+def _call_wire(self, stream_attempt_id: int):if self.agent.api_mode != "anthropic_messages":return self._call_chat_completions(stream_attempt_id)diff --git a/tests/agent/test_stream_unmask_5xx.py b/tests/agent/test_stream_unmask_5xx.pynew file mode 100644index 00000000000..7c7feefe7f2--- /dev/null+++ b/tests/agent/test_stream_unmask_5xx.py@@ -0,0 +1,148 @@+"""Streaming 5xx unmasking: the non-streaming probe surfaces the provider's real error.++Regression shape (AssemblyAI LLM Gateway, 2026-09): a gateway that validates requests+only on its non-streaming path returns an opaque ``500 something went wrong`` when+streaming the SAME request. _handle_stream_error must re-issue once non-streaming on a+pre-delta 5xx so the actionable 4xx (or a successful response) reaches the user instead+of three identical opaque 500s.+"""+from types import SimpleNamespace++import pytest++from agent import chat_completion_helpers as h+++def _make_call(api_kwargs, *, deltas_sent=False):+ call = h._StreamingCall.__new__(h._StreamingCall)+ call.agent = SimpleNamespace(+ provider="custom", model="gpt-5.6-sol",+ _interrupt_requested=False,+ _is_provider_stream_parse_error=lambda e: False,+ _buffer_status=lambda text: call.buffered.append(text),+ )+ call.buffered = []+ call.api_kwargs = api_kwargs+ call.result = {"response": None, "error": None, "partial_tool_names": []}+ call.deltas_were_sent = {"yes": deltas_sent}+ call.provider_tool_in_flight = {"yes": False}+ call._request_cancelled = {"value": False}+ return call+++class _StreamErr(Exception):+ """Stands in for the openai 5xx the stream path raises."""++ def __init__(self, status):+ super().__init__(f"Error code: {status} - something went wrong")+ self.status_code = status+++class _ProbeErr(Exception):+ def __init__(self, status):+ super().__init__(f"Error code: {status} - real validation message")+ self.status_code = status+++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):+ call = _make_call({"model": "m", "stream": True, "stream_options": {"x": 1}, "messages": []})+ seen_kwargs = []++ def fake_probe(agent, kwargs):+ seen_kwargs.append(kwargs)+ return "completed-response"++ 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+ return r++ monkeypatch.setattr(call, "_adopt_final_response", fake_adopt)++ handled = not _run_handle_stream_error(call, _StreamErr(500))++ assert handled+ assert call.result["response"] == "completed-response"+ assert call.result["error"] is None+ assert 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+ assert 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": []})+ real = _ProbeErr(400)++ def fake_probe(agent, kwargs):+ raise real++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, _StreamErr(500))++ assert not handled # loop stops, error propagates+ assert call.result["error"] is real # the REAL validation error replaces the opaque 500+ assert call.result["response"] is None+++def test_stream_5xx_probe_5xx_keeps_original_error(monkeypatch):+ call = _make_call({"model": "m", "messages": []})+ original = _StreamErr(500)++ def fake_probe(agent, kwargs):+ raise _ProbeErr(503)++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, original)++ assert not handled+ assert call.result["error"] is original # probe 5xx is no more informative; keep the first error++[email protected]("status", [400, 429])+def test_no_probe_for_client_errors(monkeypatch, status):+ call = _make_call({"model": "m", "messages": []})++ def fake_probe(agent, kwargs):+ raise AssertionError("probe must not run for non-5xx stream errors")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, _StreamErr(status))++ assert not handled+ assert call.result["response"] is None+++def test_no_probe_after_partial_delivery(monkeypatch):+ call = _make_call({"model": "m", "messages": []}, deltas_sent=True)++ def fake_probe(agent, kwargs):+ raise AssertionError("probe must not run after deltas were delivered")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, _StreamErr(500))++ assert not handled+++def test_no_probe_without_status_code(monkeypatch):+ call = _make_call({"model": "m", "messages": []})++ def fake_probe(agent, kwargs):+ raise AssertionError("probe must not run without a 5xx status")++ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)++ handled = _run_handle_stream_error(call, Exception("connection exploded"))++ assert not handled