DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(codex): fail fast on a credential that no longer refreshes instead of re-prompting every turn (#1454)
ZQR11013b467ac0eb2e
diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex ac6ae51a6..91c87c15a 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -51,6 +51,14 @@ logger = logging.getLogger(__name__)MANAGED_BY = "openai_codex_oauth"CODEX_PROFILE_ID = "llm-profile-openai-codex-managed"+# After a refresh the provider rejects, get_token stays terminal for this+# long instead of calling the token endpoint again on every turn (#1454).+# A revoked / de-authorized session used to surface a fresh reauth per+# message; one acknowledged failure now fails fast with a clear error, and+# the short window leaves room for a transient outage to clear before the+# next attempt instead of permanently locking the credential.+CODE_AUTH_FAILURE_COOLDOWN_S = 60+@dataclass(frozen=True)class CatalogSyncResult:@@ -418,6 +426,7 @@ class CodexOAuthService:self._inference_lock = asyncio.Lock()self._active_inferences = 0self._logging_out = False+ self._reauth_until: float | None = None@staticmethodasync def _start_default_callback(expected_state: str) -> LoopbackCallback:@@ -587,6 +596,7 @@ class CodexOAuthService:self._last_snapshot = snapshotoperation.activated = sync_result.activatedoperation.operation_state = "completed"+ self._clear_reauth_required()except CodexAuthError as exc:operation.error_code = exc.codeif exc.code == "login_cancelled":@@ -669,6 +679,16 @@ class CodexOAuthService:"Sign in to Codex before using this model.",401,)+ if self._reauth_required():+ # A recent refresh was rejected — the stored session no+ # longer refreshes (revoked, de-authorized). Fail fast with a+ # terminal error instead of asking the token endpoint again+ # on this turn or the next (#1454).+ raise CodexAuthError(+ "authentication_required",+ "Codex sign-in could not be renewed. Sign in to Codex again.",+ 401,+ )if credentials.expires_at - int(self._clock()) > 300:return credentials.public_token()refreshed = await self._refresh_credentials(credentials)@@ -728,7 +748,14 @@ class CodexOAuthService:self,credentials: CodexCredentials,) -> CodexCredentials:- payload = await self._oauth.refresh(credentials.refresh_token)+ 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()+ raiserefreshed = self._credentials_from_payload(payload,expected_generation=credentials.generation,@@ -758,7 +785,11 @@ class CodexOAuthService:)if credentials.generation != generation:return- await self._refresh_credentials(credentials)+ try:+ await self._refresh_credentials(credentials)+ finally:+ if not self._reauth_required():+ self._clear_reauth_required()@asynccontextmanagerasync def inference_guard(self) -> AsyncIterator[None]:@@ -806,6 +837,7 @@ class CodexOAuthService:passself._last_snapshot = Noneself._operation = None+ self._clear_reauth_required()return self.public_status()finally:async with self._inference_lock:@@ -866,6 +898,25 @@ class CodexOAuthService:self._model_catalog.update(mutate)return self.public_status()+ def _mark_reauth_required(self) -> None:+ self._reauth_until = self._clock() + CODE_AUTH_FAILURE_COOLDOWN_S++ def _clear_reauth_required(self) -> None:+ self._reauth_until = None++ def _reauth_required(self) -> bool:+ 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._operationcredentials: CodexCredentials | None = Nonediff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.pyindex db63f981e..d8ea241be 100644--- a/deeptutor/services/llm/provider_core/openai_codex_provider.py+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py@@ -99,6 +99,12 @@ class OpenAICodexProvider(LLMProvider):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()raisereturn LLMResponse(content=content,diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex b4c7ed540..011fbdfbf 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -582,6 +582,7 @@ class FakeOAuthClient:}self.exchange_error: CodexAuthError | None = Noneself.revoke_error: CodexAuthError | None = None+ self.refresh_error: CodexAuthError | None = Noneself.refresh_started: asyncio.Event | None = Noneself.refresh_release: asyncio.Event | None = Noneself.refresh_calls = 0@@ -600,6 +601,8 @@ class FakeOAuthClient:async def refresh(self, refresh_token: str) -> dict[str, Any]:del refresh_tokenself.refresh_calls += 1+ if self.refresh_error is not None:+ raise self.refresh_errorif self.refresh_started is not None:self.refresh_started.set()if self.refresh_release is not None:@@ -1548,6 +1551,101 @@ async def test_recover_after_unauthorized_forces_refresh_for_next_request(assert store.load_credentials().access_token == "refreshed-access" # type: ignore[union-attr]+async def test_get_token_stops_refreshing_after_a_failed_refresh(tmp_path: Path) -> None:+ """A refresh the provider rejects must not be retried on every get_token++ When the stored credential no longer refreshes (a revoked session, an+ account the provider no longer authorizes), every turn used to call the+ token endpoint again, fail again, and surface a fresh reauth each message.+ One failure is enough to hold the auth state for the cooldown window and+ fail fast with a clear error instead of hammering the provider per turn.+ """+ 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",+ "Codex authentication could not be refreshed.",+ 502,+ )++ with pytest.raises(CodexAuthError) as first:+ await service.get_token()+ assert first.value.code == "token_refresh_failed"+ assert oauth.refresh_calls == 1++ # Same conversation, next turn, still inside the cooldown: no second trip+ # to the provider, a clear terminal error instead.+ with pytest.raises(CodexAuthError) as second:+ await service.get_token()+ assert second.value.code == "authentication_required"+ assert oauth.refresh_calls == 1+++async def test_get_token_retries_after_the_reauth_cooldown_elapses(tmp_path: Path) -> None:+ """The cooldown is not a permanent lock: a transient failure can recover."""+ 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", "boom", 502)++ with pytest.raises(CodexAuthError):+ await service.get_token()+ assert oauth.refresh_calls == 1++ # Let the cooldown elapse; the next call is allowed one fresh attempt.+ clock[0] += 120+ oauth.refresh_error = None+ token = await service.get_token()+ assert oauth.refresh_calls == 2+ assert token.access_token == "refreshed-access"+++async def test_failed_refresh_marks_reauth_required_until_next_login(+ tmp_path: Path,+) -> None:+ """Once flagged, get_token stays terminal until a new sign-in succeeds."""+ 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", "boom", 502)++ with pytest.raises(CodexAuthError):+ await service.get_token()++ started = await service.start_login()+ query = urlsplit(started["authorize_url"]).query+ state = parse_qs(query)["state"][0]+ await service.complete_login_with_callback_url(+ f"{started['redirect_uri']}?code=authorization-code&state={state}"+ )+ await _wait_until_terminal(service)++ oauth.refresh_error = None+ token = await service.get_token()+ # A successful sign-in cleared the terminal flag and replaced the+ # credential; no refresh is triggered because the new token is fresh.+ assert token.access_token == "new-access"++_REDIRECT_URI = "http://localhost:1455/auth/callback"diff --git a/tests/services/llm/test_openai_codex_oauth_provider.py b/tests/services/llm/test_openai_codex_oauth_provider.pyindex ea8180236..4baf93b7c 100644--- a/tests/services/llm/test_openai_codex_oauth_provider.py+++ b/tests/services/llm/test_openai_codex_oauth_provider.py@@ -28,6 +28,7 @@ class FakeCodexService:self.token_calls = 0self.guard_entries = 0self.recovered_generation: int | None = None+ self.marked_reauth: bool = Falseself.runtime_validations: list[tuple[CodexToken, str, str | None]] = []async def get_token(self) -> CodexToken:@@ -45,6 +46,9 @@ class FakeCodexService:) -> None:self.runtime_validations.append((token, model_slug, reasoning_effort))+ def mark_reauth_required(self) -> None:+ self.marked_reauth = True+@asynccontextmanagerasync def inference_guard(self) -> AsyncIterator[None]:self.guard_entries += 1@@ -174,6 +178,30 @@ async def test_401_with_dead_refresh_token_does_not_promise_a_retry(assert "sign in again" in result.content.lower()+async def test_403_marks_reauth_required_account_level_denial(+ 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."""+ service = FakeCodexService()++ async def rejected_request(*_args: Any, **_kwargs: Any) -> tuple[str, list[Any], str]:+ raise CodexHTTPError(403, module._friendly_error(403))++ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)+ monkeypatch.setattr(module, "_request_codex", rejected_request)++ result = await OpenAICodexProvider().chat(+ [{"role": "user", "content": "hello"}],+ model="gpt-5.6-sol",+ )++ assert result.finish_reason == "error"+ assert "account" in result.content.lower()+ assert service.marked_reauth is True++@pytest.mark.asyncioasync def test_429_never_reads_openai_api_key_or_falls_back(monkeypatch: pytest.MonkeyPatch,