Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Classify terminal Codex refresh rejection separately from outages

Bingxi Zhao (Frank)3f77d8e4eb1e
diff --git a/deeptutor/services/codex_auth/oauth.py b/deeptutor/services/codex_auth/oauth.py
index 4948cefa9..ec846a4a9 100644
--- a/deeptutor/services/codex_auth/oauth.py
+++ b/deeptutor/services/codex_auth/oauth.py
@@ -342,6 +342,20 @@ class CodexOAuthClient:
data=data,
json=json_payload,
)
+ if error_code == "token_refresh_failed" and response.status_code in {400, 401}:
+ try:
+ rejection = response.json()
+ except ValueError:
+ rejection = None
+ if isinstance(rejection, dict) and rejection.get("error") in {
+ "invalid_grant",
+ "invalid_token",
+ }:
+ raise CodexAuthError(
+ "token_refresh_rejected",
+ "Codex sign-in could not be renewed. Sign in to Codex again.",
+ 401,
+ )
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict):
diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.py
index fb1f02f90..a3a9383de 100644
--- a/deeptutor/services/codex_auth/service.py
+++ b/deeptutor/services/codex_auth/service.py
@@ -798,11 +798,11 @@ class CodexOAuthService:
) -> CodexCredentials:
try:
payload = await self._oauth.refresh(credentials.refresh_token)
- except CodexAuthError:
- # The refresh token is not just expiring — the provider rejected
- # the refresh. Remember that so get_token fails fast for a while
- # instead of retrying a dead refresh on every turn (#1454).
- self._mark_reauth_required()
+ except CodexAuthError as exc:
+ # Only a rejected refresh grant means the user must sign in again.
+ # Transport failures and provider 5xx responses are transient.
+ if exc.code == "token_refresh_rejected":
+ self._mark_reauth_required()
raise
refreshed = self._credentials_from_payload(
payload,
@@ -819,6 +819,7 @@ class CodexOAuthService:
refreshed,
expected_generation=credentials.generation,
)
+ self._clear_reauth_required()
# Generation matching invalidates model data without discarding the
# same account's successful catalog client version.
return committed
@@ -834,11 +835,7 @@ class CodexOAuthService:
)
if credentials.generation != generation:
return
- try:
- await self._refresh_credentials(credentials)
- finally:
- if not self._reauth_required():
- self._clear_reauth_required()
+ await self._refresh_credentials(credentials)
@asynccontextmanager
async def inference_guard(self) -> AsyncIterator[None]:
@@ -956,15 +953,6 @@ class CodexOAuthService:
deadline = self._reauth_until
return deadline is not None and self._clock() < deadline
- # Public entry points for the provider layer, which is in another module
- # and calls the service across it.
- def mark_reauth_required(self) -> None:
- """Ask get_token to fail fast for the cooldown window."""
- self._mark_reauth_required()
-
- def clear_reauth_required(self) -> None:
- self._clear_reauth_required()
-
def public_status(self) -> dict[str, Any]:
operation = self._operation
credentials: CodexCredentials | None = None
diff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.py
index 8801985c8..9b27da3c2 100644
--- a/deeptutor/services/llm/provider_core/openai_codex_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py
@@ -91,20 +91,19 @@ class OpenAICodexProvider(LLMProvider):
if exc.status_code == 401:
try:
await service.recover_after_unauthorized(token.generation)
- except CodexAuthError:
+ except CodexAuthError as refresh_error:
# Only promise a retry when the session really was
# renewed; a dead refresh token needs a new sign-in.
logger.warning("Codex token renewal after HTTP 401 failed")
- raise CodexHTTPError(
- exc.status_code,
- "Codex login expired and could not be renewed. Sign in again.",
- ) from None
- elif exc.status_code == 403:
- # Account-level denial: the session itself is fine but
- # this account may no longer call the backend. Fail
- # fast for the cooldown instead of re-running an
- # auth+refresh round trip on every message (#1454).
- service.mark_reauth_required()
+ if refresh_error.code in {
+ "authentication_required",
+ "token_refresh_rejected",
+ }:
+ raise CodexHTTPError(
+ exc.status_code,
+ "Codex login expired and could not be renewed. Sign in again.",
+ ) from None
+ raise
raise
return LLMResponse(
content=content,
diff --git a/tests/services/codex_auth/test_oauth.py b/tests/services/codex_auth/test_oauth.py
index 9b3aa9d36..d31079719 100644
--- a/tests/services/codex_auth/test_oauth.py
+++ b/tests/services/codex_auth/test_oauth.py
@@ -423,3 +423,16 @@ async def test_oauth_http_failure_does_not_echo_upstream_body() -> None:
assert exc_info.value.code == "token_refresh_failed"
assert "private-upstream-detail" not in str(exc_info.value)
assert "refresh-secret" not in str(exc_info.value)
+
+
+async def test_invalid_refresh_grant_requires_new_sign_in() -> None:
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(400, json={"error": "invalid_grant"})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ with pytest.raises(CodexAuthError) as exc_info:
+ await CodexOAuthClient(http).refresh("refresh-secret")
+
+ assert exc_info.value.code == "token_refresh_rejected"
+ assert "refresh-secret" not in str(exc_info.value)
diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.py
index a894427ff..e109598bf 100644
--- a/tests/services/codex_auth/test_service.py
+++ b/tests/services/codex_auth/test_service.py
@@ -1710,14 +1710,14 @@ async def test_get_token_stops_refreshing_after_a_failed_refresh(tmp_path: Path)
expected_generation=0,
)
oauth.refresh_error = CodexAuthError(
- "token_refresh_failed",
+ "token_refresh_rejected",
"Codex authentication could not be refreshed.",
- 502,
+ 401,
)
with pytest.raises(CodexAuthError) as first:
await service.get_token()
- assert first.value.code == "token_refresh_failed"
+ assert first.value.code == "token_refresh_rejected"
assert oauth.refresh_calls == 1
# Same conversation, next turn, still inside the cooldown: no second trip
@@ -1739,7 +1739,7 @@ async def test_get_token_retries_after_the_reauth_cooldown_elapses(tmp_path: Pat
_stored_credentials(expires_at=1_200),
expected_generation=0,
)
- oauth.refresh_error = CodexAuthError("token_refresh_failed", "boom", 502)
+ oauth.refresh_error = CodexAuthError("token_refresh_rejected", "boom", 401)
with pytest.raises(CodexAuthError):
await service.get_token()
@@ -1753,6 +1753,25 @@ async def test_get_token_retries_after_the_reauth_cooldown_elapses(tmp_path: Pat
assert token.access_token == "refreshed-access"
+async def test_transient_refresh_failure_can_retry_next_turn(tmp_path: Path) -> None:
+ clock = [1_000]
+ service, _callback, oauth, _catalog, store, _models = await _oauth_service(
+ tmp_path, clock=clock
+ )
+ store.commit_credentials(_stored_credentials(expires_at=1_200), expected_generation=0)
+ oauth.refresh_error = CodexAuthError("token_refresh_failed", "Temporary failure", 502)
+
+ with pytest.raises(CodexAuthError) as failure:
+ await service.get_token()
+ assert failure.value.code == "token_refresh_failed"
+ oauth.refresh_error = None
+ token = await service.get_token()
+
+ assert oauth.refresh_calls == 2
+ assert token.access_token == "refreshed-access"
+
+
@pytest.mark.asyncio
async def test_failed_refresh_marks_reauth_required_until_next_login(
tmp_path: Path,
@@ -1766,7 +1785,7 @@ async def test_failed_refresh_marks_reauth_required_until_next_login(
_stored_credentials(expires_at=1_200),
expected_generation=0,
)
- oauth.refresh_error = CodexAuthError("token_refresh_failed", "boom", 502)
+ oauth.refresh_error = CodexAuthError("token_refresh_rejected", "boom", 401)
with pytest.raises(CodexAuthError):
await service.get_token()
diff --git a/tests/services/llm/test_openai_codex_oauth_provider.py b/tests/services/llm/test_openai_codex_oauth_provider.py
index 3e0ad2f0e..32ffb0378 100644
--- a/tests/services/llm/test_openai_codex_oauth_provider.py
+++ b/tests/services/llm/test_openai_codex_oauth_provider.py
@@ -185,11 +185,10 @@ async def test_401_with_dead_refresh_token_does_not_promise_a_retry(
@pytest.mark.asyncio
-async def test_403_marks_reauth_required_account_level_denial(
+async def test_403_does_not_mark_reauth_required(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A 403 is an account-level denial refresh cannot fix; it must not be
- replayed as a retry loop and should mark the session for fast failure."""
+ """A 403 may be model access denial, not a revoked OAuth grant."""
service = FakeCodexService()
async def rejected_request(*_args: Any, **_kwargs: Any) -> tuple[str, list[Any], str]:
@@ -205,7 +204,7 @@ async def test_403_marks_reauth_required_account_level_denial(
assert result.finish_reason == "error"
assert "account" in result.content.lower()
- assert service.marked_reauth is True
+ assert service.marked_reauth is False
@pytest.mark.asyncio