Skip to content

The agent that grows with you

fix(streaming): retry a stream that died before any visible text instead of an empty stub

teknium196f313590cfb
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 8b29626f13d..4b91cf72d71 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2670,6 +2670,12 @@ class _StreamingCall(StreamingWaitMonitor):
self.agent._fire_stream_delta(text)
self.deltas_were_sent["yes"] = True
+ def _visible_text_delivered(self) -> bool:
+ """True when visible assistant text actually reached a stream consumer this attempt
+ (``_fire_stream_delta`` records only scrubbed, delivered text; ``deltas_were_sent``
+ flips on any content delta, including whitespace/think-only ones nobody saw)."""
+ return bool((getattr(self.agent, "_current_streamed_assistant_text", "") or "").strip())
+
def _emit_reasoning(self, text: str) -> None:
self._fire_first_delta()
self.agent._fire_reasoning_delta(text)
@@ -3230,12 +3236,27 @@ class _StreamingCall(StreamingWaitMonitor):
self.clients.close_once("stream_options_rejected_retry")
return True
+ if self.deltas_were_sent["yes"]:
+ _partial_tool_in_flight = bool(self.result.get("partial_tool_names")) or self.provider_tool_in_flight["yes"]
+ if not _partial_tool_in_flight and not self._visible_text_delivered():
+ # Deltas fired but nothing visible reached a consumer (whitespace/think-only
+ # deltas, or no display consumer at all) and no tool call is in flight: from
+ # the user's and the model's point of view NOTHING was delivered. The
+ # "partial delivery" stub would be EMPTY and the loop would ask the model to
+ # continue from nowhere, so it repeats the lost step (#112419). Classify as an
+ # undelivered failure instead: same-prefix retry, then the main loop's
+ # fallback/backoff — there is no text to duplicate.
+ logger.warning(
+ "Stream died after deltas but before any visible text was delivered (0 chars, "
+ "no tool call in flight); treating as an undelivered stream failure: %s", e)
+ self._quiet(self.agent._reset_stream_delivery_tracking)
+ self.deltas_were_sent["yes"] = False
+ self.first_delta_fired["done"] = False
if self.deltas_were_sent["yes"]:
# Died AFTER tokens were delivered: normally no retry (would duplicate
# text). Exception: a tool call in flight — aborting discards it, so
# retry TRANSIENT errors (a "reconnecting" marker + duplicated
# preamble beats a failed action; no tool has executed yet).
- _partial_tool_in_flight = bool(self.result.get("partial_tool_names")) or self.provider_tool_in_flight["yes"]
if not (_partial_tool_in_flight and _is_transient and attempt < max_retries):
logger.warning("Streaming failed after partial delivery, not retrying: %s", e)
self.result["error"] = e
@@ -3434,8 +3455,10 @@ class _StreamingCall(StreamingWaitMonitor):
def _partial_stream_stub(self):
"""Tokens already reached the platform: a finish_reason="length" stub fires the
continuation machinery; tool_calls=None blocks executing incomplete calls.
- Content may be EMPTY on purpose — the loop skips appending an empty stub and
- only sends the nudge (placeholder text leaked into the stitched response)."""
+ Content may be EMPTY (dropped tool call, overflow) — the loop skips appending an
+ empty stub and only sends the nudge (placeholder text leaked into the stitched
+ response). A text-only death with 0 visible chars never gets here: the error
+ handler reclassifies it as undelivered (#112419)."""
error = self.result["error"]
_partial_text = (getattr(self.agent, "_current_streamed_assistant_text", "") or "").strip() or None
_partial_names = list(self.result.get("partial_tool_names") or [])
diff --git a/tests/agent/test_direct_contexts_stream_inline.py b/tests/agent/test_direct_contexts_stream_inline.py
index 22720f09f05..eb3bfdcf6b7 100644
--- a/tests/agent/test_direct_contexts_stream_inline.py
+++ b/tests/agent/test_direct_contexts_stream_inline.py
@@ -19,10 +19,10 @@ import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
+import httpx
import pytest
import run_agent
-from agent import chat_completion_helpers as helpers
from agent.chat_completion_helpers import (
interruptible_streaming_api_call,
should_use_direct_api_call,
@@ -190,14 +190,15 @@ def test_inline_stream_stale_detector_still_fires_from_monitor_thread(
agent = _make_agent(stalling_wire.base_url, platform="subagent")
started = time.time()
- response = interruptible_streaming_api_call(agent, dict(_KW))
+ # The one delta reached no consumer (inline contexts have none), so the killed
+ # stream is undelivered: with the retry budget spent the error surfaces to the
+ # conversation loop instead of an empty partial-stream stub (same contract as the
+ # worker path, #112419).
+ with pytest.raises(httpx.RemoteProtocolError):
+ interruptible_streaming_api_call(agent, dict(_KW))
elapsed = time.time() - started
assert elapsed < 6.0, f"inline stream was not bounded by the stale detector ({elapsed:.1f}s)"
- # A partial delta was delivered → the loop gets the length-truncated
- # partial-stream stub (same contract as the worker path).
- assert getattr(response, "id", None) == helpers.PARTIAL_STREAM_STUB_ID
- assert response.choices[0].finish_reason == helpers.FINISH_REASON_LENGTH
def test_inline_stream_cross_thread_interrupt_aborts_promptly(stalling_wire, monkeypatch):
diff --git a/tests/agent/test_streaming.py b/tests/agent/test_streaming.py
index d40f0a65291..480e47f77ef 100644
--- a/tests/agent/test_streaming.py
+++ b/tests/agent/test_streaming.py
@@ -1346,7 +1346,9 @@ class TestAnthropicStreamCallbacks:
agent._anthropic_client.messages.stream.side_effect = lambda **kwargs: attempts.pop(0)
agent._create_request_anthropic_client = lambda *a, **k: agent._anthropic_client
emitted = []
- agent._fire_stream_delta = lambda text: emitted.append(text)
+ # A real consumer: delivered text is recorded, so the second attempt counts as
+ # partial delivery (a bare _fire_stream_delta override records nothing).
+ agent.stream_delta_callback = emitted.append
response = agent._interruptible_streaming_api_call(
{"model": agent.model, "tools": [{"name": "old_tool", "input_schema": {"type": "object"}}]})
@@ -1516,40 +1518,31 @@ class TestPartialToolCallWarning:
)
- @patch("run_agent.AIAgent._create_request_openai_client")
- @patch("run_agent.AIAgent._close_request_openai_client")
- def test_empty_partial_stream_stub_stays_empty_for_loop_guard(
- self, mock_close, mock_create,
- ):
- """Stream dies with 0 recovered chars and no tool call → the stub
- keeps its empty content ON PURPOSE.
-
- The conversation loop's truncation path detects an EMPTY
- partial-stream stub (PARTIAL_STREAM_STUB_ID + no content) and skips
- appending it to history entirely — only the continuation nudge is
- sent (the #68041 class fix). An earlier iteration substituted
- '[response interrupted]' placeholder text HERE, which defeated that
- guard: the stub no longer looked empty, entered history, and the
- placeholder leaked into the stitched final response. Transcripts
- that already carry a persisted empty turn are healed at the send
- boundary by repair_empty_non_final_messages instead.
- """
+ @staticmethod
+ def _zero_char_agent(mock_create, attempts_that_die: int):
+ """Real streaming helper; the stream dies after a whitespace-only delta (nothing
+ visible reaches the consumer) on the first ``attempts_that_die`` attempts."""
from run_agent import AIAgent
- from hermes_constants import PARTIAL_STREAM_STUB_ID
+ import httpx
- class _StallError(RuntimeError):
- pass
+ calls = {"n": 0}
- def _stalling_stream():
- yield _make_stream_chunk(content="partial token")
- raise _StallError("simulated upstream stall after a delta")
+ def _create(*a, **kw):
+ calls["n"] += 1
+ attempt = calls["n"]
+
+ def _stream():
+ if attempt <= attempts_that_die:
+ yield _make_stream_chunk(content=" \n")
+ raise httpx.RemoteProtocolError("peer closed connection without sending complete message body")
+ yield _make_stream_chunk(content="Recovered answer.")
+ yield _make_stream_chunk(finish_reason="stop")
+
+ return _stream()
mock_client = MagicMock()
- mock_client.chat.completions.create.side_effect = (
- lambda *a, **kw: _stalling_stream()
- )
+ mock_client.chat.completions.create.side_effect = _create
mock_create.return_value = mock_client
-
agent = AIAgent(
api_key="test-key",
base_url="https://openrouter.ai/api/v1",
@@ -1560,32 +1553,39 @@ class TestPartialToolCallWarning:
)
agent.api_mode = "chat_completions"
agent._interrupt_requested = False
- agent._fire_stream_delta = lambda text: None
- # Empty recovered text — the exact "0 chars recovered, no tool call"
- # production condition.
- agent._current_streamed_assistant_text = ""
+ agent.stream_delta_callback = lambda text: None # a real consumer; the delta is whitespace-only
+ return agent, calls
- import os as _os
- _prev = _os.environ.get("HERMES_STREAM_RETRIES")
- _os.environ["HERMES_STREAM_RETRIES"] = "0"
- try:
+ @patch("run_agent.AIAgent._create_request_openai_client")
+ @patch("run_agent.AIAgent._close_request_openai_client")
+ def test_zero_char_partial_stream_retries_instead_of_empty_stub(self, mock_close, mock_create):
+ """A stream that dies before any VISIBLE text reached the user is undelivered, not
+ "partial delivery": the same request is retried (nothing to duplicate) instead of
+ returning an empty length stub that makes the loop ask the model to continue from
+ nowhere — which repeated the lost step (#112419)."""
+ from hermes_constants import PARTIAL_STREAM_STUB_ID
+
+ agent, calls = self._zero_char_agent(mock_create, attempts_that_die=1)
+ with patch.dict("os.environ", {"HERMES_STREAM_RETRIES": "1"}):
response = agent._interruptible_streaming_api_call({})
- finally:
- if _prev is None:
- _os.environ.pop("HERMES_STREAM_RETRIES", None)
- else:
- _os.environ["HERMES_STREAM_RETRIES"] = _prev
- # The stub must be RECOGNIZABLY empty so the loop guard can skip it.
- assert getattr(response, "id", "") == PARTIAL_STREAM_STUB_ID
- content = response.choices[0].message.content
- assert not content, (
- f"Empty-partial-stream stub must keep empty content so the "
- f"conversation loop's empty-stub guard can detect and skip it — "
- f"substituted text defeats the guard and leaks into the final "
- f"response. Got content={content!r}"
- )
- assert response.choices[0].message.tool_calls is None
+ assert calls["n"] == 2
+ assert getattr(response, "id", "") != PARTIAL_STREAM_STUB_ID
+ assert response.choices[0].finish_reason == "stop"
+ assert response.choices[0].message.content == "Recovered answer."
+
+ @patch("run_agent.AIAgent._create_request_openai_client")
+ @patch("run_agent.AIAgent._close_request_openai_client")
+ def test_zero_char_partial_stream_exhausted_raises_to_main_loop(self, mock_close, mock_create):
+ """Retries exhausted with still 0 visible chars: the stream error propagates so the
+ conversation loop's fallback/backoff owns it — never an empty stub, never
+ placeholder text (#68041) that would leak into the stitched response."""
+ import httpx
+
+ agent, calls = self._zero_char_agent(mock_create, attempts_that_die=99)
+ with patch.dict("os.environ", {"HERMES_STREAM_RETRIES": "0"}), pytest.raises(httpx.RemoteProtocolError):
+ agent._interruptible_streaming_api_call({})
+ assert calls["n"] == 1
class TestSilentRetryMidToolCall: