Skip to content

Commit c97614f

Browse files
committed
Merge remote-tracking branch 'origin/dev' into HEAD
# Conflicts: # scripts/test-layout/layout-codex-collision.json
2 parents efa2121 + 0f642c4 commit c97614f

25 files changed

Lines changed: 2050 additions & 68 deletions

‎docs-site/src/content/docs/reference/codex-retry-diagnostics.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,27 @@ that the account pool routed to the main account, the earliest known time anothe
4848
pool account recovers, whichever comes first (never sooner than one minute).
4949
Resume the Goal after that time; routing then picks an account from fresh state.
5050

51+
## Stored-account credit metadata retries
52+
53+
An explicitly selected stored account can reach its included usage limit while its last
54+
credit balance observation is older than five minutes. If credit spending is enabled for
55+
that account and the evidence is stale, missing or incomplete, its local 429 advises retrying
56+
after the 300-second base metadata cadence (or at the included reset if sooner). A later known upstream
57+
cooldown for the selected quota scope, including account-wide holds, still takes precedence; when
58+
both apply, the later deadline wins. Unrelated
59+
model-group holds are not imported. The original included-window reset remains attached to the
60+
internal refusal as `resetAt`; the shorter hint is a metadata recheck opportunity, not a new quota reset.
61+
62+
The request remains refused until fresh spendable credit evidence is available. This hint
63+
does not perform a refresh, bypass metadata-query pacing, guarantee recovery, change account
64+
selection, or enable credit spending. Direct account bindings retain their identity. Explicit
65+
credit opt-out, an older cached null without provenance, a known spending veto or a finite empty
66+
balance without unlimited entitlement retain the included-reset advice. A newly observed missing
67+
or malformed credit summary retracts spending authority but permits the short metadata retry;
68+
an explicit spending veto still wins. Unlimited credits with a zero balance require fresh evidence
69+
just like other credits. Ordinary upstream 429 delays keep the existing parser ceiling of 24 hours
70+
for numeric and HTTP-date Retry-After values.
71+
5172
## Triage: `idle timeout waiting for SSE`
5273

5374
Codex ends a stream that has sent no event for its `stream_idle_timeout_ms`

‎scripts/test-layout/layout-clients.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"agent-clients.test.ts": "clients",
33
"workbuddy-selector-recovery.test.ts": "clients",
44
"server-live-close.test.ts": "server",
5+
"server-live-cancel.test.ts": "server",
56
"link-diagnostics.test.ts": "clients",
67
"link-tunnel-history.test.ts": "clients",
78
"link-readiness.test.ts": "clients",

‎scripts/test-layout/layout-codex-collision.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"codex-cli-update-admission.test.ts": "codex-integration",
66
"codex-cli-update-recovery.test.ts": "codex-integration",
77
"codex-cli-update-worker.test.ts": "codex-integration",
8+
"codex-catalog-heal-reanchor.test.ts": "codex-integration",
89
"codex-quota-persistence.test.ts": "codex-integration",
910
"codex-sync-user-edits.test.ts": "codex-integration",
1011
"codex-stored-main-duplicate.test.ts": "codex-integration",

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494
"codex-credits-settings.test.ts": "codex-integration",
9595
"codex-credits-probes.test.ts": "codex-integration",
9696
"codex-credits-after-limit.test.ts": "codex-integration",
97-
"codex-pool-credit-policy.test.ts": "codex-integration",
97+
"codex-pool-credit-policy.test.ts": "codex-integration", "codex-credit-retry-after.test.ts": "codex-integration", "codex-credit-scoped-retry.test.ts": "codex-integration",
9898
"codex-sidecar-credit-policy.test.ts": "codex-integration",
9999
"codex-credits-after-limit-main.test.ts": "codex-integration",
100100
"service-runtime-preflight.test.ts": "service", "service-desktop-runtime-preflight.test.ts": "service",

‎src/codex/auth-context.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt } from "./pool-credit-policy";
1+
import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy";
22
import { hasSpendableCodexCredits } from "./quota-types";
33
import { nextQuotaQueryDelay } from "./quota-query-backoff";
44
import { noteMainAccountActivity } from "./main-account-external-usage";
@@ -548,17 +548,20 @@ export class CodexMainAccountHardLockError extends CodexAccountCooldownError {
548548
export class CodexPoolAccountCreditsOffError extends CodexAccountCooldownError {
549549
readonly resetAt: number;
550550

551-
constructor(accountId: string, resetAt: number) {
552-
super(accountId, resetAt);
551+
constructor(accountId: string, resetAt: number, creditRecovery = false, quotaScope?: CodexQuotaScope) {
552+
// Keep the included reset; a metadata hint neither admits nor clears an upstream hold.
553+
super(accountId, creditRecovery ? poolCreditRecoveryRetryAt(accountId, resetAt, quotaScope) : resetAt);
553554
this.name = "CodexPoolAccountCreditsOffError";
554555
this.resetAt = resetAt;
555-
this.message = "The selected Codex account reached its usage limit, and spending credits is off or no fresh spendable balance is available."
556+
this.message = creditRecovery
557+
? "The selected Codex account reached its usage limit and needs a fresh credit observation. Retry later; spending remains blocked until fresh spendable credits are observed."
558+
: "The selected Codex account reached its usage limit, and spending credits is off or no fresh spendable balance is available."
556559
+ " Wait for the limit to reset, choose another account, or explicitly allow credits for this account in Codex Auth.";
557560
}
558561
}
559562

560-
function assertPoolAccountCredits(accountId: string, resetAt: number | undefined): void {
561-
if (resetAt !== undefined) throw new CodexPoolAccountCreditsOffError(accountId, resetAt);
563+
function assertPoolAccountCredits(accountId: string, resetAt: number | undefined, creditRecovery: boolean, quotaScope?: CodexQuotaScope): void {
564+
if (resetAt !== undefined) throw new CodexPoolAccountCreditsOffError(accountId, resetAt, creditRecovery, quotaScope);
562565
}
563566

564567
/** The main login may not spend credits and one of its usage windows is full (#6334). */
@@ -780,7 +783,7 @@ export function createCodexAuthDispatchGuard(
780783
return headers => {
781784
if (config.pausedCodexAccountIds?.includes(ctx.accountId)) throw new CodexPoolAuthenticationError("Selected Codex account is paused; resume it in account settings");
782785
if (ctx.kind === "main-pool") { reserveGuard?.(headers); return; }
783-
assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, config));
786+
assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, config), poolContextCreditRecoveryNeeded(ctx, config), ctx.quotaScope);
784787
reserveGuard?.(headers);
785788
};
786789
}
@@ -1569,7 +1572,7 @@ async function resolveCodexAuthContextUnannotated(
15691572
try {
15701573
assertCodexAccountValidationReady(accountId);
15711574
if (configuredCodexMainDuplicate(config, accountId)) throw new CodexPoolAuthenticationError(CODEX_MAIN_DUPLICATE_ACTION);
1572-
assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config));
1575+
assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config), poolCreditRecoveryNeeded(policy, accountId), quotaScope);
15731576
} catch (cause) {
15741577
// Nothing will reach upstream, so give the trial back instead of leaving the held account
15751578
// unprobeable until the lease deadline lapses (#4701).
@@ -1700,7 +1703,7 @@ async function resolveCodexAuthContextUnannotated(
17001703
const token = await getValidCodexToken(accountId, { signal: options.signal });
17011704
assertCodexAccountValidationReady(accountId);
17021705
if (configuredCodexMainDuplicate(config, accountId)) throw new CodexPoolAuthenticationError(CODEX_MAIN_DUPLICATE_ACTION);
1703-
assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config));
1706+
assertPoolAccountCredits(accountId, poolCreditHoldResetAt(policy, accountId, config), poolCreditRecoveryNeeded(policy, accountId), quotaScope);
17041707
return bindPoolCreditPolicy({
17051708
kind: "pool",
17061709
accountId,
@@ -1732,7 +1735,7 @@ async function resolveCodexAuthContextUnannotated(
17321735

17331736
export function assertCodexAuthContextNotCooled(ctx: CodexAuthContext | undefined): void {
17341737
if (ctx?.kind !== "pool" && ctx?.kind !== "main-pool") return;
1735-
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx));
1738+
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx), poolContextCreditRecoveryNeeded(ctx), ctx.quotaScope);
17361739
// A context holding the probe lease was deliberately admitted through the cooldown.
17371740
if (ctx.probeLeaseId) return;
17381741
const cooldown = getCodexQuotaHealthSnapshot(ctx.accountId, ctx.quotaScope);
@@ -1748,7 +1751,7 @@ export function applyCodexAuthContextToProvider(
17481751
): OcxRuntimeProviderConfig {
17491752
if (mode !== "pool" || (ctx.kind !== "pool" && ctx.kind !== "main-pool") || provider.authMode !== "forward") return provider;
17501753
assertCodexAccountValidationReady(ctx.accountId);
1751-
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx));
1754+
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx), poolContextCreditRecoveryNeeded(ctx), ctx.quotaScope);
17521755
return {
17531756
...provider,
17541757
_codexAccountOverride: {
@@ -1803,7 +1806,7 @@ export function materializeCodexUpstreamAuth(
18031806
}
18041807
if (ctx.kind === "pool" || ctx.kind === "main-pool") {
18051808
assertCodexAccountValidationReady(ctx.accountId);
1806-
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config));
1809+
if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config), poolContextCreditRecoveryNeeded(ctx, options.config), ctx.quotaScope);
18071810
selected.set("authorization", `Bearer ${ctx.accessToken}`);
18081811
selected.set("chatgpt-account-id", ctx.chatgptAccountId);
18091812
if (ctx.kind === "main-pool") {

‎src/codex/catalog-self-heal.ts‎

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { readRuntimePort } from "../config/process-state";
33
import { readClientConnectionState } from "../client/state";
44
import { getActiveTurnCount, isDraining, isRecyclingForExit, isShutdownDraining } from "../server/lifecycle";
55
import type { OcxConfig } from "../types";
6-
import { observeCatalogHealFile, sameCatalogHealPath, selectCatalogHealPath, type CatalogObservation } from "./catalog/heal-observation";
6+
import { compareCatalogHealPaths, observeCatalogHealFile, retainCatalogHealPath, selectCatalogHealPath, type CatalogObservation } from "./catalog/heal-observation";
77
import { subscribeCatalogPublication } from "./catalog/publication-observer";
88
import { configEnablesRoutedNamespace, ocxRoutedNamespaceCounts } from "./catalog/routed-removal";
99
import { inspectCodexHomeOwner } from "./codex-home-owner";
@@ -51,6 +51,7 @@ export interface CatalogSelfHealDeps {
5151
now?: () => number;
5252
catalogPath?: () => string | null;
5353
observe?: (path: string, readContent: boolean) => CatalogObservation | null;
54+
retainPath?: typeof retainCatalogHealPath;
5455
converge?: (config: OcxConfig, lifecycle: CatalogHealLifecycle) => Promise<CatalogHealOutcome>;
5556
subscribe?: typeof subscribeCatalogPublication;
5657
gates?: Partial<CatalogSelfHealGates>;
@@ -135,14 +136,19 @@ export function startCodexCatalogSelfHeal(options: { port?: number; deps?: Catal
135136
const attempts: number[] = [];
136137
const heals: number[] = [];
137138

138-
const read = (path: string): NamespaceObservation | null => {
139+
const read = (path: string, fresh = false): NamespaceObservation | null => {
139140
const quick = observe(path, false);
140141
if (quick === null) return null;
141-
if (observed !== null && sameCatalogHealPath(observed.path, path) && observed.signature === quick.signature) return observed;
142+
if (!fresh && observed !== null) {
143+
const relation = compareCatalogHealPaths(observed.path, path);
144+
if (relation === "unknown") return null;
145+
if (relation === "same" && observed.signature === quick.signature) return observed;
146+
}
142147
const seen = observe(path, true);
143148
if (seen === null) return null;
144-
observed = { path, signature: seen.signature, namespaces: seen.catalog ? new Set(ocxRoutedNamespaceCounts(seen.catalog).keys()) : null };
145-
return observed;
149+
const result = { path, signature: seen.signature, namespaces: seen.catalog ? new Set(ocxRoutedNamespaceCounts(seen.catalog).keys()) : null };
150+
if (!fresh) observed = result;
151+
return result;
146152
};
147153
const accept = (path: string): void => {
148154
const seen = read(path);
@@ -154,18 +160,23 @@ export function startCodexCatalogSelfHeal(options: { port?: number; deps?: Catal
154160
pendingRetry = null;
155161
recheckAt = 0;
156162
};
157-
const updateTarget = (path: string | null): void => {
163+
const updateTarget = (path: string | null): boolean => {
158164
// Unavailable selection is not evidence of a different target or lost authority.
159-
if (path === null) return;
160-
if (target !== null && sameCatalogHealPath(target, path)) return;
165+
if (path === null) return false;
166+
if (target !== null) {
167+
const relation = compareCatalogHealPaths(target, path);
168+
if (relation === "unknown") return false;
169+
if (relation === "same") return true;
170+
}
161171
clear();
162172
target = path;
173+
return true;
163174
};
164175
const beforeCommit = (path: string, entryGeneration: number): boolean => {
165176
try {
166177
const selected = catalogPath();
167178
return !stopped && !released && generation === entryGeneration
168-
&& selected !== null && sameCatalogHealPath(selected, path) && evaluateCatalogSelfHealGates(gates).open;
179+
&& selected !== null && compareCatalogHealPaths(selected, path) === "same" && evaluateCatalogSelfHealGates(gates).open;
169180
} catch { return false; }
170181
};
171182
const capRetryAt = (now: number): number => {
@@ -182,8 +193,7 @@ export function startCodexCatalogSelfHeal(options: { port?: number; deps?: Catal
182193
running = true;
183194
try {
184195
const path = catalogPath();
185-
updateTarget(path);
186-
if (path === null) return;
196+
if (!updateTarget(path) || path === null) return;
187197
// Pending cache/funnel failure is independent of catalog stat or apparent repaired rows.
188198
if (pendingRetry) {
189199
const config = gates.loadConfig();
@@ -226,7 +236,7 @@ export function startCodexCatalogSelfHeal(options: { port?: number; deps?: Catal
226236
})).committed; }
227237
catch { /* Failed attempts retain pending retry and consume the attempt budget. */ }
228238
const selected = catalogPath();
229-
if (stopped || released || generation !== entryGeneration || selected === null || !sameCatalogHealPath(selected, path)) return;
239+
if (stopped || released || generation !== entryGeneration || selected === null || compareCatalogHealPaths(selected, path) !== "same") return;
230240
last = { at: new Date().toISOString(), lostNamespaces: lostEnabled.length, committed };
231241
if (committed) {
232242
heals.push(clock());
@@ -241,33 +251,43 @@ export function startCodexCatalogSelfHeal(options: { port?: number; deps?: Catal
241251

242252
const unsubscribe = (deps.subscribe ?? subscribeCatalogPublication)(event => {
243253
if (stopped) return;
254+
const release = event.kind === "native-released" || event.intent === "restore";
255+
// Bind publication evidence before comparisons can observe a retargeted alias.
256+
const stillPublished = !release && event.path !== null ? (deps.retainPath ?? retainCatalogHealPath)(event.path) : null;
244257
// Native restoration can remove the journal before notification. Fence the known
245258
// target (and target-less releases) without resolving possibly unavailable evidence.
246-
const release = event.kind === "native-released" || event.intent === "restore";
247-
if (release && (event.path === null || (target !== null && sameCatalogHealPath(event.path, target)))) {
259+
const known = event.path !== null && target !== null ? compareCatalogHealPaths(event.path, target) : "different";
260+
if (release && (event.path === null || known !== "different")) {
248261
clear();
249262
released = true;
250263
return;
251264
}
252265
const path = catalogPath();
253-
if (event.path !== null && (target === null || !sameCatalogHealPath(event.path, target))
254-
&& (path === null || !sameCatalogHealPath(event.path, path))) return;
266+
const selected = event.path !== null && path !== null ? compareCatalogHealPaths(event.path, path) : "different";
267+
if (event.path !== null && known === "different" && selected === "different") return;
255268
if (release) {
256269
clear();
257270
released = true; // Only a later accepted owner publication can re-arm this lifecycle.
258271
return;
259272
}
260-
if (running) return; // Catalog-success/cache-failure must not accept a baseline.
273+
if (running) {
274+
if (known === "unknown" || selected === "unknown") clear();
275+
return; // Catalog-success/cache-failure must not accept a baseline.
276+
}
261277
// A committed owner publication supplies a read-only baseline even while heal writes are gated.
262-
if (event.path === null || path === null || !sameCatalogHealPath(event.path, path)) return;
263-
updateTarget(path);
278+
if (event.path === null || path === null || selected !== "same" || stillPublished === null) return;
279+
// Read independently of obsolete evidence, but retire it only after current selection proof.
280+
const seen = read(event.path, true);
281+
const current = catalogPath();
282+
if (seen?.namespaces == null || current === null
283+
|| compareCatalogHealPaths(event.path, current) !== "same" || !stillPublished(seen.signature)) return;
284+
clear();
285+
target = current;
286+
baseline = observed = seen;
264287
released = false;
265-
pendingRetry = null;
266-
recheckAt = 0;
267-
accept(event.path);
268288
});
269289
// Capture immediately after startup sync, before a foreign write can become the first tick.
270-
try { updateTarget(catalogPath()); if (target !== null) accept(target); }
290+
try { const path = catalogPath(); if (updateTarget(path) && target !== null) accept(target); }
271291
catch { /* Unavailable observation can be retried by the scheduled tick. */ }
272292
const schedule = (): void => {
273293
if (stopped) return;

0 commit comments

Comments
 (0)