The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(stream): distinguish clean-EOF no-finish_reason from a transport drop
chelsealonga2a19bcc77b5
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex bc2ea9c30d1..e912eb0bbb3 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2413,7 +2413,7 @@ def cleanup_task_resources(agent, task_id: str) -> None:def _build_partial_stream_stub(role, full_content, full_reasoning, model_name, usage_obj, *,- dropped_tool_names=None, overflow_terminal=False, api_mode=None):+ dropped_tool_names=None, overflow_terminal=False, api_mode=None, clean_eof=False):"""Stub for an SSE stream that ended without ``finish_reason`` afterdelivering content. Tagged ``PARTIAL_STREAM_STUB_ID`` + ``FINISH_REASON_LENGTH``so the loop enters its continuation/retry path instead of accepting@@ -2429,6 +2429,12 @@ def _build_partial_stream_stub(role, full_content, full_reasoning, model_name, uand the loop continues instead of entering the invalid-response retry ladder(#45908). Empty content keeps one empty text block: validate_response rejectsan empty list for ``max_tokens``.++ ``clean_eof``: the stream ended with no transport exception and no+ ``finish_reason`` (server/intermediary closed cleanly). Only the two+ clean-EOF sites in ``_finish_chat_stream`` pass True; the stub built after a+ real transport exception keeps False so the loop can word the two failure+ modes differently (#102766)."""if api_mode == "anthropic_messages":return SimpleNamespace(@@ -2442,6 +2448,7 @@ def _build_partial_stream_stub(role, full_content, full_reasoning, model_name, uusage=usage_obj,_dropped_tool_names=dropped_tool_names or None,_overflow_terminal=overflow_terminal,+ _clean_eof=clean_eof,)return SimpleNamespace(id=PARTIAL_STREAM_STUB_ID,@@ -2455,6 +2462,7 @@ def _build_partial_stream_stub(role, full_content, full_reasoning, model_name, uusage=usage_obj,_dropped_tool_names=dropped_tool_names or None,_overflow_terminal=overflow_terminal,+ _clean_eof=clean_eof,)@@ -3168,6 +3176,8 @@ class _StreamingCall(StreamingWaitMonitor):if not chunk.choices:usage, finish_reason = self._choiceless_chunk(chunk, finish_reason)usage_obj = usage or usage_obj+ if finish_reason and isinstance(self.clients.diag, dict):+ self.clients.diag["finish_reason_seen"] = True # #102766continuechoice = chunk.choices[0]@@ -3175,6 +3185,8 @@ class _StreamingCall(StreamingWaitMonitor):# Read finish_reason/usage BEFORE any content-shape `continue`: the SSE-echo# guard can swallow a merged finish chunk (vLLM standalone ':' tokens).finish_reason = _normalize_finish_reason(getattr(choice, "finish_reason", None)) or finish_reason+ if finish_reason and isinstance(self.clients.diag, dict):+ self.clients.diag["finish_reason_seen"] = True # #102766if hasattr(chunk, "usage") and chunk.usage:usage_obj = chunk.usage@@ -3332,19 +3344,22 @@ class _StreamingCall(StreamingWaitMonitor):# upstream dropped mid tool-call, and stamping "length" burns 3 useless retries._dropped_names = [(tool_calls_acc[idx]["function"]["name"] or "?") for idx in sorted(tool_calls_acc)]logger.warning(- "Stream ended with no finish_reason while a tool call's arguments were still incomplete "- "(tools=%s); treating as a mid-tool-call stream drop, not an output-length truncation.",+ "Clean EOF, no finish_reason: server ended the stream (no transport exception) while a tool "+ "call's arguments were still incomplete (tools=%s). Not a network drop and not an "+ "output-length truncation.",_dropped_names)return _build_partial_stream_stub(- role, full_content, full_reasoning, model_name, usage_obj, dropped_tool_names=_dropped_names or None)+ role, full_content, full_reasoning, model_name, usage_obj, dropped_tool_names=_dropped_names or None,+ clean_eof=True)if finish_reason is None and (content_parts or reasoning_parts) and not tool_calls_acc and usage_obj is None:# Text-only (or reasoning-only) drop: otherwise the partial text is stamped "stop"# and the next step is lost — for reasoning-only, the clean-stop promotion in# finish_text_response would then surface a truncated thought as the answer.# A usage object proves the provider finished (include_usage's final chunk).logger.warning(- "Stream ended with no finish_reason after delivering text with no tool calls; treating as a mid-stream drop.")- return _build_partial_stream_stub(role, full_content, full_reasoning, model_name, usage_obj)+ "Clean EOF, no finish_reason: server ended the stream (no transport exception) after delivering "+ "text with no tool calls. Not a network drop.")+ return _build_partial_stream_stub(role, full_content, full_reasoning, model_name, usage_obj, clean_eof=True)effective_finish_reason = "length" if has_truncated_tool_args else (finish_reason or "stop")provider_stream_error = _provider_stream_error_from_text(full_content or "", effective_finish_reason, response=getattr(stream, "response", None))diff --git a/agent/stream_diag.py b/agent/stream_diag.pyindex 2ba3d12422b..1775cf3f5ee 100644--- a/agent/stream_diag.py+++ b/agent/stream_diag.py@@ -27,6 +27,9 @@ def stream_diag_init() -> Dict[str, Any]:return {"started_at": time.time(), "first_chunk_at": None, "chunks": 0, "bytes": 0,"headers": {}, "http_status": None, "serving_provider": None,+ # True once a terminal finish_reason is seen on this attempt: tells a mid-flight+ # transport failure (False) from an error raised after completion (#102766).+ "finish_reason_seen": False,}@@ -74,11 +77,12 @@ def flatten_exception_chain(error: BaseException) -> str:def _diag_fields(diag: Optional[Dict[str, Any]]) -> tuple:- """(http_status, bytes, chunks, elapsed, ttfb, serving_provider, upstream) for the retry log line;- ``-`` when unknown."""+ """(http_status, bytes, chunks, elapsed, ttfb, serving_provider, finish_reason_seen, upstream)+ for the retry log line; ``-`` when unknown."""_bytes = _chunks = 0_elapsed = 0.0_ttfb = _headers_repr = _http_status = _serving_provider = "-"+ _finish_reason_seen = Falseif isinstance(diag, dict):try:_now = time.time()@@ -96,9 +100,10 @@ def _diag_fields(diag: Optional[Dict[str, Any]]) -> tuple:_http_status = str(diag.get("http_status"))if diag.get("serving_provider"):_serving_provider = str(diag["serving_provider"])+ _finish_reason_seen = bool(diag.get("finish_reason_seen"))except Exception:pass- return _http_status, _bytes, _chunks, _elapsed, _ttfb, _serving_provider, _headers_repr+ return _http_status, _bytes, _chunks, _elapsed, _ttfb, _serving_provider, _finish_reason_seen, _headers_reprdef log_stream_retry(@@ -127,7 +132,7 @@ def log_stream_retry(logger.warning("Stream %s on attempt %s/%s — retrying. subagent_id=%s depth=%s provider=%s base_url=%s ""error_type=%s error=%s chain=%s http_status=%s bytes=%d chunks=%d elapsed=%.2fs ttfb=%s "- "serving_provider=%s upstream=[%s]",+ "serving_provider=%s finish_reason_seen=%s upstream=[%s]",kind, attempt, max_attempts,getattr(agent, "_subagent_id", None) or "-", getattr(agent, "_delegate_depth", 0),agent.provider or "-", agent.base_url or "-",diff --git a/agent/turn_truncation.py b/agent/turn_truncation.pyindex 61c44e56fc1..10bfe02c955 100644--- a/agent/turn_truncation.py+++ b/agent/turn_truncation.py@@ -452,6 +452,9 @@ def recover_from_truncation()st.window_filled = _prompt_filled_window(agent, response)agent._vprint(+ f"{agent.log_prefix}⚠️ Response truncated — server ended the stream without ever sending "+ f"finish_reason (not a network drop)"+ if st.is_stub and getattr(response, "_clean_eof", False) elsef"{agent.log_prefix}⚠️ Response truncated — stream ended before completion"if st.is_stub elsef"{agent.log_prefix}⚠️ Response truncated (finish_reason='length') - the prompt filled the "diff --git a/tests/agent/test_partial_stream_finish_reason.py b/tests/agent/test_partial_stream_finish_reason.pyindex a8d57c32d74..e678256bc20 100644--- a/tests/agent/test_partial_stream_finish_reason.py+++ b/tests/agent/test_partial_stream_finish_reason.py@@ -89,6 +89,12 @@ class TestPartialStreamStubFinishReason:)assert response.choices[0].message.content == "Here's my answer so far"assert response.choices[0].message.tool_calls is None+ assert getattr(response, "_clean_eof", False) is False, (+ "A stub built after a real transport exception (RuntimeError "+ "here) must NOT be tagged _clean_eof — that tag is reserved "+ "for a stream that ended with no exception and no "+ "finish_reason, a distinct failure class (#102766)."+ )class TestTerminalChunkFenceException:@@ -179,6 +185,11 @@ class TestTerminalChunkFenceException:assert response.id == PARTIAL_STREAM_STUB_IDassert response.choices[0].finish_reason == FINISH_REASON_LENGTH+ assert response._clean_eof is True, (+ "The stream ended with no exception and no finish_reason — "+ "that is the clean-EOF class the fix for #102766 must tag "+ "distinctly from a genuine transport drop."+ )# ── Clean stream-end mid-tool-call (no exception, no finish_reason) ─────────@@ -236,6 +247,11 @@ class TestCleanStreamEndMidToolCall:"Incomplete tool args must never auto-execute.")assert getattr(response, "_dropped_tool_names", None) == ["execute_code"]+ assert response._clean_eof is True, (+ "No exception was raised and no finish_reason ever arrived — "+ "this is the clean-EOF class the fix for #102766 must tag "+ "distinctly from a genuine transport drop."+ )# ── Clean stream-end before any argument byte arrives (#80498) ─────────────diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 088e7536349..ad8b64f0d65 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -4324,6 +4324,73 @@ class TestRunConversation:assert result["failure_reason"] == "truncated"mock_handle_function_call.assert_not_called()+ def test_clean_eof_stub_gets_distinct_truncation_message(self, agent):+ """#102766: a clean-EOF partial-stream stub (stream ended with no+ transport exception and no finish_reason) must not print the same+ 'stream ended before completion' wording used for a genuine+ network drop — that wording sends the user chasing a network+ problem a stream_diag log with finish_reason_seen=False would+ already have ruled out."""+ from hermes_constants import PARTIAL_STREAM_STUB_ID++ self._setup_agent(agent)+ bad_tc = _mock_tool_call(+ name="write_file",+ arguments='{"path":"report.md","content":"partial',+ call_id="c1",+ )+ resp = _mock_response(content="", finish_reason="length", tool_calls=[bad_tc])+ resp.id = PARTIAL_STREAM_STUB_ID+ resp._clean_eof = True+ agent.client.chat.completions.create.return_value = resp++ printed = []+ agent._print_fn = lambda *a, **k: printed.append(" ".join(str(x) for x in a))++ with (+ patch("run_agent.handle_function_call"),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ agent.run_conversation("write the report")++ text = " ".join(printed)+ assert "server ended the stream without ever sending finish_reason" in text+ assert "stream ended before completion" not in text++ def test_transport_drop_stub_keeps_original_truncation_message(self, agent):+ """Companion to the clean-EOF test above: a stub NOT tagged+ _clean_eof (the shape built after a real transport exception) must+ keep printing the original 'stream ended before completion'+ wording — issue #102766 asks that this case's existing wording+ stay as-is, only the clean-EOF case gets new wording."""+ from hermes_constants import PARTIAL_STREAM_STUB_ID++ self._setup_agent(agent)+ bad_tc = _mock_tool_call(+ name="write_file",+ arguments='{"path":"report.md","content":"partial',+ call_id="c1",+ )+ resp = _mock_response(content="", finish_reason="length", tool_calls=[bad_tc])+ resp.id = PARTIAL_STREAM_STUB_ID+ agent.client.chat.completions.create.return_value = resp++ printed = []+ agent._print_fn = lambda *a, **k: printed.append(" ".join(str(x) for x in a))++ with (+ patch("run_agent.handle_function_call"),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ agent.run_conversation("write the report")++ text = " ".join(printed)+ assert "stream ended before completion" in text+def test_truncated_tool_call_retries_once_before_refusing(self, agent):"""When tool call args are truncated, the agent retries the API call(up to 3 times). If a retry succeeds (valid JSON args), tool execution