Skip to content

The agent that grows with you

fix(agent): clean cached request pool sockets (#91286)

Kenshicf6fada002d0
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 16a95fb3519..d5f4c61d26a 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -3705,20 +3705,76 @@ def _socket_is_dead(sock) -> bool:
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:
- """Force-close and rebuild the primary client if its pool has dead sockets (CLOSE-WAIT, errors); returns True if cleaned."""
- client = getattr(agent, "client", None)
- if client is None:
+ """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
- try:
- dead_count = sum(1 for sock in _iter_pool_sockets(client) if _socket_is_dead(sock))
- if dead_count > 0:
- _ra().logger.warning("Found %d dead connection(s) in client pool — rebuilding client", dead_count)
- agent._replace_primary_openai_client(reason="dead_connection_cleanup")
- return True
- except Exception as exc:
- _ra().logger.debug("Dead connection check error: %s", exc)
- 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:
diff --git a/tests/agent/test_dead_connection_cleanup.py b/tests/agent/test_dead_connection_cleanup.py
new file mode 100644
index 00000000000..05f3ba169d0
--- /dev/null
+++ b/tests/agent/test_dead_connection_cleanup.py
@@ -0,0 +1,65 @@
+"""Regression tests for stale provider sockets in agent-owned client pools."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+from agent.agent_runtime_helpers import cleanup_dead_connections
+
+
+class _ProbeSocket:
+ def __init__(self, *, dead):
+ self.dead = dead
+
+ def setblocking(self, _enabled):
+ pass
+
+ def recv(self, _size, _flags):
+ if self.dead:
+ return b""
+ raise BlockingIOError
+
+
+def _client_with_socket(sock):
+ stream = SimpleNamespace(_sock=sock)
+ http11 = SimpleNamespace(_network_stream=stream)
+ pool_entry = SimpleNamespace(_connection=http11)
+ pool = SimpleNamespace(_connections=[pool_entry])
+ transport = SimpleNamespace(_pool=pool)
+ http_client = SimpleNamespace(_transport=transport)
+ return SimpleNamespace(_client=http_client)
+
+
+def test_cleanup_retires_dead_cached_request_client():
+ """A half-closed request pool must not be hidden by a healthy primary."""
+ primary = _client_with_socket(_ProbeSocket(dead=False))
+ request = _client_with_socket(_ProbeSocket(dead=True))
+ agent = SimpleNamespace(
+ client=primary,
+ _request_client_cache={"client": request},
+ _replace_primary_openai_client=MagicMock(),
+ _close_cached_request_openai_client=MagicMock(),
+ )
+
+ assert cleanup_dead_connections(agent) is True
+ agent._replace_primary_openai_client.assert_not_called()
+ agent._close_cached_request_openai_client.assert_called_once_with(
+ reason="dead_connection_cleanup"
+ )
+
+
+def test_cleanup_rebuilds_dead_primary_client():
+ """The existing primary-client recovery remains the cleanup path."""
+ primary = _client_with_socket(_ProbeSocket(dead=True))
+ request = _client_with_socket(_ProbeSocket(dead=False))
+ agent = SimpleNamespace(
+ client=primary,
+ _request_client_cache={"client": request},
+ _replace_primary_openai_client=MagicMock(),
+ _close_cached_request_openai_client=MagicMock(),
+ )
+
+ assert cleanup_dead_connections(agent) is True
+ agent._replace_primary_openai_client.assert_called_once_with(
+ reason="dead_connection_cleanup"
+ )
+ agent._close_cached_request_openai_client.assert_not_called()