From 2b2b94a48238fb75ea4acfea983d2d701e240d0b Mon Sep 17 00:00:00 2001 From: Gauge Date: Sun, 15 Nov 2026 07:35:52 +0800 Subject: [PATCH] fix(combo): classify quota 400/422 by provider fields, not words a client can echo Rebuilt on the release line after #25 was squash-merged. The tree is identical to the QA-approved head 4321ddc31f (tree 5f376680c5). Co-Authored-By: Claude Opus 5.5 --- src/combos/failover.ts | 22 + src/lib/anthropic-extra-usage.ts | 57 +++ src/lib/errors.ts | 90 +++- src/oauth/anthropic-pool-rotation.ts | 40 +- src/server/responses/compact.ts | 3 +- .../responses-compact-400-quota-echo.test.ts | 115 +++++ .../router-combo-400-quota-echo.test.ts | 413 ++++++++++++++++++ 7 files changed, 694 insertions(+), 46 deletions(-) create mode 100644 src/lib/anthropic-extra-usage.ts create mode 100644 tests/responses/responses-compact-400-quota-echo.test.ts create mode 100644 tests/routing/router-combo-400-quota-echo.test.ts diff --git a/src/combos/failover.ts b/src/combos/failover.ts index 0fb852770a1..257fe21d730 100644 --- a/src/combos/failover.ts +++ b/src/combos/failover.ts @@ -360,10 +360,32 @@ function isProviderScopedQuotaCap( ) { return true; } + // A 400 or 422 is a verdict on the request, and its body echoes client values, so there the + // free-tier cap counts only as a field (see hasFreePromptCapField). Other statuses keep words. + if (status === 400 || status === 422) return hasFreePromptCapField(message); return text.includes("err_free_prompt_cap") || (text.includes("free tier") && text.includes("single request")); } +/** + * `err_free_prompt_cap` as the provider's own field: `error.code`, or `error.metadata.reason` as + * the OpenRouter-style free-tier refusal carries it, in a bounded JSON envelope after an optional + * `Provider error : ` prefix. Never a word anywhere in the text. + */ +function hasFreePromptCapField(message: string): boolean { + if (message.length > 16_384) return false; + const text = message.trim().replace(/^Provider error \d{3}:\s*/, ""); + let payload: unknown; + try { payload = JSON.parse(text); } catch { return false; } + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; + const error = (payload as Record).error; + if (!error || typeof error !== "object" || Array.isArray(error)) return false; + const { code, metadata } = error as Record; + if (code === "err_free_prompt_cap") return true; + return !!metadata && typeof metadata === "object" && !Array.isArray(metadata) + && (metadata as Record).reason === "err_free_prompt_cap"; +} + /** * A free-tier cap the upstream evaluates PER REQUEST rather than per account window. These * needles used to reach only `isProviderScopedQuotaCap`, so a single oversized free-tier prompt diff --git a/src/lib/anthropic-extra-usage.ts b/src/lib/anthropic-extra-usage.ts new file mode 100644 index 00000000000..6da1d72fb0d --- /dev/null +++ b/src/lib/anthropic-extra-usage.ts @@ -0,0 +1,57 @@ +/** + * Anthropic's quota refusal wordings: the HTTP 400s Anthropic sends for a spent account rather + * than a bad request. Shared by the pool rotation and by `classifyError`, so both read the + * refusal the same way. + * + * - Extra usage: an account whose plan AND extra usage are spent ("You're out of extra usage", + * "Third-party apps now draw from your extra usage"). + * - Spend limit: usage reached an organization or workspace spend limit the customer set. Per + * https://platform.claude.com/docs/en/api/rate-limits#setting-your-own-spend-limit this is + * HTTP 400 `invalid_request_error` whose message starts with "You have reached your specified + * API usage limits" or "You have reached your specified workspace API usage limits". + * + * Only the start of `error.message` counts: a validation 400 echoes client values (tool ids, + * model names, prompt text) into its message, so a match anywhere else would let one crafted + * request pass as a spent account and cool healthy accounts or a whole combo provider. + */ +const QUOTA_REFUSAL = new RegExp( + "^(?:" + + "you['\u2019]re out of extra usage" + + "|third-party apps now draw from your extra usage" + + "|you have reached your specified (?:workspace )?api usage limits" + + ")", + "i", +); + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** Whether an already-extracted Anthropic `error.message` starts with a quota refusal wording. */ +export function isAnthropicQuotaRefusalMessage(message: string): boolean { + return QUOTA_REFUSAL.test(message.trimStart()); +} + +/** + * Whether a parsed body is Anthropic's JSON error envelope (`type: "error"`, + * `error.type: "invalid_request_error"`) whose `error.message` starts with a quota refusal wording. + */ +export function isAnthropicQuotaRefusalEnvelope(payload: unknown): boolean { + if (!isRecord(payload) || payload.type !== "error" || !isRecord(payload.error)) return false; + const { type, message } = payload.error; + return type === "invalid_request_error" + && typeof message === "string" + && isAnthropicQuotaRefusalMessage(message); +} + +/** {@link isAnthropicQuotaRefusalEnvelope} for a raw body; a non-JSON body is never the refusal. */ +export function isAnthropicQuotaRefusalBody(body: string | null | undefined): boolean { + if (!body) return false; + let payload: unknown; + try { + payload = JSON.parse(body); + } catch { + return false; + } + return isAnthropicQuotaRefusalEnvelope(payload); +} diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 1e2bc7c39c4..f497f3da6a8 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -1,3 +1,4 @@ +import { isAnthropicQuotaRefusalEnvelope, isAnthropicQuotaRefusalMessage } from "./anthropic-extra-usage"; import { parseRetryAfterFromMessage } from "./retry-delay"; export interface OcxErrorPayload { @@ -355,6 +356,47 @@ export function isUpstreamResetReplayRefusedMessage(text: string): boolean { ); } +/** This proxy's prefix for an upstream 400/422 error, and the `type: ` lead a bridge formatter adds. */ +const PROVIDER_ERROR_400_PREFIX = /^Provider error (?:400|422):\s*/i; +const INVALID_REQUEST_TYPE_LEAD = /^invalid_request_error:\s*/i; + +/** + * Quota evidence in an HTTP 400 or 422, read from fields, never from words anywhere in the text. + * + * A 400/422 is a verdict on the request, and providers echo client values into it: Anthropic's + * validation errors quote tool ids and content ("messages.3.content...: toolu_insufficient_quota"). + * Matching quota words anywhere let one crafted request read as a spent account and cool a whole + * combo provider for ten minutes. So a 400/422 is quota only when, after this proxy's + * `Provider error 400: ` (or `422: `) prefix: + * - it is a JSON error envelope whose `error.code` or `error.type` FIELD is `insufficient_quota` + * (OpenAI/Codex, and this proxy's own re-wrapped error), whose `error.code` is Volcengine Ark's + * `InvalidSubscription` (HTTP 400, Coding Plan not subscribed or expired: + * https://www.volcengine.com/docs/82379/1299023), or Anthropic's envelope whose `error.message` + * starts with a quota refusal wording (src/lib/anthropic-extra-usage.ts); an envelope whose + * `error.message` is again `Provider error 400: ...` is read the same way, at most three deep; + * - or it is not JSON and STARTS with such a wording (optionally after `invalid_request_error: `), + * which is a caller passing the already-extracted `error.message`. + * A truncated or malformed JSON body is never quota. + */ +function isQuotaBadRequestMessage(message: string): boolean { + let text = message.trim(); + for (let depth = 0; depth < 3; depth += 1) { + text = text.replace(PROVIDER_ERROR_400_PREFIX, ""); + if (!text.startsWith("{")) return isAnthropicQuotaRefusalMessage(text.replace(INVALID_REQUEST_TYPE_LEAD, "")); + let payload: unknown; + try { payload = JSON.parse(text); } catch { return false; } + if (isAnthropicQuotaRefusalEnvelope(payload)) return true; + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; + const error = (payload as { error?: unknown }).error; + if (!error || typeof error !== "object" || Array.isArray(error)) return false; + const { code, type, message: inner } = error as Record; + if (code === "insufficient_quota" || type === "insufficient_quota" || code === "InvalidSubscription") return true; + if (typeof inner !== "string" || !PROVIDER_ERROR_400_PREFIX.test(inner.trim())) return false; + text = inner.trim(); + } + return false; +} + export function classifyError(status: number, type: string, message: string): OcxErrorPayload { const text = message.toLowerCase(); if (type === "previous_response_not_found") { @@ -419,23 +461,27 @@ export function classifyError(status: number, type: string, message: string): Oc // The Cursor adapter's classified rate-limit prefix is authoritative: its DETAIL may echo // quota wording ("... quota exhausted") that would otherwise hit the insufficient_quota // branch below and break the planned retry-with-backoff contract (WP3 review blocker 1). - if (text.includes("cursor rate limit exceeded")) { + // + // No quota or rate verdict on a 400 or 422 comes from words anywhere in its text: see + // isQuotaBadRequestMessage. Those verdicts hop a combo and cool its target or provider. + const badRequest = status === 400 || status === 422; + if (!badRequest && text.includes("cursor rate limit exceeded")) { return { message, type: "rate_limit_error", code: "rate_limit_exceeded" }; } - if ( + if (badRequest ? isQuotaBadRequestMessage(message) : ( text.includes("insufficient_quota") || text.includes("exceeded your current quota") || text.includes("quota exhausted") || text.includes("account quota exceeded") || text.includes("monthly quota exceeded") || text.includes("daily quota exceeded") || - // Anthropic answers a spent plan with HTTP 400, not 429; without this it classifies as - // invalid_request_error, a hard stop, and a combo never hops to its next tier. + // Anthropic answers a spent plan with HTTP 400, not 429 (a 400 is read by + // isQuotaBadRequestMessage above); these cover callers without the upstream status. text.includes("out of extra usage") || // Same spent-plan state, newer wording: a third-party client is refused with HTTP 400 because // its usage now bills against extra usage, not the plan limits. text.includes("third-party apps now draw from your extra usage") - ) { + )) { return { message, type: "insufficient_quota", code: "insufficient_quota" }; } // A refusal this proxy made itself, kept apart from the provider rate limits below. The HTTP @@ -447,14 +493,15 @@ export function classifyError(status: number, type: string, message: string): Oc return { message, type: "rate_limit_error", code: SEND_BUDGET_EXHAUSTED_CODE }; } if ( - status === 429 || - text.includes("rate limit") || - text.includes("rate limited") || - text.includes("too many requests") || - text.includes("resource_exhausted") || - text.includes("resource exhausted") || - text.includes("throttlingexception") || - text.includes("throttling") + status === 429 || (!badRequest && ( + text.includes("rate limit") || + text.includes("rate limited") || + text.includes("too many requests") || + text.includes("resource_exhausted") || + text.includes("resource exhausted") || + text.includes("throttlingexception") || + text.includes("throttling") + )) ) { return { message, type: "rate_limit_error", code: "rate_limit_exceeded" }; } @@ -529,6 +576,9 @@ export function classifyError(status: number, type: string, message: string): Oc return { message, type, code: type || null }; } +/** `Provider error ` or `Provider error : `, exactly as this proxy writes it. */ +const EXPLICIT_PROVIDER_STATUS = /^Provider error ([1-5]\d\d)(?::|$)/; + /** * True when a provider failure should participate in rate-limit / quota health blocking. * Reuses {@link classifyError} so generic 429 wording and quota phrases stay aligned. @@ -536,7 +586,10 @@ export function classifyError(status: number, type: string, message: string): Oc export function isRateLimitOrQuotaFailureMessage(message: string): boolean { const normalized = String(message ?? "").trim(); if (!normalized) return false; - const numericStatus = Number(normalized); + // This proxy's `Provider error ` prefix states the status; the body after it echoes + // client values, so an explicit 400 is read by classifyError's 400 rules, not by its words. + const explicit = EXPLICIT_PROVIDER_STATUS.exec(normalized); + const numericStatus = explicit ? Number(explicit[1]) : Number(normalized); if (numericStatus === 429 || numericStatus === 402) return true; const statusHint = Number.isInteger(numericStatus) && numericStatus > 0 ? numericStatus : 0; const classified = classifyError(statusHint, "", normalized); @@ -548,7 +601,9 @@ export function isRateLimitOrQuotaFailureMessage(message: string): boolean { ) { return true; } - // Retained quota cue used by subagent health before classifyError covered it. + // Retained quota cue used by subagent health before classifyError covered it. Not for an + // explicit other 4xx: that is a verdict on the request, and the words may be the client's. + if (explicit && statusHint >= 400 && statusHint < 500) return false; return normalized.toLowerCase().includes("usage limit"); } @@ -561,6 +616,11 @@ export function inferHttpStatusFromAdapterMessage(message: string): number { if (isClientClosedMessage(lower)) return 499; // Codex Transport maps cyber_policy only on HTTP 400 (SSE is code-based). if (isCyberPolicyMessage(lower)) return 400; + // This proxy's own `Provider error ` prefix states the upstream status outright. The + // text after it is the provider's body, which echoes client values, so a 400 that quotes + // "rate limit" must stay 400 rather than turn into a 429 that cools a combo target. + const explicit = EXPLICIT_PROVIDER_STATUS.exec(message.trimStart()); + if (explicit) return Number(explicit[1]); // See classifyError: this prefix now only means explicit request-size overflow (400); // quota-style Cursor resource exhaustion carries the rate-limit prefix and maps to 429. if (lower.includes("cursor resource limit exceeded")) return 400; diff --git a/src/oauth/anthropic-pool-rotation.ts b/src/oauth/anthropic-pool-rotation.ts index 6ac568c4009..7026988cb75 100644 --- a/src/oauth/anthropic-pool-rotation.ts +++ b/src/oauth/anthropic-pool-rotation.ts @@ -1,45 +1,25 @@ +import { isAnthropicQuotaRefusalBody } from "../lib/anthropic-extra-usage"; import { readQuotaResetAt } from "../providers/key-failover"; /** * Why an upstream answer may move a request to the next Anthropic pool account. * * - `"429"`: a rate or quota limit, the original trigger. - * - `"quota-400"`: Anthropic answers an account whose plan AND extra usage are spent with - * HTTP 400 ("You're out of extra usage", "Third-party apps now draw from your extra usage"), - * not 429. The account is spent; another pool account may not be. + * - `"quota-400"`: Anthropic answers a spent account with HTTP 400, not 429: plan AND extra + * usage spent ("You're out of extra usage", "Third-party apps now draw from your extra usage"), + * or a spend limit the customer set ("You have reached your specified [workspace] API usage + * limits"). The account is spent; another pool account may not be. */ export type AnthropicPoolRotationTrigger = "429" | "quota-400"; /** - * Anthropic's spent-extra-usage wordings, anchored at the start of `error.message`. Only the - * start counts: a validation 400 echoes client values (tool ids, model names, text) into its - * message, so a match anywhere else would let one crafted request cool every pool account. - */ -const EXTRA_USAGE_REFUSAL = /^(?:you['\u2019]re out of extra usage|third-party apps now draw from your extra usage)/i; - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -/** - * Whether a 400 body is Anthropic's out-of-extra-usage refusal. It must be Anthropic's JSON error - * envelope (`type: "error"`, `error.type: "invalid_request_error"`) whose `error.message` starts - * with one of the two wordings. Anything else, including a non-JSON body, is a request-shape - * failure that would fail the same way on any account and must not rotate. + * Whether a 400 body is Anthropic's quota refusal: Anthropic's JSON error envelope whose + * `error.message` starts with one of its quota refusal wordings (src/lib/anthropic-extra-usage.ts). + * Anything else, including a non-JSON body, is a request-shape failure that would fail the same + * way on any account and must not rotate. */ export function isQuotaExhaustedBadRequest(status: number, body: string | null | undefined): boolean { - if (status !== 400 || !body) return false; - let payload: unknown; - try { - payload = JSON.parse(body); - } catch { - return false; - } - if (!isRecord(payload) || payload.type !== "error" || !isRecord(payload.error)) return false; - const { type, message } = payload.error; - return type === "invalid_request_error" - && typeof message === "string" - && EXTRA_USAGE_REFUSAL.test(message.trimStart()); + return status === 400 && isAnthropicQuotaRefusalBody(body); } /** The pool-rotation trigger for an upstream status and (for a 400) its body, or null. */ diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index 28ec06c02b9..5fa0ba5c8e9 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -1345,7 +1345,8 @@ export async function handleResponsesCompact( const bodyInferredQuota = !replayRefused && !buffered.ok && !explicitQuotaStatus - && isRateLimitOrQuotaFailureMessage(bufferedErrorText); + // With the real status, so an echoing 400/422 body is read by its fields, not its words. + && isRateLimitOrQuotaFailureMessage(`Provider error ${buffered.status}: ${bufferedErrorText}`); const quotaFailure = explicitQuotaStatus || bodyInferredQuota; // Record pool health only after the body is fully delivered (or definitively failed). // A premature 200 would clear soft-avoid while the client still sees a buffer 502. diff --git a/tests/responses/responses-compact-400-quota-echo.test.ts b/tests/responses/responses-compact-400-quota-echo.test.ts new file mode 100644 index 00000000000..024566e7a55 --- /dev/null +++ b/tests/responses/responses-compact-400-quota-echo.test.ts @@ -0,0 +1,115 @@ +/** + * Compact reads a non-ok body for quota evidence so a quota refusal behind a generic status still + * cools the pool account. It used to read the body with no status, so a 400 or 422 that only + * echoed client values ("rate limit", "usage limit", "insufficient_quota") was recorded as a 429 + * and cooled a healthy account. The body is now read with its real status. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountQuota, updateAccountQuota } from "../../src/codex/auth-api"; +import { clearCodexUpstreamHealth, isCodexAccountInCooldown, isCodexAccountSoftAvoided } from "../../src/codex/routing"; +import { clearUpstreamHostHealth } from "../../src/codex/upstream-host-health"; +import { handleResponsesCompact } from "../../src/server/responses"; +import type { OcxConfig } from "../../src/types"; +import { baseCompactionBody, compactionRequest, twoAccountPoolConfig } from "../helpers/compaction-routing-fixtures"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const originalFetch = globalThis.fetch; + +// The recorded Anthropic 400 (fixtures/external/anthropic/README.md). No recorded validation 400 +// that echoes client values exists yet, so the echo bodies are this recorded envelope with only +// `error.message` replaced; envelope keys, `type` and `error.type` stay as recorded. +const RECORDED_LINE = readFileSync( + join(import.meta.dir, "../../fixtures/external/anthropic/extra-usage-thirdparty-400.txt"), + "utf8", +); +const RECORDED_BODY = `${RECORDED_LINE.slice("Provider error 400: ".length)}"}}`; +function recordedEnvelopeWithMessage(message: string): string { + const recorded = JSON.parse(RECORDED_BODY) as { error: Record }; + return JSON.stringify({ ...recorded, error: { ...recorded.error, message } }); +} +const ECHO = recordedEnvelopeWithMessage( + "input.0.content.0.text: unexpected value: rate limit, too many requests, usage limit reached, toolu_insufficient_quota", +); + +async function withPoolEnv(name: string, run: (config: OcxConfig) => Promise): Promise { + const testDir = mkdtempSync(join(tmpdir(), name)); + const previousOpencodexHome = process.env.OPENCODEX_HOME; + const previousCodexHome = process.env.CODEX_HOME; + process.env.OPENCODEX_HOME = testDir; + process.env.CODEX_HOME = testDir; + const releaseSpendHome = acquireOwnedSpendHome(); + clearCodexUpstreamHealth(); + clearUpstreamHostHealth(); + clearAccountQuota(); + for (const id of ["pool-a", "pool-b"]) { + saveCodexAccountCredential(id, { + accessToken: `${id}-access-token`, + refreshToken: `${id}-refresh-token`, + expiresAt: Date.now() + 300_000, + chatgptAccountId: id === "pool-a" ? "pool_acc_a" : "pool_acc_b", + }); + updateAccountQuota(id, id === "pool-a" ? 10 : 20); + } + try { + await run(twoAccountPoolConfig()); + } finally { + globalThis.fetch = originalFetch; + clearCodexUpstreamHealth(); + clearUpstreamHostHealth(); + clearAccountQuota(); + releaseSpendHome(); + removeTreeWithRetry(testDir); + if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousOpencodexHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + } +} + +async function compactAgainst(status: number, body: string, config: OcxConfig) { + let sends = 0; + globalThis.fetch = (async () => { + sends += 1; + return new Response(body, { status, headers: { "content-type": "application/json" } }); + }) as unknown as typeof fetch; + const res = await handleResponsesCompact(compactionRequest(baseCompactionBody({})), config, { model: "", provider: "" }); + const accountMarked = isCodexAccountInCooldown("pool-a") || isCodexAccountSoftAvoided("pool-a"); + return { res, sends, accountMarked }; +} + +afterEach(() => { globalThis.fetch = originalFetch; }); + +describe("compact reads a non-ok body for quota with its real status", () => { + for (const status of [400, 422]) { + test(`MUST-FAIL: an echoing ${status} does not cool the pool account`, async () => { + await withPoolEnv(`ocx-compact-echo-${status}-`, async config => { + const result = await compactAgainst(status, ECHO, config); + expect(result.res.status).toBe(status); + expect(result.sends).toBe(1); + expect(result.accountMarked).toBe(false); + }); + }); + } + + test("a 400 whose error.code field is insufficient_quota still cools the account", async () => { + await withPoolEnv("ocx-compact-field-400-", async config => { + // OpenAI/Codex quota shape: the verdict is the `code` field, not the message words. + const body = JSON.stringify({ error: { message: "quota", type: "invalid_request_error", code: "insufficient_quota" } }); + const result = await compactAgainst(400, body, config); + expect(result.accountMarked).toBe(true); + }); + }); + + test("a quota body behind a 5xx still cools the account", async () => { + await withPoolEnv("ocx-compact-5xx-quota-", async config => { + const body = JSON.stringify({ error: { message: "The usage limit has been reached", type: "usage_limit_reached" } }); + const result = await compactAgainst(502, body, config); + expect(result.accountMarked).toBe(true); + }); + }); +}); diff --git a/tests/routing/router-combo-400-quota-echo.test.ts b/tests/routing/router-combo-400-quota-echo.test.ts new file mode 100644 index 00000000000..78124aeedaa --- /dev/null +++ b/tests/routing/router-combo-400-quota-echo.test.ts @@ -0,0 +1,413 @@ +/** + * A 400 is quota only by its fields, never by quota words anywhere in its text (Mars L1 on #25). + * + * Anthropic's validation 400s echo client values (tool ids, content) into `error.message`. + * classifyError used to match quota phrases anywhere in a 400, so one crafted request read as a + * spent account: `insufficient_quota` is a provider-scoped combo failure, which cools every target + * of that provider for ten minutes. These tests drive the same steps the combo takes on an adapter + * 400: the dispatch's client error, the combo's read of it, the hop decision and the cooldown. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { formatErrorResponse } from "../../src/bridge"; +import { adapterFailureFromEvent } from "../../src/bridge/internal"; +import { advanceComboAfterFailure, clearComboTargetCooldowns, isComboTargetInCooldown, pickComboTarget } from "../../src/combos"; +import { comboFailureCooldownScope, comboFailureDecision } from "../../src/combos/failover"; +import { + isModelHealthBlocked, + recordSubagentQuotaFailureForThreadSpawn, + resetSubagentModelFallbackStateForTests, +} from "../../src/codex/subagent-model-fallback"; +import { classifyError, inferHttpStatusFromAdapterMessage, isRateLimitOrQuotaFailureMessage } from "../../src/lib/errors"; +import { isPoolRotatableStatus } from "../../src/oauth/anthropic-pool-rotation"; +import { consumeComboFailure } from "../../src/server/responses/core-combo-failure"; +import { normalizeUpstreamErrorText } from "../../src/server/responses/core-errors"; +import type { OcxConfig } from "../../src/types"; + +// The recorded third-party refusal (fixtures/external/anthropic/README.md): a gateway log line cut +// at 200 chars. The bytes after the log prefix are Anthropic's raw envelope; only the closing quote +// and braces the cut removed are added. +const RECORDED_THIRD_PARTY_LINE = readFileSync( + join(import.meta.dir, "../../fixtures/external/anthropic/extra-usage-thirdparty-400.txt"), + "utf8", +); +const RECORDED_THIRD_PARTY_BODY = `${RECORDED_THIRD_PARTY_LINE.slice("Provider error 400: ".length)}"}}`; + +/** + * NO REAL ECHO SAMPLE: no recorded Anthropic validation 400 exists in fixtures/external/ (or + * anywhere in the workspace) yet. Until one is logged, the echo payload is the RECORDED envelope + * above with only `error.message` replaced by the client-echoing validation text. Envelope keys, + * `type` and `error.type` stay exactly as recorded. + */ +function recordedEnvelopeWithMessage(message: string): string { + const recorded = JSON.parse(RECORDED_THIRD_PARTY_BODY) as { error: Record }; + return JSON.stringify({ ...recorded, error: { ...recorded.error, message } }); +} + +// Client-chosen values echoed back: a tool_use id, and user text quoted in a content error. +const ECHOED_TOOL_ID = recordedEnvelopeWithMessage( + "messages.1: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_insufficient_quota. " + + "Each `tool_use` block must have a corresponding `tool_result` block in the next message.", +); +const ECHOED_CONTENT = recordedEnvelopeWithMessage( + "messages.3.content.0.text: unexpected value: You're out of extra usage. Add more at claude.ai/settings/usage and keep going.", +); +const ECHOED_THIRD_PARTY = recordedEnvelopeWithMessage( + "messages.3.content.0.text: Third-party apps now draw from your extra usage, not your plan limits. rate limit exceeded", +); + +function config(): OcxConfig { + return { + port: 0, + defaultProvider: "anthropic", + providers: { + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", apiKey: "ka", models: ["opus", "sonnet"] }, + b: { adapter: "openai-chat", baseUrl: "https://b.example/v1", apiKey: "kb", models: ["m2"] }, + }, + combos: { + free: { + strategy: "failover", + targets: [ + { provider: "anthropic", model: "opus" }, + { provider: "anthropic", model: "sonnet" }, + { provider: "b", model: "m2" }, + ], + }, + }, + } as OcxConfig; +} + +/** The combo's handling of one adapter 400, as core-combo runs it. */ +async function comboOn400(upstreamBody: string, now: number) { + // adapter-dispatch: the client error for an upstream 400. + const normalized = normalizeUpstreamErrorText(upstreamBody, "unknown error"); + return comboOnChild(formatErrorResponse(400, "upstream_error", `Provider error 400: ${normalized.safeText}`), now); +} + +/** The combo's handling of an adapter terminal error event that carries only its message text. */ +async function comboOnAdapterMessage(message: string, now: number) { + const { httpStatus, error } = adapterFailureFromEvent({ type: "error", message }); + return comboOnChild(formatErrorResponse(httpStatus, error.type, error.message, { code: error.code }), now); +} + +async function comboOnChild(child: Response, now: number) { + const childStatus = child.status; + const childError = (await child.clone().json() as { error: { type: string; code: string | null } }).error; + // core-combo: read the child failure, decide, and cool only when it hops. + const failure = await consumeComboFailure(child, undefined, now); + const decision = comboFailureDecision(failure.response.status, failure.classificationText, { code: failure.upstreamCode }); + const scope = comboFailureCooldownScope(failure.response.status, failure.classificationText, { code: failure.upstreamCode }); + const cfg = config(); + const pick = pickComboTarget(cfg, "free", { now })!; + expect(pick.target).toMatchObject({ provider: "anthropic", model: "opus" }); + if (decision === "hop") { + advanceComboAfterFailure(cfg, pick, { + now, + cooldownScope: scope, + retryAfter: failure.retryAfter, + status: failure.response.status, + code: failure.upstreamCode, + message: failure.classificationText, + }); + } + const cooled = (model: string, at: number) => isComboTargetInCooldown("free", { provider: "anthropic", model }, at); + return { childStatus, childError, decision, scope, cooled }; +} + +beforeEach(() => clearComboTargetCooldowns()); +afterEach(() => clearComboTargetCooldowns()); + +describe("HTTP 400 quota classification is anchored to the provider's fields", () => { + test("the recorded third-party refusal is still insufficient_quota, raw and wrapped", () => { + for (const message of [RECORDED_THIRD_PARTY_BODY, `Provider error 400: ${RECORDED_THIRD_PARTY_BODY}`]) { + expect(classifyError(400, "upstream_error", message)).toMatchObject({ type: "insufficient_quota", code: "insufficient_quota" }); + } + // The cut log line itself is not a whole envelope: truncated JSON is never quota. + expect(classifyError(400, "upstream_error", RECORDED_THIRD_PARTY_LINE).code).toBe("invalid_request_error"); + }); + + test("MUST-FAIL: an echoed client value with quota or rate words is a plain invalid request", () => { + for (const body of [ECHOED_TOOL_ID, ECHOED_CONTENT, ECHOED_THIRD_PARTY]) { + for (const message of [body, `Provider error 400: ${body}`]) { + expect(classifyError(400, "upstream_error", message)).toMatchObject({ + type: "invalid_request_error", + code: "invalid_request_error", + }); + } + } + }); + + test("OpenAI/Codex insufficient_quota counts as a field, not as words in the message", () => { + const field = JSON.stringify({ error: { message: "You exceeded your current quota.", type: "insufficient_quota", code: "insufficient_quota" } }); + expect(classifyError(400, "upstream_error", `Provider error 400: ${field}`).code).toBe("insufficient_quota"); + const echoed = JSON.stringify({ + error: { message: "Invalid 'tools[0].name': 'insufficient_quota' exceeded your current quota", type: "invalid_request_error", code: "invalid_value" }, + }); + expect(classifyError(400, "upstream_error", `Provider error 400: ${echoed}`).code).toBe("invalid_request_error"); + }); + + test("429 keeps its substring classification", () => { + expect(classifyError(429, "upstream_error", `Provider error 429: ${ECHOED_TOOL_ID}`).code).toBe("insufficient_quota"); + expect(classifyError(429, "upstream_error", "Rate limit reached for model").code).toBe("rate_limit_exceeded"); + }); +}); + +describe("combo cooldown on an Anthropic 400", () => { + test("the recorded refusal hops and cools the whole provider for ten minutes", async () => { + const now = 1_000_000; + const result = await comboOn400(RECORDED_THIRD_PARTY_BODY, now); + expect(result.childError).toMatchObject({ type: "insufficient_quota", code: "insufficient_quota" }); + expect(result.decision).toBe("hop"); + expect(result.scope).toBe("provider"); + expect(result.cooled("opus", now + 1)).toBe(true); + expect(result.cooled("sonnet", now + 10 * 60_000 - 1)).toBe(true); + expect(isComboTargetInCooldown("free", { provider: "b", model: "m2" }, now + 1)).toBe(false); + }); + + for (const [name, body] of [ + ["an echoed toolu_insufficient_quota tool id", ECHOED_TOOL_ID], + ["echoed 'out of extra usage' user content", ECHOED_CONTENT], + ["echoed third-party wording and rate words", ECHOED_THIRD_PARTY], + ] as const) { + test(`MUST-FAIL: ${name} stops and records no combo cooldown`, async () => { + const now = 2_000_000; + const result = await comboOn400(body, now); + expect(result.childError).toMatchObject({ type: "invalid_request_error", code: "invalid_request_error" }); + expect(result.decision).toBe("stop"); + expect(result.scope).not.toBe("provider"); + expect(result.cooled("opus", now + 1)).toBe(false); + expect(result.cooled("sonnet", now + 1)).toBe(false); + }); + } +}); + +// The web-search/images loops and native chat report an upstream failure as adapter text, +// `Provider error : `, and the status is inferred back from that text. +const ECHOED_RATE_WORDS = recordedEnvelopeWithMessage( + "messages.2.content.0.text: unexpected value: Rate limit reached, too many requests, throttling", +); + +describe("an explicit Provider error status is not re-inferred from echoed words", () => { + test("MUST-FAIL: a 400 echoing rate-limit words stays 400", () => { + for (const message of [ + `Provider error 400: ${ECHOED_RATE_WORDS}`, + // formatAnthropicErrorBody's `type: message` summary, as the loops write it. + "Provider error 400: invalid_request_error: messages.2.content.0.text: rate limit, too many requests", + ]) { + expect(inferHttpStatusFromAdapterMessage(message)).toBe(400); + } + }); + + test("an explicit 429 stays 429, and an explicit bare status is kept", () => { + expect(inferHttpStatusFromAdapterMessage("Provider error 429: Number of request tokens has exceeded your rate limit")).toBe(429); + expect(inferHttpStatusFromAdapterMessage("Provider error 429")).toBe(429); + expect(inferHttpStatusFromAdapterMessage("Provider error 503: invalid upstream answer")).toBe(503); + }); + + test("a message without the prefix keeps keyword inference", () => { + expect(inferHttpStatusFromAdapterMessage("Rate limit reached for requests")).toBe(429); + expect(inferHttpStatusFromAdapterMessage("too many requests, invalid model")).toBe(429); + expect(inferHttpStatusFromAdapterMessage("model not found")).toBe(400); + expect(inferHttpStatusFromAdapterMessage("upstream request timed out")).toBe(504); + // Not this proxy's exact prefix: inferred as before. + expect(inferHttpStatusFromAdapterMessage("provider error 400: rate limit")).toBe(429); + expect(inferHttpStatusFromAdapterMessage("Upstream said Provider error 400: rate limit")).toBe(429); + }); + + test("MUST-FAIL: the echoing 400 adapter error stops the combo with no cooldown", async () => { + const now = 3_000_000; + const result = await comboOnAdapterMessage(`Provider error 400: ${ECHOED_RATE_WORDS}`, now); + expect(result.childStatus).toBe(400); + expect(result.childError.code).toBe("invalid_request_error"); + expect(result.decision).toBe("stop"); + expect(result.cooled("opus", now + 1)).toBe(false); + expect(result.cooled("sonnet", now + 1)).toBe(false); + }); + + test("an explicit 429 adapter error still hops and cools its target", async () => { + const now = 4_000_000; + const result = await comboOnAdapterMessage("Provider error 429: Rate limit reached for requests", now); + expect(result.childStatus).toBe(429); + expect(result.childError.code).toBe("rate_limit_exceeded"); + expect(result.decision).toBe("hop"); + expect(result.cooled("opus", now + 1)).toBe(true); + }); +}); + +// adapter-dispatch reports a failed thread-spawn turn to subagent model health as +// `Provider error : ` (a 429 or 402 as the bare number). +describe("subagent model health reads an explicit Provider error status", () => { + const SPAWN = new Headers({ "x-openai-subagent": "collab_spawn" }); + const MODEL = "kimi/k3"; + const subagentConfig = (): OcxConfig => ({ + port: 0, + defaultProvider: "kimi", + providers: { kimi: { adapter: "openai-chat", apiKey: "test", baseUrl: "https://example.invalid", models: ["k3"] } }, + } as OcxConfig); + const blockedAfter = (message: string | number): boolean => { + resetSubagentModelFallbackStateForTests(); + const now = 5_000_000; + recordSubagentQuotaFailureForThreadSpawn(SPAWN, MODEL, message, subagentConfig(), undefined, now); + return isModelHealthBlocked(MODEL, subagentConfig(), undefined, now + 1); + }; + afterEach(() => resetSubagentModelFallbackStateForTests()); + + const ECHOED_USAGE_LIMIT = recordedEnvelopeWithMessage( + "messages.0.content.0.text: unexpected value: usage limit reached, rate limit, too many requests", + ); + + test("MUST-FAIL: an echoed 400 does not mark the model unhealthy", () => { + for (const body of [ECHOED_RATE_WORDS, ECHOED_TOOL_ID, ECHOED_CONTENT, ECHOED_USAGE_LIMIT]) { + const message = `Provider error 400: ${body}`; + expect(isRateLimitOrQuotaFailureMessage(message)).toBe(false); + expect(blockedAfter(message)).toBe(false); + } + }); + + test("the recorded extra-usage 400 and an explicit 429 still mark it unhealthy", () => { + expect(blockedAfter(`Provider error 400: ${RECORDED_THIRD_PARTY_BODY}`)).toBe(true); + expect(blockedAfter("Provider error 429: Rate limit reached for requests")).toBe(true); + expect(blockedAfter("Provider error 429")).toBe(true); + expect(blockedAfter(429)).toBe(true); + }); + + test("messages without the prefix behave as before", () => { + expect(isRateLimitOrQuotaFailureMessage("Weekly usage limit reached")).toBe(true); + expect(isRateLimitOrQuotaFailureMessage("Too Many Requests")).toBe(true); + expect(isRateLimitOrQuotaFailureMessage(`messages.0: toolu_insufficient_quota`)).toBe(true); + expect(isRateLimitOrQuotaFailureMessage("connection refused")).toBe(false); + // A 5xx keeps the usage-limit cue: Codex reports a spent window as 502. + expect(isRateLimitOrQuotaFailureMessage("Provider error 502: usage limit reached")).toBe(true); + }); +}); + +// Anthropic's spend-limit 400 (https://platform.claude.com/docs/en/api/errors and +// https://platform.claude.com/docs/en/api/rate-limits#setting-your-own-spend-limit): HTTP 400 +// `invalid_request_error` whose message STARTS with "You have reached your specified API usage +// limits" (or "...specified workspace API usage limits"). NO RECORDED SAMPLE: the body is the +// recorded envelope above with only `error.message` replaced by the documented opening. +const SPEND_LIMIT = recordedEnvelopeWithMessage( + "You have reached your specified API usage limits. You will regain access on 2026-12-01 at 00:00 UTC.", +); +const WORKSPACE_SPEND_LIMIT = recordedEnvelopeWithMessage( + "You have reached your specified workspace API usage limits. You will regain access on 2026-12-01 at 00:00 UTC.", +); +const ECHOED_SPEND_LIMIT = recordedEnvelopeWithMessage( + "messages.0.content.0.text: unexpected value: You have reached your specified API usage limits", +); + +describe("Anthropic spend-limit 400", () => { + test("is insufficient_quota and cools the provider like the extra-usage refusal", async () => { + for (const body of [SPEND_LIMIT, WORKSPACE_SPEND_LIMIT]) { + expect(classifyError(400, "upstream_error", `Provider error 400: ${body}`).code).toBe("insufficient_quota"); + clearComboTargetCooldowns(); + const now = 6_000_000; + const result = await comboOn400(body, now); + expect(result.decision).toBe("hop"); + expect(result.scope).toBe("provider"); + expect(result.cooled("sonnet", now + 1)).toBe(true); + } + }); + + test("the pool rotates on it too, through the same matcher", () => { + expect(isPoolRotatableStatus(400, SPEND_LIMIT)).toBe("quota-400"); + expect(isPoolRotatableStatus(400, WORKSPACE_SPEND_LIMIT)).toBe("quota-400"); + expect(isPoolRotatableStatus(400, ECHOED_SPEND_LIMIT)).toBeNull(); + }); + + test("echoed anywhere but the start it is a plain invalid request", () => { + expect(classifyError(400, "upstream_error", `Provider error 400: ${ECHOED_SPEND_LIMIT}`).code).toBe("invalid_request_error"); + }); +}); + +// Volcengine Ark (https://www.volcengine.com/docs/82379/1299023): HTTP 400, `error.code` +// "InvalidSubscription", "Coding Plan not subscribed or expired". NO RECORDED SAMPLE: code, type +// and message are the documented table row, in Ark's OpenAI-style `error` object. +const VOLCENGINE_INVALID_SUBSCRIPTION = JSON.stringify({ + error: { + code: "InvalidSubscription", + message: "Your account (2100000000) does not have a valid coding plan subscription, or your subscription has expired.", + param: "", + type: "Forbidden", + }, +}); + +describe("Volcengine InvalidSubscription 400", () => { + test("the error.code field is insufficient_quota", () => { + expect(classifyError(400, "upstream_error", `Provider error 400: ${VOLCENGINE_INVALID_SUBSCRIPTION}`).code).toBe("insufficient_quota"); + }); + + test("guard: the word in a message, or another field, is not", () => { + for (const body of [ + JSON.stringify({ error: { code: "InvalidParameter", message: "InvalidSubscription", param: "model", type: "BadRequest" } }), + JSON.stringify({ error: { code: "InvalidParameter", message: "x", param: "InvalidSubscription", type: "BadRequest" } }), + JSON.stringify({ code: "InvalidSubscription", error: { code: "InvalidParameter", message: "x" } }), + ]) { + expect(classifyError(400, "upstream_error", `Provider error 400: ${body}`).code).toBe("invalid_request_error"); + } + }); +}); + +describe("HTTP 422 gets the same field-only rule as 400", () => { + const echoed = recordedEnvelopeWithMessage( + "tools.0.name: unexpected value: insufficient_quota, rate limit, too many requests, usage limit reached", + ); + + test("MUST-FAIL: words in a 422 are no quota or rate verdict", () => { + for (const message of [echoed, `Provider error 422: ${echoed}`]) { + const classified = classifyError(422, "upstream_error", message); + expect(classified.code).not.toBe("insufficient_quota"); + expect(classified.code).not.toBe("rate_limit_exceeded"); + } + expect(isRateLimitOrQuotaFailureMessage(`Provider error 422: ${echoed}`)).toBe(false); + expect(inferHttpStatusFromAdapterMessage(`Provider error 422: ${echoed}`)).toBe(422); + }); + + test("MUST-FAIL: an echoing 422 stops the combo with no cooldown", async () => { + const now = 7_000_000; + const result = await comboOnChild( + formatErrorResponse(422, "upstream_error", `Provider error 422: ${echoed}`), + now, + ); + expect(result.decision).toBe("stop"); + expect(result.cooled("opus", now + 1)).toBe(false); + expect(result.cooled("sonnet", now + 1)).toBe(false); + }); + + test("a 422 field verdict and the existing non-quota 422 behaviour stay", () => { + const field = JSON.stringify({ error: { message: "quota", type: "insufficient_quota", code: "insufficient_quota" } }); + expect(classifyError(422, "upstream_error", `Provider error 422: ${field}`).code).toBe("insufficient_quota"); + expect(comboFailureDecision(422, "invalid_api_key")).toBe("hop"); + expect(comboFailureDecision(422, "unprocessable entity")).toBe("stop"); + }); +}); + +describe("the free-tier prompt cap on a 400 or 422 counts only as a field", () => { + const echoed = recordedEnvelopeWithMessage( + "messages.0.content.0.text: unexpected value: err_free_prompt_cap, longer than the free tier allows for a single request", + ); + + test("MUST-FAIL: echoed err_free_prompt_cap / free-tier words do not hop or cool the provider", () => { + for (const status of [400, 422]) { + for (const message of [echoed, `Provider error ${status}: ${echoed}`]) { + expect(comboFailureDecision(status, message)).toBe("stop"); + expect(comboFailureCooldownScope(status, message)).not.toBe("provider"); + } + } + }); + + test("the field still hops; other statuses keep the word match", () => { + // The shape the combo end-to-end test sends for the free-tier refusal (`metadata.reason`). + const field = JSON.stringify({ error: { + message: "This prompt is longer than the free tier allows for a single request.", + type: "invalid_request_error", + metadata: { reason: "err_free_prompt_cap" }, + } }); + expect(comboFailureDecision(400, field)).toBe("hop"); + expect(comboFailureCooldownScope(400, field)).toBe("none"); + expect(comboFailureCooldownScope(422, JSON.stringify({ error: { code: "err_free_prompt_cap", message: "x" } }))).toBe("provider"); + expect(comboFailureCooldownScope(429, "err_free_prompt_cap")).toBe("provider"); + expect(comboFailureDecision(413, JSON.stringify({ detail: "err_free_prompt_cap: prompt exceeds this tier" }))).toBe("hop"); + }); +});