Skip to content

Commit bbf2aad

Browse files
committed
fix(codex): keep the identity-change retry from upgrading a background refresh
CodeRabbit caught a hole in the previous commit. `forceRefresh` carries two meanings: "bypass the cache" and "the caller asked for this". Gating the reauth clear on it left `retryMainAccountInfoIfIdentityChanged` able to launder a background poll into operator intent, because that retry re-enters `fetchMainAccountInfoWhileOwned(true, ...)` purely to re-read past a stale cache. So a background refresh that crossed an identity change came back with the authority to retract a quarantine raised — by real traffic 401/403 — against the new identity while the retry probe was in flight. Split the two meanings: `explicitRefresh` defaults to `forceRefresh` and the retry propagates the caller's original value. The reauth clear now keys off `explicitRefresh`; cache bypass is unchanged. Note the purge on a genuine identity change is a separate and correct path — `reconcileMainCodexAccountRuntimeState` drops the previous identity's quarantine, quota, health, and thread map because it is a different account. The new test marks the quarantine after that purge so it pins the retry, not the purge. Verified on win32: - bun run typecheck exit 0 - 12 auth/routing/oauth suites 596 pass / 0 fail Mutation-checked: - clear gated on `forceRefresh` (this hole) → 1 fail, the new retry test - clear unconditional (the original bug) → 2 fail, both regression tests
1 parent e921346 commit bbf2aad

2 files changed

Lines changed: 50 additions & 5 deletions

File tree

‎src/codex/auth-api.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -644,12 +644,13 @@ async function retryMainAccountInfoIfIdentityChanged(
644644
requestAccountId: string | null,
645645
retriesRemaining: number,
646646
nativeMainLease: AdmissionLease,
647+
explicitRefresh: boolean,
647648
): Promise<MainAccountInfoFetchResult | null> {
648649
const currentAccountId = getMainChatgptAccountId();
649650
if (currentAccountId === null || currentAccountId === requestAccountId) return null;
650651
reconcileMainCodexAccountRuntimeState();
651652
return retriesRemaining > 0
652-
? fetchMainAccountInfoWhileOwned(true, retriesRemaining - 1, nativeMainLease)
653+
? fetchMainAccountInfoWhileOwned(true, retriesRemaining - 1, nativeMainLease, explicitRefresh)
653654
: { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
654655
}
655656

@@ -696,6 +697,13 @@ async function fetchMainAccountInfoWhileOwned(
696697
forceRefresh: boolean,
697698
retriesRemaining: number,
698699
nativeMainLease: AdmissionLease,
700+
/**
701+
* Whether the *caller* asked for this refresh. `forceRefresh` also means "bypass the
702+
* cache", and `retryMainAccountInfoIfIdentityChanged` re-enters with it set purely to
703+
* re-read after the identity changed. Keeping the two apart stops that retry from
704+
* promoting a background poll into operator intent below.
705+
*/
706+
explicitRefresh: boolean = forceRefresh,
699707
): Promise<MainAccountInfoFetchResult> {
700708
const writerGeneration = captureConfigGeneration();
701709
reconcileMainCodexAccountRuntimeState();
@@ -724,7 +732,7 @@ async function fetchMainAccountInfoWhileOwned(
724732
});
725733
if (!resp.ok) {
726734
const terminalAuthFailure = await isTerminalMainAuthResponse(resp, isMainAccountTokenVerifiablyLive());
727-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
735+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
728736
if (retried) return retried;
729737
if (terminalAuthFailure) {
730738
clearMainAccountInfoCache();
@@ -733,7 +741,7 @@ async function fetchMainAccountInfoWhileOwned(
733741
return { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
734742
}
735743
const data = (await resp.json()) as WhamUsageResponse;
736-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
744+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
737745
if (retried) return retried;
738746
const plan = nonEmptyPlan(data.plan_type) ?? nonEmptyPlan(cached?.plan) ?? nonEmptyPlan(getMainAccountPlan());
739747
const quota = parseUsageQuota({ ...data, ...(plan ? { plan_type: plan } : {}) });
@@ -754,7 +762,7 @@ async function fetchMainAccountInfoWhileOwned(
754762
// never settled and the dashboard kept showing nothing — the symptom #327 reported.
755763
// An explicit refresh is an operator asking to re-evaluate, normally right after
756764
// signing in again, so it stays authoritative.
757-
if (forceRefresh) clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
765+
if (explicitRefresh) clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
758766
// Mirror main quota + plan into the shared stores so the rotation engine can
759767
// score and auto-switch the main account exactly like a pool account (Option A).
760768
setMainAccountPlan(result.plan);
@@ -769,7 +777,7 @@ async function fetchMainAccountInfoWhileOwned(
769777
...(freshResetCredits !== undefined ? { freshResetCredits } : {}),
770778
};
771779
} catch {
772-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
780+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
773781
return retried ?? { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
774782
}
775783
}

‎tests/codex-auth-api.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,43 @@ describe("codex-auth API", () => {
892892
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
893893
});
894894

895+
test("an identity-change retry does not upgrade a background refresh into an explicit one (#327)", async () => {
896+
// `retryMainAccountInfoIfIdentityChanged` re-enters with forceRefresh=true so it can
897+
// re-read past a now-stale cache. That argument must not double as operator intent:
898+
// a background poll that crosses an identity change would otherwise come back with
899+
// the authority to retract a quarantine it was never allowed to touch.
900+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
901+
tokens: { access_token: "live-main", account_id: "acct-before" },
902+
}));
903+
clearMainAccountInfoCache();
904+
let usageCalls = 0;
905+
globalThis.fetch = (async () => {
906+
usageCalls += 1;
907+
if (usageCalls === 1) {
908+
// Identity changes on disk mid-probe. The retry's purge legitimately drops the
909+
// *previous* identity's runtime state — that is not what this test is about.
910+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
911+
tokens: { access_token: "live-main", account_id: "acct-after" },
912+
}));
913+
} else {
914+
// Real traffic quarantines the *new* identity while the retry probe is in
915+
// flight, exactly as recordCodexUpstreamOutcome does on a 401/403.
916+
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
917+
}
918+
return Response.json({
919+
920+
plan_type: "pro",
921+
rate_limit: { primary_window: { used_percent: 10, reset_at: 1783000000 } },
922+
});
923+
}) as typeof fetch;
924+
925+
await fetchMainAccountInfo(false);
926+
927+
// The retry really fired — otherwise this proves nothing about the retry path.
928+
expect(usageCalls).toBeGreaterThan(1);
929+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
930+
});
931+
895932
test("BUG-R327: main account exposes and updates needsReauth from WHAM auth responses", async () => {
896933
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
897934
tokens: {

0 commit comments

Comments
 (0)