Skip to content

The agent that grows with you

fix(agent): unmask probe owns its stream lifecycle, never leaks the latch

DavidMetcalfe7e9c80a20427
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index cc0e458b518..f2ecae136f2 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3546,8 +3546,11 @@ class _StreamingCall(StreamingWaitMonitor):
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``.
+ the original error. The successful delivery is bracketed by its own stream
+ start/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). 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"]:
@@ -3580,8 +3583,19 @@ class _StreamingCall(StreamingWaitMonitor):
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)
- self.result["response"] = self._adopt_final_response(probe)
- self.agent._disable_streaming = stream_pref # one-turn recovery, not a session latch
+ 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)
+ return False
+ finally:
+ self.agent._disable_streaming = stream_pref # one-turn recovery, not a session latch
+ self.result["response"] = adopted
return True
def _call_wire(self, stream_attempt_id: int):
diff --git a/tests/agent/test_stream_unmask_5xx.py b/tests/agent/test_stream_unmask_5xx.py
index 8ace9a96efd..4bc0f594ed2 100644
--- a/tests/agent/test_stream_unmask_5xx.py
+++ b/tests/agent/test_stream_unmask_5xx.py
@@ -13,6 +13,8 @@ Gating invariants (from cross-vendor review):
- 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)
+- the recovered delivery opens and closes its own stream pair (consumers must never
+ see deltas after the failed attempt's terminal on_stream_end)
- user interrupts re-raise; never swallowed
"""
import time
@@ -63,6 +65,24 @@ def _prime_probe_window(call):
call.agent._stream_5xx_probe_ts = 0.0
+def _record_probe(monkeypatch, message):
+ """Install a probe that RECORDS every invocation before failing.
+
+ The production code swallows any exception raised by the probe (the 4xx/5xx
+ classification lives in that ``except``), so a raise-only sentinel is invisible:
+ the call still returns "not handled" and a guard-removed build passes. The
+ recorded list is what proves the guard held.
+ """
+ calls = []
+
+ def fake_probe(agent, kwargs):
+ calls.append(kwargs)
+ raise AssertionError(message)
+
+ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)
+ return calls
+
+
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)
@@ -114,79 +134,72 @@ def test_stream_5xx_probe_5xx_keeps_original_error(monkeypatch):
call = _make_call({"model": "m", "messages": []})
_prime_probe_window(call)
original = _StreamErr(500)
+ probe_calls = []
- def fake_probe(agent, kwargs):
+ def raising_probe(agent, kwargs):
+ probe_calls.append(kwargs)
raise _ProbeErr(503)
- monkeypatch.setattr(h, "interruptible_api_call", fake_probe)
+ monkeypatch.setattr(h, "interruptible_api_call", raising_probe)
handled = _run_handle_stream_error(call, original)
assert not handled
+ assert len(probe_calls) == 1 # the probe DID run; only its error is discarded
assert call.result["error"] is original # probe 5xx is no more informative; keep the first error
@pytest.mark.parametrize("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)
+ probe_calls = _record_probe(monkeypatch, "probe must not run for non-5xx stream errors")
handled = _run_handle_stream_error(call, _StreamErr(status))
assert not handled
+ assert probe_calls == []
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)
+ probe_calls = _record_probe(monkeypatch, "probe must not run after deltas were delivered")
handled = _run_handle_stream_error(call, _StreamErr(500))
assert not handled
+ assert probe_calls == []
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)
+ probe_calls = _record_probe(monkeypatch, "probe must not run without a 5xx status")
handled = _run_handle_stream_error(call, Exception("connection exploded"))
assert not handled
+ assert probe_calls == []
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)
+ probe_calls = _record_probe(monkeypatch, "second probe within the window must not run")
handled = _run_handle_stream_error(call, _StreamErr(500))
assert not handled
+ assert probe_calls == []
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
+ seen_kwargs = []
def fake_probe(agent, kwargs):
+ seen_kwargs.append(kwargs)
return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok", reasoning_content=None))])
monkeypatch.setattr(h, "interruptible_api_call", fake_probe)
@@ -195,19 +208,77 @@ def test_probe_window_rearms_after_60s(monkeypatch):
handled = not _run_handle_stream_error(call, _StreamErr(500))
assert handled
+ assert len(seen_kwargs) == 1 # the re-armed window actually probed
+ assert call.result["response"] is not None
def test_probe_skipped_for_non_chat_completions_wire(monkeypatch):
call = _make_call({"model": "m", "messages": []}, api_mode="anthropic_messages")
+ probe_calls = _record_probe(
+ monkeypatch, "probe must not run on the anthropic wire (adoption replays chat shapes)")
+
+ handled = _run_handle_stream_error(call, _StreamErr(500))
+
+ assert not handled
+ assert probe_calls == []
+
+
+def test_probe_recovery_brackets_its_own_stream_lifecycle(monkeypatch):
+ """The failed attempt already emitted a terminal on_stream_end — deltas must not
+ follow it, so the recovered delivery opens and closes its own pair."""
+ call = _make_call({"model": "m", "messages": []})
+ _prime_probe_window(call)
+ events = []
+ call.agent._emit_stream_start = lambda: events.append(("start", None, None, None))
+ call.agent._emit_stream_end = lambda *, final_text, finished, error: events.append(
+ ("end", finished, final_text, error))
def fake_probe(agent, kwargs):
- raise AssertionError("probe must not run on the anthropic wire (adoption replays chat shapes)")
+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="recovered", reasoning_content=None))])
monkeypatch.setattr(h, "interruptible_api_call", fake_probe)
- handled = _run_handle_stream_error(call, _StreamErr(500))
+ def fake_adopt(r):
+ events.append(("delta", "recovered", None, None))
+ call.agent._disable_streaming = True # adoption's own latch
+ return r
+
+ monkeypatch.setattr(call, "_adopt_final_response", fake_adopt)
+
+ handled = not _run_handle_stream_error(call, _StreamErr(500))
+
+ assert handled
+ assert events[0][0] == "start"
+ assert events[-1] == ("end", True, "recovered", None) # closed, finished, with the text
+ assert [e[0] for e in events] == ["start", "delta", "end"]
+ assert call.agent._disable_streaming is False
+
+
+def test_adoption_failure_keeps_original_error_and_restores_streaming(monkeypatch):
+ """A probe response we cannot replay must not leak the non-streaming latch and must
+ not escape _handle_stream_error (it runs inside _call()'s except block)."""
+ call = _make_call({"model": "m", "messages": []})
+ _prime_probe_window(call)
+ call.agent._disable_streaming = False
+ original = _StreamErr(500)
+
+ def fake_probe(agent, kwargs):
+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok", reasoning_content=None))])
+
+ monkeypatch.setattr(h, "interruptible_api_call", fake_probe)
+
+ def exploding_adopt(r):
+ call.agent._disable_streaming = True # latch flipped before the failure
+ raise RuntimeError("adoption exploded")
+
+ monkeypatch.setattr(call, "_adopt_final_response", exploding_adopt)
+
+ handled = _run_handle_stream_error(call, original)
assert not handled
+ assert call.agent._disable_streaming is False # no session-wide latch leak
+ assert call.result["response"] is None
+ assert call.result["error"] is original # the opaque 5xx still reaches the loop
def test_interrupt_during_probe_reraises(monkeypatch):