The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): race IPv6/IPv4 on every startup-path sync connect, not just Codex
liuhao1024298cfd326eed
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 800f216782e..bce03a1d9ac 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -30,7 +30,7 @@ from agent.session_activity import ActivityProvenancefrom agent.model_metadata import (MINIMUM_CONTEXT_LENGTH, fetch_model_metadata, is_local_endpoint, query_ollama_num_ctx)-from agent.process_bootstrap import _install_safe_stdio+from agent.process_bootstrap import _install_safe_stdio, install_happy_eyeballs_socket_connectfrom agent.subdirectory_hints import SubdirectoryHintTrackerfrom agent.think_scrubber import StreamingThinkScrubberfrom agent.tool_guardrails import (@@ -2253,6 +2253,10 @@ def init_agent(load_soul_identity keeps ~/.hermes/SOUL.md as identity regardless."""_install_safe_stdio()+ # Every startup-path sync connect (catalog fetch via urllib, provider warm via+ # requests, sync LLM clients via httpcore) races IPv6/IPv4 instead of stalling+ # serially on a blackholed AAAA route (#114265). Idempotent process-level install.+ install_happy_eyeballs_socket_connect()_params = locals()for _name in _PASSTHROUGH_PARAMS:diff --git a/agent/process_bootstrap.py b/agent/process_bootstrap.pyindex 57745baa567..3fdb2507946 100644--- a/agent/process_bootstrap.py+++ b/agent/process_bootstrap.py@@ -23,6 +23,7 @@ from agent.proxy_bypass import first_proxy_env_value, should_bypass_proxy_OPENAI_CLS_CACHE = None_HAPPY_EYEBALLS_DELAY_SECONDS = 0.25+_SOCKET_CONNECT_RACER_INSTALLED = False# Process-wide pool of sync ``httpx.HTTPTransport`` objects shared by every# keepalive client with the same (verify, proxy, happy-eyeballs) identity.@@ -225,6 +226,59 @@ def enable_happy_eyeballs_on_client(client) -> None:_enable_happy_eyeballs(transport, proxy_pool_types)+def install_happy_eyeballs_socket_connect() -> None:+ """Race IPv6/IPv4 for every sync TCP connect in the process (RFC 8305, #114265).++ The startup path does not build its HTTP clients in one place: the model catalog+ fetch goes through ``urllib``/``http.client``, provider warm through+ ``requests``/``urllib3``, and sync LLM clients through httpcore. All three funnel+ their TCP connect into ``socket.create_connection`` (``http.client`` re-reads it+ per connection; httpcore looks it up at call time; urllib3 re-exports its own+ serial copy in ``urllib3.util.connection``), and the stock implementation walks the+ ``getaddrinfo`` results serially — on a network whose advertised IPv6 route is+ blackholed, each AAAA record burns the full connect timeout before IPv4 answers.+ Patches both entry points with the racer from this module; idempotent, best-effort.+ """+ global _SOCKET_CONNECT_RACER_INSTALLED+ if _SOCKET_CONNECT_RACER_INSTALLED:+ return+ _SOCKET_CONNECT_RACER_INSTALLED = True++ _socket_original = socket.create_connection++ def _socket_racer(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):+ effective = None if timeout is socket._GLOBAL_DEFAULT_TIMEOUT else timeout+ try:+ return _happy_eyeballs_create_connection(address, effective, source_address=source_address)+ except OSError:+ raise # every candidate failed — identical semantics to the serial original+ except Exception:+ return _socket_original(address, effective, source_address=source_address)++ socket.create_connection = _socket_racer++ try:+ from urllib3.util import connection as _urllib3_connection+ from urllib3.util.timeout import _DEFAULT_TIMEOUT as _urllib3_sentinel+ _urllib3_original = _urllib3_connection.create_connection++ def _urllib3_racer(address, timeout=_urllib3_sentinel, source_address=None, socket_options=None):+ effective = None if timeout is _urllib3_sentinel else timeout+ try:+ return _happy_eyeballs_create_connection(+ address, effective, source_address=source_address,+ socket_options=tuple(socket_options or ()))+ except OSError:+ raise+ except Exception:+ return _urllib3_original(+ address, effective, source_address=source_address, socket_options=socket_options)++ _urllib3_connection.create_connection = _urllib3_racer+ except Exception:+ pass # requests warm keeps its serial connect; the socket/http.client/httpcore paths still race++def _load_openai_cls() -> type:"""Import and cache ``openai.OpenAI``."""global _OPENAI_CLS_CACHE@@ -458,5 +512,5 @@ OpenAI = _OpenAIProxy()__all__ = ["OpenAI", "_OpenAIProxy", "_load_openai_cls", "_SafeWriter", "_install_safe_stdio", "_get_proxy_from_env","_get_proxy_for_base_url", "build_keepalive_http_client", "close_shared_transports",- "enable_happy_eyeballs_on_client",+ "enable_happy_eyeballs_on_client", "install_happy_eyeballs_socket_connect",]diff --git a/tests/agent/test_codex_happy_eyeballs.py b/tests/agent/test_codex_happy_eyeballs.pyindex 91804555af8..552e23d9704 100644--- a/tests/agent/test_codex_happy_eyeballs.py+++ b/tests/agent/test_codex_happy_eyeballs.py@@ -7,6 +7,14 @@ import pytestfrom agent import process_bootstrap+# Captured at import time, before any test can construct an AIAgent (whose+# init_agent now installs the process-level racer) — the restore fixture below+# needs the pristine originals regardless of test ordering.+from urllib3.util import connection as _urllib3_connection_util++_STOCK_SOCKET_CREATE_CONNECTION = socket.create_connection+_STOCK_URLLIB3_CREATE_CONNECTION = _urllib3_connection_util.create_connection+@pytest.fixturedef no_proxy_env(monkeypatch):@@ -323,3 +331,140 @@ def test_codex_auth_http_client_uses_happy_eyeballs_backend(no_proxy_env):)finally:client.close()+++def restored_socket_connect():+ yield+ socket.create_connection = _STOCK_SOCKET_CREATE_CONNECTION+ _urllib3_connection_util.create_connection = _STOCK_URLLIB3_CREATE_CONNECTION+ process_bootstrap._SOCKET_CONNECT_RACER_INSTALLED = False+++def test_install_happy_eyeballs_socket_connect_patches_both_stacks(restored_socket_connect):+ process_bootstrap.install_happy_eyeballs_socket_connect()++ assert socket.create_connection is not _STOCK_SOCKET_CREATE_CONNECTION+ assert _urllib3_connection_util.create_connection is not _STOCK_URLLIB3_CREATE_CONNECTION++ # Idempotent: a second install must not wrap the racer again.+ first_socket_racer = socket.create_connection+ first_urllib3_racer = _urllib3_connection_util.create_connection+ process_bootstrap.install_happy_eyeballs_socket_connect()+ assert socket.create_connection is first_socket_racer+ assert _urllib3_connection_util.create_connection is first_urllib3_racer+++def test_installed_socket_connect_races_past_blackholed_ipv6(+ monkeypatch, restored_socket_connect):+ clock = [0.0]+ sockets = []++ class FakeSocket:+ def __init__(self, family, socktype, proto):+ self.family = family+ self.closed = False+ self.timeout = None+ sockets.append(self)++ def setsockopt(self, *_args):+ pass++ def setblocking(self, _blocking):+ pass++ def settimeout(self, timeout):+ self.timeout = timeout++ def bind(self, _address):+ pass++ def connect_ex(self, _address):+ if self.family == socket.AF_INET6:+ return errno.EINPROGRESS+ return 0++ def close(self):+ self.closed = True++ class FakeSelector:+ def __init__(self):+ self.registered = set()++ def register(self, fileobj, _events):+ self.registered.add(fileobj)++ def unregister(self, fileobj):+ self.registered.discard(fileobj)++ def select(self, timeout):+ clock[0] += timeout or 0.0+ return []++ def close(self):+ pass++ monkeypatch.setattr(+ process_bootstrap.socket,+ "getaddrinfo",+ lambda *_args, **_kwargs: [+ (+ socket.AF_INET6,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ ("2001:db8::1", 443, 0, 0),+ ),+ (+ socket.AF_INET,+ socket.SOCK_STREAM,+ socket.IPPROTO_TCP,+ "",+ ("192.0.2.1", 443),+ ),+ ],+ )+ monkeypatch.setattr(process_bootstrap.socket, "socket", FakeSocket)+ monkeypatch.setattr(+ process_bootstrap.selectors, "DefaultSelector", FakeSelector+ )+ monkeypatch.setattr(+ process_bootstrap.time, "monotonic", lambda: clock[0]+ )++ process_bootstrap.install_happy_eyeballs_socket_connect()++ # http.client passes the module timeout sentinel through positionally.+ winner = socket.create_connection(+ ("example.com", 443), socket._GLOBAL_DEFAULT_TIMEOUT, None+ )++ assert winner.family == socket.AF_INET+ assert winner.timeout is None # sentinel → blocking socket, like the stock connect+ assert clock[0] == process_bootstrap._HAPPY_EYEBALLS_DELAY_SECONDS+ assert sockets[0].closed is True+ assert sockets[1] is winner+++def test_installed_racer_serves_http_client_and_urllib3_connects(restored_socket_connect):+ import http.client++ import urllib3++ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen(4)+ port = listener.getsockname()[1]++ process_bootstrap.install_happy_eyeballs_socket_connect()+ http_conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)+ urllib3_conn = urllib3.connection.HTTPConnection("127.0.0.1", port, timeout=5)+ try:+ http_conn.connect()+ urllib3_conn.connect() # exercises the socket_options kwarg of the urllib3 racer+ assert http_conn.sock is not None+ assert urllib3_conn.sock is not None+ finally:+ http_conn.close()+ urllib3_conn.close()+ listener.close()