Skip to content

Commit 79d2164

Browse files
committed
fix(codex): accept monthly-classified recovery snapshots and probe-owned refresh generations
Addresses the two unresolved Codex review threads on lidge-jun#955: - isCompleteCodexQuotaRecoverySnapshot() required weeklyPercent for every non-Go/Free plan by plan name, but the parser classifies windows by duration: a Team response with an explicitly monthly primary window parses to monthlyPercent only, so those accounts could never recover early and stayed cooled until their predicted expiry. - settleCodexQuotaRecoveryProbe() required the claim-time credential generation to match exactly. A probe-owned token refresh inside getValidCodexToken() advances the generation by one before WHAM completes, so a successful fresh reading was rejected and the account waited another probe interval. replacedAt is preserved by refresh and stamped by external replacement, so it fences the +1 transition.
1 parent 493329d commit 79d2164

3 files changed

Lines changed: 90 additions & 11 deletions

File tree

‎src/codex/quota.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,17 @@ export function isCompleteCodexQuotaRecoverySnapshot(
103103
// Recovery still fails closed on MISSING EVIDENCE — a credits-only or windowless payload
104104
// carries no usage reading at all and must never clear a cooldown. What it does not do is
105105
// fail closed on an unfamiliar plan NAME, which only ever meant "cooled forever".
106-
const required = codexQuotaWindowForPlan(plan) === "monthly"
107-
? quota.monthlyPercent
108-
: quota.weeklyPercent;
109-
return typeof required === "number" && Number.isFinite(required);
106+
//
107+
// The parser classifies windows by DURATION, not by plan name: a Team response whose
108+
// primary window is explicitly monthly parses to monthlyPercent only (no secondary
109+
// window exists), so requiring weeklyPercent because the plan is not go/free would
110+
// strand exactly those accounts until their predicted expiry. Accept whichever window(s)
111+
// the parser actually wrote; Go/Free never carry a weekly value, so monthly-only is
112+
// required there.
113+
if (codexQuotaWindowForPlan(plan) === "monthly") {
114+
return typeof quota.monthlyPercent === "number" && Number.isFinite(quota.monthlyPercent);
115+
}
116+
return hasKnownQuotaValue(quota);
110117
}
111118

112119
export function normalizeUsagePercent(value: unknown): number | undefined {

‎src/codex/routing.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@ export type CodexQuotaRecoveryProbeClaim = {
139139
leaseId: string;
140140
cooldownGeneration: number;
141141
credentialGeneration: number;
142+
/** Claim-time `replacedAt`; unchanged after a probe-owned refresh, stamped on external replacement. */
143+
credentialReplacedAt?: number;
142144
};
143145

144146
export type CodexQuotaRecoveryProbeProof = {
@@ -439,6 +441,7 @@ export function claimDueCodexQuotaRecoveryProbes(
439441
scope?: CodexQuotaScope;
440442
health: CodexUpstreamHealth;
441443
credentialGeneration: number;
444+
credentialReplacedAt?: number;
442445
order: number;
443446
}> = [];
444447
for (const [order, account] of (config.codexAccounts ?? []).entries()) {
@@ -467,6 +470,7 @@ export function claimDueCodexQuotaRecoveryProbes(
467470
...(candidate.scope ? { scope: candidate.scope } : {}),
468471
health: candidate.health,
469472
credentialGeneration: record.generation,
473+
...(record.replacedAt !== undefined ? { credentialReplacedAt: record.replacedAt } : {}),
470474
order,
471475
});
472476
}
@@ -491,6 +495,9 @@ export function claimDueCodexQuotaRecoveryProbes(
491495
leaseId,
492496
cooldownGeneration: candidate.health.cooldownGeneration ?? 0,
493497
credentialGeneration: candidate.credentialGeneration,
498+
...(candidate.credentialReplacedAt !== undefined
499+
? { credentialReplacedAt: candidate.credentialReplacedAt }
500+
: {}),
494501
};
495502
});
496503
}
@@ -506,10 +513,21 @@ export function settleCodexQuotaRecoveryProbe(
506513
? scopedHealthFor(claim.accountId, claim.scope)
507514
: upstreamHealth.get(claim.accountId);
508515
if (!health || health.probeLeaseId !== claim.leaseId) return false;
516+
const currentRecord = readCodexAccountRecord(claim.accountId);
517+
const proofGeneration = proof.credentialGeneration;
518+
// A probe-owned token refresh (getValidCodexToken) advances the credential generation by
519+
// exactly one while preserving `replacedAt`; an external credential replacement bumps the
520+
// generation too but stamps a fresh `replacedAt`. Accept the +1 transition only when the
521+
// claim-time lineage is intact AND the generation the fresh quota was proven under is live.
522+
const generationFenced = proofGeneration !== undefined
523+
&& (proofGeneration === claim.credentialGeneration
524+
? isCodexAccountGenerationLive(claim.accountId, proofGeneration)
525+
: proofGeneration === claim.credentialGeneration + 1
526+
&& currentRecord?.replacedAt === claim.credentialReplacedAt
527+
&& isCodexAccountGenerationLive(claim.accountId, proofGeneration));
509528
const fenced = (health.cooldownGeneration ?? 0) === claim.cooldownGeneration
510529
&& (health.probeLeaseGeneration ?? 0) === claim.cooldownGeneration
511-
&& claim.credentialGeneration === proof.credentialGeneration
512-
&& isCodexAccountGenerationLive(claim.accountId, claim.credentialGeneration);
530+
&& generationFenced;
513531
if (!recovered || !fenced) {
514532
const released = withProbeLeaseReleased(health, now);
515533
if (claim.scope) setScopedHealth(claim.accountId, claim.scope, released);

‎tests/codex-cooldown-recovery.test.ts‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,55 @@ describe("Codex cooldown recovery worker", () => {
117117
expect(routed).toEqual(["b", "b"]);
118118
});
119119

120+
test("recovers a Team account from a duration-classified monthly snapshot", async () => {
121+
// WHAM can legitimately return only an explicitly monthly primary window for a Team
122+
// plan (30.4-day window, no secondary). parseUsageQuota then writes monthlyPercent only,
123+
// so recovery must accept the window the parser actually classified instead of demanding
124+
// a weekly reading because the plan name is not "go"/"free".
125+
const config = makeConfig(["a"]);
126+
saveCredential("a");
127+
cool(config, "a");
128+
globalThis.fetch = async () => usageResponse(0, {
129+
plan_type: "team",
130+
rate_limit: {
131+
primary_window: { used_percent: 6, reset_at: 1_900_000_000, limit_window_seconds: 2_628_000 },
132+
secondary_window: null,
133+
tertiary_window: null,
134+
},
135+
rate_limit_reset_credits: { available_count: 0 },
136+
});
137+
await runCodexCooldownRecoveryProbes(config, due());
138+
expect(getCodexQuotaHealthSnapshot("a", "shared", due() + 1)).toBeNull();
139+
});
140+
141+
test("recovers when the probe's own token refresh advances the credential generation", async () => {
142+
// A near-expiry access token makes getValidCodexToken() refresh it inside the probe
143+
// fetch, bumping the credential generation from 1 to 2 before WHAM completes. The fresh
144+
// quota is proven under the new live generation, so settling against the claim-time
145+
// generation must accept this probe's own refresh, not treat it as a replacement.
146+
const config = makeConfig(["a"]);
147+
saveCodexAccountCredential("a", {
148+
accessToken: "access-a",
149+
refreshToken: "refresh-a",
150+
expiresAt: Date.now() + 30_000,
151+
chatgptAccountId: "acct-a",
152+
});
153+
cool(config, "a");
154+
globalThis.fetch = async input => {
155+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
156+
if (url.includes("/oauth/token")) {
157+
return new Response(JSON.stringify({
158+
access_token: "access-a-2",
159+
refresh_token: "refresh-a-2",
160+
expires_in: 3600,
161+
}), { status: 200, headers: { "Content-Type": "application/json" } });
162+
}
163+
return usageResponse(12);
164+
};
165+
await runCodexCooldownRecoveryProbes(config, due());
166+
expect(getCodexQuotaHealthSnapshot("a", "shared", due() + 1)).toBeNull();
167+
});
168+
120169
test.each([
121170
["still exhausted", () => usageResponse(100)],
122171
["credits only", () => usageResponse(0, { plan_type: "team", rate_limit_reset_credits: { available_count: 1 } })],
@@ -290,13 +339,18 @@ describe("Codex cooldown recovery worker", () => {
290339

291340
for (const plan of snapshotPlans) {
292341
const monthly = codexQuotaWindowForPlan(plan) === "monthly";
293-
const filled = monthly ? { monthlyPercent: 12 } : { weeklyPercent: 12 };
294-
const empty = monthly ? { weeklyPercent: 12 } : { monthlyPercent: 12 };
295-
expect(isCompleteCodexQuotaRecoverySnapshot(filled, plan)).toBe(true);
296-
// The other window is not evidence for this plan, in either direction.
297-
expect(isCompleteCodexQuotaRecoverySnapshot(empty, plan)).toBe(false);
342+
// The parser classifies windows by duration, so a weekly-billed plan can carry a
343+
// monthly-only reading (30-day primary, no secondary). Any window the parser actually
344+
// wrote is evidence; only Go/Free never carry a weekly value.
345+
expect(isCompleteCodexQuotaRecoverySnapshot({ weeklyPercent: 12 }, plan)).toBe(!monthly);
346+
expect(isCompleteCodexQuotaRecoverySnapshot({ monthlyPercent: 12 }, plan)).toBe(true);
298347
}
299348

349+
// Monthly-billed Go/Free parse to monthlyPercent only; a weekly-only reading is not
350+
// evidence for them.
351+
expect(isCompleteCodexQuotaRecoverySnapshot({ weeklyPercent: 12 }, "go")).toBe(false);
352+
expect(isCompleteCodexQuotaRecoverySnapshot({ weeklyPercent: 12 }, "free")).toBe(false);
353+
300354
// Absent plan follows the parser's weekly default.
301355
expect(isCompleteCodexQuotaRecoverySnapshot({ weeklyPercent: 12 }, undefined)).toBe(true);
302356
// Missing EVIDENCE still fails closed — that is the guard that matters.

0 commit comments

Comments
 (0)