Skip to content

The agent that grows with you

fix(auth): drop dead code from the Codex login retry; trim to two invariant tests

teknium1227384e332ed
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.py
index a77aa54bf7e..713934c041e 100644
--- a/hermes_cli/auth_codex.py
+++ b/hermes_cli/auth_codex.py
@@ -267,17 +267,17 @@ def _codex_login_post(url: str, *, failure: Tuple[str, str], **kwargs: Any) -> "
linear backoff before failing: losing the token exchange to a single SSL EOF wastes a
device-code approval the user already completed in the browser (#114610).
"""
- attempts = 3
- for attempt in range(1, attempts + 1):
+ attempt, attempts = 1, 3
+ while True:
try:
with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:
return client.post(url, **kwargs)
except Exception as exc:
- if attempt < attempts and _is_transient_transport_error(exc):
- time.sleep(attempt)
- continue
- raise _codex_err(f"{failure[0]}: {exc}{_ssl_interop_hint(exc)}", failure[1]) from exc
- raise _codex_err(f"{failure[0]}: exhausted retries", failure[1]) # pragma: no cover
+ if attempt == attempts or not _is_transient_transport_error(exc):
+ raise _codex_err(
+ f"{failure[0]}: {exc}{_ssl_interop_hint(exc)}", failure[1]) from exc
+ time.sleep(attempt)
+ attempt += 1
def _codex_http_client(**kwargs: Any) -> "httpx.Client":
@@ -830,9 +830,6 @@ def _codex_poll_authorization_code(
except KeyboardInterrupt:
print("\nLogin cancelled.")
raise SystemExit(130)
- except KeyboardInterrupt:
- print("\nLogin cancelled.")
- raise SystemExit(130)
if code_resp is None:
raise _codex_err("Login timed out after 15 minutes.", "device_code_timeout")
return code_resp
diff --git a/tests/hermes_cli/test_codex_device_login_transient_retry.py b/tests/hermes_cli/test_codex_device_login_transient_retry.py
index c2947db8cf2..c77604773bb 100644
--- a/tests/hermes_cli/test_codex_device_login_transient_retry.py
+++ b/tests/hermes_cli/test_codex_device_login_transient_retry.py
@@ -1,11 +1,11 @@
-"""Codex device-login survives transient transport blips (#114610).
+"""Codex device-login survives transient transport blips.
A single dropped connection (e.g. an SSL EOF between polls) used to abort the whole
-device-code flow and waste the browser approval the user had already completed. Transient
-transport errors are now retried — the poll loop tolerates up to 6 consecutive blips and the
-one-shot device-login POSTs retry twice — while persistent failures still surface the typed
-``AuthError`` with the original cause chained, and non-transport errors fail immediately
-without burning retries.
+device-code flow and waste the browser approval the user had already completed. Transport
+errors are now retried — the poll loop tolerates a bounded run of consecutive blips and the
+one-shot device-login POSTs retry twice — while the terminal contract is unchanged: a typed
+``AuthError`` with the original cause chained and the TLS hint, and non-transport errors
+still fail immediately without burning retries.
"""
import ssl
@@ -22,11 +22,8 @@ _SSL_EOF_MESSAGE = (
class _ScriptedClient:
- """Context-manager httpx.Client stand-in replaying a scripted sequence of results.
-
- Each ``post`` call pops the next entry: a ``BaseException`` is raised, anything else is
- returned as-is (tests pass simple response stubs).
- """
+ """Context-manager ``httpx.Client`` stand-in: each ``post`` pops the next scripted step —
+ a ``BaseException`` is raised, anything else is returned as the response."""
def __init__(self, script):
self._script = list(script)
@@ -71,81 +68,39 @@ def _poll():
"https://auth.openai.com", device_auth_id="da", user_code="uc", poll_interval=0)
-def test_poll_survives_transients_then_completes(monkeypatch):
+def test_poll_survives_transport_blips_but_not_other_errors(monkeypatch):
+ approval = _Response(200, {"authorization_code": "ac", "code_verifier": "cv"})
client = _ScriptedClient([
- ssl.SSLEOFError(8, _SSL_EOF_MESSAGE),
- httpx.ConnectError("connection reset by peer"),
- _Response(200, {"authorization_code": "ac", "code_verifier": "cv"})])
+ ssl.SSLEOFError(8, _SSL_EOF_MESSAGE), httpx.ConnectError("connection reset"), approval])
_install(monkeypatch, client)
- result = _poll()
-
- assert result == {"authorization_code": "ac", "code_verifier": "cv"}
+ assert _poll() == {"authorization_code": "ac", "code_verifier": "cv"}
assert client.calls == 3
-
-def test_login_post_retries_transient_blip(monkeypatch):
- client = _ScriptedClient([
- ssl.SSLEOFError(8, _SSL_EOF_MESSAGE), _Response(200, {"user_code": "uc"})])
+ bug = ValueError("decode bug")
+ client = _ScriptedClient([bug, approval])
_install(monkeypatch, client)
+ with pytest.raises(AuthError) as excinfo:
+ _poll()
+ assert excinfo.value.__cause__ is bug
+ assert client.calls == 1 # a non-transport exception is a bug, never retried
- resp = _login_post()
- assert resp.status_code == 200
- assert client.calls == 2
+def test_login_post_retries_bounded_and_keeps_typed_failure(monkeypatch):
+ client = _ScriptedClient(
+ [ssl.SSLEOFError(8, _SSL_EOF_MESSAGE), _Response(200, {"user_code": "uc"})])
+ _install(monkeypatch, client)
+ assert _login_post().status_code == 200
+ assert client.calls == 2
-def test_login_post_persistent_transient_fails_typed(monkeypatch):
exc = ssl.SSLEOFError(8, _SSL_EOF_MESSAGE)
- client = _ScriptedClient([exc, exc, exc])
+ client = _ScriptedClient([exc] * 4)
_install(monkeypatch, client)
-
with pytest.raises(AuthError) as excinfo:
_login_post()
-
err = excinfo.value
assert err.code == "device_code_request_failed"
- assert "UNEXPECTED_EOF_WHILE_READING" in str(err)
- assert "OPENSSL_CONF" in str(err)
- assert err.__cause__ is exc
- assert client.calls == 3 # capped at three attempts, not an endless retry
-
-
-def test_poll_persistent_transient_fails_after_consecutive_cap(monkeypatch):
- exc = httpx.ConnectTimeout("timed out")
- client = _ScriptedClient([exc] * 6)
- _install(monkeypatch, client)
-
- with pytest.raises(AuthError) as excinfo:
- _poll()
-
- err = excinfo.value
- assert err.code == "device_code_poll_error"
- assert "6 consecutive" in str(err)
- assert "timed out" in str(err)
+ assert "UNEXPECTED_EOF_WHILE_READING" in str(err) and "OPENSSL_CONF" in str(err)
assert err.__cause__ is exc
- assert client.calls == 6
-
-
-def test_poll_non_transport_error_fails_immediately(monkeypatch):
- exc = ValueError("decode bug")
- client = _ScriptedClient([exc, _Response(200, {"authorization_code": "ac"})])
- _install(monkeypatch, client)
-
- with pytest.raises(AuthError) as excinfo:
- _poll()
-
- assert excinfo.value.__cause__ is exc
- assert client.calls == 1 # never retried: not a network blip
-
-
-def test_login_post_non_transport_error_fails_immediately(monkeypatch):
- exc = ValueError("unsupported kwarg")
- client = _ScriptedClient([exc, _Response(200, {"user_code": "uc"})])
- _install(monkeypatch, client)
-
- with pytest.raises(AuthError) as excinfo:
- _login_post()
-
- assert excinfo.value.__cause__ is exc
- assert client.calls == 1
+ assert client.calls == 3 # capped, not an endless retry
diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.md
index 4a406a50187..99b6c0ec268 100644
--- a/website/docs/integrations/providers.md
+++ b/website/docs/integrations/providers.md
@@ -95,7 +95,7 @@ The OpenAI Codex provider authenticates via device code (open a URL, enter a cod
If a token refresh fails with a terminal error (HTTP 4xx, `invalid_grant`, revoked grant, etc.), Hermes marks the refresh token as dead and stops replaying it so you don't see a flood of identical auth failures. The next request surfaces a typed re-auth message instead. Run `hermes auth add openai-codex` (or `hermes model` → **ChatGPT or Codex Subscription**) to start a fresh device-code login; the quarantine clears on the next successful exchange.
-Device login can fail with `[SSL: UNEXPECTED_EOF_WHILE_READING]` or a TLS handshake timeout on Python/OpenSSL 3.5+ when a middlebox rejects post-quantum groups such as X25519MLKEM768 (curl may still work). Hermes does not change default TLS policy. Point `OPENSSL_CONF` at a config that restricts `Groups` to classic curves before running `hermes model`, or diagnose with TLS 1.2:
+Device login can fail with `[SSL: UNEXPECTED_EOF_WHILE_READING]` or a TLS handshake timeout on Python/OpenSSL 3.5+ when a middlebox rejects post-quantum groups such as X25519MLKEM768 (curl may still work). A one-off dropped connection is not fatal: while waiting for your browser approval Hermes keeps polling through up to six consecutive transport errors (and retries the device-code request and token exchange twice) before giving up, so only a persistently broken network surfaces this error. Hermes does not change default TLS policy. Point `OPENSSL_CONF` at a config that restricts `Groups` to classic curves before running `hermes model`, or diagnose with TLS 1.2:
```ini
openssl_conf = openssl_init