From 53c4b114f6858287ac2df834fc244ffcfbf786dd Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 16 Nov 2026 11:37:43 +0900 Subject: [PATCH 1/5] fix(codex): read usage once before a stale main hard-lock refusal (#8113) A reset redeemed outside OpenCodex left the cached main reading above the threshold until the paced background recovery ran, so Codex Desktop kept seeing a usage-limit refusal while the official UI showed quota available. Before refusing, resolveCodexAuthContext now asks for one fresh usage read when the reading behind the lock is older than 60 s. Concurrent refusals share the read and a main identity gets at most one per minute; usage backoff, a paused or reauth-required main and native-main maintenance skip it. If the fresh reading no longer blocks, the request resolves once more. A proxy-owned refusal reads through the recovery probe under the native-main claim. A caller-owned main request never reads the physical credential: it reads with its own bearer and publishes only while that bearer still matches the observed main credential. --- .../es/reference/cli/providers-accounts.md | 2 + .../docs/reference/cli/providers-accounts.md | 1 + scripts/test-layout/layout.json | 2 +- .../auth-api/main-hard-lock-refusal-read.ts | 157 ++++++++++++++ src/codex/auth-context.ts | 35 +++ structure/codex-account-controls.md | 15 ++ structure/providers/openai-tiers.md | 2 +- .../main-account-hard-lock-auth.test.ts | 13 +- ...ain-account-hard-lock-refusal-read.test.ts | 204 ++++++++++++++++++ tests/fixtures/test-layout-expected.json | 2 +- .../main-account-policy-startup-child.ts | 13 +- 11 files changed, 439 insertions(+), 7 deletions(-) create mode 100644 src/codex/auth-api/main-hard-lock-refusal-read.ts create mode 100644 tests/codex-integration/main-account-hard-lock-refusal-read.test.ts diff --git a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md index 123d0e57b40..f29e20f77af 100644 --- a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md @@ -292,6 +292,8 @@ El panel de control y el `ocx status` muestran **posible uso fuera del opencodex Una lectura ilegible de 5h no puede ocultar un bloque semanal. El uso desconocido no fabrica un cero, y una lectura faltante no borra una tupla de bloqueo ya medida. Un tiempo de reinicio predicho solo no lo desbloquea. Mientras está bloqueado, la recuperación comprueba los metadatos de uso propio en un horario limitado de 5/10/20/40/60 minutos, por lo que se observa un restablecimiento canjeado fuera de opencodex antes del restablecimiento previsto; el primer cheque espera cinco minutos, los cheques permanecen al menos cinco minutos de diferencia y el siguiente cheque se introduce al último restablecimiento de bloqueo conocido. Un principal en pausa o requerido para la re-autenticación no recibe ninguna comprobación antes de su reset predicho. Un `Retry-After` más largo también retrasa la preparación de perfiles y tokens. Solo el uso nuevo y válido o la evidencia autorizada de ausencia de ventana pueden levantar el bloqueo. En el modo Pool, una cuota `--refresh` evita la frescura de la memoria caché, pero aún honra el ritmo de lectura fallida; una lectura diferida no hace ningún nuevo intento de diagnóstico. Otros límites de pausa, reautenticación y aguas arriba permanecen independientes. +Antes de rechazar una solicitud, si la lectura de uso que sostiene el bloqueo tiene más de 60 segundos, OpenCodex vuelve a leer el uso una vez; un restablecimiento canjeado fuera de OpenCodex levanta entonces el bloqueo para esa misma solicitud. Las solicitudes rechazadas a la vez comparten esa lectura, la cuenta principal recibe como máximo una lectura así por minuto, y el ritmo de lecturas fallidas, una cuenta principal en pausa o pendiente de reautenticación y el mantenimiento del perfil nativo la omiten. Una solicitud que se autentica con el propio inicio de sesión principal usa su propia credencial para esa lectura y nunca la almacenada. + La protección trata una nueva respuesta de uso WHAM válida como un reemplazo para la lectura de 5 horas anterior cuando su ventana principal dura explícitamente **al menos 24 horas** e informa sobre el uso válido, o su ventana principal es explícitamente `null` y un secundario medido proporciona el uso semanal. En cualquier caso, las ventanas secundarias / terciarias deben ser explícitamente `null` o explícitamente durar al menos 24 horas e informar el uso válido. Esto sigue el límite corto / largo del analizador, por lo que una ventana de un día califica, así como ventanas semanales / mensuales. La ventana actual sigue utilizando el mismo umbral de ventana larga configurado (98% por defecto). Esto se basa en la única instantánea reportada; no se requieren observaciones repetidas. Cualquier campo de ventana omitido, una duración desconocida o encabezados de respuesta parcial no pueden borrar un bloque anterior. Las respuestas totalmente nulas con solo créditos y lecturas complementarias mensuales tampoco pueden establecer la recuperación. El proxy comprueba la credencial almacenada de nuevo antes de aplicar una respuesta retardada. Un archivo ilegible o portador reemplazado no puede actualizar la memoria caché de uso, liberar el bloqueo o poner en cuarentena la nueva credencial, incluso para la misma cuenta sin leer la segunda cuota. Su uso ordinario analizado aún se puede devolver al llamante solicitante, sin actualizaciones de estado compartido o evidencia de recuperación. La tarjeta de cuenta muestra el uso publicado en caché, manteniendo su cuota alineada con el estado de bloqueo; Direct cuota de proveedor omite una respuesta no publicada y su informe en caché anterior. Las identidades de cuentas en conflicto y las respuestas obsoletas 401/403 retienen la información almacenada en caché actual y no pueden borrar o establecer el estado de reautenticación de la cuenta actual. Responses a las solicitudes enviadas con la credencial principal identificada actualizan su uso en caché desde sus cabeceras de cuota, ya sea que el proxy sustituya la credencial almacenada o el llamante envíe la misma credencial. Una respuesta se aplica solo si esa credencial sigue siendo la credencial principal observada cuando llega; una credencial propiedad del llamante para otra cuenta o espacio de trabajo nunca actualiza el uso de la cuenta principal. diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index 28f525b0618..ed3e99d2e30 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -511,6 +511,7 @@ stay at least five minutes apart, and the next check is pulled in to the latest or reauthentication-required main receives no checks before its predicted reset. A longer `Retry-After` also delays profile and token preparation. Only fresh valid usage or authoritative window-absence evidence can lift the block. In Pool mode, a quota `--refresh` bypasses cache freshness but still honors failed-read pacing; a deferred read makes no new diagnostic attempt. Other pause, reauthentication, and upstream limits remain independent. +Before refusing a request, if the usage reading behind the block is more than 60 seconds old, OpenCodex first reads usage once more; a reset redeemed outside OpenCodex then lifts the block for that same request. Concurrent refusals share that read, the main account gets at most one such read per minute, and failed-read pacing, a paused or reauthentication-required main, and native-main maintenance skip it. A request that authenticates as the main login itself uses its own credential for that read and never the stored one. Protection treats one fresh valid WHAM usage response as a replacement for the old 5h reading when its primary window explicitly lasts **at least 24 hours** and reports valid usage, or its primary window is diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 05605249cbe..db450b2c9e6 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1190,7 +1190,7 @@ "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", - "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", + "main-account-hard-lock-refusal-read.test.ts": "codex-integration", "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", "main-account-policy-binding-wait.test.ts": "codex-integration", "main-device-reauth-api.test.ts": "codex-integration", "main-device-reauth-ui.test.ts": "gui", diff --git a/src/codex/auth-api/main-hard-lock-refusal-read.ts b/src/codex/auth-api/main-hard-lock-refusal-read.ts new file mode 100644 index 00000000000..b30316e75b5 --- /dev/null +++ b/src/codex/auth-api/main-hard-lock-refusal-read.ts @@ -0,0 +1,157 @@ +import type { OcxConfig } from "../../types"; +import { MAIN_CODEX_ACCOUNT_ID } from "../account-id"; +import { reconcileMainCodexAccountRuntimeState } from "../account-lifecycle"; +import { isCodexAccountPaused } from "../account-pause"; +import { isAccountNeedsReauth } from "../account-runtime-state"; +import { getMainAccountHardLockStatus } from "../main-account-hard-lock"; +import { getValidMainAccountToken, mainAccountTokenIsCurrent, mainAccountTokenQuotaWriter } from "../main-account"; +import { + captureMainAccountIdentityGeneration, captureMainQuotaWriter, getMainQuotaCredentialGeneration, getObservedMainQuotaIdentityKey, + isMainAccountIdentityGenerationLive, isMainQuotaWriterLive, matchesMainQuotaCredential, observeMainQuotaCredential, +} from "../main-account-cache"; +import { tryAcquireNativeMainProfileClaim } from "../native-main-admission"; +import { isNativeMainTrafficBlocked } from "../native-profile-startup"; +import { + getMainPolicyQuota, isValidWhamHistoryObservation, parseMainPolicyUsageQuota, parseUsageQuota, setAccountQuotaFromParsed, + type WhamUsageResponse, +} from "../quota"; +import { fetchCodexUsage, nextCodexUsageQueryAt } from "../quota-query-backoff"; +import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing"; +import { captureConfigGeneration } from "../../lib/state-store-sweeper"; +import type { AdmissionLease } from "../../lib/admission"; +import { fetchMainAccountInfoAttempt } from "./main-account-probe"; + +/** A hard-lock reading younger than this is current enough to refuse on (#8113). */ +export const MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS = 60_000; +/** At most one refusal-triggered WHAM read per main identity in this window. */ +export const MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS = 60_000; + +let lastRead: { identity: string; at: number } | undefined; +let inFlight: Promise | undefined; + +/** + * The caller's own credential when the refused request authenticates as the main login itself + * (caller-owned Direct, or a request-scoped main bearer in Pool). Such a request may not read the + * physical main credential, so its fresh read uses this bearer, which the lock already proved is + * the observed main credential. + */ +export interface MainHardLockRefusalCaller { + bearer: string; + accountId: string; +} + +/** Test-only: forget the per-identity pacing and any settled read. */ +export function resetMainHardLockRefusalReadForTests(): void { + lastRead = undefined; + inFlight = undefined; +} + +/** + * Before a main hard-lock refusal, read WHAM once when the reading behind the lock is stale (#8113). + * + * A reset redeemed outside OpenCodex leaves the cached reading above the threshold until a later + * observation replaces it, and the paced background recovery may not run for minutes. When the + * cached reading is older than {@link MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS}, this reads usage once: + * with the proxy-owned main credential and the native-main claim through the recovery probe, or, + * for a caller-owned main request, with the caller's own bearer, published only while that bearer + * still matches the observed main credential. Concurrent refusals share + * one read, and each main identity gets at most one read per + * {@link MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS}. Server-advised usage backoff, a paused main, + * reauthentication quarantine and native-main maintenance all skip the read. The read is passive: + * it never sets or clears the reauthentication quarantine. + * + * Returns `true` when the lock no longer blocks, so the caller may resolve the request again; + * `false` keeps the refusal. A failed read keeps the existing policy observation. + */ +export async function refreshMainHardLockBeforeRefusal( + config: OcxConfig, + policy: Parameters[0] = config, + signal?: AbortSignal, + /** The caller-owned main credential; `null` when the request is caller-owned but unusable for a read. */ + caller?: MainHardLockRefusalCaller | null, + now: () => number = Date.now, +): Promise { + const blocked = () => getMainAccountHardLockStatus(policy, now()).state === "blocked"; + if (!blocked()) return true; + if (caller === null) return false; + const quota = getMainPolicyQuota(); + if (quota && now() - quota.updatedAt < MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS) return false; + if (isNativeMainTrafficBlocked() || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID) + || isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID)) return false; + if (!inFlight) { + const identity = getObservedMainQuotaIdentityKey() ?? ""; + if (lastRead?.identity === identity && now() - lastRead.at < MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS) return false; + const queryAfter = nextCodexUsageQueryAt(`main:${captureConfigGeneration()}:${getMainQuotaCredentialGeneration()}`); + if (queryAfter !== undefined && queryAfter > now()) return false; + let read: Promise; + if (caller) { + lastRead = { identity, at: now() }; + read = readCallerMainUsage(caller); + } else { + const lease = tryAcquireNativeMainProfileClaim(); + if (!lease) return false; + lastRead = { identity, at: now() }; + read = readMainUsage(config, lease).finally(() => lease.release()); + } + read = read + .catch(() => { /* the refusal stands on the existing observation */ }) + .finally(() => { if (inFlight === read) inFlight = undefined; }); + inFlight = read; + } + await abortable(inFlight, signal); + return !blocked(); +} + +async function readMainUsage(config: OcxConfig, lease: AdmissionLease): Promise { + reconcileMainCodexAccountRuntimeState(); + const identityGeneration = captureMainAccountIdentityGeneration(); + // Refresh can need an exclusive credential claim, so obtain the token before WHAM's shared claim. + const prepared = await getValidMainAccountToken({ preserveReauth: true }); + if (!prepared) return; + if (mainAccountTokenQuotaWriter(prepared)) { + if (!mainAccountTokenIsCurrent(prepared)) return; + } else observeMainQuotaCredential(prepared.accessToken, prepared.chatgptAccountId); + if (!isMainAccountIdentityGenerationLive(identityGeneration) || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)) return; + await fetchMainAccountInfoAttempt(true, 1, lease, false, false, false, config, { passive: true, preparedToken: prepared }); +} + +/** Usage read with the caller's own main bearer: no physical credential read, no reauth state. */ +async function readCallerMainUsage(caller: MainHardLockRefusalCaller): Promise { + const writer = captureMainQuotaWriter(caller.accountId); + if (!writer || !matchesMainQuotaCredential(caller.bearer, caller.accountId)) return; + const writerGeneration = captureConfigGeneration(); + const credentialGeneration = getMainQuotaCredentialGeneration(); + const key = `main:${writerGeneration}:${credentialGeneration}`; + const admission = await fetchCodexUsage(key, { + headers: { Authorization: `Bearer ${caller.bearer}`, "ChatGPT-Account-Id": caller.accountId }, + signal: AbortSignal.timeout(WHAM_REQUEST_TIMEOUT_MS), + }, undefined, { pacingKey: key }); + // A joined read belongs to another owner, which publishes its own evidence. + if (!admission || admission.kind === "joined") return; + let usable = false; + try { + if (!admission.response.ok) return; + const data = await admission.response.json() as WhamUsageResponse; + if (data === null || typeof data !== "object" || Array.isArray(data)) return; + // The main login may have changed while the read was in flight; never publish across it. + if (!matchesMainQuotaCredential(caller.bearer, caller.accountId) || !isMainQuotaWriterLive(writer) + || credentialGeneration !== getMainQuotaCredentialGeneration()) return; + const quota = parseUsageQuota(data); + if (!quota) return; + setAccountQuotaFromParsed(MAIN_CODEX_ACCOUNT_ID, quota, writerGeneration, writer, parseMainPolicyUsageQuota(data), + undefined, false, false, isValidWhamHistoryObservation(data) ? quota : null); + usable = true; + } finally { + admission.settle(usable); + } +} + +function abortable(promise: Promise, signal?: AbortSignal): Promise { + if (!signal) return promise; + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)); + }); +} diff --git a/src/codex/auth-context.ts b/src/codex/auth-context.ts index 30ebc2cc2cd..f4043137b35 100644 --- a/src/codex/auth-context.ts +++ b/src/codex/auth-context.ts @@ -1063,6 +1063,41 @@ export async function resolveCodexAuthContext( config: OcxConfig, mode: CodexAccountMode, options: ResolveCodexAuthContextOptions = {}, +): Promise { + try { + return await resolveCodexAuthContextWithHint(headers, config, mode, options); + } catch (error) { + // #8113: a refusal resting on a reading older than 60 s first gets one fresh WHAM read, so a + // reset redeemed outside OpenCodex lifts the lock now instead of at the next paced recovery. + if (!(error instanceof CodexMainAccountHardLockError)) throw error; + const { refreshMainHardLockBeforeRefusal } = await import("./auth-api/main-hard-lock-refusal-read"); + if (!await refreshMainHardLockBeforeRefusal(config, options.codexAuthPolicy ?? config, options.signal, + callerOwnedMainRefusal(headers, mode, options))) throw error; + return await resolveCodexAuthContextWithHint(headers, config, mode, options); + } +} + +/** + * A refusal for a request that authenticates as the main login itself. That request may never + * read the physical main credential, so its fresh read uses the caller's own bearer (#8113). + * Any other refusal is about the proxy-owned main credential. + */ +function callerOwnedMainRefusal( + headers: Headers, mode: CodexAccountMode, options: ResolveCodexAuthContextOptions, +): { bearer: string; accountId: string } | null | undefined { + if (options.substituteMainCredentialForDirect === true || !hasCallerCodexBearer(headers)) return undefined; + if (mode !== "direct" && options.requestScopedMainCredential !== true) return undefined; + const bearer = authorizationCredential(headers); + const accountId = headers.get("chatgpt-account-id") ?? (bearer ? extractAccountId(undefined, bearer) : undefined); + // Caller-owned without a usable credential: no read at all, never the physical one. + return bearer && accountId ? { bearer, accountId } : null; +} + +async function resolveCodexAuthContextWithHint( + headers: Headers, + config: OcxConfig, + mode: CodexAccountMode, + options: ResolveCodexAuthContextOptions, ): Promise { // Filled by the inner resolver with the request's own fenced model evidence, so the hint obeys it. const eligibility: RecoveryHintEligibility = {}; diff --git a/structure/codex-account-controls.md b/structure/codex-account-controls.md index f80d2a765f8..6d2a5f847ed 100644 --- a/structure/codex-account-controls.md +++ b/structure/codex-account-controls.md @@ -140,3 +140,18 @@ gets no opt-out, so main alone counts as no Codex login under the policy. Paused unchanged, and the policy never makes an ineligible stored account usable. Coverage: `tests/codex-integration/codex-pool-only-policy.test.ts`; `tests/codex-integration/codex-pool-caller-fallback-policy.test.ts` keeps the default-mode fallbacks. +## Hard-lock refusal read + +`resolveCodexAuthContext` (`src/codex/auth-context.ts`) catches a `CodexMainAccountHardLockError` and asks +`refreshMainHardLockBeforeRefusal` (`src/codex/auth-api/main-hard-lock-refusal-read.ts`) for one fresh +usage read before refusing (#8113). The read runs only when the policy reading behind the block is older +than 60 s; concurrent refusals share one in-flight read, and one main identity gets at most one read per +minute. Usage-query backoff, a paused or reauthentication-required main and native-main maintenance skip +it, and the read is passive: it never sets or clears the reauthentication quarantine. If the fresh reading +no longer blocks, the request is resolved once more; otherwise the original refusal stands. +A refusal on the proxy-owned main credential reads through the recovery probe under the native-main claim. +A caller-owned main request (caller-owned Direct, or a request-scoped main bearer in Pool) never reads the +physical credential: it reads with its own bearer and publishes only while that bearer still HMAC-matches the +observed main credential, the writer is live and the credential generation is unchanged. Coverage: +`tests/codex-integration/main-account-hard-lock-refusal-read.test.ts` and the startup restore cases in +`tests/codex-integration/main-account-hard-lock-auth.test.ts`. diff --git a/structure/providers/openai-tiers.md b/structure/providers/openai-tiers.md index 215cfdcdde3..fb80933cc30 100644 --- a/structure/providers/openai-tiers.md +++ b/structure/providers/openai-tiers.md @@ -397,7 +397,7 @@ a replacement credential. A longer valid Retry-After from any main usage reader current credential before the recovery worker takes a profile lease or prepares a token; a replacement credential has a separate key and may proceed immediately. Nonterminal 401/403 responses do not arm the successful-but-blocked recovery delay; the next -sweep may retry, while terminal authentication failure keeps its reauth quarantine. +sweep may retry, while terminal authentication failure keeps its reauth quarantine. A refusal on a reading older than 60 s first reads usage once ([refusal read](../codex-account-controls.md#hard-lock-refusal-read)). Only fresh lower usage or validated window absence releases the lock; no reset-credit consumption is added. Failed, missing, non-finite or out-of-range readings do not release the block. Policy validation precedes legacy clamping. Supplementary monthly data cannot become the fallback governing window without a diff --git a/tests/codex-integration/main-account-hard-lock-auth.test.ts b/tests/codex-integration/main-account-hard-lock-auth.test.ts index 68c9a37d522..16a29bc14ae 100644 --- a/tests/codex-integration/main-account-hard-lock-auth.test.ts +++ b/tests/codex-integration/main-account-hard-lock-auth.test.ts @@ -236,6 +236,9 @@ describe("main quota policy at native admission", () => { const belowHardLock = scenario === "owned-97"; const quota = { weeklyPercent: scenario === "owned-97" ? 97 : scenario === "owned-98" ? 98 : 99, updatedAt: Date.now() - 7 * 60 * 60_000 }; + // The first refusal on the hours-old restored tuple reads usage once (#8113); the fixture + // answers with a reading that still blocks, which then replaces the restored tuple. + const freshBlock = expect.objectContaining({ shortPercent: 99, weeklyPercent: 99 }); const identityKey = createHash("sha256").update("opencodex-main-quota-v1\0").update(restoredId).digest("hex"); if (scenario.startsWith("invalid-") || scenario === "mismatched-identity") { writeFileSync(join(home, "auth.json"), JSON.stringify({ tokens: { @@ -278,6 +281,8 @@ describe("main quota policy at native admission", () => { expect(result.before).toMatchObject({ matched: false, policy: null, tokenReads: 0 }); expect(result.listeners[0].tokenReads).toBe(0); expect(result.unexpectedNetwork).toEqual([]); + // Only a hard-lock refusal reads usage, once, because the restored reading is hours old. + expect(result.usageReads).toBe(result.response.hardLockError ? 1 : 0); expect(result.policyReadsPinned).toBe(true); expect(result.beforePrimaryUpstreamCalls).toBe(scenario === "retained-unknown-binding" ? 3 : 0); const unowned = scenario === "foreign" || scenario === "unknown"; @@ -298,7 +303,9 @@ describe("main quota policy at native admission", () => { expect(result.response.status).toBe(200); expect(result.primaryUpstreamCalls).toBe(1); } else { - expect(result.after).toMatchObject({ matched: true, policy: quota }); + // Only retained-unknown-binding refuses before `after` is observed. + expect(result.after).toMatchObject({ matched: true, + policy: scenario === "retained-unknown-binding" ? freshBlock : quota }); expect(result.response.status).toBe(belowHardLock ? 200 : 429); expect(result.primaryUpstreamCalls).toBe(belowHardLock ? 1 : 0); if (!belowHardLock) expect(result.response.hardLockError).toBe(true); @@ -341,8 +348,8 @@ describe("main quota policy at native admission", () => { if (scenario === "retained-unknown-binding") { expect(result.retainedUnknown.map((entry: { kind: string }) => entry.kind)) .toEqual(["malformed", "conflicting", "conflicting-tokens"]); - for (const entry of result.retainedUnknown) { - expect(entry.observed).toMatchObject({ matched: true, policy: quota }); + for (const [index, entry] of result.retainedUnknown.entries()) { + expect(entry.observed).toMatchObject({ matched: true, policy: index === 0 ? quota : freshBlock }); expect(entry.main).toMatchObject({ status: 429, hardLockError: true }); expect(entry.other.status).toBe(200); } diff --git a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts new file mode 100644 index 00000000000..08698ea378b --- /dev/null +++ b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts @@ -0,0 +1,204 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { MAIN_CODEX_ACCOUNT_ID as MAIN } from "../../src/codex/account-id"; +import * as authCollision from "../../src/codex/auth-collision"; +import { reconcileMainCodexAccountRuntimeState, resetMainCodexAccountIdentityTrackingForTests } from "../../src/codex/account-lifecycle"; +import { clearAccountNeedsReauth } from "../../src/codex/account-runtime-state"; +import { + MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS, refreshMainHardLockBeforeRefusal, resetMainHardLockRefusalReadForTests, +} from "../../src/codex/auth-api/main-hard-lock-refusal-read"; +import { CodexMainAccountHardLockError, resolveCodexAuthContext } from "../../src/codex/auth-context"; +import { captureMainQuotaWriter, clearMainAccountInfoCache, observeMainQuotaCredential } from "../../src/codex/main-account-cache"; +import { getMainAccountHardLockStatus } from "../../src/codex/main-account-hard-lock"; +import { setMainAccountPlan } from "../../src/codex/main-account"; +import { clearAccountQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { resetQuotaQueryBackoffForTests } from "../../src/codex/quota-query-backoff"; +import { clearCodexUpstreamHealth } from "../../src/codex/routing"; +import { flushConfigDirHardeningForTests } from "../../src/config/paths"; +import { setAsyncIcaclsRunnerForTests, setIcaclsRunnerForTests } from "../../src/lib/windows-secret-acl"; +import { getNativeMainProfileRequestCount, resetLifecycleDrainStateForTests } from "../../src/server/lifecycle"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// #8113: a hard-lock refusal reads WHAM once when the reading behind it is older than 60 s. +const accountId = "fixture-refusal-main"; +const whamUrl = "https://chatgpt.com/backend-api/wham/usage"; +let home: string; +let previousHome: string | undefined; +let previousCodexHome: string | undefined; +let previousFetch: typeof fetch; +let clock: number; +let mainToken: string; + +function config(): OcxConfig { + return { port: 10100, defaultProvider: "openai", providers: { openai: { + adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", codexAccountMode: "pool", + } }, codexMainAccountHardLock: true, activeCodexAccountId: MAIN, codexAccounts: [] }; +} + +/** Synthetic unsigned claims for the fixture identity; not a real credential. */ +function bearer(): string { + const payload = Buffer.from(JSON.stringify({ + exp: Math.floor(Date.now() / 1000) + 86_400, + "https://api.openai.com/auth": { chatgpt_account_id: accountId }, + })).toString("base64url"); + return `header.${payload}.signature`; +} + +/** Seed a blocking 99% short-window reading observed at the current fixture clock. */ +function block(): void { + const writer = captureMainQuotaWriter(accountId); + if (!writer) throw new Error("fixture identity must be observed"); + setAccountQuotaFromParsed(MAIN, { shortPercent: 99, shortWindowSeconds: 18_000 }, undefined, writer); +} + +function usage(percent: number): Response { + return Response.json({ plan_type: "plus", rate_limit: { + primary_window: { used_percent: percent, limit_window_seconds: 18_000, reset_at: Math.floor(clock / 1000) + 3_600 }, + } }); +} + +/** Stub WHAM. An owned read runs under the native-main claim; a caller-owned read takes none. */ +function wham(respond: () => Response, gate?: Promise, claimed = true): string[] { + const calls: string[] = []; + globalThis.fetch = Object.assign(async (input: Parameters[0]) => { + const url = String(input); + calls.push(url); + expect(url).toBe(whamUrl); + expect(getNativeMainProfileRequestCount()).toBe(claimed ? 1 : 0); + await gate; + return respond(); + }, { preconnect: previousFetch.preconnect }); + return calls; +} + +const age = (ms: number) => { clock += ms; }; + +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + previousCodexHome = process.env.CODEX_HOME; + previousFetch = globalThis.fetch; + home = mkdtempSync(join(tmpdir(), "ocx-main-refusal-read-")); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = home; + const aclOk = { success: true, exitCode: 0, timedOut: false, stdout: "" }; + setIcaclsRunnerForTests(() => aclOk); + setAsyncIcaclsRunnerForTests(async () => aclOk); + clock = Date.now(); + spyOn(Date, "now").mockImplementation(() => clock); + clearAccountQuota(); + clearAccountNeedsReauth(MAIN); + clearCodexUpstreamHealth(); + clearMainAccountInfoCache(); + resetMainCodexAccountIdentityTrackingForTests(); + resetLifecycleDrainStateForTests(); + resetMainHardLockRefusalReadForTests(); + resetQuotaQueryBackoffForTests(); + setMainAccountPlan(null); + mainToken = bearer(); + writeFileSync(join(home, "auth.json"), JSON.stringify({ tokens: { + access_token: mainToken, refresh_token: "fixture-refresh", account_id: accountId, + } })); + reconcileMainCodexAccountRuntimeState(); + block(); +}); + +afterEach(async () => { + globalThis.fetch = previousFetch; + (Date.now as unknown as { mockRestore(): void }).mockRestore(); + clearAccountQuota(); + clearAccountNeedsReauth(MAIN); + clearCodexUpstreamHealth(); + clearMainAccountInfoCache(); + resetMainCodexAccountIdentityTrackingForTests(); + resetLifecycleDrainStateForTests(); + resetMainHardLockRefusalReadForTests(); + resetQuotaQueryBackoffForTests(); + setMainAccountPlan(null); + try { await flushConfigDirHardeningForTests(); } finally { + setIcaclsRunnerForTests(null); + setAsyncIcaclsRunnerForTests(null); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + removeTreeWithRetry(home); + } +}); + +test("a reading younger than 60 s refuses without a WHAM read", async () => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS - 1); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(false); + await expect(resolveCodexAuthContext(new Headers(), config(), "pool")).rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(calls).toEqual([]); +}); + +test("a stale reading is re-read once before refusing, and a reset redeemed elsewhere lifts the lock", async () => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + await expect(resolveCodexAuthContext(new Headers(), config(), "pool")) + .resolves.toMatchObject({ kind: "main-pool", accountId: MAIN }); + expect(calls).toEqual([whamUrl]); + expect(getMainAccountHardLockStatus(config()).state).toBe("ready"); +}); + +test("a fresh read that still blocks keeps the refusal", async () => { + const calls = wham(() => usage(99)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + await expect(resolveCodexAuthContext(new Headers(), config(), "pool")).rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(calls).toEqual([whamUrl]); +}); + +test("a failed read keeps the refusal, and the main identity is read at most once a minute", async () => { + const calls = wham(() => new Response("unavailable", { status: 503 })); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(false); + expect(calls).toHaveLength(1); + // The failed read also paces WHAM for minutes; lift that so only the per-identity minute applies. + resetQuotaQueryBackoffForTests(); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS - 1); + await expect(resolveCodexAuthContext(new Headers(), config(), "pool")).rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(calls).toHaveLength(1); + age(1); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(false); + expect(calls).toHaveLength(2); +}); + +test("concurrent refusals share one in-flight read", async () => { + const gate = Promise.withResolvers(); + const calls = wham(() => usage(0), gate.promise); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + const first = refreshMainHardLockBeforeRefusal(config()); + const second = refreshMainHardLockBeforeRefusal(config()); + gate.resolve(); + expect(await Promise.all([first, second])).toEqual([true, true]); + expect(calls).toEqual([whamUrl]); +}); + +test("a paused main receives no refusal read", async () => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + expect(await refreshMainHardLockBeforeRefusal({ ...config(), pausedCodexAccountIds: [MAIN] })).toBe(false); + expect(calls).toEqual([]); +}); +test("a caller-owned main bearer refusal gets the same fresh read", async () => { + const calls = wham(() => usage(0), undefined, false); + // A caller-owned request may never read the physical main credential, so the read uses its bearer. + const physicalReads = spyOn(authCollision, "readCodexTokensResult"); + // The caller presents the main login itself, so the observed-main lock applies to it. + observeMainQuotaCredential(mainToken, accountId); + const headers = new Headers({ authorization: `Bearer ${mainToken}`, "chatgpt-account-id": accountId }); + await expect(resolveCodexAuthContext(headers, config(), "pool", { requestScopedMainCredential: true })) + .rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(calls).toEqual([]); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + await expect(resolveCodexAuthContext(headers, config(), "pool", { requestScopedMainCredential: true })) + .resolves.toMatchObject({ kind: "main" }); + expect(calls).toEqual([whamUrl]); + expect(physicalReads).not.toHaveBeenCalled(); + physicalReads.mockRestore(); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 5074f0e4e77..6a43ed2548b 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1050,7 +1050,7 @@ "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", - "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", + "main-account-hard-lock-refusal-read.test.ts": "codex-integration", "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", "main-account-policy-binding-wait.test.ts": "codex-integration", "main-device-reauth-api.test.ts": "codex-integration", "main-device-reauth-ui.test.ts": "gui", "main-device-reauth.test.ts": "codex-integration", "main-quota-evidence-validation.test.ts": "codex-integration", diff --git a/tests/helpers/main-account-policy-startup-child.ts b/tests/helpers/main-account-policy-startup-child.ts index 0b1a48cc98e..0a8b232841f 100644 --- a/tests/helpers/main-account-policy-startup-child.ts +++ b/tests/helpers/main-account-policy-startup-child.ts @@ -16,6 +16,7 @@ interface Fixture { const fixture: Fixture = JSON.parse(readFileSync(process.env.OCX_POLICY_STARTUP_FIXTURE!, "utf8")); let upstreamCalls = 0; +let usageReads = 0; const unexpectedNetwork: string[] = []; // Install before product imports. Every response is synthetic; no endpoint can escape the fixture. globalThis.fetch = Object.assign(async (input: RequestInfo | URL, init?: RequestInit) => { @@ -28,6 +29,16 @@ globalThis.fetch = Object.assign(async (input: RequestInfo | URL, init?: Request model: "gpt-5.6-sol", output: [], usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 }, }); } + // A refusal resting on the restored, hours-old reading earns one fresh usage read (#8113). It + // still reports the block, so the refusal under test stands. + if (url.hostname === "chatgpt.com" && url.pathname === "/backend-api/wham/usage") { + usageReads++; + const resetAt = Math.floor(Date.now() / 1000) + 3_600; + return Response.json({ plan_type: "plus", rate_limit: { + primary_window: { used_percent: 99, limit_window_seconds: 18_000, reset_at: resetAt }, + secondary_window: { used_percent: 99, limit_window_seconds: 604_800, reset_at: resetAt }, + } }); + } unexpectedNetwork.push(`${url.hostname}${url.pathname}`); throw new Error("Unexpected network request in startup policy fixture"); }, { preconnect() {} }) as typeof fetch; @@ -286,7 +297,7 @@ try { thresholds: { global: config.autoSwitchThreshold, mainOverride: config.codexAccountAutoSwitchThresholds?.[MAIN_CODEX_ACCOUNT_ID] ?? null }, retainedUnknown, validReplacement, settled, after, settledAdmission, response, beforePrimaryUpstreamCalls, primaryUpstreamCalls, originalResponse, - unexpectedNetwork, + unexpectedNetwork, usageReads, policyReadsPinned: tokenReads.every(path => path === manager.context.authPath), })); } finally { From ba21c0753539130af634a7eacebd78c099ba1dde Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 16 Nov 2026 11:52:35 +0900 Subject: [PATCH 2/5] fix(codex): fence refusal reads on credential commits, pacing and identity history (#8113) Review round 1 found three gaps in the hard-lock refusal read: - a caller-owned read could publish after a credential commit advanced the mutation epoch; it now captures the MainQuotaDispatch proof and requires it to be live before publishing; - Direct-mode owned reads were unpaced, so a 429 Retry-After was not recorded; refusal reads now always use paced usage scheduling; - the per-minute limiter kept only the latest identity, so A->B->A could read A twice; it now keeps per-identity timestamps for the full interval. --- src/codex/auth-api/main-account-probe.ts | 4 +- .../auth-api/main-hard-lock-refusal-read.ts | 37 ++++++----- structure/codex-account-controls.md | 10 +-- ...ain-account-hard-lock-refusal-read.test.ts | 63 +++++++++++++++++-- 4 files changed, 89 insertions(+), 25 deletions(-) diff --git a/src/codex/auth-api/main-account-probe.ts b/src/codex/auth-api/main-account-probe.ts index 1ed67345060..a30812e8969 100644 --- a/src/codex/auth-api/main-account-probe.ts +++ b/src/codex/auth-api/main-account-probe.ts @@ -154,6 +154,8 @@ export interface MainAccountInfoProbeOptions { passive?: boolean; /** Exact owned result obtained before entering WHAM's shared credential claim. Never serialized. */ preparedToken?: MainAccountToken | null; + /** Always use paced usage scheduling, so failure backoff and Retry-After are recorded in every mode. */ + paced?: boolean; } export const EMPTY_MAIN_ACCOUNT_INFO: MainAccountInfo = { email: null, plan: null, quota: null }; @@ -215,7 +217,7 @@ export async function fetchMainAccountInfoAttempt( } } const probeOptions = preparedToken === undefined ? options : { ...options, preparedToken }; - const paced = sharedMainQuotaPacingEnabled(config ?? loadConfig()); + const paced = options.paced === true || sharedMainQuotaPacingEnabled(config ?? loadConfig()); const operation = async () => ({ ...await fetchMainAccountInfoWhileOwned(forceRefresh, retriesRemaining, nativeMainLease, explicitRefresh, postReset, paced, probeOptions), identityGeneration: captureMainAccountIdentityGeneration(), diff --git a/src/codex/auth-api/main-hard-lock-refusal-read.ts b/src/codex/auth-api/main-hard-lock-refusal-read.ts index b30316e75b5..ca71fbe8480 100644 --- a/src/codex/auth-api/main-hard-lock-refusal-read.ts +++ b/src/codex/auth-api/main-hard-lock-refusal-read.ts @@ -6,8 +6,8 @@ import { isAccountNeedsReauth } from "../account-runtime-state"; import { getMainAccountHardLockStatus } from "../main-account-hard-lock"; import { getValidMainAccountToken, mainAccountTokenIsCurrent, mainAccountTokenQuotaWriter } from "../main-account"; import { - captureMainAccountIdentityGeneration, captureMainQuotaWriter, getMainQuotaCredentialGeneration, getObservedMainQuotaIdentityKey, - isMainAccountIdentityGenerationLive, isMainQuotaWriterLive, matchesMainQuotaCredential, observeMainQuotaCredential, + captureMainAccountIdentityGeneration, captureMainQuotaDispatch, getMainQuotaCredentialGeneration, getObservedMainQuotaIdentityKey, + isMainAccountIdentityGenerationLive, isMainQuotaDispatchLive, matchesMainQuotaCredential, observeMainQuotaCredential, } from "../main-account-cache"; import { tryAcquireNativeMainProfileClaim } from "../native-main-admission"; import { isNativeMainTrafficBlocked } from "../native-profile-startup"; @@ -26,7 +26,8 @@ export const MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS = 60_000; /** At most one refusal-triggered WHAM read per main identity in this window. */ export const MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS = 60_000; -let lastRead: { identity: string; at: number } | undefined; +// Last refusal read per main identity, kept for the whole interval so an A→B→A switch cannot reset it. +const lastReadAt = new Map(); let inFlight: Promise | undefined; /** @@ -42,7 +43,7 @@ export interface MainHardLockRefusalCaller { /** Test-only: forget the per-identity pacing and any settled read. */ export function resetMainHardLockRefusalReadForTests(): void { - lastRead = undefined; + lastReadAt.clear(); inFlight = undefined; } @@ -80,17 +81,20 @@ export async function refreshMainHardLockBeforeRefusal( || isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID)) return false; if (!inFlight) { const identity = getObservedMainQuotaIdentityKey() ?? ""; - if (lastRead?.identity === identity && now() - lastRead.at < MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS) return false; + for (const [key, at] of lastReadAt) { + if (now() - at >= MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS) lastReadAt.delete(key); + } + if (lastReadAt.has(identity)) return false; const queryAfter = nextCodexUsageQueryAt(`main:${captureConfigGeneration()}:${getMainQuotaCredentialGeneration()}`); if (queryAfter !== undefined && queryAfter > now()) return false; let read: Promise; if (caller) { - lastRead = { identity, at: now() }; + lastReadAt.set(identity, now()); read = readCallerMainUsage(caller); } else { const lease = tryAcquireNativeMainProfileClaim(); if (!lease) return false; - lastRead = { identity, at: now() }; + lastReadAt.set(identity, now()); read = readMainUsage(config, lease).finally(() => lease.release()); } read = read @@ -112,16 +116,19 @@ async function readMainUsage(config: OcxConfig, lease: AdmissionLease): Promise< if (!mainAccountTokenIsCurrent(prepared)) return; } else observeMainQuotaCredential(prepared.accessToken, prepared.chatgptAccountId); if (!isMainAccountIdentityGenerationLive(identityGeneration) || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)) return; - await fetchMainAccountInfoAttempt(true, 1, lease, false, false, false, config, { passive: true, preparedToken: prepared }); + // Paced in every account mode: a failed or Retry-After answer must defer the next read. + await fetchMainAccountInfoAttempt(true, 1, lease, false, false, false, config, + { passive: true, preparedToken: prepared, paced: true }); } /** Usage read with the caller's own main bearer: no physical credential read, no reauth state. */ async function readCallerMainUsage(caller: MainHardLockRefusalCaller): Promise { - const writer = captureMainQuotaWriter(caller.accountId); - if (!writer || !matchesMainQuotaCredential(caller.bearer, caller.accountId)) return; const writerGeneration = captureConfigGeneration(); - const credentialGeneration = getMainQuotaCredentialGeneration(); - const key = `main:${writerGeneration}:${credentialGeneration}`; + // The dispatch proof also fences credential commits (refresh, reauthentication) that advance the + // mutation epoch before the observed credential itself changes. + const dispatch = captureMainQuotaDispatch(caller.bearer, caller.accountId, writerGeneration); + if (!dispatch) return; + const key = `main:${writerGeneration}:${dispatch.credentialGeneration}`; const admission = await fetchCodexUsage(key, { headers: { Authorization: `Bearer ${caller.bearer}`, "ChatGPT-Account-Id": caller.accountId }, signal: AbortSignal.timeout(WHAM_REQUEST_TIMEOUT_MS), @@ -134,11 +141,11 @@ async function readCallerMainUsage(caller: MainHardLockRefusalCaller): Promise expect(physicalReads).not.toHaveBeenCalled(); physicalReads.mockRestore(); }); +test("a credential commit during a caller-owned read keeps the refusal", async () => { + const gate = Promise.withResolvers(); + const calls = wham(() => usage(0), gate.promise, false); + observeMainQuotaCredential(mainToken, accountId); + const headers = new Headers({ authorization: `Bearer ${mainToken}`, "chatgpt-account-id": accountId }); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + const pending = resolveCodexAuthContext(headers, config(), "pool", { requestScopedMainCredential: true }); + while (calls.length === 0) await Promise.resolve(); + // A native refresh or same-account reauthentication commits before the observed HMAC changes. + advanceCodexCredentialMutationEpoch(); + gate.resolve(); + await expect(pending).rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(calls).toEqual([whamUrl]); + expect(getMainAccountHardLockStatus(config()).state).toBe("blocked"); +}); + +test("a Direct-mode refusal read records Retry-After, so the next minute does not read again", async () => { + const direct = { ...config(), providers: { openai: { ...config().providers.openai!, codexAccountMode: "direct" as const } } }; + const calls = wham(() => new Response("slow down", { status: 429, headers: { "retry-after": "600" } })); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + expect(await refreshMainHardLockBeforeRefusal(direct)).toBe(false); + age(MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS); + expect(await refreshMainHardLockBeforeRefusal(direct)).toBe(false); + expect(calls).toEqual([whamUrl]); +}); + +test("switching main logins A, B, A inside one minute reads A only once", async () => { + const calls = wham(() => new Response("unavailable", { status: 503 })); + const stale = async (): Promise => { + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(false); + // Lift the failed-read pacing so only the per-identity minute decides. + resetQuotaQueryBackoffForTests(); + clock -= MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS; + }; + await stale(); + signInMain("fixture-refusal-other"); + await stale(); + signInMain(accountId); + await stale(); + expect(calls).toHaveLength(2); +}); From 11e6e84e35045455849d9386462e9b140a3abb63 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 16 Nov 2026 12:49:20 +0900 Subject: [PATCH 3/5] fix(codex): age refusal reads by usage measurement and publish in dispatch order (#8113) Follow-ups from CodeRabbit on #8786: - the 60 s check read the snapshot's updatedAt, which credits-only merges rewrite; quota.ts now keeps a process-local usage measurement time (getMainPolicyUsageObservedAt), never persisted, so a restored reading counts as stale; - a caller-owned response publishes only while its quota dispatch sequence is current, so it cannot overwrite a newer probe's reading; - an explicit stored-account selection is proxy-owned whatever bearer arrives, and a caller read without a live dispatch proof no longer spends the minute; - docs no longer promise that a reset lifts the block: a fresh read releases it only when no window still blocks, and the read can be skipped or deferred. --- .../es/reference/cli/providers-accounts.md | 2 +- .../docs/reference/cli/providers-accounts.md | 2 +- .../auth-api/main-hard-lock-refusal-read.ts | 26 +++++++++----- src/codex/auth-context.ts | 2 ++ src/codex/quota.ts | 26 ++++++++++++-- structure/codex-account-controls.md | 9 +++-- structure/providers/openai-tiers.md | 2 +- ...ain-account-hard-lock-refusal-read.test.ts | 35 +++++++++++++++++++ 8 files changed, 86 insertions(+), 18 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md index f29e20f77af..67b6880a298 100644 --- a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md @@ -292,7 +292,7 @@ El panel de control y el `ocx status` muestran **posible uso fuera del opencodex Una lectura ilegible de 5h no puede ocultar un bloque semanal. El uso desconocido no fabrica un cero, y una lectura faltante no borra una tupla de bloqueo ya medida. Un tiempo de reinicio predicho solo no lo desbloquea. Mientras está bloqueado, la recuperación comprueba los metadatos de uso propio en un horario limitado de 5/10/20/40/60 minutos, por lo que se observa un restablecimiento canjeado fuera de opencodex antes del restablecimiento previsto; el primer cheque espera cinco minutos, los cheques permanecen al menos cinco minutos de diferencia y el siguiente cheque se introduce al último restablecimiento de bloqueo conocido. Un principal en pausa o requerido para la re-autenticación no recibe ninguna comprobación antes de su reset predicho. Un `Retry-After` más largo también retrasa la preparación de perfiles y tokens. Solo el uso nuevo y válido o la evidencia autorizada de ausencia de ventana pueden levantar el bloqueo. En el modo Pool, una cuota `--refresh` evita la frescura de la memoria caché, pero aún honra el ritmo de lectura fallida; una lectura diferida no hace ningún nuevo intento de diagnóstico. Otros límites de pausa, reautenticación y aguas arriba permanecen independientes. -Antes de rechazar una solicitud, si la lectura de uso que sostiene el bloqueo tiene más de 60 segundos, OpenCodex vuelve a leer el uso una vez; un restablecimiento canjeado fuera de OpenCodex levanta entonces el bloqueo para esa misma solicitud. Las solicitudes rechazadas a la vez comparten esa lectura, la cuenta principal recibe como máximo una lectura así por minuto, y el ritmo de lecturas fallidas, una cuenta principal en pausa o pendiente de reautenticación y el mantenimiento del perfil nativo la omiten. Una solicitud que se autentica con el propio inicio de sesión principal usa su propia credencial para esa lectura y nunca la almacenada. +Antes de rechazar una solicitud, si el uso que sostiene el bloqueo se midió por última vez hace más de 60 segundos, OpenCodex puede volver a leer el uso una vez. Si esa lectura nueva ya no bloquea según los umbrales configurados, por ejemplo después de que un restablecimiento canjeado fuera de OpenCodex despejara todas las ventanas bloqueantes, la solicitud se resuelve de nuevo; una lectura que sigue bloqueando, o una lectura fallida o aplazada, mantiene el rechazo. Las solicitudes rechazadas a la vez comparten esa lectura, la cuenta principal recibe como máximo una lectura así por minuto, y el ritmo de lecturas fallidas, una cuenta principal en pausa o pendiente de reautenticación y el mantenimiento del perfil nativo la omiten. Una solicitud que se autentica con el propio inicio de sesión principal usa su propia credencial para esa lectura y nunca la almacenada. La protección trata una nueva respuesta de uso WHAM válida como un reemplazo para la lectura de 5 horas anterior cuando su ventana principal dura explícitamente **al menos 24 horas** e informa sobre el uso válido, o su ventana principal es explícitamente `null` y un secundario medido proporciona el uso semanal. En cualquier caso, las ventanas secundarias / terciarias deben ser explícitamente `null` o explícitamente durar al menos 24 horas e informar el uso válido. Esto sigue el límite corto / largo del analizador, por lo que una ventana de un día califica, así como ventanas semanales / mensuales. La ventana actual sigue utilizando el mismo umbral de ventana larga configurado (98% por defecto). Esto se basa en la única instantánea reportada; no se requieren observaciones repetidas. Cualquier campo de ventana omitido, una duración desconocida o encabezados de respuesta parcial no pueden borrar un bloque anterior. Las respuestas totalmente nulas con solo créditos y lecturas complementarias mensuales tampoco pueden establecer la recuperación. El proxy comprueba la credencial almacenada de nuevo antes de aplicar una respuesta retardada. Un archivo ilegible o portador reemplazado no puede actualizar la memoria caché de uso, liberar el bloqueo o poner en cuarentena la nueva credencial, incluso para la misma cuenta sin leer la segunda cuota. Su uso ordinario analizado aún se puede devolver al llamante solicitante, sin actualizaciones de estado compartido o evidencia de recuperación. La tarjeta de cuenta muestra el uso publicado en caché, manteniendo su cuota alineada con el estado de bloqueo; Direct cuota de proveedor omite una respuesta no publicada y su informe en caché anterior. Las identidades de cuentas en conflicto y las respuestas obsoletas 401/403 retienen la información almacenada en caché actual y no pueden borrar o establecer el estado de reautenticación de la cuenta actual. diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index ed3e99d2e30..95baa4be84e 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -511,7 +511,7 @@ stay at least five minutes apart, and the next check is pulled in to the latest or reauthentication-required main receives no checks before its predicted reset. A longer `Retry-After` also delays profile and token preparation. Only fresh valid usage or authoritative window-absence evidence can lift the block. In Pool mode, a quota `--refresh` bypasses cache freshness but still honors failed-read pacing; a deferred read makes no new diagnostic attempt. Other pause, reauthentication, and upstream limits remain independent. -Before refusing a request, if the usage reading behind the block is more than 60 seconds old, OpenCodex first reads usage once more; a reset redeemed outside OpenCodex then lifts the block for that same request. Concurrent refusals share that read, the main account gets at most one such read per minute, and failed-read pacing, a paused or reauthentication-required main, and native-main maintenance skip it. A request that authenticates as the main login itself uses its own credential for that read and never the stored one. +Before refusing a request, if the usage behind the block was last measured more than 60 seconds ago, OpenCodex may read usage once more. When that fresh reading no longer blocks under the configured thresholds, for example after a reset redeemed outside OpenCodex cleared every blocking window, the request is resolved again; a reading that still blocks, or a failed or deferred read, keeps the refusal. Concurrent refusals share that read, the main account gets at most one such read per minute, and failed-read pacing, a paused or reauthentication-required main, and native-main maintenance skip it. A request that authenticates as the main login itself uses its own credential for that read and never the stored one. Protection treats one fresh valid WHAM usage response as a replacement for the old 5h reading when its primary window explicitly lasts **at least 24 hours** and reports valid usage, or its primary window is diff --git a/src/codex/auth-api/main-hard-lock-refusal-read.ts b/src/codex/auth-api/main-hard-lock-refusal-read.ts index ca71fbe8480..43cdef9e70c 100644 --- a/src/codex/auth-api/main-hard-lock-refusal-read.ts +++ b/src/codex/auth-api/main-hard-lock-refusal-read.ts @@ -12,7 +12,7 @@ import { import { tryAcquireNativeMainProfileClaim } from "../native-main-admission"; import { isNativeMainTrafficBlocked } from "../native-profile-startup"; import { - getMainPolicyQuota, isValidWhamHistoryObservation, parseMainPolicyUsageQuota, parseUsageQuota, setAccountQuotaFromParsed, + getMainPolicyUsageObservedAt, isValidWhamHistoryObservation, parseMainPolicyUsageQuota, parseUsageQuota, setAccountQuotaFromParsed, type WhamUsageResponse, } from "../quota"; import { fetchCodexUsage, nextCodexUsageQueryAt } from "../quota-query-backoff"; @@ -20,6 +20,7 @@ import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing"; import { captureConfigGeneration } from "../../lib/state-store-sweeper"; import type { AdmissionLease } from "../../lib/admission"; import { fetchMainAccountInfoAttempt } from "./main-account-probe"; +import { isQuotaDispatchCurrent, nextQuotaDispatchSequence, publishQuotaDispatch } from "./pool-quota-probe"; /** A hard-lock reading younger than this is current enough to refuse on (#8113). */ export const MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS = 60_000; @@ -75,8 +76,9 @@ export async function refreshMainHardLockBeforeRefusal( const blocked = () => getMainAccountHardLockStatus(policy, now()).state === "blocked"; if (!blocked()) return true; if (caller === null) return false; - const quota = getMainPolicyQuota(); - if (quota && now() - quota.updatedAt < MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS) return false; + // The usage measurement's age, not the snapshot's write time: credits-only merges rewrite the latter. + const observedAt = getMainPolicyUsageObservedAt(); + if (observedAt !== undefined && now() - observedAt < MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS) return false; if (isNativeMainTrafficBlocked() || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID) || isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID)) return false; if (!inFlight) { @@ -89,8 +91,11 @@ export async function refreshMainHardLockBeforeRefusal( if (queryAfter !== undefined && queryAfter > now()) return false; let read: Promise; if (caller) { + // Without a live proof for the caller's credential there is nothing to read; keep the minute. + const dispatch = captureMainQuotaDispatch(caller.bearer, caller.accountId, captureConfigGeneration()); + if (!dispatch) return false; lastReadAt.set(identity, now()); - read = readCallerMainUsage(caller); + read = readCallerMainUsage(caller, dispatch); } else { const lease = tryAcquireNativeMainProfileClaim(); if (!lease) return false; @@ -122,12 +127,14 @@ async function readMainUsage(config: OcxConfig, lease: AdmissionLease): Promise< } /** Usage read with the caller's own main bearer: no physical credential read, no reauth state. */ -async function readCallerMainUsage(caller: MainHardLockRefusalCaller): Promise { - const writerGeneration = captureConfigGeneration(); +async function readCallerMainUsage( + caller: MainHardLockRefusalCaller, dispatch: NonNullable>, +): Promise { // The dispatch proof also fences credential commits (refresh, reauthentication) that advance the // mutation epoch before the observed credential itself changes. - const dispatch = captureMainQuotaDispatch(caller.bearer, caller.accountId, writerGeneration); - if (!dispatch) return; + const writerGeneration = dispatch.configGeneration; + // Ordered like the main probe: a response publishes only if no later dispatch already published. + const sequence = nextQuotaDispatchSequence(); const key = `main:${writerGeneration}:${dispatch.credentialGeneration}`; const admission = await fetchCodexUsage(key, { headers: { Authorization: `Bearer ${caller.bearer}`, "ChatGPT-Account-Id": caller.accountId }, @@ -142,11 +149,12 @@ async function readCallerMainUsage(caller: MainHardLockRefusalCaller): Promise & { shortWindowAbsent?: true; monthlyWindowAbsent?: true }; let mainPolicyQuota: MainPolicyQuota | null = null; +/** + * When a usage-bearing main policy write last landed in this process (#8113). Process-local and never + * persisted, so a reading restored from disk has no measurement time; credits-only merges keep it. + */ +let mainPolicyUsageObservation: { identityKey: string; at: number } | undefined; let diskHydrated = false; let persistTimer: ReturnType | null = null; let persistStartedAt: number | null = null; @@ -442,6 +447,10 @@ export function setAccountQuotaFromParsed( const policyExisting = mainWriter && mainPolicyQuota?.identityKey === mainWriter.identityKey ? mainPolicyQuota.quota : undefined; + // A credits-only merge refreshes `updatedAt` but measures no window, so it cannot age the usage tuple. + if (mainWriter && policyQuota && snapshotHasUsage(policyQuota)) { + mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at: updatedAt }; + } mainPolicyQuota = mainWriter && (policyQuota || policyExisting) ? { identityKey: mainWriter.identityKey, @@ -831,7 +840,7 @@ export function updateAccountQuota( stampCodexQuotaUsageObservation(quota, { weeklyPercent: nextWeekly, monthlyPercent: nextMonthly }, existing); accountQuota.set(accountId, quota); // This legacy writer has no physical credential provenance. - if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null; + if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; } schedulePersistAccountQuotas(); // Observed like the other committed write. This function has no in-repo caller today, but it // is re-exported as public API through src/codex/auth-api.ts, so a future caller would @@ -898,6 +907,7 @@ function hydrateAccountQuotasFromDisk(): void { quotaHistory.hydrate(parsed.history); // Policy evidence deliberately outlives the legacy six-hour rotation-cache TTL. mainPolicyQuota = readMainPolicyQuota(parsed.mainPolicyQuota); + mainPolicyUsageObservation = undefined; const now = Date.now(); for (const [accountId, quota] of Object.entries(parsed.quotas)) { if (!quota || typeof quota !== "object" || typeof quota.updatedAt !== "number") continue; @@ -955,6 +965,16 @@ export function getMainPolicyQuota(): StoredAccountQuota | null { return structuredClone(mainPolicyQuota.quota); } +/** + * When the observed main identity's policy usage was last measured in this process, or undefined + * when this process has not measured it (for example a reading restored from disk) (#8113). + */ +export function getMainPolicyUsageObservedAt(): number | undefined { + hydrateAccountQuotasFromDisk(); + if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return undefined; + return mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey ? mainPolicyUsageObservation.at : undefined; +} + /** An owned identity observation may retire legacy main quota only when its retained policy tag proves replacement. */ export function discardMismatchedMainQuota(): void { hydrateAccountQuotasFromDisk(); @@ -1001,14 +1021,14 @@ export function clearAccountQuota(accountId?: string): void { if (accountId) { hydrateAccountQuotasFromDisk(); accountQuota.delete(accountId); - if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null; + if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; } schedulePersistAccountQuotas(); forgetCodexQuotaBaseline(accountId); return; } accountQuota.clear(); forgetCodexQuotaBaseline(); - mainPolicyQuota = null; + { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; } diskHydrated = false; if (persistTimer) { clearTimeout(persistTimer); diff --git a/structure/codex-account-controls.md b/structure/codex-account-controls.md index 478b83b9798..3e63221992c 100644 --- a/structure/codex-account-controls.md +++ b/structure/codex-account-controls.md @@ -144,8 +144,9 @@ keeps the default-mode fallbacks. `resolveCodexAuthContext` (`src/codex/auth-context.ts`) catches a `CodexMainAccountHardLockError` and asks `refreshMainHardLockBeforeRefusal` (`src/codex/auth-api/main-hard-lock-refusal-read.ts`) for one fresh -usage read before refusing (#8113). The read runs only when the policy reading behind the block is older -than 60 s; concurrent refusals share one in-flight read, and each main identity gets at most one read per +usage read before refusing (#8113). The read runs only when the blocking usage was last measured more +than 60 s ago (`getMainPolicyUsageObservedAt` in `src/codex/quota.ts`; credits-only merges keep that time, and a +reading restored from disk has none, so it counts as stale); concurrent refusals share one in-flight read, and each main identity gets at most one read per minute, remembered per identity so switching logins cannot reset it. Usage-query backoff, a paused or reauthentication-required main and native-main maintenance skip it, and the read is passive: it never sets or clears the reauthentication quarantine. If the fresh reading no longer blocks, the request is resolved once more; otherwise the original refusal stands. @@ -154,6 +155,8 @@ always with paced usage scheduling so a failure or `Retry-After` defers the next A caller-owned main request (caller-owned Direct, or a request-scoped main bearer in Pool) never reads the physical credential: it reads with its own bearer and publishes only while that bearer still HMAC-matches the observed main credential and its `MainQuotaDispatch` proof is still live, which also fences credential commits -that advance the mutation epoch before the observed credential changes. Coverage: +that advance the mutation epoch before the observed credential changes, and it takes a quota dispatch sequence so a response +older than a published dispatch never overwrites it. An explicit stored-account selection is proxy-owned whatever bearer +arrived. Coverage: `tests/codex-integration/main-account-hard-lock-refusal-read.test.ts` and the startup restore cases in `tests/codex-integration/main-account-hard-lock-auth.test.ts`. diff --git a/structure/providers/openai-tiers.md b/structure/providers/openai-tiers.md index fb80933cc30..0e123788d69 100644 --- a/structure/providers/openai-tiers.md +++ b/structure/providers/openai-tiers.md @@ -397,7 +397,7 @@ a replacement credential. A longer valid Retry-After from any main usage reader current credential before the recovery worker takes a profile lease or prepares a token; a replacement credential has a separate key and may proceed immediately. Nonterminal 401/403 responses do not arm the successful-but-blocked recovery delay; the next -sweep may retry, while terminal authentication failure keeps its reauth quarantine. A refusal on a reading older than 60 s first reads usage once ([refusal read](../codex-account-controls.md#hard-lock-refusal-read)). +sweep may retry, while terminal authentication failure keeps its reauth quarantine. An eligible refusal on usage measured more than 60 s ago may read usage once first; skips and pacing are in [refusal read](../codex-account-controls.md#hard-lock-refusal-read). Only fresh lower usage or validated window absence releases the lock; no reset-credit consumption is added. Failed, missing, non-finite or out-of-range readings do not release the block. Policy validation precedes legacy clamping. Supplementary monthly data cannot become the fallback governing window without a diff --git a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts index c49748fe960..b670fd44e27 100644 --- a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts +++ b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts @@ -11,6 +11,7 @@ import { resetMainHardLockRefusalReadForTests, } from "../../src/codex/auth-api/main-hard-lock-refusal-read"; import { advanceCodexCredentialMutationEpoch } from "../../src/codex/credential-mutation-epoch"; +import { nextQuotaDispatchSequence, publishQuotaDispatch } from "../../src/codex/auth-api/pool-quota-probe"; import { CodexMainAccountHardLockError, resolveCodexAuthContext } from "../../src/codex/auth-context"; import { captureMainQuotaWriter, clearMainAccountInfoCache, observeMainQuotaCredential } from "../../src/codex/main-account-cache"; import { getMainAccountHardLockStatus } from "../../src/codex/main-account-hard-lock"; @@ -255,3 +256,37 @@ test("switching main logins A, B, A inside one minute reads A only once", async await stale(); expect(calls).toHaveLength(2); }); +test("a credits-only update does not make a stale usage reading look fresh", async () => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS - 1_000); + // Credits carry the previous usage tuple and rewrite the snapshot time, but measure no window. + setAccountQuotaFromParsed(MAIN, { resetCredits: 2 }, undefined, captureMainQuotaWriter(accountId)); + age(2_000); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(true); + expect(calls).toEqual([whamUrl]); +}); + +test("a caller-owned response older than a published dispatch does not overwrite it", async () => { + const gate = Promise.withResolvers(); + const calls = wham(() => usage(0), gate.promise, false); + observeMainQuotaCredential(mainToken, accountId); + const headers = new Headers({ authorization: `Bearer ${mainToken}`, "chatgpt-account-id": accountId }); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + const pending = resolveCodexAuthContext(headers, config(), "pool", { requestScopedMainCredential: true }); + while (calls.length === 0) await Promise.resolve(); + // A later main probe publishes a still-blocking reading while the caller's read is in flight. + publishQuotaDispatch(nextQuotaDispatchSequence()); + gate.resolve(); + await expect(pending).rejects.toBeInstanceOf(CodexMainAccountHardLockError); + expect(getMainAccountHardLockStatus(config()).state).toBe("blocked"); +}); + +test("an explicit stored-main selection reads through the owned probe whatever bearer arrives", async () => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + const unrelated = new Headers({ authorization: `Bearer ${bearer("fixture-unrelated")}`, "chatgpt-account-id": "fixture-unrelated" }); + const direct = { ...config(), providers: { openai: { ...config().providers.openai!, codexAccountMode: "direct" as const } } }; + await resolveCodexAuthContext(unrelated, direct, "direct", { accountId: MAIN }).catch(error => error); + // The stub asserts the native-main claim, which only the owned probe takes. + expect(calls).toEqual([whamUrl]); +}); From 65ca6a901e658193a1cd3339e239a3f78606aedd Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 16 Nov 2026 12:55:43 +0900 Subject: [PATCH 4/5] fix(codex): measure refusal-read age per usage window (#8113) Review round 3: a single measurement time could be renewed by reset metadata or by a reading of a different window while a stale blocking percentage was retained, and a writer-free invalidation kept the old time. quota.ts now keeps a measurement time per policy window, renewed only when that window's percentage is measured, reports the oldest among the windows the reading retains (none means stale), and drops the times whenever the policy reading is cleared. --- src/codex/quota.ts | 35 ++++++++++++++----- structure/codex-account-controls.md | 5 +-- ...ain-account-hard-lock-refusal-read.test.ts | 19 +++++++++- 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/src/codex/quota.ts b/src/codex/quota.ts index 466b8bba36a..0d8b92d0f82 100644 --- a/src/codex/quota.ts +++ b/src/codex/quota.ts @@ -43,10 +43,13 @@ type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota }; type MainPolicyQuotaObservation = Omit & { shortWindowAbsent?: true; monthlyWindowAbsent?: true }; let mainPolicyQuota: MainPolicyQuota | null = null; /** - * When a usage-bearing main policy write last landed in this process (#8113). Process-local and never - * persisted, so a reading restored from disk has no measurement time; credits-only merges keep it. + * When each main policy usage window was last measured in this process (#8113). A window's time + * moves only when a write measures that window's percentage; reset metadata, credits and other + * windows never renew it. Process-local and never persisted: a reading restored from disk has none. */ -let mainPolicyUsageObservation: { identityKey: string; at: number } | undefined; +type PolicyUsageWindow = "shortPercent" | "weeklyPercent" | "monthlyPercent"; +const POLICY_USAGE_WINDOWS: readonly PolicyUsageWindow[] = ["shortPercent", "weeklyPercent", "monthlyPercent"]; +let mainPolicyUsageObservation: { identityKey: string; at: Partial> } | undefined; let diskHydrated = false; let persistTimer: ReturnType | null = null; let persistStartedAt: number | null = null; @@ -447,9 +450,12 @@ export function setAccountQuotaFromParsed( const policyExisting = mainWriter && mainPolicyQuota?.identityKey === mainWriter.identityKey ? mainPolicyQuota.quota : undefined; - // A credits-only merge refreshes `updatedAt` but measures no window, so it cannot age the usage tuple. - if (mainWriter && policyQuota && snapshotHasUsage(policyQuota)) { - mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at: updatedAt }; + // Only a measured percentage renews its own window; anything else keeps the earlier time. + if (mainWriter && policyQuota) { + const at = mainPolicyUsageObservation?.identityKey === mainWriter.identityKey && policyExisting + ? { ...mainPolicyUsageObservation.at } : {}; + for (const window of POLICY_USAGE_WINDOWS) if (finitePercent(policyQuota[window])) at[window] = updatedAt; + mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at }; } mainPolicyQuota = mainWriter && (policyQuota || policyExisting) ? { @@ -459,6 +465,7 @@ export function setAccountQuotaFromParsed( : policyExisting!, } : null; + if (!mainPolicyQuota) mainPolicyUsageObservation = undefined; } schedulePersistAccountQuotas(); // Credits carry the previous usage tuple; they must not refresh its observation clock. @@ -966,13 +973,23 @@ export function getMainPolicyQuota(): StoredAccountQuota | null { } /** - * When the observed main identity's policy usage was last measured in this process, or undefined - * when this process has not measured it (for example a reading restored from disk) (#8113). + * The oldest measurement time among the windows the observed main identity's policy reading + * retains, or undefined when any of them was not measured in this process (for example a reading + * restored from disk) (#8113). Any stale retained window therefore makes the whole reading stale. */ export function getMainPolicyUsageObservedAt(): number | undefined { hydrateAccountQuotasFromDisk(); if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return undefined; - return mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey ? mainPolicyUsageObservation.at : undefined; + const observation = mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey + ? mainPolicyUsageObservation.at : undefined; + let oldest: number | undefined; + for (const window of POLICY_USAGE_WINDOWS) { + if (!finitePercent(mainPolicyQuota.quota[window])) continue; + const at = observation?.[window]; + if (at === undefined) return undefined; + oldest = oldest === undefined ? at : Math.min(oldest, at); + } + return oldest; } /** An owned identity observation may retire legacy main quota only when its retained policy tag proves replacement. */ diff --git a/structure/codex-account-controls.md b/structure/codex-account-controls.md index 3e63221992c..fe122dfcc62 100644 --- a/structure/codex-account-controls.md +++ b/structure/codex-account-controls.md @@ -145,8 +145,9 @@ keeps the default-mode fallbacks. `resolveCodexAuthContext` (`src/codex/auth-context.ts`) catches a `CodexMainAccountHardLockError` and asks `refreshMainHardLockBeforeRefusal` (`src/codex/auth-api/main-hard-lock-refusal-read.ts`) for one fresh usage read before refusing (#8113). The read runs only when the blocking usage was last measured more -than 60 s ago (`getMainPolicyUsageObservedAt` in `src/codex/quota.ts`; credits-only merges keep that time, and a -reading restored from disk has none, so it counts as stale); concurrent refusals share one in-flight read, and each main identity gets at most one read per +than 60 s ago (`getMainPolicyUsageObservedAt` in `src/codex/quota.ts`: the oldest per-window measurement time among the +windows the reading retains; only a measured percentage renews its own window, never credits, reset metadata or +another window, and a reading restored from disk has none, so it counts as stale); concurrent refusals share one in-flight read, and each main identity gets at most one read per minute, remembered per identity so switching logins cannot reset it. Usage-query backoff, a paused or reauthentication-required main and native-main maintenance skip it, and the read is passive: it never sets or clears the reauthentication quarantine. If the fresh reading no longer blocks, the request is resolved once more; otherwise the original refusal stands. diff --git a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts index b670fd44e27..95f7395f37f 100644 --- a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts +++ b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts @@ -16,7 +16,7 @@ import { CodexMainAccountHardLockError, resolveCodexAuthContext } from "../../sr import { captureMainQuotaWriter, clearMainAccountInfoCache, observeMainQuotaCredential } from "../../src/codex/main-account-cache"; import { getMainAccountHardLockStatus } from "../../src/codex/main-account-hard-lock"; import { setMainAccountPlan } from "../../src/codex/main-account"; -import { clearAccountQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { clearAccountQuota, getMainPolicyUsageObservedAt, setAccountQuotaFromParsed } from "../../src/codex/quota"; import { resetQuotaQueryBackoffForTests } from "../../src/codex/quota-query-backoff"; import { clearCodexUpstreamHealth } from "../../src/codex/routing"; import { flushConfigDirHardeningForTests } from "../../src/config/paths"; @@ -290,3 +290,20 @@ test("an explicit stored-main selection reads through the owned probe whatever b // The stub asserts the native-main claim, which only the owned probe takes. expect(calls).toEqual([whamUrl]); }); +test.each([ + ["reset metadata alone", { shortResetAt: 1_900_000_000 }], + ["a reading of another window", { weeklyPercent: 10 }], +] as const)("%s does not renew the retained blocking window's age", async (_label, partial) => { + const calls = wham(() => usage(0)); + age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); + setAccountQuotaFromParsed(MAIN, partial, undefined, captureMainQuotaWriter(accountId)); + expect(getMainAccountHardLockStatus(config()).state).toBe("blocked"); + expect(await refreshMainHardLockBeforeRefusal(config())).toBe(true); + expect(calls).toEqual([whamUrl]); +}); + +test("a writer-free invalidation drops the measurement times with the policy reading", () => { + setAccountQuotaFromParsed(MAIN, { shortPercent: 5 }, undefined, undefined); + setAccountQuotaFromParsed(MAIN, { resetCredits: 1 }, undefined, captureMainQuotaWriter(accountId)); + expect(getMainPolicyUsageObservedAt()).toBeUndefined(); +}); From 08612a938a03f1d43cb58af46bc0815b5ce72bc1 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 16 Nov 2026 13:08:45 +0900 Subject: [PATCH 5/5] test(codex): assert stored-main recovery and the native-main claim directly (#8113) --- .../main-account-hard-lock-refusal-read.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts index 95f7395f37f..57d6fb1e2bf 100644 --- a/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts +++ b/tests/codex-integration/main-account-hard-lock-refusal-read.test.ts @@ -74,11 +74,13 @@ function usage(percent: number): Response { } /** Stub WHAM. An owned read runs under the native-main claim; a caller-owned read takes none. */ -function wham(respond: () => Response, gate?: Promise, claimed = true): string[] { - const calls: string[] = []; +function wham(respond: () => Response, gate?: Promise, claimed = true): string[] & { claims: number[] } { + const calls = Object.assign([] as string[], { claims: [] as number[] }); globalThis.fetch = Object.assign(async (input: Parameters[0]) => { const url = String(input); calls.push(url); + // Recorded as well as asserted: a failed assertion here becomes a handled refusal upstream. + calls.claims.push(getNativeMainProfileRequestCount()); expect(url).toBe(whamUrl); expect(getNativeMainProfileRequestCount()).toBe(claimed ? 1 : 0); await gate; @@ -286,9 +288,12 @@ test("an explicit stored-main selection reads through the owned probe whatever b age(MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS + 1); const unrelated = new Headers({ authorization: `Bearer ${bearer("fixture-unrelated")}`, "chatgpt-account-id": "fixture-unrelated" }); const direct = { ...config(), providers: { openai: { ...config().providers.openai!, codexAccountMode: "direct" as const } } }; - await resolveCodexAuthContext(unrelated, direct, "direct", { accountId: MAIN }).catch(error => error); - // The stub asserts the native-main claim, which only the owned probe takes. + // Stored main serves the request once the owned probe's fresh reading lifts the lock. + await expect(resolveCodexAuthContext(unrelated, direct, "direct", { accountId: MAIN })) + .resolves.toMatchObject({ accountId: MAIN }); expect(calls).toEqual([whamUrl]); + // Only the owned probe holds the native-main claim while it reads. + expect(calls.claims).toEqual([1]); }); test.each([ ["reset metadata alone", { shortResetAt: 1_900_000_000 }],