Repository navigation
fix(codex): stop rotating accounts inside an organization-scoped quota refusal (#4546) - #4764
Conversation
…a refusal (#4546) [skip ci] A pre-stream HTTP 429 or 402 moved the request to another pool account on status alone. That is right for a limit the account owns and wrong for one it merely belongs to. "credit_balance_exhausted", "organization_spend_limit_exceeded", "project_spend_limit_exceeded" and "organization_usage_limit_exceeded" all name a balance or cap held by the organization or project, so the second credential meets the same counter. The move bought nothing and paid a second cold prompt prefix for it, which is the send amplification this unit exists to stop. classifyCodexPreStreamRejection now reports a "scoped-quota-exhaustion" kind with alternateRetryEligible false and scopedExhaustionCode set, and shouldRetryCodexPoolAccountQuota consults that evidence before authorizing the move. Withholding the move does not withhold the accounting: passthrough-delivery.ts applies the response's quota headers to the serving account and records the 429 on the ordinary delivery path, so the account still earns its cooldown and leaves the selection pool. Only the futile second send is gone. These codes are deliberately absent from the reset-eligible set. A reset credit reconciles a ChatGPT plan window; it cannot pay an organization's bill. The classification fails closed. An empty, truncated, unparseable, duplicate-keyed or aborted body keeps the existing broad behaviour from #584, and a code/type pair that disagrees or a case or whitespace near-miss yields no code at all, so only positive evidence can ever withhold a rotation. "rate_limit_exceeded", "slow_down" and plan-level exhaustion still rotate exactly as before, and the regression test pins both directions. openai/codex reached the same classification from the client side: #44492 maps exactly these HTTP 429 codes to a terminal QuotaExceeded rather than a retry-limit failure, and #45602 extends it to the SSE path while keeping "rate_limit_exceeded" and "slow_down" retryable. The OpenAI platform rate-limit documentation states the rule for the whole class: "It does not mean that quota, billing, or other errors that require user action can be resolved by retrying." The two exhaustion classifications now share one parser rather than keeping a second hand-written copy of the strictness that makes a near-miss safe.
The cache rule's conclusion is right and its source was not. The comment claimed OpenAI "documents that changing keys inside one organization does not guarantee a hit", and the prompt-caching guide contains no such sentence: the phrase "API key" appears on that page zero times, so it never addresses two keys in one organization in either direction. What the page does say is the separating half, verbatim: "Caches are not shared across organizations and cannot be reused across regional processing boundaries." The nearest statement about keys is "Keys influence routing; they do not pin requests to a machine or guarantee a cache hit." The classification is unchanged. A different org or region still relates distinct, an identical one still relates unknown, and evidence stays "separates". Only the reason moves: same org and region is unknown because the provider never promised the hit, not because the provider denied it. A reader who went looking for the denial this comment described would not have found it, and would have had to guess whether the code or the comment was wrong. The OpenAI quota rule gains its verbatim source in the same pass -- "Rate limits are defined at the organization level and at the project level, not user level" -- which is what "separates-and-shares" rests on. structure/catalog.md carried the same mis-citation and is corrected to match. Sources read from the signed-in platform documentation on 2026-09-16.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (11)
📝 WalkthroughWalkthroughThe pull request adds scoped Codex quota classification, fail-closed quota rotation checks, and uploaded-file account-change refusals. It also updates OpenAI identity-domain documentation and adds tests for quota parsing, account routing, and file-reference handling. ChangesCodex quota classification
Uploaded-file account safety
Identity-domain documentation
Estimated code review effort: 4 (Complex) | ~45 minutes Change: Bug fix Sequence Diagram(s)Scoped quota handlingsequenceDiagram
participant Upstream
participant QuotaClassifier
participant RotationGate
participant CodexPool
Upstream->>QuotaClassifier: Return HTTP 429 or 402 response
QuotaClassifier->>QuotaClassifier: Parse scoped exhaustion code
QuotaClassifier-->>Upstream: Return terminal scoped-quota-exhaustion
Upstream->>RotationGate: Evaluate pool account rotation
RotationGate-->>CodexPool: Suppress rotation for scoped exhaustion
Uploaded-file account changessequenceDiagram
participant Request
participant RequestPreparation
participant FileReferenceCheck
participant AlternateAccount
Request->>RequestPreparation: Submit request with uploaded-file references
RequestPreparation->>FileReferenceCheck: Check account change and file references
FileReferenceCheck-->>RequestPreparation: Return HTTP 400 refusal when accounts differ
RequestPreparation-->>Request: Stop before dispatch
Request->>AlternateAccount: Avoid alternate-account retry when files are present
Suggested reviewers: ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
리뷰 · 우선순위 76 / 80이 PR은 이슈 #4546의 한 조각을 고칩니다. 여러 Codex 계정이 풀에 있을 때, 업스트림이 조직(또는 프로젝트) 한도에 걸려 429/402를 주면, 지금 고치는 축은 두 곳입니다. (1) 로테이션을 막아도 회계는 남깁니다. 실제 회전 호출은 현재 라인 ~224 (core-codex-account.ts 메인테이너의 판단이 필요한 지점
너의 추천 이 댓글은 grok-bot이 작성했습니다 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02b939127b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const { codexScopedExhaustionCode } = await import("../../codex/quota-rejection"); | ||
| return await codexScopedExhaustionCode(response, { signal }) === undefined; |
There was a problem hiding this comment.
Keep retries across distinct quota domains
When a pool contains credentials from different organizations or projects, this code only proves that the current credential's quota domain is exhausted, yet it returns false before resolveCodexAuthContext can select an alternate. The retry resolver currently excludes only the failed account (core-codex-account.ts:523-536), so a healthy credential belonging to a different organization is now stranded and the caller receives the original 429/402. This also contradicts the distinct/unknown quota-domain handling documented in src/routing/identity-domains.ts:99-104; suppress the retry only when the candidate is proven to share the exhausted domain, or make alternate selection domain-aware.
Useful? React with 👍 / 👎.
…4710) [skip ci] The classifier has always called an uploaded file_id account-bound, and the scrubber has always removed only previous_response_id and conversation. A body whose only account-bound state was a file reference therefore reported nothing scrubbed and was replayed unchanged against the new account, which is exactly the case the advertised safety fix was supposed to cover. Deleting the references is not the fix. A file reference is content the caller attached, not continuation state the turn can do without, and dropping it silently answers a different question than the one that was asked with no way for the caller to tell. Pinning the request to the issuing account is not available either: every call site resolves and materialises its credential before reaching here, and the retry sites are reached precisely because the issuing account just refused the request. So the move is refused before dispatch, with HTTP 400 and an instruction to re-upload. Not a retryable status, which would invite the same request back unchanged. The check reads the carriers directly rather than the portability verdict. That verdict reports the FIRST reason it finds, so a body carrying both a previous response id and a file reference reports only the response id, and the file would slip through the scrub that follows. Wired at the initial Codex selection and at the native compact dispatch, both of which can answer with a Response. The two alternate-account retry sites still only scrub: refusing there needs a new outcome variant on their result types and on their callers, which is a larger change than this one. The detection now lives in one exported place, so neither site can drift further from it. Closes #4710
|
✅ Deterministic PR hygiene checks passed. |
…t paths too (#4710) The carried change refuses an uploaded-file move at the two sites that can answer with a status, and leaves the two alternate-account retry sites scrubbing only. This closes those two, and it does not need the new result variant the deferral assumed. A retry site does not have to raise a status, because an earlier response already exists and is what the caller returns. It only has to decline the move. And the question it declines on does not depend on which alternate would be chosen -- an uploaded file is readable only by the account that received it -- so it can be asked from the body alone, before an alternate is resolved. conversationCarriesUploadedFiles is that predicate. Asking there reserves no send, cancels no response, and leaves the first account's rejection intact for the caller, which is the guarantee the comment above the compact resolution already depended on. Refusal still beats a previous_response_id at both sites, for the same reason the carried change reads the carriers directly instead of the portability verdict: the verdict reports only the first denial it finds. Two corrections to the carried code. collectConversationStateCarriers(body).fileIds is optional on the carrier type and was dereferenced directly, which does not survive a strict typecheck; the emptiness test now lives in one exported place so no caller can get it wrong again. And the refusal message named the cause but not the consequence. The reference stays in the conversation's history, so once rotation has moved a conversation carrying an attachment, every later turn is refused the same way. A caller told only that the reference is invalid resends unchanged and watches the conversation die. The message now says what happened, that it will keep happening, and the two things that end it: re-upload under the serving account, or start a new conversation. A same-account replay is unaffected, and a single-account install never reaches any of this, because serving and issuing accounts cannot differ without pool rotation. Pinning a file-carrying conversation to its issuing account is the real answer and is routing-affinity work; filed as #4778. Co-authored-by: JUN <[email protected]>
|
Landing the lane into CI evidence transfers by tree identity. The verified head 3ae8ca7 has tree Maintainer integration decision under MAINTAINERS.md / AGENTS.md: a maintainer with maintain or admin access may integrate into What lands: upstream 429 organization and project spend-limit codes are reclassified as terminal quota exhaustion so the pool stops rotating between accounts that share the same limit; the identity-domain comment now quotes the sentence its cited page actually contains; and an account change that would carry an uploaded file reference to an account which cannot read it is refused before dispatch, without ever deleting the reference. |
…pend-limit-classification fix(codex): stop rotating accounts inside an organization-scoped quota refusal (lidge-jun#4546)
Summary
A pre-stream HTTP 429 or 402 from the ChatGPT backend moved the request to another pool account on status alone.
shouldRetryCodexPoolAccountQuotareturnedtruefor every 429 and 402 without reading the body, so the rotation could not tell apart a limit the account owns from a limit it merely belongs to.That distinction is the whole bug.
usage_limit_exceededdescribes the account that was asked, and another pool account carries its own plan allowance, so moving is a real move. Butcredit_balance_exhausted,organization_spend_limit_exceeded,project_spend_limit_exceededandorganization_usage_limit_exceededeach name a balance or cap held by the organization or project the credential belongs to. Two credentials inside that organization are refused by the same counter. The move bought nothing and paid a second cold prompt prefix for it, which is exactly the amplification #4546 is about.Before: upstream answers
429 {"error":{"code":"organization_spend_limit_exceeded"}}. The proxy selects a second account, rebuilds the full credential/transport/replay identity, replays the entire prompt, and is refused by the same organization counter.After: the same response is classified
scoped-quota-exhaustionand no second send is made. The original 429 is returned to the caller.Two pieces:
src/codex/quota-rejection.tsgains the organization-scoped code set.classifyCodexPreStreamRejectionreports a newscoped-quota-exhaustionkind withalternateRetryEligible: falseandscopedExhaustionCodeset. The newcodexScopedExhaustionCodeexposes just that answer for the rotation gate.src/server/responses/core-codex-account.tsconsults it at the one line that authorized the move (line 224).Withholding the move does not withhold the accounting. This was the failure mode worth being careful about: skipping the retry path must not leave the exhausted account looking healthy. It does not.
src/server/responses/passthrough-delivery.tsapplies the response's quota headers to the serving account and records the 429 outcome on the ordinary delivery path, independently of whether the alternate retry ran, so the account still earns its cooldown and leaves the selection pool. Only the futile second send is gone.These codes are deliberately not added to the reset-eligible set. A reset credit reconciles a ChatGPT plan window; it cannot pay an organization's bill, so
resetCreditEligiblestays false and no reset-credit path is reachable from them.The classification fails closed. An empty, truncated, unparseable, duplicate-keyed or aborted body keeps the existing broad behaviour from #584, and a
code/typepair that disagrees or a case or whitespace near-miss yields no code at all. Only positive evidence can withhold a rotation.rate_limit_exceeded,slow_downand plan-level exhaustion rotate exactly as before.Why these four codes
openai/codex reached the same classification from the client side. openai/codex#44492 maps exactly these HTTP 429 codes to a terminal
QuotaExceededrather than a retry-limit failure, and openai/codex#45602 extends it to the SSE path while deliberately keepingrate_limit_exceededandslow_downretryable. The OpenAI platform rate-limit documentation states the rule for the whole class:The organization and project scoping is documented in the same place:
This is the concrete case
src/routing/identity-domains.tswas written to describe -- a quota refusal inside one domain must not be answered by rotating within it -- reached through the upstream error code rather than through the classifier, which no routing boundary calls yet.Part of #4546.
Verification
Local verification was NOT run, by explicit instruction from the repository owner. No
bun run test, no individual test file, nobun run typecheck, nobun install, no build. This push used--no-verify. The only evidence for this change is hosted CI at the exact head SHA of this branch, and a green run against any earlier commit is not evidence for the head that merges.What was done instead:
shouldRetryCodexPoolAccountQuotaatsrc/server/responses/passthrough-dispatch.ts:1250, not byclassifyCodexPreStreamRejection, which production calls only for a 403 denial. Both are updated so the classification and the gate agree.src/server/responses/passthrough-delivery.ts:218-260:applyAccountQuotaFromUpstreamHeadersandrecordCodexUpstreamOutcomeboth run on the delivery path for the serving account regardless of the retry decision.structure/providers/openai-tiers.mdis 580 lines andstructure/transports/responses.mdis graced inmanifest.json, so neither trips the 600-line budget rule inscripts/structure-ssot.ts; both backtick-quoted repository paths added exist in the index.New coverage in
tests/codex-integration/codex-quota-rejection.test.ts, an existing file, so no test-layout registration changes. It pins both directions, because the suppression is worth nothing if the ordinary rate limit stops failing over: each of the four codes classifies terminal and withholds the send;rate_limit_exceeded,slow_down,usage_limit_exceededandinsufficient_quotastill rotate; and six fail-closed shapes (empty, unparseable, duplicate-keyed, disagreeingcode/type, uppercase and padded near-misses) plus an aborted read all still rotate.Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Documentation