Skip to content

The agent that grows with you

fix(codex): extend Happy-Eyeballs racing to Codex OAuth/auth clients; pin async native racing

Teknium419232d49bb0
diff --git a/agent/process_bootstrap.py b/agent/process_bootstrap.py
index 7ef4cf2df84..341126c9198 100644
--- a/agent/process_bootstrap.py
+++ b/agent/process_bootstrap.py
@@ -269,6 +269,49 @@ def _enable_happy_eyeballs(transport) -> None:
pool._network_backend = _HappyEyeballsSyncBackend()
+def enable_happy_eyeballs_on_client(client) -> None:
+ """Install the sync racing backend on every direct transport of a client.
+
+ Covers a ready-built ``httpx.Client`` (its default transport plus any
+ mounts), for callers that construct clients inline instead of going
+ through :func:`build_keepalive_http_client` — e.g. the Codex OAuth token
+ refresh / device-login / usage-probe clients in ``hermes_cli.auth``.
+
+ Proxy-backed transports (``httpcore.HTTPProxy`` / SOCKS pools) are left
+ untouched: with a proxy in play the TCP connect goes to the proxy host,
+ which is out of scope for the direct-transport racing added in #94388.
+ Async clients are also left untouched — httpcore's async backend already
+ performs RFC 8305 racing natively via
+ ``anyio.connect_tcp(happy_eyeballs_delay=0.25)``.
+
+ Best-effort and hasattr-guarded like ``_enable_happy_eyeballs``; on an
+ incompatible httpx/httpcore this silently keeps the default backend.
+ """
+ try:
+ import httpcore
+
+ proxy_pool_types = tuple(
+ t
+ for t in (
+ getattr(httpcore, "HTTPProxy", None),
+ getattr(httpcore, "SOCKSProxy", None),
+ )
+ if t is not None
+ )
+ except Exception:
+ return
+
+ transports = [getattr(client, "_transport", None)]
+ transports.extend((getattr(client, "_mounts", None) or {}).values())
+ for transport in transports:
+ pool = getattr(transport, "_pool", None)
+ if pool is None or not hasattr(pool, "_network_backend"):
+ continue
+ if proxy_pool_types and isinstance(pool, proxy_pool_types):
+ continue
+ pool._network_backend = _HappyEyeballsSyncBackend()
+
+
def _load_openai_cls() -> type:
"""Import and cache ``openai.OpenAI``."""
global _OPENAI_CLS_CACHE
@@ -421,6 +464,10 @@ def build_keepalive_http_client(
if proxy is None:
http_transport = transport_cls(verify=verify)
https_transport = transport_cls(verify=verify)
+ # Async transports need no explicit racing: httpcore's anyio
+ # backend already implements RFC 8305 natively
+ # (``anyio.connect_tcp(happy_eyeballs_delay=0.25)``), covered by
+ # tests/agent/test_codex_happy_eyeballs.py.
if not async_mode and _uses_codex_cloud_transport(base_url):
_enable_happy_eyeballs(http_transport)
_enable_happy_eyeballs(https_transport)
@@ -459,4 +506,5 @@ __all__ = [
"_get_proxy_from_env",
"_get_proxy_for_base_url",
"build_keepalive_http_client",
+ "enable_happy_eyeballs_on_client",
]
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index d04b28341bd..3392157b00a 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -4051,6 +4051,32 @@ def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]:
return dict(imported)
+def _codex_http_client(**kwargs: Any) -> "httpx.Client":
+ """Build an ``httpx.Client`` for Codex OAuth/probe endpoints with racing.
+
+ Same broken-IPv6 failure mode as the chat transport (#13834): a host that
+ advertises AAAA records but blackholes IPv6 makes each serial connect
+ attempt eat the full connect timeout before IPv4 is tried, so token
+ refresh / device login / usage probes time out where the official Codex
+ CLI (which races families per RFC 8305) works. Install the same
+ Happy-Eyeballs sync backend #94388 added for the chat transport.
+
+ Best-effort: if the racing backend can't be installed (unexpected
+ httpx/httpcore internals, mocked client in tests), the client still works
+ with the default serial connect behavior. Proxy-backed transports are
+ intentionally left on the default backend (the TCP connect goes to the
+ proxy, not to auth.openai.com/chatgpt.com).
+ """
+ client = httpx.Client(**kwargs)
+ try:
+ from agent.process_bootstrap import enable_happy_eyeballs_on_client
+
+ enable_happy_eyeballs_on_client(client)
+ except Exception:
+ pass
+ return client
+
+
def refresh_codex_oauth_pure(
access_token: str,
refresh_token: str,
@@ -4068,7 +4094,7 @@ def refresh_codex_oauth_pure(
)
timeout = httpx.Timeout(max(5.0, float(timeout_seconds)))
- with httpx.Client(
+ with _codex_http_client(
timeout=timeout,
headers={
"Accept": "application/json",
@@ -4517,7 +4543,7 @@ def _probe_codex_quota_restored(
)
if isinstance(account_id, str) and account_id.strip():
headers["ChatGPT-Account-Id"] = account_id.strip()
- with httpx.Client(timeout=10.0) as client:
+ with _codex_http_client(timeout=10.0) as client:
response = client.get(_codex_usage_probe_url(base_url), headers=headers)
if response.status_code == 200:
payload = response.json() or {}
@@ -8424,7 +8450,7 @@ def _codex_device_code_login() -> Dict[str, Any]:
max_attempts = 4
for attempt in range(1, max_attempts + 1):
try:
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:
resp = client.post(
f"{issuer}/api/accounts/deviceauth/usercode",
json={"client_id": client_id},
@@ -8499,7 +8525,7 @@ def _codex_device_code_login() -> Dict[str, Any]:
code_resp = None
try:
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:
while _time.monotonic() - start < max_wait:
_time.sleep(poll_interval)
poll_resp = client.post(
@@ -8540,7 +8566,7 @@ def _codex_device_code_login() -> Dict[str, Any]:
)
try:
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:
token_resp = client.post(
CODEX_OAUTH_TOKEN_URL,
data={
diff --git a/tests/agent/test_codex_happy_eyeballs.py b/tests/agent/test_codex_happy_eyeballs.py
index 48e0bbe38f2..91804555af8 100644
--- a/tests/agent/test_codex_happy_eyeballs.py
+++ b/tests/agent/test_codex_happy_eyeballs.py
@@ -146,3 +146,180 @@ def test_connection_staggers_past_blackholed_ipv6(monkeypatch):
assert clock[0] == process_bootstrap._HAPPY_EYEBALLS_DELAY_SECONDS
assert sockets[0].closed is True
assert sockets[1].closed is False
+
+
+def test_async_codex_client_relies_on_native_anyio_racing(no_proxy_env):
+ """The async transport needs no custom backend — anyio races natively.
+
+ httpcore's ``AnyIOBackend.connect_tcp`` delegates to
+ ``anyio.connect_tcp``, whose ``happy_eyeballs_delay`` default (0.25s)
+ implements RFC 8305 staggered family racing. This pins the contract the
+ ``async_mode`` branch of ``build_keepalive_http_client`` documents: if
+ anyio ever drops the parameter (or the default stops racing), this fails
+ and the async path needs an explicit backend like the sync one.
+ """
+ import inspect
+
+ import anyio
+
+ params = inspect.signature(anyio.connect_tcp).parameters
+ assert "happy_eyeballs_delay" in params
+ assert params["happy_eyeballs_delay"].default == pytest.approx(0.25)
+
+ client = process_bootstrap.build_keepalive_http_client(
+ "https://chatgpt.com/backend-api/codex", async_mode=True
+ )
+ try:
+ assert all(
+ not isinstance(backend, process_bootstrap._HappyEyeballsSyncBackend)
+ for backend in _client_backends(client)
+ )
+ finally:
+ import asyncio
+
+ asyncio.get_event_loop_policy().new_event_loop().run_until_complete(
+ client.aclose()
+ )
+
+
+def test_async_connect_races_past_blackholed_ipv6(monkeypatch):
+ """IPv4 completes ~250ms after a hanging IPv6 attempt on the async path.
+
+ Mirrors ``test_connection_staggers_past_blackholed_ipv6`` for the async
+ transport: resolve a fake host to a blackholed IPv6 address plus a live
+ local IPv4 listener and assert httpcore's async backend connects fast
+ instead of serially waiting out the IPv6 connect timeout.
+ """
+ import asyncio
+ import threading
+ import time as _time
+
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.bind(("127.0.0.1", 0))
+ server.listen(5)
+ port = server.getsockname()[1]
+
+ def _accept_loop():
+ while True:
+ try:
+ conn, _ = server.accept()
+ conn.close()
+ except OSError:
+ return
+
+ thread = threading.Thread(target=_accept_loop, daemon=True)
+ thread.start()
+
+ real_getaddrinfo = socket.getaddrinfo
+
+ def fake_getaddrinfo(host, *args, **kwargs):
+ name = host.decode() if isinstance(host, (bytes, bytearray)) else str(host)
+ if name == "codex-he-async.test":
+ return [
+ (
+ socket.AF_INET6,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("100::1", port, 0, 0), # RFC 6666 discard prefix: blackhole
+ ),
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("127.0.0.1", port),
+ ),
+ ]
+ return real_getaddrinfo(host, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)
+
+ async def _connect():
+ from httpcore._backends.auto import AutoBackend
+
+ backend = AutoBackend()
+ start = _time.monotonic()
+ stream = await backend.connect_tcp(
+ "codex-he-async.test", port, timeout=30.0
+ )
+ elapsed = _time.monotonic() - start
+ await stream.aclose()
+ return elapsed
+
+ try:
+ elapsed = asyncio.run(_connect())
+ finally:
+ server.close()
+
+ # Native anyio racing: IPv6 is attempted first, IPv4 starts 0.25s later
+ # and wins immediately. Serial behavior would block until the IPv6
+ # connect timeout (tens of seconds). Generous bound for slow CI hosts.
+ assert elapsed < 5.0
+
+
+class _RecordingPool:
+ def __init__(self):
+ self._network_backend = "default"
+
+
+class _RecordingTransport:
+ def __init__(self):
+ self._pool = _RecordingPool()
+
+
+def test_enable_happy_eyeballs_on_client_covers_transport_and_mounts():
+ class _Client:
+ pass
+
+ client = _Client()
+ client._transport = _RecordingTransport()
+ client._mounts = {"https://": _RecordingTransport(), "http://": None}
+
+ process_bootstrap.enable_happy_eyeballs_on_client(client)
+
+ assert isinstance(
+ client._transport._pool._network_backend,
+ process_bootstrap._HappyEyeballsSyncBackend,
+ )
+ assert isinstance(
+ client._mounts["https://"]._pool._network_backend,
+ process_bootstrap._HappyEyeballsSyncBackend,
+ )
+
+
+def test_enable_happy_eyeballs_on_client_skips_proxy_pools(no_proxy_env):
+ import httpcore
+ import httpx
+
+ client = httpx.Client(proxy="http://127.0.0.1:3128")
+ try:
+ process_bootstrap.enable_happy_eyeballs_on_client(client)
+ proxy_pools = [
+ transport._pool
+ for transport in client._mounts.values()
+ if transport is not None
+ and isinstance(getattr(transport, "_pool", None), httpcore.HTTPProxy)
+ ]
+ assert proxy_pools # the all:// mount is proxy-backed
+ assert all(
+ not isinstance(
+ pool._network_backend, process_bootstrap._HappyEyeballsSyncBackend
+ )
+ for pool in proxy_pools
+ )
+ finally:
+ client.close()
+
+
+def test_codex_auth_http_client_uses_happy_eyeballs_backend(no_proxy_env):
+ from hermes_cli.auth import _codex_http_client
+
+ client = _codex_http_client(timeout=5.0)
+ try:
+ assert any(
+ isinstance(backend, process_bootstrap._HappyEyeballsSyncBackend)
+ for backend in _client_backends(client)
+ )
+ finally:
+ client.close()