Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions src/codex/quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1063,7 +1063,8 @@ export function parseMainPolicyUsageQuota(data: WhamUsageResponse): MainPolicyQu
const windows = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
if (windows.some(window => isInvalidPolicyUsagePercent(window?.used_percent))) return null;
const quota = filterMainPolicyMonthlyQuota(parseUsageQuota(data), isThirtyDayOnlyCodexPlan(data.plan_type));
return quota ? withWhamShortWindowAbsence(data, quota) : null;
// #8596: a complete, allowed main read retires a carried monthly tuple under the pool proof (#8067).
return quota ? withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota)) : null;
}

/** Derive absence from complete WHAM topology without changing the display quota. */
Expand Down Expand Up @@ -1097,22 +1098,33 @@ export function poolWhamPolicyObservation(
data: WhamUsageResponse, quota: Omit<StoredAccountQuota, "updatedAt"> | null,
): MainPolicyQuotaObservation | null {
if (!quota || !isValidWhamHistoryObservation(data)) return null;
// Retirement releases a block, so a present reading that does not parse is not "unknown".
if (data.rate_limit?.allowed === false || hasMalformedWhamReading(data)) return quota;
return withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota));
}

/** Retirement releases a block, so a present reading that does not parse is not "unknown". */
function hasMalformedWhamReading(data: WhamUsageResponse): boolean {
const readings = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
for (const limit of Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : []) {
if (limit && typeof limit === "object") readings.push(limit.rate_limit?.primary_window, limit.rate_limit?.secondary_window);
}
const malformed = readings.some(window => window?.used_percent != null
return readings.some(window => window?.used_percent != null
&& normalizeUsagePercent(window.used_percent) === undefined);
if (data.rate_limit?.allowed === false || malformed) return quota;
const observation = withWhamShortWindowAbsence(data, quota);
// #8067: the same complete topology proves a pool account has no monthly window when no window
// declares a monthly duration and no tertiary window is present, so a plan change away from a
// monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
// keep their existing retention rules.
}

/**
* #8067/#8596: the complete topology that proves short-window absence also proves there is no
* monthly window when no window declares a monthly duration and no tertiary window is present,
* so a plan change away from a monthly primary (Free to Pro Lite) retires the carried tuple.
* An explicit denial and invalid or unparseable readings never supply that proof.
*/
function withWhamMonthlyWindowAbsence(
data: WhamUsageResponse, observation: MainPolicyQuotaObservation,
): MainPolicyQuotaObservation {
if (observation.shortWindowAbsent !== true || data.rate_limit?.allowed === false) return observation;
if (!isValidWhamHistoryObservation(data) || hasMalformedWhamReading(data)) return observation;
const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
return observation.shortWindowAbsent === true
&& !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
return !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
? { ...observation, monthlyWindowAbsent: true }
: observation;
}
Expand Down
2 changes: 1 addition & 1 deletion structure/providers/openai-tiers.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ cannot prove that the short window disappeared. All-null credits-only and tertia
the resulting weekly/monthly window still blocks at its long threshold (98% by default). This prevents old short-window exhaustion
from surviving indefinitely on a now weekly/monthly account. A live main writer applies that same
retirement proof to the display/rotation cache, so account selection cannot keep refusing the
recovered main account on its old short tuple. Pool accounts get the same proof from a valid complete WHAM probe (#7961): `poolWhamPolicyObservation` marks the observation from its window topology only, so a Plus to Pro upgrade cannot keep a stored pool account on the old plan's 5-hour tuple, while partial WHAM, invalid or unparseable readings, an explicit `allowed: false` verdict and response headers keep carrying it. A pool probe retires the tuple only with a live captured pool writer for that account and credential generation, the same proof its history write needs; a missing, stale or other-account writer keeps the tuple. The login usage read marks its observation the same way, but reauthentication clears the row before writing and creation refuses existing ids, so it has nothing to retire. The same complete topology, when no window declares a monthly duration and no tertiary window is present, also retires a carried monthly tuple under the same writer proof (#8067), so a Free to Pro Lite change cannot keep a pool account on the old plan's exhausted monthly reading. Main-only monthly filtering is not applied to pool observations, and a main observation without a live main writer still carries its tuple. Coverage lives in `tests/codex-integration/codex-credits-probes.test.ts` (pool),
recovered main account on its old short tuple. Pool accounts get the same proof from a valid complete WHAM probe (#7961): `poolWhamPolicyObservation` marks the observation from its window topology only, so a Plus to Pro upgrade cannot keep a stored pool account on the old plan's 5-hour tuple, while partial WHAM, invalid or unparseable readings, an explicit `allowed: false` verdict and response headers keep carrying it. A pool probe retires the tuple only with a live captured pool writer for that account and credential generation, the same proof its history write needs; a missing, stale or other-account writer keeps the tuple. The login usage read marks its observation the same way, but reauthentication clears the row before writing and creation refuses existing ids, so it has nothing to retire. The same complete topology, when no window declares a monthly duration and no tertiary window is present, also retires a carried monthly tuple under the same writer proof (#8067), so a Free to Pro Lite change cannot keep a pool account on the old plan's exhausted monthly reading. A complete main WHAM read with a live main writer carries the same monthly proof into both the display cache and the identity-bound policy snapshot (#8596), so a stale monthly tuple with no upstream window cannot refuse every main request; an explicit `allowed: false`, invalid or unparseable readings (additional windows included), partial topology and response headers keep it. Main-only monthly filtering is not applied to pool observations, and a main observation without a live main writer still carries its tuple. Coverage lives in `tests/codex-integration/codex-credits-probes.test.ts` (pool),
`tests/codex-integration/main-quota-evidence-validation.test.ts`,
`tests/codex-integration/main-account-hard-lock-retirement.test.ts`,
`tests/codex-integration/main-quota-provenance.test.ts`, and
Expand Down
179 changes: 175 additions & 4 deletions tests/codex-integration/pool-monthly-window-retirement.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { capturePoolQuotaWriter, readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store";
Expand All @@ -9,7 +9,8 @@ import { resetCodexCreditsForTests } from "../../src/codex/credits";
import { captureMainQuotaWriter, clearMainAccountInfoCache, observeMainQuotaIdentity } from "../../src/codex/main-account-cache";
import {
applyAccountQuotaFromUpstreamHeaders, clearAccountQuota, getAccountQuota, getMainPolicyQuota, isCodexQuotaExhausted,
parseMainPolicyUsageQuota, parseUsageQuota, poolWhamPolicyObservation, setAccountQuotaFromParsed, type WhamUsageResponse,
parseMainPolicyUsageQuota, parseUsageQuota, poolWhamPolicyObservation, setAccountQuotaFromParsed, settleQuotaPersistenceForTests,
type WhamUsageResponse,
} from "../../src/codex/quota";
import { resetQuotaQueryBackoffForTests } from "../../src/codex/quota-query-backoff";
import { captureConfigGeneration } from "../../src/lib/state-store-sweeper";
Expand Down Expand Up @@ -130,7 +131,7 @@ describe("pool WHAM monthly-window retirement (#8067)", () => {
});
});

describe("main observations keep their monthly retention rules", () => {
describe("main WHAM monthly-window retirement (#8596)", () => {
const mainIdentity = "monthly-retire-main-fixture";
const publish = (data: WhamUsageResponse) => setAccountQuotaFromParsed(MAIN, parseUsageQuota(data), undefined,
captureMainQuotaWriter(mainIdentity), parseMainPolicyUsageQuota(data));
Expand Down Expand Up @@ -162,5 +163,175 @@ describe("main observations keep their monthly retention rules", () => {
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100);
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "prolite")).toBe(true);
});

// The #8596 payload: Plus, weekly primary, secondary_window null and no tertiary key at all.
const plusWeeklyOnly = (rate: Record<string, unknown> = {}) => ({ plan_type: "plus",
rate_limit: { allowed: true, limit_reached: false, primary_window: weekly(1), secondary_window: null, ...rate } });
const exhaustMonthly = () => publish({ plan_type: "free", rate_limit: { allowed: false, primary_window: monthly(), secondary_window: null } });

test("a complete allowed weekly-only read retires the carried monthly tuple in both caches", () => {
observeMainQuotaIdentity(mainIdentity);
exhaustMonthly();
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(true);
expect(parseMainPolicyUsageQuota(plusWeeklyOnly())?.monthlyWindowAbsent).toBe(true);
publish(plusWeeklyOnly());
for (const quota of caches()) {
expect(quota?.weeklyPercent).toBe(1);
expect(quota?.monthlyPercent).toBeUndefined();
expect(quota?.monthlyResetAt).toBeUndefined();
expect(quota?.monthlyIsPrimaryWindow).toBeUndefined();
expect(quota).not.toHaveProperty("monthlyWindowAbsent");
}
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(false);
// An explicit null tertiary is the same complete topology.
exhaustMonthly();
publish(plusWeeklyOnly({ tertiary_window: null }));
for (const quota of caches()) expect(quota?.monthlyPercent).toBeUndefined();
});

test("a present monthly window replaces the reading instead of retiring it", () => {
observeMainQuotaIdentity(mainIdentity);
exhaustMonthly();
publish(plusWeeklyOnly({ tertiary_window: monthly(40) }));
expect(getAccountQuota(MAIN)?.monthlyPercent).toBe(40);
exhaustMonthly();
publish({ plan_type: "free", rate_limit: { allowed: true, primary_window: monthly(30), secondary_window: null } });
for (const quota of caches()) {
expect(quota?.monthlyPercent).toBe(30);
expect(quota?.monthlyIsPrimaryWindow).toBe(true);
}
// A genuine monthly-primary plan with a weekly secondary (Team) keeps its monthly reading.
publish({ plan_type: "team", rate_limit: { allowed: true, primary_window: monthly(5), secondary_window: weekly(2) } });
expect(parseMainPolicyUsageQuota({ plan_type: "team", rate_limit: { allowed: true, primary_window: monthly(5), secondary_window: weekly(2) } })
?.monthlyWindowAbsent).toBeUndefined();
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(5);
});

test("partial, invalid, header-only and writerless main reads keep the carried tuple", () => {
observeMainQuotaIdentity(mainIdentity);
exhaustMonthly();
publish({ plan_type: "plus", rate_limit: { primary_window: weekly(1) } });
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100);
publish({ plan_type: "plus", rate_limit: { primary_window: weekly(1), secondary_window: null } });
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100);
publish(plusWeeklyOnly({ primary_window: { ...weekly(), used_percent: -1 } }));
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100);
publish(plusWeeklyOnly({ primary_window: { ...weekly(), used_percent: "n/a" } }));
for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100);
applyAccountQuotaFromUpstreamHeaders(MAIN, new Headers({
"x-codex-primary-used-percent": "1", "x-codex-primary-window-minutes": "10080",
}));
expect(getAccountQuota(MAIN)?.monthlyPercent).toBe(100);
const data = plusWeeklyOnly();
setAccountQuotaFromParsed(MAIN, parseUsageQuota(data), undefined, undefined, parseMainPolicyUsageQuota(data));
expect(getAccountQuota(MAIN)?.monthlyPercent).toBe(100);
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(true);
});
});


describe("main monthly retirement survives saves, restarts and stale writers (#8596)", () => {
const identityA = "monthly-retire-main-a";
const identityB = "monthly-retire-main-b";
const exhausted = { plan_type: "free", rate_limit: { allowed: false, primary_window: monthly(), secondary_window: null } };
const weeklyOnly = { plan_type: "plus", rate_limit: { allowed: true, primary_window: weekly(1), secondary_window: null } };
const publishWith = (writer: ReturnType<typeof captureMainQuotaWriter>, data: WhamUsageResponse) =>
setAccountQuotaFromParsed(MAIN, parseUsageQuota(data), undefined, writer, parseMainPolicyUsageQuota(data));
const writerFor = (identity: string) => {
observeMainQuotaIdentity(identity);
const writer = captureMainQuotaWriter(identity);
if (!writer) throw new Error("Expected an observed main quota writer");
return writer;
};
const monthlyFields = (quota: Record<string, unknown> | null | undefined) =>
["monthlyPercent", "monthlyResetAt", "monthlyIsPrimaryWindow", "monthlyWindowAbsent"].filter(key => quota?.[key] !== undefined);

// Capture quota's debounced persistence callback so the real serializer runs without a sleep.
let pendingPersist: { run: () => void; timer: ReturnType<typeof setTimeout> } | undefined;
let timerSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
const nativeSetTimeout = globalThis.setTimeout;
pendingPersist = undefined;
timerSpy = spyOn(globalThis, "setTimeout").mockImplementation(((
callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]
) => {
if (delay !== 250) return nativeSetTimeout(callback, delay, ...args);
const timer = nativeSetTimeout(() => {}, 60_000);
pendingPersist = { run: () => callback(...args), timer };
return timer;
}) as typeof setTimeout);
});
afterEach(() => {
if (pendingPersist) clearTimeout(pendingPersist.timer);
pendingPersist = undefined;
timerSpy.mockRestore();
});
async function flushPersistence(): Promise<{ quotas: Record<string, Record<string, unknown>>; mainPolicyQuota?: { quota: Record<string, unknown> } }> {
if (!pendingPersist) throw new Error("Expected a scheduled quota persistence");
const pending = pendingPersist;
pendingPersist = undefined;
clearTimeout(pending.timer);
pending.run();
await settleQuotaPersistenceForTests();
return JSON.parse(readFileSync(join(testDir, "codex-quota-cache.json"), "utf8"));
}

test("the retirement is saved for both caches and a restart does not bring the tuple back", async () => {
const writer = writerFor(identityA);
publishWith(writer, exhausted);
const before = await flushPersistence();
expect(before.quotas[MAIN].monthlyPercent).toBe(100);
expect(before.mainPolicyQuota?.quota.monthlyPercent).toBe(100);
publishWith(writer, weeklyOnly);
const saved = await flushPersistence();
expect(monthlyFields(saved.quotas[MAIN])).toEqual([]);
expect(monthlyFields(saved.mainPolicyQuota?.quota)).toEqual([]);
expect(saved.quotas[MAIN].weeklyPercent).toBe(1);
// Restart: drop the process state, then hydrate from exactly the saved bytes.
const bytes = readFileSync(join(testDir, "codex-quota-cache.json"), "utf8");
clearAccountQuota();
writeFileSync(join(testDir, "codex-quota-cache.json"), bytes);
observeMainQuotaIdentity(identityA);
expect(getAccountQuota(MAIN)?.weeklyPercent).toBe(1);
expect(getMainPolicyQuota()?.weeklyPercent).toBe(1);
for (const quota of [getAccountQuota(MAIN), getMainPolicyQuota()]) expect(monthlyFields(quota as never)).toEqual([]);
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(false);
});

test("later partial, header-only and credits-only saves cannot reintroduce the retired tuple", async () => {
const writer = writerFor(identityA);
publishWith(writer, exhausted);
publishWith(writer, weeklyOnly);
await flushPersistence();
publishWith(writer, { plan_type: "plus", rate_limit: { primary_window: weekly(2) } });
applyAccountQuotaFromUpstreamHeaders(MAIN, new Headers({
"x-codex-primary-used-percent": "3", "x-codex-primary-window-minutes": "10080",
}));
setAccountQuotaFromParsed(MAIN, { resetCredits: 0 }, undefined, writer);
const saved = await flushPersistence();
expect(monthlyFields(saved.quotas[MAIN])).toEqual([]);
expect(monthlyFields(saved.mainPolicyQuota?.quota)).toEqual([]);
for (const quota of [getAccountQuota(MAIN), getMainPolicyQuota()]) expect(monthlyFields(quota as never)).toEqual([]);
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(false);
});

test("a stale-identity writer can neither retire the tuple nor restore it after a live retirement", async () => {
const stale = writerFor(identityA);
publishWith(stale, exhausted);
// A -> B -> A: the writer captured before the transition is no longer live.
writerFor(identityB);
const live = writerFor(identityA);
publishWith(live, exhausted);
publishWith(stale, weeklyOnly);
for (const quota of [getAccountQuota(MAIN), getMainPolicyQuota()]) expect(quota?.monthlyPercent).toBe(100);
expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(true);
publishWith(live, weeklyOnly);
for (const quota of [getAccountQuota(MAIN), getMainPolicyQuota()]) expect(quota?.monthlyPercent).toBeUndefined();
// A delayed commit of the old exhausted reading from the stale writer is refused.
publishWith(stale, exhausted);
for (const quota of [getAccountQuota(MAIN), getMainPolicyQuota()]) expect(monthlyFields(quota as never)).toEqual([]);
const saved = await flushPersistence();
expect(monthlyFields(saved.quotas[MAIN])).toEqual([]);
expect(monthlyFields(saved.mainPolicyQuota?.quota)).toEqual([]);
});
});
Loading