7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(routing): stop stale models and broke keys from burning the failover budget (#1242)
Tashfeenfc5d0a9aaf68
diff --git a/docs/en/architecture/04-degraded-mode-and-failover.md b/docs/en/architecture/04-degraded-mode-and-failover.mdindex 1881f1a2..4ef1856f 100644--- a/docs/en/architecture/04-degraded-mode-and-failover.md+++ b/docs/en/architecture/04-degraded-mode-and-failover.md@@ -199,7 +199,7 @@ interface FallbackHooks {| Error | Skip Scope | Cooldown | Model Penalty | Limit Learn ||-------|------------|----------|---------------|-------------|| 401 invalid key | key | 5 min | no | no |-| 402 payment required | key | 24h | no | no |+| 402 payment required | **key, every model of the platform** (#1239) | 24h | no | no || 403 model forbidden | **model** | 24h | no | no || 429 daily exhausted | model+key | until midnight / Retry-After | **heavy (3)** | yes || 429 transient (rpm/tpm) | key | 90s / ladder | light (1) | yes |@@ -232,10 +232,10 @@ interface FallbackHooks {2. **All context_too_large** → 413 `invalid_request_error` (`context_length_exceeded`).3. **All model_not_found** → 404 `invalid_request_error` (`model_not_found`).4. **Last error = degraded 400** (NVIDIA NIM) → 503 `service_unavailable` (`provider_degraded`).-5. **Last error = provider bad request** → 400 `invalid_request_error` (`provider_rejected_request`).+5. **All provider_bad_request** (or legacy no-trail, last error = provider bad request) → 400 `invalid_request_error` (`provider_rejected_request`). A mixed trail with only some bad-request hops falls through to 8 — the last hop's shape alone never blames the caller's request (#1239).6. **Circuit breaker** → 503 `service_unavailable` (`upstream_unhealthy`).7. **All UNAVAILABLE_UNTIL_KNOWN_TIME** (rate_limited, daily_quota_exhausted, out_of_credits, forbidden) → 429 `rate_limit_error` with `retryAtMs` + `Retry-After`.-8. **Mixed/other** → 502 `provider_error` (`upstream_failed`) — never 500 (our bugs).+8. **Mixed/other** → 502 `provider_error` (`upstream_failed`) — never 500 (our bugs). The message carries a per-class tally (`provider_bad_request ×5, out_of_credits ×3`) and only says "not a problem with your request" when no hop was a provider-side request rejection.**Synchronous exhaustion (zero attempts):** `routingExhaustionBody(routeErr)` maps diagnostics to same taxonomy:- All config (no key, no provider) → 503 `no_providers_configured`diff --git a/docs/zh-cn/architecture/04-degraded-mode-and-failover.md b/docs/zh-cn/architecture/04-degraded-mode-and-failover.mdindex 778abda4..0d79bd79 100644--- a/docs/zh-cn/architecture/04-degraded-mode-and-failover.md+++ b/docs/zh-cn/architecture/04-degraded-mode-and-failover.md@@ -197,7 +197,7 @@ interface FallbackHooks {| 错误 | 跳过范围 | 冷却 | 模型惩罚 | 限额学习 ||-------|------------|------|---------------|-------------|| 401 无效密钥 | 密钥 | 5 min | 否 | 否 |-| 402 需付款 | 密钥 | 24h | 否 | 否 |+| 402 需付款 | **密钥,覆盖该平台全部模型** (#1239) | 24h | 否 | 否 || 403 模型被禁 | **模型** | 24h | 否 | 否 || 429 每日耗尽 | 模型+密钥 | 到午夜 / Retry-After | **重 (3)** | 是 || 429 瞬时 (rpm/tpm) | 密钥 | 90s / 阶梯 | 轻 (1) | 是 |@@ -230,7 +230,7 @@ interface FallbackHooks {2. **全 context_too_large** → 413 `invalid_request_error` (`context_length_exceeded`)。3. **全 model_not_found** → 404 `invalid_request_error` (`model_not_found`)。4. **末尾错误 = degraded 400**(NVIDIA NIM) → 503 `service_unavailable` (`provider_degraded`)。-5. **末尾错误 = 提供方坏请求** → 400 `invalid_request_error` (`provider_rejected_request`)。+5. **全 provider_bad_request**(或无 trail 的旧形态且末尾错误 = 提供方坏请求) → 400 `invalid_request_error` (`provider_rejected_request`)。混合 trail 中仅部分为坏请求时落到第 8 条——末尾一跳的形态不再单独归咎于调用方请求(#1239)。6. **断路器** → 503 `service_unavailable` (`upstream_unhealthy`)。7. **全 UNAVAILABLE_UNTIL_KNOWN_TIME**(rate_limited、daily_quota_exhausted、out_of_credits、forbidden) → 429 `rate_limit_error` 带 `retryAtMs` + `Retry-After`。8. **混合/其他** → 502 `provider_error` (`upstream_failed`) —— 绝不 500(那是我们的 bug)。diff --git a/server/src/__tests__/lib/fallback-loop-issue-1239.test.ts b/server/src/__tests__/lib/fallback-loop-issue-1239.test.tsnew file mode 100644index 00000000..a0a8c42c--- /dev/null+++ b/server/src/__tests__/lib/fallback-loop-issue-1239.test.ts@@ -0,0 +1,319 @@+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';++// Issue #1239 — "All rejected": a Claude Code user's request burned its whole+// 45s failover budget on eight hops that were never going to work and was then+// told the REQUEST was invalid. The trail:+//+// navy/gpt-5.4-mini key1: provider_bad_request; navy/gpt-5-search-api key1:+// provider_bad_request; navy/o4-mini key1: provider_bad_request;+// huggingface/thinkingmachines/Inkling key2: out_of_credits; navy/o3 key1:+// provider_bad_request; huggingface/Qwen/Qwen3-VL-235B-A22B-Instruct key2:+// out_of_credits; huggingface/moonshotai/Kimi-K3 key2: out_of_credits;+// navy/o3-mini key1: provider_bad_request.+// Last error: NavyAI API error 400: The model 'o3-mini' does not exist or is+// not supported for chat completions.+//+// Three router defects, each covered below:+// 1. NavyAI's "The model 'x' does not exist" wording missed the model-not-+// found classifier (the model id sits between "model" and "does not+// exist"), so every stale row was booked as a per-key bad request.+// 2. A 402 benched only the one model+key that failed, so the same broke+// HuggingFace key was retried on two more models in the same request.+// 3. The exhaustion ladder rendered 400 "rejected the request as invalid"+// because the LAST error was bad-request shaped, although 3 of 8 attempts+// were out of credits and none said anything about the request.++vi.mock('../../services/health.js', () => ({+ checkKeyHealth: vi.fn(),+ markKeyHealthyFromRequest: vi.fn(),+}));++import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import {+ newFallbackState,+ recordRetryableFailure,+ classifyAttemptError,+ cooldownDecisionForError,+ exhaustedRetryError,+ runFallbackLoop,+ resetModelFailureWindows,+ type AttemptRecord,+ type AttemptErrorClass,+ type FallbackHooks,+} from '../../lib/fallback-loop.js';+import {+ isModelNotFoundError,+ isProviderBadRequestError,+ isRetryableError,+ isModelAccessForbiddenError,+} from '../../lib/error-classify.js';+import {+ isOnCooldown,+ clearCooldownsForKey,+ resetKeyLocalityCache,+} from '../../services/ratelimit.js';+import type { RouteResult } from '../../services/router.js';++// A platform the bundled baseline seeds with several models, so the key-wide+// bench has real rows to walk (the 402 test needs the models table).+const PLATFORM = 'groq';+let keyA = 0;+let keyB = 0;+let models: { id: number; model_id: string }[] = [];++function insertKey(label: string): number {+ const { encrypted, iv, authTag } = encrypt(`test-${label}`);+ const info = getDb().prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES (?, ?, ?, ?, ?, 'healthy', 1)+ `).run(PLATFORM, label, encrypted, iv, authTag);+ return Number(info.lastInsertRowid);+}++function routeFor(model: { id: number; model_id: string }, keyId: number, platform = PLATFORM): RouteResult {+ return {+ provider: {} as any,+ modelId: model.model_id,+ modelDbId: model.id,+ apiKey: 'k',+ keyId,+ platform,+ displayName: model.model_id,+ rpdLimit: null,+ tpdLimit: null,+ };+}++// The exact upstream bodies from the report.+const NAVY_STALE = (id = 'o3-mini') => Object.assign(+ new Error(`NavyAI API error 400: The model '${id}' does not exist or is not supported for chat completions.`),+ { status: 400 },+);+const HF_402 = () => Object.assign(+ new Error('HuggingFace API error 402: Payment required'),+ { status: 402 },+);+// A genuine request-shape rejection, for contrast: stays provider_bad_request.+const REAL_BAD_REQUEST = () => Object.assign(+ new Error('Google API error 400: Invalid JSON payload received. Unknown name "x-google-enum-descriptions"'),+ { status: 400 },+);++beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ keyA = insertKey('key-a');+ keyB = insertKey('key-b');+ resetKeyLocalityCache();+ models = db.prepare(+ 'SELECT id, model_id FROM models WHERE platform = ? AND enabled = 1 ORDER BY id',+ ).all(PLATFORM) as { id: number; model_id: string }[];+ expect(models.length).toBeGreaterThanOrEqual(3);+});++beforeEach(() => {+ clearCooldownsForKey(keyA);+ clearCooldownsForKey(keyB);+ getDb().prepare('DELETE FROM rate_limit_cooldowns').run();+ resetModelFailureWindows();+});++// ── 1. classification ────────────────────────────────────────────────────────++describe("NavyAI \"The model 'x' does not exist\" is a stale model, not a bad request", () => {+ it('matches the exact reported body and its quoting variants', () => {+ expect(isModelNotFoundError(NAVY_STALE())).toBe(true);+ expect(isModelNotFoundError(NAVY_STALE('gpt-5-search-api'))).toBe(true);+ expect(isModelNotFoundError(new Error('API error 400: The model "o3" does not exist'))).toBe(true);+ expect(isModelNotFoundError(new Error('API error 400: model o4-mini does not exist'))).toBe(true);+ expect(isModelNotFoundError(new Error("API error 400: Model `gpt-5.4-mini` doesn't exist"))).toBe(true);+ // Only the second half of the NavyAI sentence, on its own.+ expect(isModelNotFoundError(new Error('API error 400: o3-mini is not supported for chat completions'))).toBe(true);+ // The pre-existing bare phrasing still matches.+ expect(isModelNotFoundError(new Error('API error 400: model does not exist'))).toBe(true);+ });++ it('still fails over (retryable) and classifies for the trail as model_not_found', () => {+ expect(isRetryableError(NAVY_STALE())).toBe(true);+ expect(classifyAttemptError(NAVY_STALE())).toBe('model_not_found');+ });++ it('leaves genuine request rejections and tier 403s where they were', () => {+ expect(isModelNotFoundError(REAL_BAD_REQUEST())).toBe(false);+ expect(isProviderBadRequestError(REAL_BAD_REQUEST())).toBe(true);+ expect(classifyAttemptError(REAL_BAD_REQUEST())).toBe('provider_bad_request');+ // #256: "model X is not available on the free tier" is a tier verdict.+ const tier = Object.assign(new Error('Groq API error 403: model llama-guard is not available on the free tier'), { status: 403 });+ expect(isModelNotFoundError(tier)).toBe(false);+ expect(isModelAccessForbiddenError(tier)).toBe(true);+ // Unrelated sentences that merely contain both words.+ expect(isModelNotFoundError(new Error('API error 400: parameter temperature does not exist for this model family'))).toBe(false);+ });++ it('rules the WHOLE model out for the rest of the request', () => {+ const state = newFallbackState();+ recordRetryableFailure(routeFor(models[0], keyA), NAVY_STALE(models[0].model_id), state);+ expect(state.skipModels.has(models[0].id)).toBe(true);+ // Not a platform verdict: the platform's other rows are still candidates.+ expect(state.skipPlatforms.has(PLATFORM)).toBe(false);+ });+});++// ── 2. 402 benches the key across the platform ───────────────────────────────++describe('a 402 benches the key on every model of its platform', () => {+ it('cools every enabled model on the broke key for the credit window and skips them for this request', () => {+ const state = newFallbackState();+ recordRetryableFailure(routeFor(models[0], keyA), HF_402(), state);++ expect(cooldownDecisionForError(routeFor(models[0], keyA), HF_402()).source).toBe('credit');+ for (const m of models) {+ expect(isOnCooldown(PLATFORM, m.model_id, keyA), m.model_id).toBe(true);+ expect(state.skipKeys.has(`${PLATFORM}:${m.model_id}:${keyA}`), m.model_id).toBe(true);+ }+ });++ it('leaves a sibling key (a different wallet) and the platform itself in play', () => {+ const state = newFallbackState();+ recordRetryableFailure(routeFor(models[0], keyA), HF_402(), state);+ for (const m of models) {+ expect(isOnCooldown(PLATFORM, m.model_id, keyB), m.model_id).toBe(false);+ expect(state.skipKeys.has(`${PLATFORM}:${m.model_id}:${keyB}`)).toBe(false);+ }+ // Unlike a suspension, the platform is NOT ruled out: keyB may have credits.+ expect(state.skipPlatforms.has(PLATFORM)).toBe(false);+ });++ it('a genuine bad request stays on the per-route path', () => {+ const state = newFallbackState();+ recordRetryableFailure(routeFor(models[0], keyA), REAL_BAD_REQUEST(), state);+ expect(isOnCooldown(PLATFORM, models[1].model_id, keyA)).toBe(false);+ expect(state.skipKeys.has(`${PLATFORM}:${models[1].model_id}:${keyA}`)).toBe(false);+ });+});++// ── 3. exhaustion ladder ─────────────────────────────────────────────────────++const record = (classes: AttemptErrorClass[]): AttemptRecord[] =>+ classes.map((errorClass, i) => ({ platform: 'fake', modelId: `m${i}`, keyOrdinal: 1 + (i % 2), errorClass }));++describe('exhaustedRetryError only blames the request when every attempt did', () => {+ it("the reported trail (5× bad request + 3× out of credits) renders a 502, not 'rejected as invalid'", () => {+ const attempts = record([+ 'provider_bad_request', 'provider_bad_request', 'provider_bad_request', 'out_of_credits',+ 'provider_bad_request', 'out_of_credits', 'out_of_credits', 'provider_bad_request',+ ]);+ const body = exhaustedRetryError(NAVY_STALE(), 20, { attempts, timedOut: true, budgetMs: 45_000 });+ expect(body.status).toBe(502);+ expect(body.kind).toBe('upstream');+ expect(body.code).toBe('upstream_failed');+ expect(body.message).not.toContain('rejected the request as invalid');+ // Names the mix so the reader sees what actually happened…+ expect(body.message).toContain('provider_bad_request ×5');+ expect(body.message).toContain('out_of_credits ×3');+ // …and neither promises the request was fine nor blames it outright.+ expect(body.message).not.toContain('not a problem with your request');+ expect(body.message).toContain('rejected the request shape');+ expect(body.message).toContain('retry time budget 45s exceeded');+ expect(body.message).toContain('Attempt trail:');+ });++ it('a unanimous bad-request trail keeps the 400 invalid_request contract', () => {+ const body = exhaustedRetryError(REAL_BAD_REQUEST(), 20, { attempts: record(['provider_bad_request', 'provider_bad_request']) });+ expect(body.status).toBe(400);+ expect(body.code).toBe('provider_rejected_request');+ expect(body.message).toContain('rejected the request as invalid');+ });++ it('the legacy no-trail shape still falls back to the last error', () => {+ const body = exhaustedRetryError(REAL_BAD_REQUEST(), 20, { attempts: [] });+ expect(body.status).toBe(400);+ expect(body.code).toBe('provider_rejected_request');+ });++ it('a mix with no bad-request hop keeps the plain provider-side wording', () => {+ const body = exhaustedRetryError(HF_402(), 20, { attempts: record(['model_not_found', 'out_of_credits', 'upstream_error']) });+ expect(body.status).toBe(502);+ expect(body.message).toContain('not a problem with your request');+ expect(body.message).toContain('model_not_found ×1');+ });++ it('with the classifier fix the same trail reads stale models + credits and renders 502 end to end', () => {+ // What the reporter's chain becomes once NavyAI's wording is classified:+ // every navy hop is model_not_found, every HF hop out_of_credits.+ const attempts = record([+ 'model_not_found', 'model_not_found', 'model_not_found', 'out_of_credits',+ 'model_not_found', 'out_of_credits', 'out_of_credits', 'model_not_found',+ ]);+ const body = exhaustedRetryError(NAVY_STALE(), 20, { attempts });+ expect(body.status).toBe(502);+ expect(body.message).toContain('model_not_found ×5');+ expect(body.message).not.toContain('rejected the request as invalid');+ });+});++// ── End to end through the loop: the reported chain collapses to two hops ────++describe('runFallbackLoop on the reported chain', () => {+ function hooks(overrides: Partial<FallbackHooks>): FallbackHooks {+ return {+ state: newFallbackState(),+ timeBudgetMs: 0,+ route: () => { throw new Error('unused'); },+ dispatch: async () => 'done',+ logFailure: () => {},+ onFatal: () => {},+ onRoutingExhausted: () => {},+ onExhausted: () => {},+ ...overrides,+ };+ }++ it('skips the stale model on its sibling key and the broke key on its sibling models, then serves', async () => {+ const state = newFallbackState();+ const dispatched: string[] = [];+ const onExhausted = vi.fn();+ const onRoutingExhausted = vi.fn();++ // Candidate order, mimicking a router that walks the chain and honours+ // skipModels / skipKeys / cooldowns:+ // stale/keyA → stale/keyB (must be skipped: model-level)+ // → m1/keyA 402 → m2/keyA (must be skipped: key-level) → m2/keyB serves.+ const stale = { id: 987_654, model_id: 'o3-mini' };+ const candidates: RouteResult[] = [+ routeFor(stale, keyA, 'navy'),+ routeFor(stale, keyB, 'navy'),+ routeFor(models[1], keyA),+ routeFor(models[2], keyA),+ routeFor(models[2], keyB),+ ];+ const route = (): RouteResult => {+ for (const c of candidates) {+ if (state.skipModels.has(c.modelDbId)) continue;+ if (state.skipKeys.has(`${c.platform}:${c.modelId}:${c.keyId}`)) continue;+ if (isOnCooldown(c.platform, c.modelId, c.keyId)) continue;+ return c;+ }+ throw Object.assign(new Error('All models exhausted'), { status: 429 });+ };+ const dispatch = vi.fn(async (r: RouteResult) => {+ dispatched.push(`${r.platform}/${r.modelId}/key${r.keyId === keyA ? 'A' : 'B'}`);+ if (r.platform === 'navy') throw NAVY_STALE(r.modelId);+ if (r.keyId === keyA) throw HF_402();+ return 'done' as const;+ });++ await runFallbackLoop(hooks({ state, maxRetries: 20, route, dispatch, onExhausted, onRoutingExhausted }));++ expect(onExhausted).not.toHaveBeenCalled();+ expect(onRoutingExhausted).not.toHaveBeenCalled();+ expect(dispatched).toEqual([+ `navy/o3-mini/keyA`,+ `${PLATFORM}/${models[1].model_id}/keyA`,+ `${PLATFORM}/${models[2].model_id}/keyB`,+ ]);+ });+});diff --git a/server/src/lib/error-classify.ts b/server/src/lib/error-classify.tsindex 8fdf928d..c4a26cac 100644--- a/server/src/lib/error-classify.ts+++ b/server/src/lib/error-classify.ts@@ -492,6 +492,12 @@ export function isPaymentRequiredError(err: any): boolean {|| msg.includes('insufficient balance');}+// "model 'x' does not exist" / "model \"x\" does not exist" / "model x does not+// exist" — one non-space token (optionally quoted) between the word "model" and+// the verdict. Bounded so an unrelated sentence containing both words never+// matches; the model id itself is never inspected.+const MODEL_ID_DOES_NOT_EXIST = /\bmodel\b\s+['"`]?[^\s'"`]{1,200}['"`]?\s+(?:does\s+not|doesn't)\s+exist\b/;+// A 404 "model removed/deprecated upstream" error. It's a MODEL-level failure,// not a key-level one: every key for the platform will 404 the same way, so the// retry loop skips the entire model for the rest of the request instead of@@ -516,9 +522,21 @@ export function isModelNotFoundError(err: any): boolean {// identically), so they belong here for the whole-model skip.|| msg.includes('no model found') || msg.includes('model not found')|| msg.includes('unknown model') || msg.includes('model does not exist')- || msg.includes('no such model');+ || msg.includes('no such model')+ // The same verdict with the model id quoted in the middle (#1239: NavyAI+ // 400 "The model 'o3-mini' does not exist or is not supported for chat+ // completions."). The bare "model does not exist" substring above never+ // matches that wording, so every one of a platform's stale rows was booked+ // as provider_bad_request — no whole-model skip, a hop burned per dead+ // model, and the exhaustion body blamed the caller's request.+ || MODEL_ID_DOES_NOT_EXIST.test(msg)+ // "not supported for chat completions" is MODEL-level too: the id is real+ // but this platform cannot serve it on the endpoint we use, and a sibling+ // key would be told the same. Route it out for the request like a 404.+ || msg.includes('not supported for chat completions');}+// A 403 that suspends the ACCOUNT, not one model: NavyAI answers every model// behind a benched free key with "The Free plan is temporarily disabled due to// abuse. You can purchase a plan ...". Every model of the platform fails thediff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.tsindex 48d7d2b6..ba6a1234 100644--- a/server/src/lib/fallback-loop.ts+++ b/server/src/lib/fallback-loop.ts@@ -118,10 +118,19 @@ function clearModelFailure(route: RouteResult): void {/** Bench one key on every enabled model of its platform it can route to (the* route's own model is benched by the caller). For KEY-level verdicts only —- * an account suspension — never for a model-level one. Never throws: an- * unreadable catalog leaves the narrower per-route bench in place.+ * an account suspension, an empty balance — never for a model-level one.+ * Also rules the key out on those models for the rest of THIS request via+ * state.skipKeys, so the loop's next hop cannot land on the same account.+ * Never throws: an unreadable catalog leaves the narrower per-route bench in+ * place.*/-function benchKeyAcrossPlatform(route: RouteResult, durationMs: number, source: CooldownSource): void {+function benchKeyAcrossPlatform(+ route: RouteResult,+ durationMs: number,+ source: CooldownSource,+ state: FallbackState,+ reason: string,+): void {let modelIds: string[] = [];try {modelIds = (getDb().prepare(@@ -135,9 +144,10 @@ function benchKeyAcrossPlatform(route: RouteResult, durationMs: number, source:for (const modelId of modelIds) {if (modelId === route.modelId) continue;setCooldown(route.platform, modelId, route.keyId, durationMs, source);+ state.skipKeys.add(`${route.platform}:${modelId}:${route.keyId}`);benched++;}- console.warn(`[FallbackLoop] ${route.platform} key ${route.keyId} reports the account suspended; benched it on ${benched + 1} model(s) for ${Math.round(durationMs / 60_000)}min`);+ console.warn(`[FallbackLoop] ${route.platform} key ${route.keyId} ${reason}; benched it on ${benched + 1} model(s) for ${Math.round(durationMs / 60_000)}min`);}// ── Wall-clock retry budget ──────────────────────────────────────────────────@@ -419,7 +429,15 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: Fall// the next PROVIDER is the better hop.if (isAccountSuspendedError(err)) {state.skipPlatforms.add(route.platform);- benchKeyAcrossPlatform(route, decision.durationMs, decision.source);+ benchKeyAcrossPlatform(route, decision.durationMs, decision.source, state, 'reports the account suspended');+ } else if (isPaymentRequiredError(err)) {+ // A 402 is the ACCOUNT's balance, not one model's (#1239: one broke+ // HuggingFace key answered three different models with 402 in a single+ // request, three hops spent rediscovering the same empty wallet). Bench+ // the key on every model of the platform for the credit window. Unlike a+ // suspension the platform itself stays in play: a sibling key is a+ // different wallet and may well have credits, so only THIS key is out.+ benchKeyAcrossPlatform(route, decision.durationMs, decision.source, state, 'is out of credits (402)');}// Model-level failure benching: a model failing across keys (or repeatedly on// one key) must sink out of routing instead of being re-picked every request.@@ -836,7 +854,15 @@ export function exhaustedRetryError(lastError: any, maxRetries?: number, ctx?: E};}- if (isProviderBadRequestError(lastError)) {+ // 400 only when the trail agrees with the last error: EVERY attempt was a+ // provider-side request rejection (or the legacy no-trail shape). A mixed+ // trail — stale models, an empty wallet, a rate limit, and one bad-request+ // hop that happened to come last — is not evidence the caller's request is+ // invalid, and rendering it as one sent users debugging their own payload+ // (#1239: 5× provider_bad_request + 3× out_of_credits read as "All routed+ // providers rejected the request as invalid"). Those fall through to the+ // mixed 502 below, whose message names the class breakdown.+ if (isProviderBadRequestError(lastError) && (attempts.length === 0 || everyAttempt('provider_bad_request'))) {return {kind: 'bad_request',status: 400,@@ -887,17 +913,39 @@ export function exhaustedRetryError(lastError: any, maxRetries?: number, ctx?: E// those with rate limits): the upstream pool failed us, so say 502 — not 429// (which would promise recovery-by-waiting the attempts don't support) and// not 500 (which would blame our own code).+ //+ // The breakdown names how many attempts fell in each class so a mixed trail+ // reads as what it is. When SOME hops were provider-side request rejections+ // the body must not promise the request was fine either — it says which+ // providers rejected it and leaves the verdict to the reader.+ const breakdown = formatClassBreakdown(attempts);+ const someBadRequest = attempts.some(a => a.errorClass === 'provider_bad_request');+ const verdict = someBadRequest+ ? 'Most of these failures are provider-side (stale models, exhausted credits or quotas), but some providers ' ++ 'also rejected the request shape — check the attempt trail for which ones before changing your request.'+ : 'This is a provider-side failure, not a problem with your request; retry, or check provider status.';return {kind: 'upstream',status: 502,type: 'provider_error',code: 'upstream_failed',- message: `All ${attempts.length} routed attempt(s) failed with upstream provider errors${budgetNote}. ` +- `This is a provider-side failure, not a problem with your request; retry, or check provider status.` +- `${trail} Last error: ${safeLastError}`,+ message: `All ${attempts.length} routed attempt(s) failed with upstream provider errors${breakdown}${budgetNote}. ` ++ `${verdict}${trail} Last error: ${safeLastError}`,};}+/** " (provider_bad_request ×5, out_of_credits ×3)" — the per-class tally of a+ * mixed trail, most frequent first; empty when there is nothing to tally. */+function formatClassBreakdown(attempts: readonly AttemptRecord[]): string {+ if (attempts.length === 0) return '';+ const counts = new Map<AttemptErrorClass, number>();+ for (const a of attempts) counts.set(a.errorClass, (counts.get(a.errorClass) ?? 0) + 1);+ const parts = [...counts.entries()]+ .sort((a, b) => b[1] - a[1])+ .map(([cls, n]) => `${cls} ×${n}`);+ return ` (${parts.join(', ')})`;+}+// ── Routing exhaustion (zero attempts ran) ───────────────────────────────────// When routeRequest gives up before ANY upstream was tried, the only evidence// is its per-candidate diagnostics. Map them onto the same honest-terminal-