The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): abandon on the first kill when the limit is 1; retry, not stub, after invisible deltas
unsupportedpastelsad8101333ac3
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex c7455371c96..ae964c9f32b 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3594,22 +3594,7 @@ 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+ _partial_tool_in_flight = self._forget_invisible_deltas(e)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@@ -3974,6 +3959,7 @@ class _StreamingCall(StreamingWaitMonitor):raise InterruptedError("Agent interrupted during streaming API call (post-worker)")if self._abandon_error is not None: # the abandoned worker may still write into ``result``self.result = {**self.result, "response": None, "error": self._abandon_error}+ self._forget_invisible_deltas(self._abandon_error) # nothing visible: retry, not a stubif self.result["error"] is not None:if self.deltas_were_sent["yes"]:return self._partial_stream_stub()diff --git a/agent/chat_completion_stream_monitor.py b/agent/chat_completion_stream_monitor.pyindex 920848ca6ae..7f5ca23673c 100644--- a/agent/chat_completion_stream_monitor.py+++ b/agent/chat_completion_stream_monitor.py@@ -33,13 +33,30 @@ class StreamingWaitMonitor:rekill = bool(attempt) and attempt == self._last_killed_attemptself._last_killed_attempt = attemptself._same_attempt_kills = self._same_attempt_kills + 1 if rekill else 1- if rekill and self.worker is not None and self._same_attempt_kills >= env_int(- "HERMES_STREAM_STALE_ABANDON_KILLS", 3):+ limit = env_int("HERMES_STREAM_STALE_ABANDON_KILLS", 3) # 0 or less: never abandon+ if attempt and self.worker is not None and 0 < limit <= self._same_attempt_kills:self._abandon_wedged_worker(elapsed, attempt)returnself.agent._emit_diagnostic_wait(f"⚠ no output from provider for {int(elapsed)}s — reconnecting...")self.agent._touch_activity(f"stale stream detected after {int(elapsed)}s, reconnecting")+ def _forget_invisible_deltas(self, exc) -> bool:+ """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). Reset delivery so the failure is handled as undelivered (retry+ the unchanged request) instead. Returns whether a partial tool call is in flight."""+ tool_in_flight = bool(self.result.get("partial_tool_names")) or self.provider_tool_in_flight["yes"]+ if self.deltas_were_sent["yes"] and not tool_in_flight and not self._visible_text_delivered():+ logging.getLogger("agent.chat_completion_helpers").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", exc)+ self._quiet(self.agent._reset_stream_delivery_tracking)+ self.deltas_were_sent["yes"] = False+ self.first_delta_fired["done"] = False+ return tool_in_flight+def _abandon_wedged_worker(self, elapsed: float, attempt: int) -> None:"""Like the /stop path, leave the (daemon) worker behind and end this call with aretryable timeout; ``run()`` discards anything the worker writes later."""diff --git a/tests/agent/test_stream_stale_abandon.py b/tests/agent/test_stream_stale_abandon.pyindex 603222c87d1..c8772f63970 100644--- a/tests/agent/test_stream_stale_abandon.py+++ b/tests/agent/test_stream_stale_abandon.py@@ -201,3 +201,46 @@ def test_turn_retries_an_abandoned_stream_and_completes(monkeypatch):assert len(calls) == 2assert result.get("completed") is True and result.get("final_response") == "done after retry"assert len(session_ends) == 1 and session_ends[0]["completed"] is True++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_abandon_limit_of_one_abandons_on_the_first_kill(wedged, monkeypatch, caplog):+ monkeypatch.setenv("HERMES_STREAM_STALE_ABANDON_KILLS", "1")+ with caplog.at_level("WARNING"):+ caller, outcome = _call_in_thread(wedged)+ caller.join(timeout=10.0)++ assert not caller.is_alive()+ assert isinstance(outcome.get("error"), TimeoutError), outcome+ assert _log_count(caplog, "Stream stale for") == 1, "a limit of one must not wait a second window"+ assert _log_count(caplog, "abandoning the request") == 1++[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")+def test_abandon_after_invisible_deltas_retries_instead_of_an_empty_stub(monkeypatch):+ """Whitespace-only text reached no consumer before the worker wedged: nothing was+ delivered, so the abandon must surface as a retryable error, not an empty partial stub."""+ monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "0.3")+ monkeypatch.setenv("HERMES_STREAM_STALE_GIVEUP", "5")+ agent = _anthropic_agent()+ agent._abort_request_anthropic_client = lambda client, reason=None: None+ release = threading.Event()++ def _events():+ yield SimpleNamespace(type="content_block_start", index=0,+ content_block=SimpleNamespace(type="text", text=""))+ yield SimpleNamespace(type="content_block_delta", index=0,+ delta=SimpleNamespace(type="text_delta", text=" \n"))+ release.wait(timeout=30.0)+ yield SimpleNamespace(type="message_stop")++ agent._anthropic_client.messages.stream.side_effect = _stream_of(_events)+ try:+ caller, outcome = _call_in_thread(agent)+ caller.join(timeout=10.0)+ finally:+ release.set()++ assert not caller.is_alive()+ assert "value" not in outcome, f"an empty partial stub was returned: {outcome.get('value')!r}"+ assert isinstance(outcome.get("error"), TimeoutError), outcome