Skip to content

The agent that grows with you

fix: rotate Codex pool credentials on a ChatGPT-account model entitlement 400

teknium17958cbf2de65
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index a1c2028e840..6d0606bcc31 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -906,6 +906,11 @@ def recover_with_credential_pool(
pool, has_retried_429=has_retried_429, error_context=error_context,
api_key_hint=api_key_hint, credential_id=credential_id, rotate_and_swap=_rotate_and_swap,
)
+ if effective_reason == FailoverReason.model_entitlement:
+ # The pool benches (credential, model) only and hands back the next entry that is not
+ # benched for this model; None once every entry rejected it, so the caller falls
+ # through to the single-credential handling in _mark_entitlement_rejected_model (#71970).
+ return _rotate_and_swap(400, "model entitlement"), has_retried_429
if effective_reason == FailoverReason.auth:
return _recover_auth_failure(
agent, pool, status_code=status_code, has_retried_429=has_retried_429,
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 852ab636614..a9df6fc866a 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1978,11 +1978,12 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
if entry is None:
return None
_label = entry.label or entry.id[:8]
- if self._is_model_scoped_rate_limit(status_code, model, failure_reason):
- # A generic Anthropic 429 is a per-model rate limit: bench this
- # model only, the credential stays available for its siblings.
+ if self._is_model_scoped_failure(status_code, model, failure_reason):
+ # A generic Anthropic 429 (per-model rate limit) or a Codex account model
+ # entitlement rejection: bench this model only, the credential stays
+ # available for its siblings.
self._cool_down_model(entry, model, error_context)
- logger.info("credential pool: %s rate-limited for model %s; other models stay available", _label, model)
+ logger.info("credential pool: %s unavailable for model %s; other models stay available", _label, model)
self._current_id = None
next_entry, _pending = self._select_unlocked(refresh=False, model=model)
return next_entry
diff --git a/agent/credential_pool_model_cooldowns.py b/agent/credential_pool_model_cooldowns.py
index 89439d6a3a2..fa6da883cae 100644
--- a/agent/credential_pool_model_cooldowns.py
+++ b/agent/credential_pool_model_cooldowns.py
@@ -54,13 +54,19 @@ class CredentialPoolModelCooldownMixin:
for entry in self._entries
)
- def _is_model_scoped_rate_limit(
+ def _is_model_scoped_failure(
self, status_code: Optional[int], model: Optional[str], failure_reason: Optional[str],
) -> bool:
+ """Anthropic per-model 429s, and a Codex ChatGPT-account model entitlement 400: the
+ account cannot use *model*, but the credential stays valid for every other model (#71970)."""
from agent.credential_pool import FAILURE_REASON_BILLING, FAILURE_REASON_BILLING_UNVERIFIED
+ if not model:
+ return False
+ if failure_reason == "model_entitlement":
+ return True
return (
- self.provider == "anthropic" and status_code == 429 and bool(model)
+ self.provider == "anthropic" and status_code == 429
and failure_reason not in (FAILURE_REASON_BILLING, FAILURE_REASON_BILLING_UNVERIFIED)
)
diff --git a/agent/error_classifier.py b/agent/error_classifier.py
index be91240975c..10d9038d212 100644
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@ -49,6 +49,7 @@ class FailoverReason(enum.Enum):
model_not_found = "model_not_found" # 404 or invalid model — fallback to different model
provider_policy_blocked = "provider_policy_blocked" # Aggregator account data/privacy policy excluded the only endpoint
content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — don't retry unchanged
+ model_entitlement = "model_entitlement" # This account cannot use the requested model — rotate credential (model-scoped), else fall back
format_error = "format_error" # 400 bad request — abort or strip + retry
role_alternation = "role_alternation" # Strict chat template rejected adjacent same-role messages — merge them for this destination and retry
invalid_encrypted_content = "invalid_encrypted_content" # Responses replay blob rejected — strip replay state and retry
@@ -260,6 +261,9 @@ _CONTEXT_OVERFLOW_PATTERNS = (
# Last entry: OpenRouter 404 when no endpoint supports tool calling —
# model_not_found triggers fallback instead of burning retries (#58446).
+# Codex ChatGPT-account entitlement 400 — the account can never use the named slug (#71970, #106475).
+CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER = "model is not supported when using codex with a chatgpt account"
+
_MODEL_NOT_FOUND_PATTERNS = (
"is not a valid model", "invalid model", "model not found", "model_not_found", "does not exist",
"no such model", "unknown model", "unsupported model", "no endpoints found that support tool use",
@@ -435,6 +439,8 @@ _V_AUTH_ROTATE = _v(_R.auth, retryable=False, **_ROTATE_FALLBACK)
_V_AUTH_FALLBACK = _v(_R.auth, **_ABORT_FALLBACK)
_V_MODEL_NOT_FOUND = _v(_R.model_not_found, **_ABORT_FALLBACK)
_V_CONTENT_BLOCKED = _v(_R.content_policy_blocked, **_ABORT_FALLBACK)
+# Another account in the same pool may hold the entitlement; the credential itself is healthy.
+_V_MODEL_ENTITLEMENT = _v(_R.model_entitlement, retryable=False, **_ROTATE_FALLBACK)
_V_FORMAT_ERROR = _v(_R.format_error, **_ABORT_FALLBACK)
# A different provider (direct instead of the aggregator; another host's TLS chain) can fix these.
_V_POLICY_BLOCKED = _v(_R.provider_policy_blocked, **_ABORT_FALLBACK)
@@ -985,6 +991,10 @@ def _classify_400(c: _Ctx) -> Verdict:
verdict = _first_match(msg, _IMAGE_TOOL_RULES)
if verdict is not None:
return verdict
+ # Codex ChatGPT-account model rejection: exact normalized text only, so arbitrary 400s never
+ # rotate. Before request-validation, whose "not supported" wording would abort as format_error (#71970).
+ if CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER in msg:
+ return _V_MODEL_ENTITLEMENT
# Invalid encrypted reasoning replay blob (OpenAI Responses); before
# overflow because "encrypted content … could not be verified" trips it.
if code == "invalid_encrypted_content" or "invalid_encrypted_content" in msg or (
diff --git a/agent/fallback_cooldown.py b/agent/fallback_cooldown.py
index ee4efae5db2..fcd62fbed01 100644
--- a/agent/fallback_cooldown.py
+++ b/agent/fallback_cooldown.py
@@ -29,31 +29,29 @@ def _arm_rate_limit_cooldown(agent, reason: "FailoverReason | None") -> int | No
return backoff_seconds
-# Codex ChatGPT-account entitlement 400 — the account can never use the named slug, so with
-# nothing to rotate it is a config error, not a transient failure (#106475).
-_CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER = "model is not supported when using codex with a chatgpt account"
-
-
def _mark_entitlement_rejected_model(agent, api_error) -> bool:
"""Record a Codex ChatGPT-account 400 that rejects the current model for this account.
- With a single credential there is no pool to rotate (#71970 covers that case), so the
- (provider, model) pair is treated as dead for the session: the fallback walk skips it and
- restore_primary_runtime stops switching back — otherwise every turn re-fails on the primary,
- announces an unverified "Primary model restored", and oscillates forever (#106475).
+ Pool rotation runs first (recover_with_credential_pool benches (credential, model) and
+ moves to the next entitled entry, #71970); this runs only once no pool entry is left for
+ the model, so the (provider, model) pair is treated as dead for the session: the fallback
+ walk skips it and restore_primary_runtime stops switching back — otherwise every turn
+ re-fails on the primary, announces an unverified "Primary model restored", and oscillates
+ forever (#106475).
"""
if getattr(api_error, "status_code", None) != 400:
return False
- pool = getattr(agent, "_credential_pool", None)
- if pool is not None and len(pool.entries()) > 1:
- return False # another account in the pool may be entitled; leave rotation to it
+ from agent.error_classifier import CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER
haystack = str(getattr(api_error, "message", "") or api_error).lower()
- if _CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER not in haystack:
+ if CODEX_ACCOUNT_MODEL_ENTITLEMENT_MARKER not in haystack:
return False
provider = str(getattr(agent, "provider", "") or "").strip().lower()
model = str(getattr(agent, "model", "") or "").strip()
if not provider or not model:
return False
+ pool = getattr(agent, "_credential_pool", None)
+ if pool is not None and pool.has_available(model=model):
+ return False # another pool entry is still eligible for this model; rotation owns it
rejected = getattr(agent, "_entitlement_rejected_models", None)
if rejected is None:
rejected = agent._entitlement_rejected_models = set()
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..f16d38ebbf3
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1 @@
+kilhyeonjun
diff --git a/tests/agent/test_codex_model_entitlement_rotation.py b/tests/agent/test_codex_model_entitlement_rotation.py
new file mode 100644
index 00000000000..367e7c6f8d4
--- /dev/null
+++ b/tests/agent/test_codex_model_entitlement_rotation.py
@@ -0,0 +1,89 @@
+"""A Codex ChatGPT-account model entitlement 400 rotates to the next pool credential (#71970).
+
+The exact normalized rejection benches only (credential, model) and hands the next eligible entry
+back; every other 400 stays a plain request failure. Once every entry rejects the model, the
+single-credential handling from #106475 takes over.
+"""
+import json
+import types
+
+import pytest
+
+from agent.error_classifier import FailoverReason, classify_api_error
+
+MODEL = "gpt-5.3-codex"
+OTHER_MODEL = "gpt-5.3-codex-mini"
+TOKENS = ("tok-account-a", "tok-account-b")
+
+
+class _Err(Exception):
+ def __init__(self, status, body):
+ self.status_code = status
+ self.body = body
+ self.response = types.SimpleNamespace(status_code=status, headers={}, text=json.dumps(body), json=lambda: body)
+ self.message = f"Error code: {status} - {json.dumps(body)}"
+ super().__init__(self.message)
+
+
+def _entitlement_400():
+ return _Err(400, {"detail": f"The '{MODEL}' model is not supported when using Codex with a ChatGPT account."})
+
+
+def pool(tmp_path, monkeypatch):
+ root = tmp_path / "hermes-root"
+ root.mkdir()
+ (tmp_path / "fakehome").mkdir()
+ monkeypatch.setenv("HOME", str(tmp_path / "fakehome"))
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ import hermes_constants
+ hermes_constants._default_hermes_root_memo = None # type: ignore[attr-defined]
+ (root / "auth.json").write_text(json.dumps({"credential_pool": {"openai-codex": [
+ {"id": f"cred-{i}", "label": f"acct-{i}", "auth_type": "oauth", "priority": i, "source": "manual",
+ "access_token": tok, "refresh_token": f"rt-{i}", "expires_at_ms": 4_000_000_000_000}
+ for i, tok in enumerate(TOKENS)
+ ]}}))
+ from agent.credential_pool import load_pool
+ return load_pool("openai-codex")
+
+
+def test_entitlement_400_benches_only_that_model_and_rotates(pool):
+ verdict = classify_api_error(_entitlement_400(), provider="openai-codex", model=MODEL)
+ assert verdict.reason == FailoverReason.model_entitlement
+ assert verdict.should_rotate_credential and verdict.should_fallback and not verdict.retryable
+
+ generic = classify_api_error(_Err(400, {"detail": "Invalid request: bad field"}), provider="openai-codex", model=MODEL)
+ assert generic.reason == FailoverReason.format_error and not generic.should_rotate_credential
+
+ assert pool.select(model=MODEL).id == "cred-0"
+ next_entry = pool.mark_exhausted_and_rotate(
+ status_code=400, api_key_hint=TOKENS[0], credential_id="cred-0",
+ failure_reason=verdict.reason.value, model=MODEL,
+ )
+ assert next_entry is not None and next_entry.id == "cred-1"
+ first = pool.entries()[0]
+ assert first.last_status is None # credential-wide state untouched: other models stay usable
+ assert set(first.model_cooldowns) == {MODEL}
+ assert pool.select(model=OTHER_MODEL).id == "cred-0"
+
+
+def test_all_entries_rejecting_falls_back_to_session_marker(pool):
+ from agent.fallback_cooldown import _is_entitlement_rejected, _mark_entitlement_rejected_model
+
+ agent = types.SimpleNamespace(
+ provider="openai-codex", model=MODEL, _credential_pool=pool,
+ _buffer_diagnostic_status=lambda *_a, **_k: None,
+ )
+ pool.mark_exhausted_and_rotate(
+ status_code=400, api_key_hint=TOKENS[0], credential_id="cred-0", failure_reason="model_entitlement", model=MODEL,
+ )
+ # cred-1 is still eligible for the model: rotation owns the recovery, no session-wide marker.
+ assert _mark_entitlement_rejected_model(agent, _entitlement_400()) is False
+ assert not _is_entitlement_rejected(agent, "openai-codex", MODEL)
+
+ assert pool.mark_exhausted_and_rotate(
+ status_code=400, api_key_hint=TOKENS[1], credential_id="cred-1", failure_reason="model_entitlement", model=MODEL,
+ ) is None
+ assert _mark_entitlement_rejected_model(agent, _entitlement_400()) is True
+ assert _is_entitlement_rejected(agent, "openai-codex", MODEL)
diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py
index 58ca757516e..348261d2434 100644
--- a/tests/agent/test_error_classifier.py
+++ b/tests/agent/test_error_classifier.py
@@ -70,6 +70,7 @@ class TestFailoverReason:
"reasoning_mandatory",
"provider_policy_blocked",
"content_policy_blocked",
+ "model_entitlement",
"thinking_signature", "long_context_tier",
"oauth_long_context_beta_forbidden",
"llama_cpp_grammar_pattern",
diff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.md
index 2292f0977ff..90ff0d5a3b6 100644
--- a/website/docs/user-guide/features/credential-pools.md
+++ b/website/docs/user-guide/features/credential-pools.md
@@ -37,6 +37,9 @@ Your request
→ 401 auth expired?
→ Try refreshing the token (OAuth)
→ Refresh failed → rotate to next pool key
+ → 400 "model is not supported when using Codex with a ChatGPT account"?
+ → Bench this key for that model only, rotate to the next key (other models stay usable)
+ → Every key rejects the model → fallback_model; the model is skipped for the session
→ Success → continue normally
```
@@ -175,6 +178,7 @@ The pool handles different errors differently:
| **429 Rate Limit** | Retry same key once (transient). Second consecutive 429 rotates to next key | 1 hour |
| **402 Billing/Quota** | Immediately rotate to next key | 1 hour |
| **401 Auth Expired** | Try refreshing the OAuth token first. Rotate only if refresh fails | 5 minutes |
+| **400 Codex model entitlement** (`The '<model>' model is not supported when using Codex with a ChatGPT account.`) | Bench this key for the rejected model only and rotate to the next key; other models keep using the key. Other 400s never rotate | 1 hour (per model) |
| **All keys exhausted** | Fall through to `fallback_model` if configured | — |
Provider-supplied `reset_at` timestamps override these default cooldowns.