Skip to content

Commit 77ebee3

Browse files
committed
fix(codex): retain short-window quota end to end
1 parent a5ec641 commit 77ebee3

4 files changed

Lines changed: 139 additions & 9 deletions

File tree

‎src/codex/quota.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ function normalizeResetAt(value: unknown): number | undefined {
186186
}
187187

188188
function hasKnownQuotaValue(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
189-
return [quota.weeklyPercent, quota.monthlyPercent]
189+
return [quota.weeklyPercent, quota.monthlyPercent, quota.shortPercent]
190190
.some(value => typeof value === "number" && Number.isFinite(value));
191191
}
192192

@@ -226,8 +226,14 @@ function snapshotHasMonthly(quota: Omit<StoredAccountQuota, "updatedAt">): boole
226226
return quota.monthlyPercent !== undefined || quota.monthlyResetAt !== undefined;
227227
}
228228

229+
function snapshotHasShort(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
230+
return quota.shortPercent !== undefined
231+
|| quota.shortResetAt !== undefined
232+
|| quota.shortWindowSeconds !== undefined;
233+
}
234+
229235
function snapshotHasUsage(quota: Omit<StoredAccountQuota, "updatedAt">): boolean {
230-
return snapshotHasWeekly(quota) || snapshotHasMonthly(quota);
236+
return snapshotHasWeekly(quota) || snapshotHasMonthly(quota) || snapshotHasShort(quota);
231237
}
232238
export function setAccountQuotaFromParsed(
233239
accountId: string,
@@ -246,6 +252,9 @@ export function setAccountQuotaFromParsed(
246252
if (existing?.monthlyPercent !== undefined) next.monthlyPercent = existing.monthlyPercent;
247253
if (existing?.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
248254
if (existing?.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
255+
if (existing?.shortPercent !== undefined) next.shortPercent = existing.shortPercent;
256+
if (existing?.shortResetAt !== undefined) next.shortResetAt = existing.shortResetAt;
257+
if (existing?.shortWindowSeconds !== undefined) next.shortWindowSeconds = existing.shortWindowSeconds;
249258
next.resetCredits = quota.resetCredits;
250259
accountQuota.set(accountId, next);
251260
schedulePersistAccountQuotas();
@@ -270,12 +279,25 @@ export function setAccountQuotaFromParsed(
270279
// while silently dropping `monthlyIsPrimaryWindow` would look like tertiary-only data to
271280
// any future reader, and that failure would be invisible.
272281
if (quota.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
273-
} else if (snapshotHasWeekly(quota) && existing?.monthlyPercent !== undefined) {
282+
} else if ((snapshotHasWeekly(quota) || snapshotHasShort(quota))
283+
&& existing?.monthlyPercent !== undefined) {
274284
next.monthlyPercent = existing.monthlyPercent;
275285
if (existing.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
276286
if (existing.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
277287
}
278288

289+
if (snapshotHasShort(quota)) {
290+
if (quota.shortPercent !== undefined) next.shortPercent = quota.shortPercent;
291+
if (quota.shortResetAt !== undefined) next.shortResetAt = quota.shortResetAt;
292+
if (quota.shortWindowSeconds !== undefined) next.shortWindowSeconds = quota.shortWindowSeconds;
293+
} else {
294+
// Header and reset-credit updates are partial snapshots. Preserve the last full WHAM
295+
// burst tuple when those updates do not carry enough window metadata to replace it.
296+
if (existing?.shortPercent !== undefined) next.shortPercent = existing.shortPercent;
297+
if (existing?.shortResetAt !== undefined) next.shortResetAt = existing.shortResetAt;
298+
if (existing?.shortWindowSeconds !== undefined) next.shortWindowSeconds = existing.shortWindowSeconds;
299+
}
300+
279301
if (quota.resetCredits !== undefined) next.resetCredits = quota.resetCredits;
280302
else if (existing?.resetCredits !== undefined) next.resetCredits = existing.resetCredits;
281303

@@ -369,6 +391,9 @@ export function updateAccountQuota(
369391
: {}),
370392
...(existing?.weeklyResetAt !== undefined ? { weeklyResetAt: existing.weeklyResetAt } : {}),
371393
...(existing?.monthlyResetAt !== undefined ? { monthlyResetAt: existing.monthlyResetAt } : {}),
394+
...(existing?.shortPercent !== undefined ? { shortPercent: existing.shortPercent } : {}),
395+
...(existing?.shortResetAt !== undefined ? { shortResetAt: existing.shortResetAt } : {}),
396+
...(existing?.shortWindowSeconds !== undefined ? { shortWindowSeconds: existing.shortWindowSeconds } : {}),
372397
...(existing?.resetCredits !== undefined ? { resetCredits: existing.resetCredits } : {}),
373398
updatedAt: Date.now(),
374399
};

‎src/codex/routing.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -322,14 +322,12 @@ function deleteScopedHealth(accountId: string, scope: CodexQuotaScope): void {
322322
export function computeCodexUsageScore(quota: {
323323
weeklyPercent?: number;
324324
monthlyPercent?: number;
325+
shortPercent?: number;
325326
} | null, plan?: unknown): number {
326327
if (!quota) return CODEX_UNKNOWN_USAGE_SCORE;
327-
if (isThirtyDayOnlyCodexPlan(plan)) {
328-
return typeof quota.monthlyPercent === "number" && Number.isFinite(quota.monthlyPercent)
329-
? quota.monthlyPercent
330-
: CODEX_UNKNOWN_USAGE_SCORE;
331-
}
332-
const values = [quota.weeklyPercent, quota.monthlyPercent]
328+
const values = (isThirtyDayOnlyCodexPlan(plan)
329+
? [quota.monthlyPercent, quota.shortPercent]
330+
: [quota.weeklyPercent, quota.monthlyPercent, quota.shortPercent])
333331
.filter((value): value is number => typeof value === "number" && Number.isFinite(value));
334332
return values.length > 0 ? Math.max(...values) : CODEX_UNKNOWN_USAGE_SCORE;
335333
}

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

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1183,6 +1183,56 @@ describe("codex-auth API", () => {
11831183
expect(getAccountQuota("preserve-valid")).toEqual(before);
11841184
});
11851185

1186+
test("quota cache rebuilds preserve the short-window tuple", () => {
1187+
setAccountQuotaFromParsed("short-cache", {
1188+
weeklyPercent: 1,
1189+
weeklyResetAt: 2_000_586_800,
1190+
monthlyPercent: 3,
1191+
monthlyResetAt: 2_002_592_000,
1192+
shortPercent: 0,
1193+
shortResetAt: 2_000_000_000,
1194+
shortWindowSeconds: 18_000,
1195+
});
1196+
expect(getAccountQuota("short-cache")).toMatchObject({
1197+
weeklyPercent: 1,
1198+
shortPercent: 0,
1199+
shortResetAt: 2_000_000_000,
1200+
shortWindowSeconds: 18_000,
1201+
});
1202+
1203+
setAccountQuotaFromParsed("short-cache", {
1204+
shortPercent: 4,
1205+
shortResetAt: 2_000_000_100,
1206+
shortWindowSeconds: 18_000,
1207+
});
1208+
expect(getAccountQuota("short-cache")).toMatchObject({
1209+
weeklyPercent: 1,
1210+
monthlyPercent: 3,
1211+
shortPercent: 4,
1212+
shortResetAt: 2_000_000_100,
1213+
shortWindowSeconds: 18_000,
1214+
});
1215+
1216+
updateAccountQuota("short-cache", 2, 2_000_586_900);
1217+
expect(getAccountQuota("short-cache")).toMatchObject({
1218+
weeklyPercent: 2,
1219+
monthlyPercent: 3,
1220+
shortPercent: 4,
1221+
shortResetAt: 2_000_000_100,
1222+
shortWindowSeconds: 18_000,
1223+
});
1224+
1225+
setAccountQuotaFromParsed("short-cache", { resetCredits: 3 });
1226+
expect(getAccountQuota("short-cache")).toMatchObject({
1227+
weeklyPercent: 2,
1228+
monthlyPercent: 3,
1229+
shortPercent: 4,
1230+
shortResetAt: 2_000_000_100,
1231+
shortWindowSeconds: 18_000,
1232+
resetCredits: 3,
1233+
});
1234+
});
1235+
11861236
test("GET /api/codex-auth/quota returns stored quotas", async () => {
11871237
updateAccountQuota("q-test", 30);
11881238
const req = new Request("http://localhost/api/codex-auth/quota", { method: "GET" });
@@ -1230,6 +1280,47 @@ describe("codex-auth API", () => {
12301280
}
12311281
});
12321282

1283+
test("GET /api/codex-auth/accounts preserves a parsed K12 short window through cache and DTO", async () => {
1284+
const config = makeConfig();
1285+
seedPoolAccount(config, {
1286+
id: "pool-k12-short",
1287+
1288+
plan: "k12",
1289+
accessToken: "tok",
1290+
refreshToken: "ref",
1291+
chatgptAccountId: "acc-pool-k12-short",
1292+
});
1293+
1294+
const originalFetch = globalThis.fetch;
1295+
globalThis.fetch = (async () => Response.json({
1296+
plan_type: "k12",
1297+
rate_limit: {
1298+
primary_window: { used_percent: 0, reset_at: 2_000_000_000, limit_window_seconds: 18_000 },
1299+
secondary_window: { used_percent: 1, reset_at: 2_000_586_800, limit_window_seconds: 604_800 },
1300+
},
1301+
})) as typeof fetch;
1302+
1303+
try {
1304+
const req = new Request("http://localhost/api/codex-auth/accounts?refresh=1", { method: "GET" });
1305+
const resp = await handleCodexAuthAPI(req, new URL(req.url), config);
1306+
expect(resp!.status).toBe(200);
1307+
const data = await resp!.json() as {
1308+
accounts: Array<{ id: string; quota?: Record<string, unknown> }>;
1309+
};
1310+
const quota = data.accounts.find(account => account.id === "pool-k12-short")?.quota;
1311+
expect(quota).toMatchObject({
1312+
weeklyPercent: 1,
1313+
weeklyResetAt: 2_000_586_800,
1314+
shortPercent: 0,
1315+
shortResetAt: 2_000_000_000,
1316+
shortWindowSeconds: 18_000,
1317+
});
1318+
expect(getAccountQuota("pool-k12-short")).toMatchObject(quota!);
1319+
} finally {
1320+
globalThis.fetch = originalFetch;
1321+
}
1322+
});
1323+
12331324
test("GET /api/codex-auth/accounts refresh=1 bypasses cached pool quota", async () => {
12341325
const config = makeConfig();
12351326
seedPoolAccount(config, {

‎tests/codex-routing.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,8 @@ describe("codex routing", () => {
119119
test("usage score uses the hottest known quota window", () => {
120120
expect(computeCodexUsageScore({ weeklyPercent: 81 })).toBe(81);
121121
expect(computeCodexUsageScore({ weeklyPercent: 15, monthlyPercent: 91 })).toBe(91);
122+
expect(computeCodexUsageScore({ weeklyPercent: 15, monthlyPercent: 20, shortPercent: 92 })).toBe(92);
123+
expect(computeCodexUsageScore({ shortPercent: 0 })).toBe(0);
122124
expect(computeCodexUsageScore({ weeklyPercent: 15 })).toBe(15);
123125
});
124126

@@ -179,6 +181,7 @@ describe("codex routing", () => {
179181
test("go and free plans use only the 30d quota window", () => {
180182
expect(computeCodexUsageScore({ weeklyPercent: 99, monthlyPercent: 12 }, "go")).toBe(12);
181183
expect(computeCodexUsageScore({ weeklyPercent: 99, monthlyPercent: 13 }, "free")).toBe(13);
184+
expect(computeCodexUsageScore({ weeklyPercent: 99, monthlyPercent: 12, shortPercent: 14 }, "go")).toBe(14);
182185
expect(computeCodexUsageScore({ weeklyPercent: 1 }, "go")).toBe(CODEX_UNKNOWN_USAGE_SCORE);
183186
});
184187

@@ -1274,6 +1277,19 @@ describe("codex routing", () => {
12741277
});
12751278
});
12761279

1280+
test("a zero-valued short-only WHAM snapshot remains known quota (#2047)", () => {
1281+
expect(parseUsageQuota({
1282+
plan_type: "k12",
1283+
rate_limit: {
1284+
primary_window: { used_percent: 0, reset_at: 2000000000, limit_window_seconds: 18000 },
1285+
},
1286+
})).toMatchObject({
1287+
shortPercent: 0,
1288+
shortResetAt: 2000000000,
1289+
shortWindowSeconds: 18000,
1290+
});
1291+
});
1292+
12771293
test("an exhausted burst window takes the account out of rotation (#1791)", () => {
12781294
// Upstream enforces the 5-hour window independently, so an account at 100% there is
12791295
// genuinely blocked even while its weekly quota is untouched. Reporting it as usable

0 commit comments

Comments
 (0)