The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): unmask probe suspends the stream stale watchdog, replays without latching
kshitijk4poor6927ccf2e04a
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 40d03a6e072..a3e3bd91d44 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -1235,6 +1235,7 @@ def _apply_display_config(agent, _agent_cfg, platform):"Invalid model.streaming=%r; expected a boolean. Using streaming (default).",_model_section.get("streaming"),)+ agent._stream_5xx_probe_ts = None # monotonic time of the last streaming-5xx unmask probetry:agent._tool_guardrails = ToolCallGuardrailController(diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 74980d16e2c..75f8fce5528 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -27,7 +27,8 @@ from typing import Any, Dict, Optionalfrom hermes_cli.timeouts import get_provider_request_timeout, get_provider_stale_timeoutfrom hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTHfrom agent.error_classifier import (- FailoverReason, PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE, PROVIDER_STREAM_NON_JSON_ERROR_CODE)+ FailoverReason, PROVIDER_STREAM_EMPTY_FRAME_ERROR_CODE, PROVIDER_STREAM_NON_JSON_ERROR_CODE,+ _extract_status_code)from agent.sdk_transform_bypass import bypass_chat_sdk_request_transformfrom agent.errors import EmptyStreamErrorfrom agent.chat_completion_stream_monitor import StreamingWaitMonitor@@ -3170,6 +3171,10 @@ class _StreamingCall(StreamingWaitMonitor):"switching %s/%s to non-streaming for this session.", self.agent.provider or "unknown",self.agent.model or "unknown")self.agent._disable_streaming = True+ return self._replay_final_response(final_response)++ def _replay_final_response(self, final_response):+ """Replay a completed chat-completions response's reasoning/content as deltas."""choices = final_response.choicesmessage = getattr(choices[0] if isinstance(choices, (list, tuple)) and choices else None, "message", None)if message is not None:@@ -3541,65 +3546,65 @@ 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 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 probe per 60s window (timestamped 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 latchingnon-streaming (a transient gateway 500 must not permanently disable streaming);on a probe 4xx that error REPLACES the opaque 5xx; any other probe failure keepsthe original error. The successful delivery is bracketed by its own streamstart/end pair (the failed attempt already emitted a terminal end), and a response- that cannot be replayed restores the saved preference before propagating ``e``.- Interrupts re-raise (the outer handler routes them), and a /stop that arrived before+ that cannot be replayed propagates ``e``. The probe runs on this worker thread while+ the stream monitor still polls, so its stale check is suspended for the probe's+ duration (the probe has its own non-streaming watchdog). Interrupts re-raise (the outer handler routes them), and a /stop that arrived beforethis point suppresses the probe entirely — the loop's pre-retry interrupt check ownsthat decision, so a pending stop must not buy one more request.True = handled (caller must not overwrite result); False = propagate ``e``."""if getattr(self.agent, "_interrupt_requested", False):return False- 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"]:+ status = _extract_status_code(e)+ if status is None or status < 500 or self.deltas_were_sent["yes"]:return Falseif 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+ return False # replay handles chat-completions shapes only+ now = time.monotonic()+ last_probe = self.agent._stream_5xx_probe_ts+ if last_probe is not None and now - last_probe < _STREAM_5XX_PROBE_WINDOW_S:+ return False # one probe per 60s windowself.agent._stream_5xx_probe_ts = nowprobe_kwargs = {k: v for k, v in self.api_kwargs.items() if k not in ("stream", "stream_options")}+ stale_timeout = self._stream_stale_timeout+ self._stream_stale_timeout = float("inf") # no chunks arrive during the probetry: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)- if isinstance(probe_status, int) and probe_status < 500:+ probe_status = _extract_status_code(probe_err)+ if probe_status is not None 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_errreturn Truelogger.info("Non-streaming unmask probe failed: %s", probe_err)return False+ finally:+ self._stream_stale_timeout = stale_timeoutlogger.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.")- stream_pref = getattr(self.agent, "_disable_streaming", False)try:# The failed attempt already emitted its terminal on_stream_end(finished=False),# so the recovered delivery opens and closes its OWN stream pair — consumers must# never see deltas after that error event.- adopted = _with_stream_emitters(self.agent, lambda: self._adopt_final_response(probe))- except Exception as adopt_err:- # A response we cannot replay must not escape into _call()'s except block, and- # must not leave streaming latched off for the session.- logger.exception("Non-streaming unmask probe response could not be adopted: %s", adopt_err)+ replayed = _with_stream_emitters(self.agent, lambda: self._replay_final_response(probe))+ except Exception as replay_err:+ # A response we cannot replay must not escape into _call()'s except block.+ logger.exception("Non-streaming unmask probe response could not be replayed: %s", replay_err)return False- finally:- self.agent._disable_streaming = stream_pref # one-turn recovery, not a session latch- self.result["response"] = adopted+ self.result["response"] = replayedreturn 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 94cb2fe9400..fe2458f2355 100644--- a/tests/agent/test_stream_unmask_5xx.py+++ b/tests/agent/test_stream_unmask_5xx.py@@ -29,8 +29,14 @@ def _make_call(api_kwargs, *, deltas_sent=False, api_mode="chat_completions"):_interrupt_requested=False,_is_provider_stream_parse_error=lambda e: False,_buffer_status=lambda text: call.buffered.append(text),+ _disable_streaming=False, _stream_5xx_probe_ts=None,+ _fire_stream_delta=lambda text: call.deltas.append(text),)call.buffered = []+ call.deltas = []+ call.first_delta_fired = {"done": True}+ call.on_first_delta = None+ call._stream_stale_timeout = 180.0call.api_kwargs = api_kwargscall.result = {"response": None, "error": None, "partial_tool_names": []}call.deltas_were_sent = {"yes": deltas_sent}@@ -57,43 +63,33 @@ def _run_handle_stream_error(call, e):return call._handle_stream_error(e, attempt=2, max_retries=2)-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)+ seen_kwargs.append((kwargs, call._stream_stale_timeout))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 inside adoption- return r-- monkeypatch.setattr(call, "_adopt_final_response", fake_adopt)handled = not _run_handle_stream_error(call, _StreamErr(500))assert handledassert call.result["response"] is not Noneassert call.result["error"] is None- assert seen_kwargs and "stream" not in seen_kwargs[0] and "stream_options" not in seen_kwargs[0]- # One-turn recovery: adoption's internal latch is RESTORED, not kept.+ probe_kwargs, stale_during_probe = seen_kwargs[0]+ assert "stream" not in probe_kwargs and "stream_options" not in probe_kwargs+ assert call.deltas == ["ok"]+ # One-turn recovery: streaming is never latched off for the session.assert call.agent._disable_streaming is False+ # No chunks arrive during the probe: the stream monitor must not stale-kill it.+ assert stale_during_probe == float("inf") and call._stream_stale_timeout == 180.0assert 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):