The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): share the shutdown-only socket primitives with the pool sweep
kshitijk4poorb82c79ac50b4
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 20c4be45478..cd3e768e191 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -1203,7 +1203,7 @@ def restore_primary_runtime(agent) -> bool:# Transient transport failures worth one more attempt with a rebuilt client / connection pool._TRANSIENT_TRANSPORT_ERRORS = frozenset({- "ReadTimeout", "ConnectTimeout", "PoolTimeout", "ConnectError", "RemoteProtocolError",+ "ReadTimeout", "ConnectTimeout", "PoolTimeout", "ConnectError", "ReadError", "RemoteProtocolError","APIConnectionError", "APITimeoutError",})_INLINE_REASONING_PATTERNS = tuple(@@ -3023,10 +3023,17 @@ def _connection_candidates(conn: Any):yield objfor attr in ("_connection", "_stream", "_httpcore_stream"):nxt = getattr(obj, attr, None)- if nxt is not None and id(nxt) not in seen:+ if nxt is not None:stack.append(nxt)+def _socket_from_candidate(candidate: Any):+ """Raw socket behind a connection/stream wrapper yielded by ``_connection_candidates``."""+ stream = getattr(candidate, "_network_stream", None) or getattr(candidate, "_stream", None)+ sock = _socket_from_stream(stream) if stream is not None else None+ return sock if sock is not None else _socket_from_stream(candidate)++def _socket_from_stream(stream: Any):"""Raw socket behind an httpcore network stream (several backends), or None."""sock = getattr(stream, "_sock", None)@@ -3077,8 +3084,7 @@ def _iter_pool_sockets(client: Any):connections.append(conn)for conn in connections:for candidate in _connection_candidates(conn):- stream = getattr(candidate, "_network_stream", None) or getattr(candidate, "_stream", None)- sock = _socket_from_stream(stream) if stream is not None else None+ sock = _socket_from_candidate(candidate)if sock is not None and id(sock) not in seen:seen.add(id(sock))yield sock@@ -3215,24 +3221,30 @@ def apply_pending_steer_to_tool_results(agent, messages: list, num_tool_msgs: in)-def force_close_tcp_sockets(client: Any) -> int:- """Abort in-flight TCP I/O via ``shutdown(SHUT_RDWR)`` WITHOUT closing FDs. ``close()`` from- a non-owner thread is unsafe: the SSL BIO caches the raw FD, the kernel recycles it, and a- flushed TLS record lands in the wrong file (once clobbered a SQLite header). ``shutdown()``- is FD-safe from any thread. Returns the count (logged as ``tcp_force_closed=N``)."""+def _shutdown_socket(sock: Any) -> None:+ """``shutdown(SHUT_RDWR)`` WITHOUT closing the FD. ``close()`` from a non-owner thread is+ unsafe: the SSL BIO caches the raw FD, the kernel recycles it, and a flushed TLS record lands+ in the wrong file (once clobbered a SQLite header). ``shutdown()`` is FD-safe from any thread.+ Already shut down / not connected / FD invalid are all benign."""import socket as _socket+ try:+ # Clear a blocking timeout so a hung SSL_read notices the shutdown. Still no close().+ settimeout = getattr(sock, "settimeout", None)+ if callable(settimeout):+ with contextlib.suppress(OSError):+ settimeout(0)+ sock.shutdown(_socket.SHUT_RDWR)+ except OSError:+ pass+++def force_close_tcp_sockets(client: Any) -> int:+ """Abort in-flight TCP I/O on every pool socket via ``_shutdown_socket``. Returns the count+ (logged as ``tcp_force_closed=N``)."""shutdown_count = 0try:for sock in _iter_pool_sockets(client):- try:- # Clear a blocking timeout so a hung SSL_read notices the shutdown. Still no close().- settimeout = getattr(sock, "settimeout", None)- if callable(settimeout):- with contextlib.suppress(OSError):- settimeout(0)- sock.shutdown(_socket.SHUT_RDWR)- except OSError:- pass # already shut down / not connected / FD invalid: all benign+ _shutdown_socket(sock)shutdown_count += 1except Exception as exc:_ra().logger.debug("Force-close TCP sockets sweep error: %s", exc)diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex ebef520cb74..946df820107 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3096,11 +3096,8 @@ class _StreamingCall(StreamingWaitMonitor):logger.debug("Streaming worker caught %s after request cancellation — exiting without retry.", type(e).__name__)return False_is_timeout = isinstance(e, (_httpx.ReadTimeout, _httpx.ConnectTimeout, _httpx.PoolTimeout))- # ReadError is the aborted/reset body read (a stale-killed attempt's socket- # was shut down under a parked reader, ECONNRESET mid-body): the retry loop- # owns recovery. Without it an abort-induced read failure ended the turn- # instead of reconnecting — the "no response ... reconnecting" loop with- # no recovery.+ # ReadError: abort/reset mid-body (stale-kill shutdown under a parked reader,+ # ECONNRESET) — the retry loop owns recovery._is_conn_err = isinstance(e, (_httpx.ConnectError, _httpx.ReadError, _httpx.RemoteProtocolError, ConnectionError))_is_stream_parse_err = self.agent._is_provider_stream_parse_error(e)_is_empty_stream = isinstance(e, EmptyStreamError)@@ -3223,38 +3220,21 @@ class _StreamingCall(StreamingWaitMonitor):if response is None or response is not self._attempt_stream_response:returntry:- import socket as _socket- from agent.agent_runtime_helpers import _connection_candidates, _socket_from_stream+ from agent.agent_runtime_helpers import (+ _connection_candidates, _shutdown_socket, _socket_from_candidate,+ )exts = getattr(response, "extensions", None) or {}direct = exts.get("network_stream") if isinstance(exts, dict) else None- stream_obj = getattr(response, "stream", None)- inner = getattr(stream_obj, "_httpcore_stream", None)- if inner is None:- # httpx 0.28 nests one level deeper: BoundSyncStream._stream- # (ResponseStream)._httpcore_stream (httpcore byte stream).- inner = getattr(getattr(stream_obj, "_stream", None), "_httpcore_stream", None)- seen: set = set()- for start in (direct, inner, stream_obj, response):- if start is None or id(start) in seen:+ for start in (direct, getattr(response, "stream", None)):+ if start is None:continue- seen.add(id(start))for candidate in _connection_candidates(start):- net = getattr(candidate, "_network_stream", None) or getattr(candidate, "_stream", None)- sock = _socket_from_stream(net) if net is not None else None- if sock is None:- sock = _socket_from_stream(candidate)+ sock = _socket_from_candidate(candidate)if sock is None:continue- try:- settimeout = getattr(sock, "settimeout", None)- if callable(settimeout):- with contextlib.suppress(OSError):- settimeout(0)- sock.shutdown(_socket.SHUT_RDWR)- logger.info("Shut down the stale stream's socket to unblock the reader "- "(attempt superseded; model=%s).", self.api_kwargs.get("model", "unknown"))- except OSError:- pass # already shut / not connected: benign+ _shutdown_socket(sock)+ logger.info("Shut down the stale stream's socket to unblock the reader "+ "(attempt superseded; model=%s).", self.api_kwargs.get("model", "unknown"))returnlogger.debug("Stale stream socket shutdown found no socket; pool sweep is the only abort")except Exception:diff --git a/tests/agent/test_stream_stale_kill_unwedge.py b/tests/agent/test_stream_stale_kill_unwedge.pyindex a56d3aa409c..d6f52c9565d 100644--- a/tests/agent/test_stream_stale_kill_unwedge.py+++ b/tests/agent/test_stream_stale_kill_unwedge.py@@ -52,7 +52,6 @@ def _recv_shutdown_proof(reader, writer):``settimeout(0)`` then ``shutdown(SHUT_RDWR)`` (which emits FIN), so thepeer must observe EOF. An untouched socket would still be blocking withits default timeout and the peer recv would time out instead."""- assert reader.gettimeout() == 0.0, "helper never reached this socket"writer.settimeout(5)assert writer.recv(1) == b"", "the killed attempt's socket was not shut down"@@ -140,7 +139,7 @@ class _SilentFirstRequest:self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)self.server.daemon_threads = True- threading.Thread(target=self.server.serve_forever, daemon=True).start()+ threading.Thread(target=lambda: self.server.serve_forever(poll_interval=0.05), daemon=True).start()self.base_url = f"http://127.0.0.1:{self.server.server_address[1]}/v1"def close(self):@@ -161,7 +160,7 @@ def test_wedged_stream_unwinds_within_its_stale_budget_and_reconnects(silent_wirever issued and the call only ended at the byte-read timeout (>= 20s here,120s by default). Now the kill unblocks the reader, the abort-induced readerror is transient, and the retry lands."""- monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "2")+ monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "1")monkeypatch.setenv("HERMES_STREAM_RETRIES", "1")monkeypatch.setenv("HERMES_STREAM_READ_TIMEOUT", "20")agent = run_agent.AIAgent(