Skip to content

The agent that grows with you

refactor(agent): move dead-connection sweep into a runtime-helpers sibling

Brooklyn Nicholson82732650a18f
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index d5f4c61d26a..257d1ed5af1 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -3690,93 +3690,6 @@ def _iter_pool_sockets(client: Any):
yield sock
-def _socket_is_dead(sock) -> bool:
- """Probe socket health with a non-blocking recv peek."""
- import socket as _socket
- try:
- sock.setblocking(False)
- return sock.recv(1, _socket.MSG_PEEK | _socket.MSG_DONTWAIT) == b""
- except BlockingIOError:
- return False # no data available: socket is healthy
- except OSError:
- return True
- finally:
- with contextlib.suppress(OSError):
- sock.setblocking(True)
-
-
-def _count_dead_pool_sockets(client: Any) -> int:
- """Return the number of sockets in ``client``'s pool that have reached EOF (CLOSE-WAIT)."""
- return sum(1 for sock in _iter_pool_sockets(client) if _socket_is_dead(sock))
-
-
-def cleanup_dead_connections(agent) -> bool:
- """Detect and clean up dead TCP connections owned by an agent.
-
- Long-lived chat-completion turns use a cached per-request OpenAI client
- for sequential calls, while ``agent.client`` remains the primary client
- used for runtime rebuilds and provider management. Inspect both pools:
- a provider FIN on the cached client otherwise stays in CLOSE-WAIT until
- session teardown and can be handed back to the next request.
-
- Dead sockets on the primary client rebuild that client. Dead sockets on
- the request cache go through the cache's ownership-aware teardown hook so
- an in-flight worker is aborted safely and an idle client is closed by its
- owner. Returns True if dead connections were found and cleaned up.
- """
- primary = getattr(agent, "client", None)
- cache = getattr(agent, "_request_client_cache", None)
- request_client = cache.get("client") if isinstance(cache, dict) else None
-
- clients: list[tuple[str, Any]] = []
- if primary is not None:
- clients.append(("primary", primary))
- if request_client is not None and request_client is not primary:
- clients.append(("request", request_client))
- if not clients:
- return False
-
- dead_clients: list[tuple[str, Any, int]] = []
- for label, client in clients:
- try:
- dead_count = _count_dead_pool_sockets(client)
- if dead_count:
- dead_clients.append((label, client, dead_count))
- except Exception as exc:
- _ra().logger.debug(
- "Dead connection check error for %s client: %s",
- label,
- exc,
- )
-
- if not dead_clients:
- return False
-
- total_dead = sum(count for _label, _client, count in dead_clients)
- labels = ", ".join(label for label, _client, _count in dead_clients)
- _ra().logger.warning(
- "Found %d dead connection(s) in %s client pool(s) — cleaning up",
- total_dead,
- labels,
- )
-
- for label, _client, _count in dead_clients:
- try:
- if label == "primary":
- agent._replace_primary_openai_client(reason="dead_connection_cleanup")
- else:
- # This hook clears the cache and chooses close() vs socket
- # shutdown based on whether another worker owns the client.
- agent._close_cached_request_openai_client(reason="dead_connection_cleanup")
- except Exception as exc:
- _ra().logger.debug(
- "Dead connection cleanup error for %s client: %s",
- label,
- exc,
- )
- return True
-
-
def _set_reset_from_retry_after(context: Dict[str, Any], retry_after: Any) -> None:
if "reset_at" in context:
return
@@ -3959,7 +3872,7 @@ __all__ = [
"dump_api_request_debug", "prompt_caching_disabled_from_config", "blank_cache_policy_stub",
"plan_cache_sections_for_destination", "anthropic_prompt_cache_policy", "create_openai_client",
"switch_model", "invoke_tool", "repair_tool_call", "sanitize_api_messages",
- "looks_like_codex_intermediate_ack", "copy_reasoning_content_for_api", "cleanup_dead_connections",
+ "looks_like_codex_intermediate_ack", "copy_reasoning_content_for_api",
"extract_api_error_context", "apply_pending_steer_to_tool_results", "_iter_pool_sockets",
"force_close_tcp_sockets",
]
diff --git a/agent/agent_runtime_helpers_dead_connections.py b/agent/agent_runtime_helpers_dead_connections.py
new file mode 100644
index 00000000000..60e436d8390
--- /dev/null
+++ b/agent/agent_runtime_helpers_dead_connections.py
@@ -0,0 +1,93 @@
+"""Pre-turn dead-connection sweep over an agent's OpenAI client pools (primary + cached request
+client). Sibling of ``agent.agent_runtime_helpers``, which owns the pool-socket walk."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+from typing import Any
+
+logger = logging.getLogger("run_agent") # origin module's logger name: log records / caplog filters unchanged
+
+
+def _socket_is_dead(sock) -> bool:
+ """Probe socket health with a non-blocking recv peek."""
+ import socket as _socket
+ try:
+ sock.setblocking(False)
+ return sock.recv(1, _socket.MSG_PEEK | _socket.MSG_DONTWAIT) == b""
+ except BlockingIOError:
+ return False # no data available: socket is healthy
+ except OSError:
+ return True
+ finally:
+ with contextlib.suppress(OSError):
+ sock.setblocking(True)
+
+
+def _count_dead_pool_sockets(client: Any) -> int:
+ """Return the number of sockets in ``client``'s pool that have reached EOF (CLOSE-WAIT)."""
+ from agent.agent_runtime_helpers import _iter_pool_sockets
+ return sum(1 for sock in _iter_pool_sockets(client) if _socket_is_dead(sock))
+
+
+def cleanup_dead_connections(agent) -> bool:
+ """Detect and clean up dead TCP connections owned by an agent.
+
+ Long-lived chat-completion turns use a cached per-request OpenAI client
+ for sequential calls, while ``agent.client`` remains the primary client
+ used for runtime rebuilds and provider management. Inspect both pools:
+ a provider FIN on the cached client otherwise stays in CLOSE-WAIT until
+ session teardown and can be handed back to the next request.
+
+ Dead sockets on the primary client rebuild that client. Dead sockets on
+ the request cache go through the cache's ownership-aware teardown hook so
+ an in-flight worker is aborted safely and an idle client is closed by its
+ owner. Returns True if dead connections were found and cleaned up.
+ """
+ primary = getattr(agent, "client", None)
+ cache = getattr(agent, "_request_client_cache", None)
+ request_client = cache.get("client") if isinstance(cache, dict) else None
+
+ clients: list[tuple[str, Any]] = []
+ if primary is not None:
+ clients.append(("primary", primary))
+ if request_client is not None and request_client is not primary:
+ clients.append(("request", request_client))
+ if not clients:
+ return False
+
+ dead_clients: list[tuple[str, Any, int]] = []
+ for label, client in clients:
+ try:
+ dead_count = _count_dead_pool_sockets(client)
+ if dead_count:
+ dead_clients.append((label, client, dead_count))
+ except Exception:
+ # Best-effort probe over private httpcore internals: one client's failure must not
+ # skip the other's check or abort the turn.
+ logger.debug("Dead connection check error for %s client", label, exc_info=True)
+
+ if not dead_clients:
+ return False
+
+ total_dead = sum(count for _label, _client, count in dead_clients)
+ labels = ", ".join(label for label, _client, _count in dead_clients)
+ logger.warning(
+ "Found %d dead connection(s) in %s client pool(s) — cleaning up",
+ total_dead,
+ labels,
+ )
+
+ for label, _client, _count in dead_clients:
+ try:
+ if label == "primary":
+ agent._replace_primary_openai_client(reason="dead_connection_cleanup")
+ else:
+ # This hook clears the cache and chooses close() vs socket
+ # shutdown based on whether another worker owns the client.
+ agent._close_cached_request_openai_client(reason="dead_connection_cleanup")
+ except Exception:
+ # Cleaning one pool must not stop the other pool's cleanup.
+ logger.debug("Dead connection cleanup error for %s client", label, exc_info=True)
+ return True
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index 152a378fe5a..2842dfe0362 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -191,7 +191,7 @@ class ClientLifecycleMixin:
_create_openai_client = _forward("agent.agent_runtime_helpers", "create_openai_client")
_force_close_tcp_sockets = _forward_static("agent.agent_runtime_helpers", "force_close_tcp_sockets")
- _cleanup_dead_connections = _forward("agent.agent_runtime_helpers", "cleanup_dead_connections")
+ _cleanup_dead_connections = _forward("agent.agent_runtime_helpers_dead_connections", "cleanup_dead_connections")
_run_codex_stream = _forward("agent.codex_runtime", "run_codex_stream")
_recover_with_credential_pool = _forward("agent.agent_runtime_helpers", "recover_with_credential_pool")
diff --git a/tests/agent/test_dead_connection_cleanup.py b/tests/agent/test_dead_connection_cleanup.py
index 05f3ba169d0..de64e982bd7 100644
--- a/tests/agent/test_dead_connection_cleanup.py
+++ b/tests/agent/test_dead_connection_cleanup.py
@@ -3,7 +3,7 @@
from types import SimpleNamespace
from unittest.mock import MagicMock
-from agent.agent_runtime_helpers import cleanup_dead_connections
+from agent.agent_runtime_helpers_dead_connections import cleanup_dead_connections
class _ProbeSocket: