Skip to content

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

feat(gateway): fallback hardening pack (401 rotation, rich exhaustion, daily-quota bench, truncation policy, retry budget, usage fallback) (#484)

Tashfeene57a0f89b75c
diff --git a/.env.example b/.env.example
index db84f424..78cfc33b 100644
--- a/.env.example
+++ b/.env.example
@@ -38,6 +38,14 @@ PORT=3001
# set to 0 to disable the cap. Example — cap OpenRouter at 50 requests/day:
# PROVIDER_DAILY_REQUEST_CAP_OPENROUTER=50
+# Wall-clock budget for provider failover, in milliseconds (default: 45000).
+# A request that keeps failing over stops STARTING new attempts once this much
+# time has passed and returns the exhaustion error instead (the first attempt
+# always runs; an in-flight attempt is never cut off). Set to 0 to disable and
+# retry until the attempt cap. Can also be set at runtime via the
+# fallback_time_budget_ms settings key, which takes precedence.
+# FALLBACK_TIME_BUDGET_MS=45000
+
# Opt-in response cache. When on, a successful non-streaming /v1/chat/completions
# answer is stored in a bounded in-memory LRU keyed by a canonical hash of the
# request, so an IDENTICAL later request is served from memory without spending
diff --git a/server/src/__tests__/lib/fallback-loop.test.ts b/server/src/__tests__/lib/fallback-loop.test.ts
new file mode 100644
index 00000000..091d9842
--- /dev/null
+++ b/server/src/__tests__/lib/fallback-loop.test.ts
@@ -0,0 +1,351 @@
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+// Unit tests for the shared fallback loop's PR-B hardening: auth-fatal key
+// rotation + immediate revalidation, the attempt trail in exhaustion bodies,
+// daily-allocation benching until UTC midnight, the reasoning-truncation
+// skipBench exemption, the wall-clock retry budget, and the dispatch-outcome
+// contract enforcement.
+
+const { mockCheckKeyHealth } = vi.hoisted(() => ({ mockCheckKeyHealth: vi.fn() }));
+vi.mock('../../services/health.js', () => ({ checkKeyHealth: mockCheckKeyHealth }));
+
+import { initDb, getDb } from '../../db/index.js';
+import {
+ runFallbackLoop,
+ newFallbackState,
+ cooldownForError,
+ recordRetryableFailure,
+ exhaustedRetryError,
+ formatAttemptTrail,
+ classifyAttemptError,
+ msUntilNextUtcMidnight,
+ getFallbackTimeBudgetMs,
+ DEFAULT_FALLBACK_TIME_BUDGET_MS,
+ AUTH_FAILURE_COOLDOWN_MS,
+ type AttemptRecord,
+ type FallbackHooks,
+} from '../../lib/fallback-loop.js';
+import { isKeyAuthError, isDailyQuotaExhaustedError } from '../../lib/error-classify.js';
+import { getAllPenalties } from '../../services/router.js';
+import type { RouteResult } from '../../services/router.js';
+
+// Distinct keyId AND modelDbId per fake route: the router's penalty map and the
+// cooldown store are module-global, so shared ids would leak state across tests.
+let keySeq = 100;
+function fakeRoute(overrides: Partial<RouteResult> = {}): RouteResult {
+ const n = ++keySeq;
+ return {
+ provider: {} as any, modelId: 'fake-model', modelDbId: 424000 + n, apiKey: 'k',
+ keyId: n, platform: 'fake', displayName: 'Fake Model',
+ rpdLimit: null, tpdLimit: null,
+ ...overrides,
+ };
+}
+
+function hooksSkeleton(overrides: Partial<FallbackHooks>): FallbackHooks {
+ return {
+ state: newFallbackState(),
+ timeBudgetMs: 0, // disabled unless a test opts in
+ route: () => fakeRoute(),
+ dispatch: async () => 'done',
+ logFailure: () => {},
+ onFatal: () => {},
+ onRoutingExhausted: () => {},
+ onExhausted: () => {},
+ ...overrides,
+ };
+}
+
+const authRecord = (n: number): AttemptRecord[] =>
+ Array.from({ length: n }, (_, i) => ({ platform: 'fake', modelId: 'm', keyOrdinal: i + 1, errorClass: 'auth' as const }));
+
+beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+});
+
+beforeEach(() => {
+ mockCheckKeyHealth.mockReset();
+ mockCheckKeyHealth.mockResolvedValue('invalid');
+ getDb().prepare('DELETE FROM rate_limit_cooldowns').run();
+});
+
+describe('isKeyAuthError (401 = key-fatal, rotate instead of 502)', () => {
+ it('flags a structured 401 and common invalid-key phrasings', () => {
+ expect(isKeyAuthError(Object.assign(new Error('Unauthorized'), { status: 401 }))).toBe(true);
+ expect(isKeyAuthError(new Error('Groq API error 401: Invalid API Key'))).toBe(true);
+ expect(isKeyAuthError(new Error('unauthorized'))).toBe(true);
+ expect(isKeyAuthError(new Error('invalid_api_key: Incorrect API key provided'))).toBe(true);
+ });
+
+ it('does not flag 403s, 429s, or plain validation 400s', () => {
+ expect(isKeyAuthError(Object.assign(new Error('forbidden'), { status: 403 }))).toBe(false);
+ expect(isKeyAuthError(new Error('429 Too Many Requests'))).toBe(false);
+ expect(isKeyAuthError(new Error('400 Bad Request'))).toBe(false);
+ // A structured non-401 status wins over a suspicious message.
+ expect(isKeyAuthError(Object.assign(new Error('unauthorized model'), { status: 403 }))).toBe(false);
+ });
+
+ it('flags Google-style HTTP 400 bad-key errors via key-specific substrings only (#268)', () => {
+ // Google reports a bad/expired key as HTTP 400 INVALID_ARGUMENT, and every
+ // adapter attaches err.status (providerHttpError), so the 400 path must
+ // accept the key-specific phrasings...
+ expect(isKeyAuthError(Object.assign(new Error('Google API error 400: API key not valid. Please pass a valid API key.'), { status: 400 }))).toBe(true);
+ expect(isKeyAuthError(Object.assign(new Error('Google API error 400: API key expired. Please renew the API key.'), { status: 400 }))).toBe(true);
+ expect(isKeyAuthError(Object.assign(new Error('400 INVALID_ARGUMENT: API_KEY_INVALID'), { status: 400 }))).toBe(true);
+ // ...while ordinary payload 400s (even with generic auth-ish wording) stay
+ // provider-bad-request, not key-auth.
+ expect(isKeyAuthError(Object.assign(new Error('Google API error 400: Invalid JSON payload received. Unknown name "x"'), { status: 400 }))).toBe(false);
+ expect(isKeyAuthError(Object.assign(new Error('Cerebras API error 400: unauthorized field in tool schema'), { status: 400 }))).toBe(false);
+ });
+});
+
+describe('isDailyQuotaExhaustedError + midnight benching (drift: 90s cooldown on a dead-for-the-day provider)', () => {
+ it('flags real daily-allocation 429 bodies', () => {
+ expect(isDailyQuotaExhaustedError(new Error('Cloudflare API error 429: you have used up your daily free allocation of 10,000 neurons'))).toBe(true);
+ expect(isDailyQuotaExhaustedError(new Error('Rate limit exceeded: free-models-per-day'))).toBe(true);
+ expect(isDailyQuotaExhaustedError(new Error('You have exceeded your daily request limit'))).toBe(true);
+ });
+
+ it('does not flag per-minute 429s or generic errors', () => {
+ expect(isDailyQuotaExhaustedError(new Error('429 Too Many Requests'))).toBe(false);
+ expect(isDailyQuotaExhaustedError(new Error('tokens per minute (TPM): Limit 30000, Requested 33476'))).toBe(false);
+ expect(isDailyQuotaExhaustedError(new Error('503 Service Unavailable'))).toBe(false);
+ });
+
+ it('cooldownForError benches a daily-allocation 429 until the next UTC midnight', () => {
+ const route = fakeRoute();
+ const err = Object.assign(new Error('you have used up your daily free allocation of 10,000 neurons'), { status: 429 });
+ const ms = cooldownForError(route, err);
+ expect(Math.abs(ms - msUntilNextUtcMidnight())).toBeLessThan(5_000);
+ expect(ms).toBeGreaterThanOrEqual(60_000);
+ });
+
+ it('msUntilNextUtcMidnight floors at one minute near midnight', () => {
+ const justBeforeMidnight = Date.UTC(2026, 6, 7, 23, 59, 59, 900);
+ expect(msUntilNextUtcMidnight(justBeforeMidnight)).toBe(60_000);
+ });
+
+ it('honors an explicit Retry-After over the midnight bench (rolling daily windows)', () => {
+ // Groq-style rolling RPD: the body names a daily limit AND the response
+ // carries Retry-After ("try again in 7m12s"). The provider knows its own
+ // reset time; benching to UTC midnight would over-bench by hours.
+ const route = fakeRoute();
+ const retryAfterMs = 432_000; // 7m12s
+ const err = Object.assign(
+ new Error('Groq API error 429: Rate limit reached on requests per day (RPD): Limit 1000. Please try again in 7m12s.'),
+ { status: 429, retryAfterMs },
+ );
+ expect(cooldownForError(route, err)).toBe(retryAfterMs);
+ });
+});
+
+describe('recordRetryableFailure skipBench exemption (reasoning truncation)', () => {
+ it('skips cooldown + penalty but still rules the key out for this request', () => {
+ const route = fakeRoute();
+ const state = newFallbackState();
+ const err = Object.assign(new Error(`empty completion from ${route.displayName}`), { skipBench: true });
+ recordRetryableFailure(route, err, state);
+
+ expect(state.skipKeys.has(`fake:fake-model:${route.keyId}`)).toBe(true);
+ const cooldown = getDb().prepare('SELECT 1 FROM rate_limit_cooldowns WHERE platform = ? AND key_id = ?').get('fake', route.keyId);
+ expect(cooldown).toBeUndefined();
+ expect(getAllPenalties().some(p => p.modelDbId === route.modelDbId)).toBe(false);
+ });
+
+ it('control: the same error WITHOUT the flag benches and penalizes as before', () => {
+ const route = fakeRoute();
+ const state = newFallbackState();
+ recordRetryableFailure(route, new Error(`empty completion from ${route.displayName}`), state);
+
+ const cooldown = getDb().prepare('SELECT 1 FROM rate_limit_cooldowns WHERE platform = ? AND key_id = ?').get('fake', route.keyId);
+ expect(cooldown).toBeDefined();
+ // modelDbId 424242 has no sibling key rows, so the penalty fires.
+ expect(getAllPenalties().some(p => p.modelDbId === route.modelDbId)).toBe(true);
+ });
+});
+
+describe('exhaustedRetryError attempt trail + auth exhaustion', () => {
+ it('all-auth attempts produce a distinct 502 provider_error body, not a rate-limit 429', () => {
+ const body = exhaustedRetryError(new Error('Groq API error 401: Invalid API Key'), 20, { attempts: authRecord(3) });
+ expect(body.kind).toBe('auth');
+ expect(body.status).toBe(502);
+ expect(body.type).toBe('provider_error');
+ expect(body.message).toContain('failed authentication');
+ expect(body.message).toContain('Attempt trail:');
+ expect(body.message).not.toContain('rate-limited');
+ });
+
+ it('mixed attempts keep the rate-limit body and carry the trail + attempt count', () => {
+ const attempts: AttemptRecord[] = [
+ { platform: 'groq', modelId: 'llama-3.3-70b', keyOrdinal: 1, errorClass: 'rate_limited' },
+ { platform: 'cloudflare', modelId: 'qwen', keyOrdinal: 2, errorClass: 'daily_quota_exhausted' },
+ ];
+ const body = exhaustedRetryError(new Error('429 Too Many Requests'), 20, { attempts });
+ expect(body.kind).toBe('rate_limit');
+ expect(body.status).toBe(429);
+ expect(body.message).toContain('after 2 attempts');
+ expect(body.message).toContain('groq/llama-3.3-70b key1: rate_limited');
+ expect(body.message).toContain('cloudflare/qwen key2: daily_quota_exhausted');
+ });
+
+ it('a timed-out loop says so in the body', () => {
+ const body = exhaustedRetryError(new Error('429'), 20, { attempts: authRecord(1), timedOut: true, budgetMs: 45000 });
+ expect(body.message).toContain('retry time budget 45s exceeded');
+ });
+
+ it('provider-invalid exhaustion keeps the 400 invalid_request body (unchanged contract)', () => {
+ const err = Object.assign(new Error('Google API error 400: Invalid JSON payload received'), { status: 400 });
+ const body = exhaustedRetryError(err, 20, {
+ attempts: [{ platform: 'google', modelId: 'gemini', keyOrdinal: 1, errorClass: 'provider_bad_request' }],
+ });
+ expect(body.status).toBe(400);
+ expect(body.type).toBe('invalid_request_error');
+ expect(body.message).toContain('rejected the request as invalid');
+ expect(body.message).toContain('Attempt trail:');
+ });
+
+ it('formatAttemptTrail caps the shown entries', () => {
+ const trail = formatAttemptTrail(authRecord(14));
+ expect(trail).toContain('+4 more');
+ });
+
+ it('classifyAttemptError distinguishes the interesting classes', () => {
+ expect(classifyAttemptError(Object.assign(new Error('x'), { status: 401 }))).toBe('auth');
+ expect(classifyAttemptError(new Error('HuggingFace Router API error 402: Payment required'))).toBe('out_of_credits');
+ expect(classifyAttemptError(new Error('used up your daily free allocation'))).toBe('daily_quota_exhausted');
+ expect(classifyAttemptError(new Error('empty completion from X'))).toBe('empty_completion');
+ expect(classifyAttemptError(new Error('429 Too Many Requests'))).toBe('rate_limited');
+ expect(classifyAttemptError(Object.assign(new Error('Bad Gateway'), { status: 502 }))).toBe('upstream_error');
+ });
+});
+
+describe('runFallbackLoop: auth rotation (401 is key-fatal, not request-fatal)', () => {
+ it('rotates past a 401 key, benches it, and fires an immediate revalidation', async () => {
+ const badRoute = fakeRoute();
+ const goodRoute = fakeRoute();
+ const routes = [badRoute, goodRoute];
+ const dispatch = vi.fn()
+ .mockRejectedValueOnce(Object.assign(new Error('Invalid API Key'), { status: 401 }))
+ .mockResolvedValueOnce('done');
+ const onFatal = vi.fn();
+ const state = newFallbackState();
+
+ await runFallbackLoop(hooksSkeleton({
+ state,
+ route: (attempt) => routes[attempt],
+ dispatch,
+ onFatal,
+ }));
+
+ expect(dispatch).toHaveBeenCalledTimes(2); // rotated instead of 502
+ expect(onFatal).not.toHaveBeenCalled();
+ expect(state.skipKeys.has(`fake:fake-model:${badRoute.keyId}`)).toBe(true);
+ expect(mockCheckKeyHealth).toHaveBeenCalledWith(badRoute.keyId);
+ // Benched to cover the window until revalidation flips the key status.
+ const row = getDb().prepare('SELECT expires_at_ms FROM rate_limit_cooldowns WHERE platform = ? AND key_id = ?').get('fake', badRoute.keyId) as { expires_at_ms: number };
+ expect(row.expires_at_ms - Date.now()).toBeGreaterThan(AUTH_FAILURE_COOLDOWN_MS - 10_000);
+ // A key problem is not a model problem: no model penalty.
+ expect(getAllPenalties().some(p => p.modelDbId === badRoute.modelDbId)).toBe(false);
+ });
+});
+
+describe('runFallbackLoop: wall-clock retry budget', () => {
+ it('stops starting new attempts once the budget is spent and reports timedOut', async () => {
+ const dispatch = vi.fn(async () => {
+ await new Promise(r => setTimeout(r, 25));
+ throw Object.assign(new Error('429 Too Many Requests'), { status: 429 });
+ });
+ const onExhausted = vi.fn();
+
+ await runFallbackLoop(hooksSkeleton({
+ timeBudgetMs: 20, // spent after the first ~25ms attempt
+ dispatch,
+ onExhausted,
+ }));
+
+ expect(dispatch).toHaveBeenCalledTimes(1); // first attempt always runs, no second start
+ expect(onExhausted).toHaveBeenCalledTimes(1);
+ const [body, info] = onExhausted.mock.calls[0];
+ expect(info.timedOut).toBe(true);
+ expect(body.message).toContain('retry time budget');
+ expect(info.attempts).toHaveLength(1);
+ });
+
+ it('budget 0 disables the check', async () => {
+ const dispatch = vi.fn(async () => {
+ await new Promise(r => setTimeout(r, 5));
+ throw Object.assign(new Error('429 Too Many Requests'), { status: 429 });
+ });
+ const onExhausted = vi.fn();
+
+ await runFallbackLoop(hooksSkeleton({
+ maxRetries: 3,
+ timeBudgetMs: 0,
+ dispatch,
+ onExhausted,
+ }));
+
+ expect(dispatch).toHaveBeenCalledTimes(3);
+ expect(onExhausted.mock.calls[0][1].timedOut).toBe(false);
+ });
+
+ it('getFallbackTimeBudgetMs: env var wins over the default; setting wins over env', () => {
+ const original = process.env.FALLBACK_TIME_BUDGET_MS;
+ try {
+ delete process.env.FALLBACK_TIME_BUDGET_MS;
+ expect(getFallbackTimeBudgetMs()).toBe(DEFAULT_FALLBACK_TIME_BUDGET_MS);
+ process.env.FALLBACK_TIME_BUDGET_MS = '12345';
+ expect(getFallbackTimeBudgetMs()).toBe(12345);
+ getDb().prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('fallback_time_budget_ms', '999')").run();
+ expect(getFallbackTimeBudgetMs()).toBe(999);
+ } finally {
+ getDb().prepare("DELETE FROM settings WHERE key = 'fallback_time_budget_ms'").run();
+ if (original === undefined) delete process.env.FALLBACK_TIME_BUDGET_MS;
+ else process.env.FALLBACK_TIME_BUDGET_MS = original;
+ }
+ });
+});
+
+describe('runFallbackLoop: dispatch outcome contract', () => {
+ it('fails loudly when dispatch returns neither done nor committed', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onFatal = vi.fn();
+ const logFailure = vi.fn();
+
+ await runFallbackLoop(hooksSkeleton({
+ dispatch: (async () => undefined) as any, // a buggy adapter's bare `return`
+ onFatal,
+ logFailure,
+ }));
+
+ expect(consoleError).toHaveBeenCalledWith('[FallbackLoop]', expect.stringContaining('dispatch contract violation'));
+ expect(logFailure).toHaveBeenCalledTimes(1);
+ expect(onFatal).toHaveBeenCalledTimes(1); // rendered as a non-retryable error, not silently swallowed
+ consoleError.mockRestore();
+ });
+
+ it('never retries a violation whose modelId embeds a retryable-looking digit run', async () => {
+ // The violation message contains route.modelId; "mistral-small-2503" holds
+ // the substring '503', which the retryable classifier would match if the
+ // violation were thrown into the ordinary catch. The guard must bypass
+ // classification entirely: immediate onFatal, exactly one dispatch.
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onFatal = vi.fn();
+ const onExhausted = vi.fn();
+ const dispatch = vi.fn(async () => undefined) as any;
+
+ await runFallbackLoop(hooksSkeleton({
+ route: () => fakeRoute({ modelId: 'mistral-small-2503' }),
+ dispatch,
+ onFatal,
+ onExhausted,
+ }));
+
+ expect(dispatch).toHaveBeenCalledTimes(1); // no re-dispatch of the buggy adapter
+ expect(onFatal).toHaveBeenCalledTimes(1); // immediate 502 render
+ expect(onExhausted).not.toHaveBeenCalled(); // never loops to exhaustion
+ expect(onFatal.mock.calls[0][1].message).toContain('dispatch contract violation');
+ consoleError.mockRestore();
+ });
+});
diff --git a/server/src/__tests__/routes/fallback-hardening.test.ts b/server/src/__tests__/routes/fallback-hardening.test.ts
new file mode 100644
index 00000000..112fcf7a
--- /dev/null
+++ b/server/src/__tests__/routes/fallback-hardening.test.ts
@@ -0,0 +1,244 @@
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import type { Express } from 'express';
+
+// Route-level characterization tests for the fallback hardening pack:
+// item 3 — a daily-allocation 429 (Cloudflare "used up your daily free
+// allocation") benches until the next UTC midnight, not 90s;
+// item 4 — an empty completion with finish_reason 'length' (reasoning model
+// spent the whole output budget on hidden reasoning) fails over
+// WITHOUT a cooldown or model penalty;
+// item 5 — the wall-clock retry budget stops new attempts and returns the
+// rich exhaustion error;
+// item 6 — a provider response without a `usage` block no longer logs 0
+// tokens (chars/4 estimation, matching the streaming path).
+
+const chatCompletion = vi.fn();
+const streamChatCompletion = vi.fn();
+const fakeProvider = { name: 'fake', chatCompletion, streamChatCompletion } as any;
+
+vi.mock('../../providers/index.js', async (importOriginal) => {
+ const actual = await importOriginal() as any;
+ return {
+ ...actual,
+ getProvider: () => fakeProvider,
+ resolveProvider: () => fakeProvider,
+ };
+});
+
+const { createApp } = await import('../../app.js');
+const { initDb, getDb, getUnifiedApiKey } = await import('../../db/index.js');
+const { encrypt } = await import('../../lib/crypto.js');
+const { setRoutingStrategy, getAllPenalties } = await import('../../services/router.js');
+const { msUntilNextUtcMidnight } = await import('../../lib/fallback-loop.js');
+
+async function post(app: Express, path: string, body: any, key: string) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ });
+ const raw = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(raw); } catch { /* SSE */ }
+ return { status: res.status, body: json, raw, headers: res.headers };
+}
+
+const GOOD_RESULT = {
+ choices: [{ message: { role: 'assistant', content: 'a real answer' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 },
+};
+// Provider omits `usage` entirely (several free tiers do on some endpoints).
+const NO_USAGE_RESULT = {
+ choices: [{ message: { role: 'assistant', content: 'an answer without a usage block' }, finish_reason: 'stop' }],
+};
+const emptyWithFinish = (finish: string) => ({
+ choices: [{ message: { role: 'assistant', content: '' }, finish_reason: finish }],
+ usage: { prompt_tokens: 10, completion_tokens: 0, total_tokens: 10 },
+});
+
+function firstCalledModelDbId(): number {
+ const modelId = chatCompletion.mock.calls[0][2] as string;
+ const row = getDb().prepare("SELECT id FROM models WHERE platform = 'groq' AND model_id = ?").get(modelId) as { id: number };
+ return row.id;
+}
+
+function cooldownRowFor(modelId: string) {
+ return getDb().prepare(
+ "SELECT expires_at_ms FROM rate_limit_cooldowns WHERE platform = 'groq' AND model_id = ?",
+ ).get(modelId) as { expires_at_ms: number } | undefined;
+}
+
+describe('fallback hardening (items 3, 4, 5, 6)', () => {
+ let app: Express;
+ let key: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+
+ const db = getDb();
+ setRoutingStrategy('priority');
+ const { encrypted, iv, authTag } = encrypt('hardening-test-key');
+ db.prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES ('groq', 'hardening', ?, ?, ?, 'healthy', 1)
+ `).run(encrypted, iv, authTag);
+ });
+
+ beforeEach(() => {
+ chatCompletion.mockReset();
+ streamChatCompletion.mockReset();
+ const db = getDb();
+ db.prepare('DELETE FROM rate_limit_cooldowns').run();
+ db.prepare('DELETE FROM rate_limit_usage').run();
+ db.prepare('DELETE FROM requests').run();
+ });
+
+ afterEach(() => {
+ delete process.env.FALLBACK_TIME_BUDGET_MS;
+ });
+
+ it('item 3: a daily-allocation 429 benches until the next UTC midnight, not 90s', async () => {
+ chatCompletion
+ .mockRejectedValueOnce(Object.assign(
+ new Error('Cloudflare API error 429: you have used up your daily free allocation of 10,000 neurons'),
+ { status: 429 },
+ ))
+ .mockResolvedValueOnce(GOOD_RESULT);
+
+ const before = Date.now();
+ const { status } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'daily allocation bench test' }],
+ }, key);
+
+ expect(status).toBe(200); // failed over
+ const firstModel = chatCompletion.mock.calls[0][2] as string;
+ const row = cooldownRowFor(firstModel);
+ expect(row).toBeDefined();
+ // Benched to (roughly) the next UTC midnight, far beyond the 90s transient.
+ const expected = before + msUntilNextUtcMidnight(before);
+ expect(Math.abs(row!.expires_at_ms - expected)).toBeLessThan(10_000);
+ });
+
+ it('item 4: empty completion with finish_reason length fails over without cooldown or penalty', async () => {
+ chatCompletion
+ .mockResolvedValueOnce(emptyWithFinish('length')) // hidden-reasoning truncation
+ .mockResolvedValueOnce(GOOD_RESULT);
+
+ const { status, body } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'reasoning truncation policy test' }],
+ }, key);
+
+ expect(status).toBe(200);
+ expect(body.choices[0].message.content).toBe('a real answer');
+ expect(chatCompletion).toHaveBeenCalledTimes(2); // still failed over
+ const firstModel = chatCompletion.mock.calls[0][2] as string;
+ // The truncated turn is NOT a provider-health signal: no bench, no penalty.
+ expect(cooldownRowFor(firstModel)).toBeUndefined();
+ expect(getAllPenalties().some(p => p.modelDbId === firstCalledModelDbId())).toBe(false);
+ });
+
+ it('item 4 control: an empty completion with finish_reason stop still benches as before', async () => {
+ chatCompletion
+ .mockResolvedValueOnce(emptyWithFinish('stop'))
+ .mockResolvedValueOnce(GOOD_RESULT);
+
+ const { status } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'empty stop control test' }],
+ }, key);
+
+ expect(status).toBe(200);
+ const firstModel = chatCompletion.mock.calls[0][2] as string;
+ expect(cooldownRowFor(firstModel)).toBeDefined(); // genuine dead turn: benched
+ });
+
+ it('item 4 (stream): a zero-text stream ending in finish_reason length skips the bench', async () => {
+ async function* lengthTruncatedStream() {
+ yield { id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] };
+ yield { id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: {}, finish_reason: 'length' }] };
+ }
+ async function* goodStream() {
+ yield { id: 'c2', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: { content: 'streamed answer' }, finish_reason: null }] };
+ yield { id: 'c2', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] };
+ }
+ streamChatCompletion
+ .mockReturnValueOnce(lengthTruncatedStream())
+ .mockReturnValueOnce(goodStream());
+
+ const { status, raw } = await post(app, '/v1/chat/completions', {
+ stream: true, messages: [{ role: 'user', content: 'stream truncation policy test' }],
+ }, key);
+
+ expect(status).toBe(200);
+ expect(raw).toContain('streamed answer');
+ expect(streamChatCompletion).toHaveBeenCalledTimes(2);
+ const firstModel = streamChatCompletion.mock.calls[0][2] as string;
+ expect(cooldownRowFor(firstModel)).toBeUndefined();
+ });
+
+ it('item 5: the wall-clock budget stops retries and returns the rich exhaustion error', async () => {
+ process.env.FALLBACK_TIME_BUDGET_MS = '1';
+ chatCompletion.mockImplementation(async () => {
+ await new Promise(r => setTimeout(r, 15)); // ensure the budget is spent after attempt 0
+ throw Object.assign(new Error('Groq API error 429: rate limit'), { status: 429 });
+ });
+
+ const { status, body, headers } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'time budget test' }],
+ }, key);
+
+ expect(status).toBe(429);
+ expect(chatCompletion).toHaveBeenCalledTimes(1); // the first attempt always runs; no second start
+ expect(body.error.message).toContain('retry time budget');
+ expect(body.error.message).toContain('Attempt trail:');
+ expect(headers.get('x-fallback-attempts')).toBe('1');
+ });
+
+ it('item 6: /v1/chat/completions logs estimated tokens when the provider omits usage', async () => {
+ chatCompletion.mockResolvedValueOnce(NO_USAGE_RESULT);
+
+ const { status } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'usage fallback test with a reasonably long prompt' }],
+ }, key);
+
+ expect(status).toBe(200);
+ const row = getDb().prepare("SELECT input_tokens, output_tokens FROM requests WHERE status = 'success' ORDER BY id DESC LIMIT 1")
+ .get() as { input_tokens: number; output_tokens: number };
+ expect(row.input_tokens).toBeGreaterThan(0); // was 0 pre-fix
+ expect(row.output_tokens).toBeGreaterThan(0); // was 0 pre-fix
+ // The rate-limit token ledger is fed too (was recordTokens(…, 0)).
+ const usage = getDb().prepare("SELECT COALESCE(SUM(tokens), 0) AS t FROM rate_limit_usage WHERE kind = 'tokens'").get() as { t: number };
+ expect(usage.t).toBeGreaterThan(0);
+ });
+
+ it('item 6: legacy /v1/completions logs estimated tokens when usage is missing', async () => {
+ chatCompletion.mockResolvedValueOnce(NO_USAGE_RESULT);
+
+ const { status } = await post(app, '/v1/completions', {
+ prompt: 'legacy usage fallback test prompt',
+ }, key);
+
+ expect(status).toBe(200);
+ const row = getDb().prepare("SELECT input_tokens, output_tokens FROM requests WHERE status = 'success' ORDER BY id DESC LIMIT 1")
+ .get() as { input_tokens: number; output_tokens: number };
+ expect(row.input_tokens).toBeGreaterThan(0);
+ expect(row.output_tokens).toBeGreaterThan(0);
+ });
+
+ it('item 6: /v1/responses feeds the rate-limit token ledger when usage is missing', async () => {
+ chatCompletion.mockResolvedValueOnce(NO_USAGE_RESULT);
+
+ const { status } = await post(app, '/v1/responses', {
+ input: 'responses usage fallback test',
+ }, key);
+
+ expect(status).toBe(200);
+ const usage = getDb().prepare("SELECT COALESCE(SUM(tokens), 0) AS t FROM rate_limit_usage WHERE kind = 'tokens'").get() as { t: number };
+ expect(usage.t).toBeGreaterThan(0); // was recordTokens(…, usage?.total_tokens ?? 0)
+ });
+});
diff --git a/server/src/__tests__/routes/proxy-auth-rotation.test.ts b/server/src/__tests__/routes/proxy-auth-rotation.test.ts
new file mode 100644
index 00000000..a3900dd7
--- /dev/null
+++ b/server/src/__tests__/routes/proxy-auth-rotation.test.ts
@@ -0,0 +1,238 @@
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+import type { Express } from 'express';
+
+// Item 1 of the fallback hardening: an upstream 401 (invalid provider key) is
+// KEY-fatal, not request-fatal. Live-verified bug: it returned a 502
+// immediately, never rotating to the provider's healthy sibling key, and the
+// bad key stayed in rotation failing ~50% of traffic until the 5-minute health
+// cycle. Now the loop rotates past the key, benches it, and fires an immediate
+// targeted revalidation; an all-auth exhaustion is reported distinctly from a
+// rate-limit exhaustion (item 2: with the attempt trail + X-Fallback-Attempts).
+
+const chatCompletion = vi.fn();
+const streamChatCompletion = vi.fn();
+const fakeProvider = { name: 'fake', chatCompletion, streamChatCompletion } as any;
+
+vi.mock('../../providers/index.js', async (importOriginal) => {
+ const actual = await importOriginal() as any;
+ return {
+ ...actual,
+ getProvider: () => fakeProvider,
+ resolveProvider: () => fakeProvider,
+ };
+});
+
+const { mockCheckKeyHealth } = vi.hoisted(() => ({ mockCheckKeyHealth: vi.fn() }));
+vi.mock('../../services/health.js', () => ({ checkKeyHealth: mockCheckKeyHealth }));
+
+const { createApp } = await import('../../app.js');
+const { initDb, getDb, getUnifiedApiKey } = await import('../../db/index.js');
+const { encrypt } = await import('../../lib/crypto.js');
+const { setRoutingStrategy, getAllPenalties } = await import('../../services/router.js');
+
+async function post(app: Express, path: string, body: any, key: string, extraHeaders: Record<string, string> = {}) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}`, ...extraHeaders },
+ body: JSON.stringify(body),
+ });
+ const raw = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(raw); } catch { /* SSE */ }
+ return { status: res.status, body: json, headers: res.headers };
+}
+
+const GOOD_RESULT = {
+ choices: [{ message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 },
+};
+const err401 = () => Object.assign(new Error('Groq API error 401: Invalid API Key'), { status: 401 });
+const err429 = () => Object.assign(new Error('Groq API error 429: rate limit'), { status: 429 });
+
+interface Setup { modelDbId: number; modelId: string; keyA: number; keyB: number }
+
+// Distinct groq model per test so module-global rate-limit state (cooldowns,
+// round-robin, penalties — keyed by model) can't leak between tests.
+function setup(rank: number): Setup {
+ const db = getDb();
+ setRoutingStrategy('priority');
+ db.prepare("DELETE FROM settings WHERE key = 'active_profile_id'").run();
+ db.prepare('DELETE FROM api_keys').run();
+ db.prepare('DELETE FROM rate_limit_cooldowns').run();
+ db.prepare('DELETE FROM rate_limit_usage').run();
+
+ const models = db.prepare("SELECT id, model_id FROM models WHERE platform = 'groq' ORDER BY id").all() as { id: number; model_id: string }[];
+ const model = models[rank];
+ db.prepare('UPDATE models SET enabled = 0').run();
+ db.prepare('UPDATE models SET enabled = 1, rpm_limit = NULL, rpd_limit = NULL, tpm_limit = NULL, tpd_limit = NULL WHERE id = ?').run(model.id);
+
+ const ids: number[] = [];
+ for (const label of ['a', 'b']) {
+ const { encrypted, iv, authTag } = encrypt(`groq-auth-${rank}-${label}`);
+ const info = db.prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES ('groq', ?, ?, ?, ?, 'healthy', 1)
+ `).run(`auth-${rank}-${label}`, encrypted, iv, authTag);
+ ids.push(Number(info.lastInsertRowid));
+ }
+ return { modelDbId: model.id, modelId: model.model_id, keyA: ids[0], keyB: ids[1] };
+}
+
+describe('upstream 401 rotates to the sibling key instead of 502 (item 1)', () => {
+ let app: Express;
+ let key: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+ });
+
+ beforeEach(() => {
+ chatCompletion.mockReset();
+ streamChatCompletion.mockReset();
+ mockCheckKeyHealth.mockReset();
+ mockCheckKeyHealth.mockResolvedValue('invalid');
+ });
+
+ it('fails over to the healthy sibling key and revalidates the bad one', async () => {
+ const s = setup(0);
+ chatCompletion
+ .mockRejectedValueOnce(err401()) // first key: invalid
+ .mockResolvedValueOnce(GOOD_RESULT); // sibling key: healthy
+
+ const { status, body, headers } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'auth rotation test' }],
+ }, key);
+
+ expect(status).toBe(200); // previously an immediate 502 with the sibling key stranded
+ expect(body.choices[0].message.content).toBe('ok');
+ expect(headers.get('x-fallback-attempts')).toBe('1');
+ expect(chatCompletion).toHaveBeenCalledTimes(2);
+ // Immediate targeted revalidation fired for the failing key (one of the two).
+ expect(mockCheckKeyHealth).toHaveBeenCalledTimes(1);
+ expect([s.keyA, s.keyB]).toContain(mockCheckKeyHealth.mock.calls[0][0]);
+ // A key problem is not a model problem: no model-level penalty.
+ expect(getAllPenalties().some(p => p.modelDbId === s.modelDbId)).toBe(false);
+ // The bad key is benched (roughly the health-cycle window) so it leaves
+ // rotation even before the revalidation lands.
+ const benched = getDb().prepare(
+ 'SELECT expires_at_ms FROM rate_limit_cooldowns WHERE platform = ? AND model_id = ? AND key_id = ?',
+ ).get('groq', s.modelId, mockCheckKeyHealth.mock.calls[0][0]) as { expires_at_ms: number };
+ expect(benched.expires_at_ms - Date.now()).toBeGreaterThan(3 * 60 * 1000);
+ });
+
+ it('all-auth exhaustion returns a distinct 502 with the attempt trail (items 1+2)', async () => {
+ setup(1);
+ chatCompletion.mockRejectedValue(err401()); // both keys invalid
+
+ const { status, body, headers } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'all keys invalid test' }],
+ }, key);
+
+ expect(status).toBe(502); // NOT a misleading 429 rate-limit exhaustion
+ expect(body.error.type).toBe('provider_error');
+ expect(body.error.message).toContain('failed authentication');
+ expect(body.error.message).toContain('Attempt trail:');
+ expect(body.error.message).toContain('auth');
+ expect(headers.get('x-fallback-attempts')).toBe('2');
+ expect(chatCompletion).toHaveBeenCalledTimes(2);
+ });
+
+ it('anthropic surface: all-auth exhaustion is Anthropic-shaped (api_error)', async () => {
+ setup(2);
+ chatCompletion.mockRejectedValue(err401());
+
+ const { status, body, headers } = await post(app, '/v1/messages', {
+ model: 'claude-sonnet-4-5', max_tokens: 32,
+ messages: [{ role: 'user', content: 'anthropic auth exhaustion test' }],
+ }, key, { 'anthropic-version': '2023-06-01' });
+
+ expect(status).toBe(502);
+ expect(body.type).toBe('error');
+ expect(body.error.type).toBe('api_error'); // 'provider_error' remapped for the Anthropic wire
+ expect(body.error.message).toContain('failed authentication');
+ expect(headers.get('x-fallback-attempts')).toBe('2');
+ });
+
+ it('Google-style 400 bad key rotates + revalidates and never blames the client request (#268)', async () => {
+ // Google reports a dead/expired key as HTTP 400 "API key not valid", NOT a
+ // 401. Before the fix that classified as a provider bad-request, so an
+ // exhaustion could surface to the client as 400 "All routed providers
+ // rejected the request as invalid" — blaming the request for a bad key.
+ const googleBadKey = () => Object.assign(
+ new Error('Google API error 400: API key not valid. Please pass a valid API key.'),
+ { status: 400 },
+ );
+ setup(4);
+ chatCompletion
+ .mockRejectedValueOnce(googleBadKey()) // first key: dead Google-style key
+ .mockResolvedValueOnce(GOOD_RESULT); // sibling key: healthy
+
+ const first = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'google bad key rotation test' }],
+ }, key);
+
+ expect(first.status).toBe(200); // rotated, not a client-blaming 400
+ expect(first.headers.get('x-fallback-attempts')).toBe('1');
+ expect(chatCompletion).toHaveBeenCalledTimes(2);
+ expect(mockCheckKeyHealth).toHaveBeenCalledTimes(1); // immediate revalidation fired
+
+ // Now the surviving key dies the same way: exhaustion must be the distinct
+ // auth 502, never the invalid-request 400.
+ chatCompletion.mockRejectedValue(googleBadKey());
+ const second = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'google bad key exhaustion test' }],
+ }, key);
+
+ expect(second.status).toBe(502);
+ expect(second.status).not.toBe(400);
+ expect(second.body.error.type).toBe('provider_error');
+ expect(second.body.error.message).toContain('failed authentication');
+ expect(second.body.error.message).not.toContain('rejected the request as invalid');
+ });
+});
+
+describe('exhaustion error quality: attempt trail + reset hint + header (item 2)', () => {
+ let app: Express;
+ let key: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+ });
+
+ beforeEach(() => {
+ chatCompletion.mockReset();
+ streamChatCompletion.mockReset();
+ mockCheckKeyHealth.mockReset();
+ mockCheckKeyHealth.mockResolvedValue('healthy');
+ });
+
+ it('a rate-limit exhaustion body names each attempt and the soonest reset', async () => {
+ const s = setup(3);
+ chatCompletion.mockRejectedValue(err429()); // both keys rate-limited
+
+ const { status, body, headers } = await post(app, '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'trail quality test' }],
+ }, key);
+
+ expect(status).toBe(429);
+ expect(body.error.type).toBe('rate_limit_error');
+ // Previously: terse "All models rate-limited after N attempts. Last error: X".
+ expect(body.error.message).toContain('after 2 attempts');
+ expect(body.error.message).toContain('Attempt trail:');
+ expect(body.error.message).toContain(`groq/${s.modelId} key1: rate_limited`);
+ expect(body.error.message).toContain(`groq/${s.modelId} key2: rate_limited`);
+ // The cooldowns just recorded make a soonest-reset hint available.
+ expect(body.error.message).toContain('Soonest cooldown reset');
+ // X-Fallback-Attempts now stamps ERROR responses too (was success-only).
+ expect(headers.get('x-fallback-attempts')).toBe('2');
+ });
+});
diff --git a/server/src/lib/error-classify.ts b/server/src/lib/error-classify.ts
index 9e0cad3b..83f48f43 100644
--- a/server/src/lib/error-classify.ts
+++ b/server/src/lib/error-classify.ts
@@ -68,6 +68,55 @@ export function isRetryableError(err: any): boolean {
|| msg.includes('unparseable inline tool-call dialect');
}
+// A 401 / invalid-API-key error from a provider. KEY-fatal, not request-fatal:
+// the same request is fine on the provider's sibling key or on another provider,
+// so the fallback loop rotates past the bad key (and triggers an immediate
+// health revalidation) instead of 502-ing the whole request. Deliberately NOT
+// added to isRetryableError: a bad key must be skipped and revalidated, not
+// blindly re-benched like a rate limit — the loop handles it as its own class.
+//
+// Status handling: every provider adapter attaches err.status (providerHttpError
+// in providers/base.ts), so the structured status is the primary signal.
+// - 401 → always key-auth.
+// - 400 → key-auth ONLY for Google-style key-specific phrasings: Google
+// reports a bad/expired key as HTTP 400 INVALID_ARGUMENT with "API key not
+// valid" / "API key expired" / API_KEY_INVALID (#268, providers/google.ts).
+// Without this a dead Google key classified as a provider bad-request and
+// could exhaust into a client-blaming 400 "rejected the request as invalid".
+// Generic auth wording (unauthorized etc.) stays excluded on a 400 so
+// ordinary payload rejections never classify as key-auth.
+// - any other status → not key-auth (e.g. a 403 stays model-forbidden).
+// - no status at all → key-specific OR generic auth substrings.
+export function isKeyAuthError(err: any): boolean {
+ const status = typeof err?.status === 'number' ? err.status : 0;
+ if (status === 401) return true;
+ const msg = (err?.message ?? '').toLowerCase();
+ const keySpecific = msg.includes('api key not valid')
+ || msg.includes('api key expired')
+ || msg.includes('api_key_invalid');
+ if (status === 400) return keySpecific;
+ if (status !== 0) return false;
+ return keySpecific
+ || msg.includes('401')
+ || msg.includes('unauthorized')
+ || msg.includes('invalid api key')
+ || msg.includes('invalid_api_key')
+ || msg.includes('incorrect api key')
+ || msg.includes('authentication failed');
+}
+
+// A 429 whose body says the provider's DAILY free allocation is spent (observed
+// live: Cloudflare "you have used up your daily free allocation of 10,000
+// neurons"; OpenRouter "free-models-per-day"). A transient 90s cooldown just
+// makes the router re-pick a dead-for-the-day provider all day, so the caller
+// benches until the next UTC midnight instead. Requires BOTH a daily marker and
+// a quota/allocation marker so an ordinary per-minute 429 never matches.
+export function isDailyQuotaExhaustedError(err: any): boolean {
+ const msg = (err?.message ?? '').toLowerCase();
+ if (!/daily|per[ -_]?day|\btoday\b/.test(msg)) return false;
+ return /allocation|quota|limit|exhaust|used up/.test(msg);
+}
+
// Provider-side 400s are retryable because another provider may accept the same
// request shape. If every routed provider rejects it, however, the client should
// see an invalid-request error rather than a misleading rate-limit exhaustion.
diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.ts
index b5bc0c9b..4fa1d0e4 100644
--- a/server/src/lib/fallback-loop.ts
+++ b/server/src/lib/fallback-loop.ts
@@ -10,36 +10,72 @@
// selection, per-key failure bookkeeping, exhaustion status — while each
// surface keeps its own request/stream translation as a thin `dispatch` adapter.
//
-// Pure control-flow + accounting: no Express, no wire-format knowledge. The
-// per-surface bytes (SSE framing, error-body shape, context handoff, group
-// routing) live in the caller's hooks, so this stays reviewable as unification.
+// Almost pure control-flow + accounting: no Express, no wire-format knowledge.
+// The per-surface bytes (SSE framing, error-body shape, context handoff, group
+// routing) live in the caller's hooks. The one side effect beyond bookkeeping is
+// the fire-and-forget key revalidation kicked off on an upstream 401 (below).
import type { RouteResult } from '../services/router.js';
-import { recordRateLimitHit, recordSuccess, hasOtherUsableKey } from '../services/router.js';
+import { recordRateLimitHit, recordSuccess, hasOtherUsableKey, formatResetEta } from '../services/router.js';
import {
recordRequest,
recordTokens,
setCooldown,
getCooldownDurationForLimit,
+ getSoonestCooldownExpiry,
PAYMENT_REQUIRED_COOLDOWN_MS,
MODEL_FORBIDDEN_COOLDOWN_MS,
learnLimitFromError,
} from '../services/ratelimit.js';
import {
isRetryableError,
+ isKeyAuthError,
+ isDailyQuotaExhaustedError,
isPaymentRequiredError,
isModelNotFoundError,
isModelAccessForbiddenError,
isProviderBadRequestError,
} from './error-classify.js';
import { sanitizeProviderErrorMessage } from './error-redaction.js';
+import { checkKeyHealth } from '../services/health.js';
+import { getSetting } from '../db/index.js';
// Every surface caps failover hops at the same number.
export const FALLBACK_MAX_RETRIES = 20;
+// ── Wall-clock retry budget ──────────────────────────────────────────────────
+// Serial failover has no time bound of its own: the observed worst case was a
+// 38.8s TTFB over 11 attempts, and the theoretical worst is maxRetries x the
+// per-attempt HTTP timeout. The budget is checked before STARTING each retry
+// (the first attempt always runs), so one slow attempt is never aborted
+// mid-flight — it just becomes the last one. 0 disables the budget entirely.
+// Precedence mirrors the response cache: the settings-table value wins when
+// present (runtime-tunable), then the env var, then the default.
+// TODO(fallback-v2): AbortController hedging so a stalled attempt can be
+// abandoned mid-flight instead of only refusing to start the next one.
+export const DEFAULT_FALLBACK_TIME_BUDGET_MS = 45_000;
+export const FALLBACK_TIME_BUDGET_SETTING = 'fallback_time_budget_ms';
+
+export function getFallbackTimeBudgetMs(): number {
+ let stored: string | undefined;
+ try {
+ stored = getSetting(FALLBACK_TIME_BUDGET_SETTING);
+ } catch {
+ stored = undefined; // DB not ready — never throw on the proxy hot path
+ }
+ const candidates = [stored, process.env.FALLBACK_TIME_BUDGET_MS];
+ for (const raw of candidates) {
+ if (raw === undefined || raw.trim() === '') continue;
+ const n = Number(raw);
+ if (Number.isFinite(n) && n >= 0) return n;
+ }
+ return DEFAULT_FALLBACK_TIME_BUDGET_MS;
+}
+
// Mutable per-request skip state threaded through the loop and mutated by
-// recordRetryableFailure. skipKeys entries are "platform:modelId:keyId";
-// skipModels holds model_db_ids ruled out for the rest of this request.
+// recordRetryableFailure / recordAuthFailure. skipKeys entries are
+// "platform:modelId:keyId"; skipModels holds model_db_ids ruled out for the
+// rest of this request.
export interface FallbackState {
skipKeys: Set<string>;
skipModels: Set<number>;
@@ -49,21 +85,34 @@ export function newFallbackState(): FallbackState {
return { skipKeys: new Set<string>(), skipModels: new Set<number>() };
}
+// Milliseconds until the next UTC midnight — when most providers' daily free
+// allocations reset. Floored at one minute so a hit seconds before midnight
+// still records a real bench instead of a no-op.
+export function msUntilNextUtcMidnight(now = Date.now()): number {
+ const d = new Date(now);
+ const next = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1);
+ return Math.max(next - now, 60_000);
+}
+
/**
* The one true cooldown-duration selection after a retryable upstream failure:
* - 402 out-of-credits → a full day (PAYMENT_REQUIRED_COOLDOWN_MS)
* - 403 model-not-on-tier → a full day (MODEL_FORBIDDEN_COOLDOWN_MS), because a
* tier/subscription gate won't clear on the next minute window (issue #256)
+ * - a 429 that says the DAILY free allocation is spent (Cloudflare "used up
+ * your daily free allocation of 10,000 neurons") → benched until the next
+ * UTC midnight, like the 402 path. The old transient 90s cooldown made the
+ * router re-pick a dead-for-the-day provider all day long. An explicit
+ * provider Retry-After wins over the midnight heuristic: rolling daily
+ * windows (Groq RPD "try again in 7m12s" with a Retry-After header) reset
+ * well before midnight, and the provider knows its own reset time best.
* - anything else → the transient/daily escalation ladder, honoring the
* provider's Retry-After as a floor (getCooldownDurationForLimit).
- *
- * Convergence: /v1/responses previously skipped BOTH the 403 day-bench (it fell
- * through to the 90s transient) AND the Retry-After floor. Now every surface
- * benches identically.
*/
export function cooldownForError(route: RouteResult, err: any): number {
if (isPaymentRequiredError(err)) return PAYMENT_REQUIRED_COOLDOWN_MS;
if (isModelAccessForbiddenError(err)) return MODEL_FORBIDDEN_COOLDOWN_MS;
+ if (isDailyQuotaExhaustedError(err)) return err?.retryAfterMs ?? msUntilNextUtcMidnight();
return getCooldownDurationForLimit(
route.platform,
route.modelId,
@@ -87,6 +136,13 @@ export function cooldownForError(route: RouteResult, err: any): number {
* - learn a provider-reported ceiling (e.g. a Groq 413 "TPM: Limit 30000")
* from the error body so the next pre-check fails over before the 413.
*
+ * Reasoning-truncation exemption: an error thrown with `skipBench: true` (a
+ * reasoning model that spent the whole max_tokens budget on hidden reasoning,
+ * finish_reason 'length') still fails over — the key is skipped for THIS
+ * request — but is NOT a provider-health signal, so no cooldown, no model
+ * penalty, and no limit-learning are recorded. Benching those was costing
+ * healthy models a 90s cooldown + a scorer penalty per truncated turn.
+ *
* Callers add the just-failed key to skipKeys via this function (do not pre-add).
*/
export function recordRetryableFailure(route: RouteResult, err: any, state: FallbackState): void {
@@ -94,6 +150,7 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: Fall
state.skipModels.add(route.modelDbId);
}
state.skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
+ if (err?.skipBench === true) return;
setCooldown(route.platform, route.modelId, route.keyId, cooldownForError(route, err));
// Model-level penalty only when no sibling key can still serve (#454).
if (!hasOtherUsableKey(route.modelDbId, route.keyId, state.skipKeys)) {
@@ -102,6 +159,44 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: Fall
learnLimitFromError(route.modelDbId, err);
}
+// ── Upstream 401 handling (key-fatal, not request-fatal) ─────────────────────
+// A 401 means THIS key is bad, not this model or this request. The old behavior
+// (non-retryable → 502) stranded the provider's healthy sibling key and every
+// other provider in the chain, and left the bad key in rotation failing traffic
+// until the next 5-minute health cycle. Now the loop skips the key, benches the
+// model+key long enough to cover the health cycle, and kicks an immediate
+// targeted revalidation so a confirmed-bad key flips to status 'invalid' (and
+// out of routing) within seconds instead of minutes.
+export const AUTH_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
+
+// Dedupe window for the fire-and-forget revalidation: many concurrent requests
+// hitting the same bad key must not stampede the provider's validate endpoint.
+const REVALIDATION_DEDUPE_MS = 30_000;
+const lastRevalidation = new Map<number, number>();
+
+function triggerKeyRevalidation(platform: string, keyId: number): void {
+ const now = Date.now();
+ const last = lastRevalidation.get(keyId) ?? 0;
+ if (now - last < REVALIDATION_DEDUPE_MS) return;
+ lastRevalidation.set(keyId, now);
+ console.warn(`[FallbackLoop] Upstream 401 from ${platform} key ${keyId}; revalidating it now instead of waiting for the health cycle`);
+ void checkKeyHealth(keyId).catch(err => {
+ console.error(`[FallbackLoop] Immediate revalidation of key ${keyId} failed:`, err?.message);
+ });
+}
+
+/**
+ * Bookkeeping for an auth-fatal (401 / invalid key) attempt: skip the key for
+ * this request, bench the model+key for the health-cycle window, and start an
+ * immediate revalidation. Deliberately NO model penalty and NO limit-learning —
+ * a bad key says nothing about the model's health.
+ */
+export function recordAuthFailure(route: RouteResult, state: FallbackState): void {
+ state.skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
+ setCooldown(route.platform, route.modelId, route.keyId, AUTH_FAILURE_COOLDOWN_MS);
+ triggerKeyRevalidation(route.platform, route.keyId);
+}
+
/**
* The success-side accounting every surface runs after a completed attempt:
* count the request + its tokens against the model+key's rate-limit windows and
@@ -114,38 +209,126 @@ export function recordUpstreamSuccess(route: RouteResult, rateLimitTokens: numbe
recordSuccess(route.modelDbId);
}
+// ── Attempt trail ─────────────────────────────────────────────────────────────
+// One record per dispatched-and-failed attempt, so the final exhaustion error
+// can show the client WHAT was tried instead of only the last error. Key ids
+// are internal DB integers; the trail shows a per-request ordinal (key1, key2…)
+// instead, which is stable, readable, and leaks nothing.
+
+export type AttemptErrorClass =
+ | 'auth'
+ | 'out_of_credits'
+ | 'daily_quota_exhausted'
+ | 'model_not_found'
+ | 'forbidden'
+ | 'provider_bad_request'
+ | 'empty_completion'
+ | 'timeout'
+ | 'rate_limited'
+ | 'upstream_error'
+ | 'error';
+
+export interface AttemptRecord {
+ platform: string;
+ modelId: string;
+ keyOrdinal: number;
+ errorClass: AttemptErrorClass;
+}
+
+export function classifyAttemptError(err: any): AttemptErrorClass {
+ if (isKeyAuthError(err)) return 'auth';
+ if (isPaymentRequiredError(err)) return 'out_of_credits';
+ if (isDailyQuotaExhaustedError(err)) return 'daily_quota_exhausted';
+ if (isModelNotFoundError(err)) return 'model_not_found';
+ if (isModelAccessForbiddenError(err)) return 'forbidden';
+ if (isProviderBadRequestError(err)) return 'provider_bad_request';
+ const msg = (err?.message ?? '').toLowerCase();
+ if (msg.includes('empty completion')) return 'empty_completion';
+ if (msg.includes('timeout') || msg.includes('stalled') || msg.includes('etimedout') || msg.includes('aborted')) return 'timeout';
+ if (msg.includes('429') || msg.includes('rate limit') || msg.includes('too many requests') || msg.includes('quota')) return 'rate_limited';
+ const status = typeof err?.status === 'number' ? err.status : 0;
+ if (status >= 500 || msg.includes('500') || msg.includes('502') || msg.includes('503') || msg.includes('unavailable') || msg.includes('internal server error')) return 'upstream_error';
+ return 'error';
+}
+
+const TRAIL_MAX_SHOWN = 10;
+
+export function formatAttemptTrail(attempts: AttemptRecord[]): string {
+ const shown = attempts
+ .slice(0, TRAIL_MAX_SHOWN)
+ .map(a => `${a.platform}/${a.modelId} key${a.keyOrdinal}: ${a.errorClass}`);
+ const extra = attempts.length - shown.length;
+ return shown.join('; ') + (extra > 0 ? `; +${extra} more` : '');
+}
+
export interface ExhaustionBody {
status: number;
type: string;
message: string;
+ // Coarse class of the exhaustion, for surfaces that need to remap `type` to
+ // their own wire vocabulary (the Anthropic route maps 'auth' → 'api_error').
+ kind: 'auth' | 'bad_request' | 'rate_limit';
+}
+
+export interface ExhaustionContext {
+ attempts?: AttemptRecord[];
+ // True when the wall-clock retry budget stopped the loop before maxRetries.
+ timedOut?: boolean;
+ budgetMs?: number;
}
/**
- * The shared exhaustion response body. A request every routed provider rejected
- * as invalid (isProviderBadRequestError) is a client error → 400
- * invalid_request_error, not a misleading rate-limit exhaustion; otherwise 429
- * rate_limit_error. The two `type` strings are valid error types on the OpenAI,
- * Responses AND Anthropic surfaces, so all four call sites render this directly.
- *
- * Convergence: /v1/messages used to hand-roll a fixed 429 here, losing the 400
- * branch. (Moved out of routes/proxy.ts, which re-exports it for compatibility.)
+ * The shared exhaustion response body.
+ * - Every attempt failed auth (401/invalid key) → 502 provider_error saying the
+ * PROVIDER keys are bad — distinct from a rate-limit exhaustion, and never
+ * 'authentication_error' (which would wrongly blame the CLIENT's key).
+ * - A request every routed provider rejected as invalid → 400
+ * invalid_request_error, not a misleading rate-limit exhaustion.
+ * - Otherwise → 429 rate_limit_error.
+ * All bodies carry the attempt trail (what was tried, per attempt) and the
+ * soonest-cooldown-reset hint that previously only reached clients when routing
+ * failed before any attempt (summarizeExhaustion) — after one attempt they got a
+ * terse "Last error" line with none of that context.
*/
-export function exhaustedRetryError(lastError: any, maxRetries?: number): ExhaustionBody {
+export function exhaustedRetryError(lastError: any, maxRetries?: number, ctx?: ExhaustionContext): ExhaustionBody {
const safeLastError = sanitizeProviderErrorMessage(lastError?.message);
+ const attempts = ctx?.attempts ?? [];
+ const trail = attempts.length > 0 ? ` Attempt trail: ${formatAttemptTrail(attempts)}.` : '';
+ const budgetNote = ctx?.timedOut
+ ? ` (stopped early: retry time budget ${Math.round((ctx.budgetMs ?? 0) / 1000)}s exceeded)`
+ : '';
+
+ if (attempts.length > 0 && attempts.every(a => a.errorClass === 'auth')) {
+ return {
+ kind: 'auth',
+ status: 502,
+ type: 'provider_error',
+ message: `All ${attempts.length} attempted provider key(s) failed authentication${budgetNote}. ` +
+ 'The configured upstream API key(s) look invalid or expired; they are being revalidated now and will be marked invalid automatically. ' +
+ `Check the provider keys in the dashboard.${trail} Last error: ${safeLastError}`,
+ };
+ }
+
if (isProviderBadRequestError(lastError)) {
return {
+ kind: 'bad_request',
status: 400,
type: 'invalid_request_error',
- message: `All routed providers rejected the request as invalid. Last error: ${safeLastError}`,
+ message: `All routed providers rejected the request as invalid${budgetNote}.${trail} Last error: ${safeLastError}`,
};
}
- const scope = maxRetries == null
+
+ const attemptCount = attempts.length > 0 ? attempts.length : maxRetries;
+ const scope = attemptCount == null
? 'All models rate-limited'
- : `All models rate-limited after ${maxRetries} attempts`;
+ : `All models rate-limited after ${attemptCount} attempt${attemptCount === 1 ? '' : 's'}`;
+ const eta = formatResetEta(getSoonestCooldownExpiry());
+ const etaNote = eta ? ` Soonest cooldown reset ${eta}.` : '';
return {
+ kind: 'rate_limit',
status: 429,
type: 'rate_limit_error',
- message: `${scope}. Last error: ${safeLastError}`,
+ message: `${scope}${budgetNote}.${etaNote}${trail} Last error: ${safeLastError}`,
};
}
@@ -157,11 +340,22 @@ export function exhaustedRetryError(lastError: any, maxRetries?: number): Exhaus
// possible, so stop without recording another retry.
export type DispatchOutcome = 'done' | 'committed';
+// Per-request exhaustion metadata handed to the exhaustion hooks, so each
+// surface can stamp X-Fallback-Attempts on error responses (previously
+// success-only) without re-deriving the count.
+export interface ExhaustionInfo {
+ attempts: AttemptRecord[];
+ timedOut: boolean;
+}
+
export interface FallbackHooks {
// Defaults to FALLBACK_MAX_RETRIES.
maxRetries?: number;
- // Skip state; recordRetryableFailure (called by the loop) mutates it, and the
- // surface's route() reads it to exclude failed keys/models.
+ // Wall-clock retry budget override, mostly for tests. Defaults to
+ // getFallbackTimeBudgetMs() (setting → env → 45s; 0 disables).
+ timeBudgetMs?: number;
+ // Skip state; recordRetryableFailure / recordAuthFailure (called by the loop)
+ // mutate it, and the surface's route() reads it to exclude failed keys/models.
state: FallbackState;
/**
@@ -178,61 +372,122 @@ export interface FallbackHooks {
* or an "empty completion" / "unparseable inline tool-call dialect" Error the
* classifier already treats as retryable — to trigger failover; a
* non-retryable throw becomes onFatal. A pre-commit failure MUST throw (not
- * return 'committed') so the loop can fail over invisibly.
+ * return 'committed') so the loop can fail over invisibly. The loop enforces
+ * this contract: any other return value is a programming error and fails
+ * loudly instead of silently swallowing the request.
*/
dispatch(route: RouteResult, attempt: number): Promise<DispatchOutcome>;
/** Trace + log a per-attempt failure (per-surface scope + logRequest args). */
logFailure(route: RouteResult, err: any, attempt: number): void;
- /** Render a non-retryable provider error (per-surface body/status). */
- onFatal(route: RouteResult, err: any): void;
+ /** Render a non-retryable provider error (per-surface body/status). `attempt`
+ * is the failing attempt's index = the number of prior fallback hops. */
+ onFatal(route: RouteResult, err: any, attempt: number): void;
/**
- * Render exhaustion when route() threw. `lastError` is the last upstream error
- * if any attempt ran, else null (routing gave up before trying anything).
+ * Render exhaustion when route() threw. `exhaustion` is the shared body when
+ * at least one attempt ran (render it); null when routing gave up before any
+ * upstream was tried (render routeErr as a routing error instead).
*/
- onRoutingExhausted(lastError: any, routeErr: any): void;
+ onRoutingExhausted(lastError: any, routeErr: any, exhaustion: ExhaustionBody | null, info: ExhaustionInfo): void;
- /** Render exhaustion after all attempts were tried and failed. */
- onExhausted(lastError: any): void;
+ /** Render exhaustion after the attempt cap or the time budget was hit. */
+ onExhausted(exhaustion: ExhaustionBody, info: ExhaustionInfo): void;
}
/**
- * The shared attempt loop. Owns iteration, the routeRequest-exhaustion path, the
- * retryable-vs-fatal classification, the per-failure bookkeeping
- * (recordRetryableFailure), and the final exhaustion path. Everything
- * surface-specific — request translation, stream framing, error-body shape,
- * context handoff, group routing — lives in the hooks.
+ * The shared attempt loop. Owns iteration, the wall-clock retry budget, the
+ * routeRequest-exhaustion path, the auth/retryable/fatal classification, the
+ * per-failure bookkeeping (recordRetryableFailure / recordAuthFailure), the
+ * attempt trail, and the final exhaustion body. Everything surface-specific —
+ * request translation, stream framing, error-body shape, context handoff, group
+ * routing — lives in the hooks.
*/
export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {
const maxRetries = hooks.maxRetries ?? FALLBACK_MAX_RETRIES;
+ const budgetMs = hooks.timeBudgetMs ?? getFallbackTimeBudgetMs();
+ const startedAt = Date.now();
+ const attempts: AttemptRecord[] = [];
+ const keyOrdinals = new Map<string, number>();
+ const keyOrdinal = (route: RouteResult): number => {
+ const key = `${route.platform}:${route.keyId}`;
+ let ord = keyOrdinals.get(key);
+ if (ord === undefined) {
+ ord = keyOrdinals.size + 1;
+ keyOrdinals.set(key, ord);
+ }
+ return ord;
+ };
let lastError: any = null;
for (let attempt = 0; attempt < maxRetries; attempt++) {
+ // Wall-clock budget: refuse to START another retry once spent. The first
+ // attempt always runs; a slow attempt is never aborted mid-flight (that is
+ // the TODO(fallback-v2) hedging work), it just becomes the last one.
+ if (attempt > 0 && budgetMs > 0 && Date.now() - startedAt >= budgetMs) {
+ hooks.onExhausted(
+ exhaustedRetryError(lastError, maxRetries, { attempts, timedOut: true, budgetMs }),
+ { attempts, timedOut: true },
+ );
+ return;
+ }
+
let route: RouteResult;
try {
route = hooks.route(attempt);
} catch (routeErr) {
- hooks.onRoutingExhausted(lastError, routeErr);
+ const exhaustion = lastError
+ ? exhaustedRetryError(lastError, undefined, { attempts })
+ : null;
+ hooks.onRoutingExhausted(lastError, routeErr, exhaustion, { attempts, timedOut: false });
return;
}
+ let outcome: DispatchOutcome;
try {
- // 'done' or 'committed' — either way the response is finished.
- await hooks.dispatch(route, attempt);
- return;
+ outcome = await hooks.dispatch(route, attempt);
} catch (err: any) {
hooks.logFailure(route, err, attempt);
+ if (isKeyAuthError(err)) {
+ // KEY-fatal, not request-fatal: rotate past the bad key and revalidate
+ // it immediately instead of 502-ing while healthy routes sit idle.
+ recordAuthFailure(route, hooks.state);
+ attempts.push({ platform: route.platform, modelId: route.modelId, keyOrdinal: keyOrdinal(route), errorClass: 'auth' });
+ lastError = err;
+ continue;
+ }
if (isRetryableError(err)) {
recordRetryableFailure(route, err, hooks.state);
+ attempts.push({ platform: route.platform, modelId: route.modelId, keyOrdinal: keyOrdinal(route), errorClass: classifyAttemptError(err) });
lastError = err;
continue;
}
- hooks.onFatal(route, err);
+ hooks.onFatal(route, err, attempt);
return;
}
+
+ // Enforce the dispatch contract: 'done'/'committed' mean the response is
+ // finished. Anything else (a stray `return` in an adapter) would silently
+ // swallow the request, so fail loudly. Deliberately OUTSIDE the try/catch:
+ // the violation message embeds route.modelId, and a model id containing a
+ // digit run like "2503" would match a retryable-error substring and make
+ // the loop re-dispatch the buggy adapter until exhaustion. Routing straight
+ // to onFatal renders an immediate 502 with no retryability classification.
+ if (outcome !== 'done' && outcome !== 'committed') {
+ const violation = new Error(
+ `fallback-loop dispatch contract violation on ${route.platform}/${route.modelId}: ` +
+ `expected 'done' or 'committed', got ${JSON.stringify(outcome)}`,
+ );
+ console.error('[FallbackLoop]', violation.message);
+ hooks.logFailure(route, violation, attempt);
+ hooks.onFatal(route, violation, attempt);
+ }
+ return;
}
- hooks.onExhausted(lastError);
+ hooks.onExhausted(
+ exhaustedRetryError(lastError, maxRetries, { attempts }),
+ { attempts, timedOut: false },
+ );
}
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index 68a1bda4..0c515957 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -7,7 +7,6 @@ import type {
ChatToolCall,
ChatToolDefinition,
ChatToolChoice,
- ChatContent,
ChatContentBlock,
} from '@freellmapi/shared/types.js';
import { routeRequest, routingReserveTokens, type RouteResult } from '../services/router.js';
@@ -18,7 +17,7 @@ import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarke
import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
import { logRequest } from '../lib/request-log.js';
import { extractApiToken, timingSafeStringEqual, getStickyModel, setStickyModel } from './proxy.js';
-import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, exhaustedRetryError } from '../lib/fallback-loop.js';
+import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, type ExhaustionBody } from '../lib/fallback-loop.js';
import { resolveAnthropicModel } from '../services/anthropic-map.js';
import { buildModelListing } from '../services/model-listing.js';
@@ -105,17 +104,18 @@ interface AnthropicMessageResponse {
usage: { input_tokens: number; output_tokens: number };
}
-// Carries an HTTP status + Anthropic error type through the routing loop.
-class AnthropicError extends Error {
- constructor(readonly status: number, readonly errorType: string, message: string) {
- super(message);
- }
-}
-
function sendError(res: Response, status: number, errorType: string, message: string): void {
res.status(status).json({ type: 'error', error: { type: errorType, message } });
}
+// The shared exhaustion body's `type` strings are chosen to be valid on the
+// OpenAI-shaped surfaces; the all-keys-failed-auth exhaustion carries
+// 'provider_error', which is not an Anthropic error type. Remap it onto
+// Anthropic's generic 'api_error' so this surface stays wire-correct.
+function anthropicErrorType(body: ExhaustionBody): string {
+ return body.kind === 'auth' ? 'api_error' : body.type;
+}
+
function newMessageId(): string {
return `msg_${crypto.randomBytes(12).toString('hex')}`;
}
@@ -414,9 +414,13 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
let respToolCalls = respMsg?.tool_calls ?? [];
// Empty completion → fail over via the shared loop, exactly like the
- // OpenAI route.
+ // OpenAI route; finish_reason 'length' (whole output budget spent on
+ // hidden reasoning) skips the cooldown/penalty.
if (!respText && respToolCalls.length === 0) {
- throw new Error(`empty completion from ${route.displayName}`);
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName}`),
+ result.choices?.[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
}
// Inline tool-call dialect rescue (#231): a tool-bearing request answered
@@ -478,20 +482,21 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
logFailure: (route, err) => {
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, sanitizeProviderErrorMessage(err.message), null, pinnedModelId);
},
- onFatal: (route, err) => {
+ onFatal: (route, err, attempt) => {
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
sendError(res, 502, 'api_error', `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`);
},
- onRoutingExhausted: (lastError, routeErr) => {
- if (lastError) {
- const e = exhaustedRetryError(lastError);
- sendError(res, e.status, e.type, e.message);
+ onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
+ if (exhaustion) {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ sendError(res, exhaustion.status, anthropicErrorType(exhaustion), exhaustion.message);
} else {
sendError(res, routeErr?.status ?? 503, 'api_error', routeErr?.message ?? 'No model available to route this request');
}
},
- onExhausted: (lastError) => {
- const e = exhaustedRetryError(lastError, MAX_RETRIES);
- sendError(res, e.status, e.type, e.message);
+ onExhausted: (exhaustion, info) => {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ sendError(res, exhaustion.status, anthropicErrorType(exhaustion), exhaustion.message);
},
});
});
@@ -669,7 +674,13 @@ async function streamCompletion(
// Nothing usable came out — fail over (message_start was never sent, so the
// client never saw this attempt).
if (!messageStarted && completedCalls.length === 0) {
- throw new Error(`empty completion from ${route.displayName} (stream produced no content and no tool calls)`);
+ // finish_reason 'length' = the model spent the whole output budget on
+ // hidden reasoning before any visible text: fail over, but skip the
+ // cooldown/penalty (not a provider-health signal).
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName} (stream produced no content and no tool calls)`),
+ upstreamFinish === 'length' ? { skipBench: true } : {},
+ );
}
ensureMessageStart();
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index d79bc500..ac0499ff 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -732,6 +732,7 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
let headerSent = false;
let ttfbMs: number | null = null;
let sawText = false;
+ let upstreamFinish: string | null = null;
const buffered: unknown[] = [];
const flushHeaders = () => {
@@ -759,6 +760,8 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
for await (const chunk of gen) {
const text = streamChunkText(chunk);
if (text.length > 0) sawText = true;
+ const finish = (chunk as any)?.choices?.[0]?.finish_reason;
+ if (finish) upstreamFinish = finish;
totalOutputTokens += Math.ceil(text.length / 4);
const frame = legacyCompletionChunk(route, chunk, text);
// Commit point: hold headers until the first real text, so a stream
@@ -772,7 +775,13 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
}
if (!sawText) {
- throw new Error(`empty completion from ${route.displayName} (legacy stream produced no text)`);
+ // finish_reason 'length' means the model spent the whole output
+ // budget before any visible text (hidden reasoning) — fail over,
+ // but skip the cooldown/penalty: not a provider-health signal.
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName} (legacy stream produced no text)`),
+ upstreamFinish === 'length' ? { skipBench: true } : {},
+ );
}
flushHeaders();
@@ -824,10 +833,20 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
const text = completionTextFromChat(result);
if (!text) {
- throw new Error(`empty completion from ${route.displayName}`);
+ // finish_reason 'length' = output budget consumed by hidden reasoning
+ // before any visible text: fail over without a cooldown/penalty.
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName}`),
+ result.choices?.[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
}
- const totalTokens = result.usage?.total_tokens ?? 0;
+ // Usage fallback: providers that omit `usage` used to be logged as 0
+ // tokens, silently undercounting analytics and the rate-limit ledger.
+ // Fall back to the same chars/4 estimate the streaming path uses.
+ const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
+ const completionTokens = result.usage?.completion_tokens ?? Math.ceil(text.length / 4);
+ const totalTokens = result.usage?.total_tokens ?? (promptTokens + completionTokens);
recordUpstreamSuccess(route, totalTokens);
res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
@@ -853,10 +872,10 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
platform: route.platform,
model: route.modelId,
latencyMs: Date.now() - start,
- inputTokens: result.usage?.prompt_tokens ?? 0,
- outputTokens: result.usage?.completion_tokens ?? 0,
+ inputTokens: promptTokens,
+ outputTokens: completionTokens,
});
- logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
+ logRequest(route.platform, route.modelId, route.keyId, 'success', promptTokens, completionTokens, Date.now() - start, null, null, pinnedModelId);
return 'done';
},
logFailure: (route, err, attempt) => {
@@ -873,7 +892,8 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError, null, pinnedModelId);
},
- onFatal: (route, err) => {
+ onFatal: (route, err, attempt) => {
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
res.status(502).json({
error: {
message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`,
@@ -881,10 +901,10 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
},
});
},
- onRoutingExhausted: (lastError, routeErr) => {
- if (lastError) {
- const error = exhaustedRetryError(lastError);
- res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
+ if (exhaustion) {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ res.status(exhaustion.status).json({ error: { message: exhaustion.message, type: exhaustion.type } });
} else {
const disposition: string[] = Array.isArray(routeErr.diagnostics) ? routeErr.diagnostics : [];
console.warn(
@@ -895,9 +915,9 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
res.status(routeErr.status ?? 503).json({ error: { message: routeErr.message, type: 'routing_error' } });
}
},
- onExhausted: (lastError) => {
- const error = exhaustedRetryError(lastError, MAX_RETRIES);
- res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ onExhausted: (exhaustion, info) => {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ res.status(exhaustion.status).json({ error: { message: exhaustion.message, type: exhaustion.type } });
},
});
});
@@ -1565,7 +1585,13 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// Nothing usable came out — same failover semantics as the
// non-stream empty-completion path. Headers can't have been sent
// (header flush requires payload), so the client never notices.
- throw new Error(`empty completion from ${route.displayName} (stream produced no content and no tool calls)`);
+ // finish_reason 'length' = the model spent the whole output budget
+ // on hidden reasoning before any visible text: fail over, but skip
+ // the cooldown/penalty (not a provider-health signal).
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName} (stream produced no content and no tool calls)`),
+ upstreamFinish === 'length' ? { skipBench: true } : {},
+ );
}
flushHeaders();
@@ -1643,7 +1669,14 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
const respMsg = result.choices?.[0]?.message;
const respText = contentToString(respMsg?.content ?? '');
if (!respText && (respMsg?.tool_calls?.length ?? 0) === 0) {
- throw new Error(`empty completion from ${route.displayName}`);
+ // finish_reason 'length' = the model spent the whole output budget on
+ // hidden reasoning before any visible text (observed live: 5 of 11
+ // hops in one chain). Still fail over, but skipBench tells the shared
+ // loop not to cooldown/penalize a healthy model for a truncated turn.
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName}`),
+ result.choices?.[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
}
// Inline tool-call dialect rescue (#231 audit): a tool-bearing
@@ -1670,7 +1703,15 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
}
}
- const totalTokens = result.usage?.total_tokens ?? 0;
+ // Usage fallback: providers that omit `usage` used to be logged as 0
+ // tokens, silently undercounting analytics and the rate-limit ledger.
+ // Fall back to the same chars/4 estimate the streaming path uses (tool
+ // arguments included, mirroring the stream accounting).
+ const respToolArgChars = (respMsg?.tool_calls ?? []).reduce((n, tc) => n + (tc?.function?.arguments?.length ?? 0), 0);
+ const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
+ const completionTokens = result.usage?.completion_tokens
+ ?? Math.ceil((contentToString(respMsg?.content ?? '').length + respToolArgChars) / 4);
+ const totalTokens = result.usage?.total_tokens ?? (promptTokens + completionTokens);
recordUpstreamSuccess(route, totalTokens);
// Use stickyStrategyKey (not the global strategyKey) so a group-pinned
// request writes its sticky entry under the SAME key the next turn reads
@@ -1709,8 +1750,8 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
platform: route.platform,
modelId: route.modelId,
keyId: route.keyId,
- promptTokens: result.usage?.prompt_tokens ?? 0,
- completionTokens: result.usage?.completion_tokens ?? 0,
+ promptTokens,
+ completionTokens,
});
}
@@ -1721,10 +1762,10 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
platform: route.platform,
model: route.modelId,
latencyMs: Date.now() - start,
- inputTokens: result.usage?.prompt_tokens ?? 0,
- outputTokens: result.usage?.completion_tokens ?? 0,
+ inputTokens: promptTokens,
+ outputTokens: completionTokens,
});
- logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
+ logRequest(route.platform, route.modelId, route.keyId, 'success', promptTokens, completionTokens, Date.now() - start, null, null, pinnedModelId);
return 'done';
}
},
@@ -1742,8 +1783,9 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError, null, pinnedModelId);
},
- onFatal: (route, err) => {
- // Non-retryable error (auth, bare 4xx, etc.): don't retry.
+ onFatal: (route, err, attempt) => {
+ // Non-retryable error (bare 4xx, etc.): don't retry.
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
res.status(502).json({
error: {
message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`,
@@ -1751,11 +1793,11 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
},
});
},
- onRoutingExhausted: (lastError, routeErr) => {
+ onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
// No more models available.
- if (lastError) {
- const error = exhaustedRetryError(lastError);
- res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ if (exhaustion) {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ res.status(exhaustion.status).json({ error: { message: exhaustion.message, type: exhaustion.type } });
} else {
// Synchronous exhaustion: the router rejected every candidate before any
// upstream was tried, so this is the ONLY place the per-model disposition
@@ -1770,9 +1812,9 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
res.status(routeErr.status ?? 503).json({ error: { message: routeErr.message, type: 'routing_error' } });
}
},
- onExhausted: (lastError) => {
- const error = exhaustedRetryError(lastError, MAX_RETRIES);
- res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ onExhausted: (exhaustion, info) => {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ res.status(exhaustion.status).json({ error: { message: exhaustion.message, type: exhaustion.type } });
},
});
});
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index 70e5fbad..ca189aa7 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -23,7 +23,7 @@ import {
traceRouteEvent,
logRequest,
} from './proxy.js';
-import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, exhaustedRetryError } from '../lib/fallback-loop.js';
+import { runFallbackLoop, newFallbackState, recordUpstreamSuccess } from '../lib/fallback-loop.js';
import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
@@ -407,6 +407,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
// streamed normally). Mirrors the /chat/completions stream loop.
let dialectMode: 'undecided' | 'passthrough' | 'dialect' = 'undecided';
let heldText = '';
+ let upstreamFinish: string | null = null;
// Commit point: headers + the response.created/in_progress skeleton go
// out only when the first MEANINGFUL output item is about to be emitted
@@ -467,7 +468,9 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
throw new Error(`in-band provider error from ${route.displayName}: ${anyChunk.error.message ?? 'provider error'}`);
}
- const delta = chunk.choices?.[0]?.delta;
+ const choice0 = chunk.choices?.[0];
+ if (choice0?.finish_reason) upstreamFinish = choice0.finish_reason;
+ const delta = choice0?.delta;
if (!delta) continue;
// Text deltas → output_text events on a single message item, after
@@ -571,7 +574,13 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
// been committed yet (the skeleton is lazy), so throwing lets the
// shared loop fail over to the next model on the same SSE connection.
if (msgText.length === 0 && toolAcc.size === 0) {
- throw new Error(`empty completion from ${route.displayName}`);
+ // finish_reason 'length' = the model spent the whole output budget
+ // on hidden reasoning before any visible text: fail over, but skip
+ // the cooldown/penalty (not a provider-health signal).
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName}`),
+ upstreamFinish === 'length' ? { skipBench: true } : {},
+ );
}
// Finalize any open text item.
@@ -673,12 +682,19 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
const completionTokens = result.usage?.completion_tokens ?? Math.ceil(text.length / 4);
- // Empty completion → fail over via the shared loop (see the streaming path).
+ // Empty completion → fail over via the shared loop (see the streaming
+ // path); finish_reason 'length' skips the cooldown/penalty.
if (!text && toolCalls.length === 0) {
- throw new Error(`empty completion from ${route.displayName}`);
+ throw Object.assign(
+ new Error(`empty completion from ${route.displayName}`),
+ result.choices[0]?.finish_reason === 'length' ? { skipBench: true } : {},
+ );
}
- recordUpstreamSuccess(route, result.usage?.total_tokens ?? 0);
+ // Usage fallback: a missing provider `usage` block used to record 0
+ // tokens against the rate-limit ledger; promptTokens/completionTokens
+ // above already carry the chars/4 estimate.
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? (promptTokens + completionTokens));
setStickyModel(messages, route.modelDbId, sessionIdHeader);
res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
@@ -715,30 +731,31 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError);
},
- onFatal: (route, err) => {
+ onFatal: (route, err, attempt) => {
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
res.status(502).json({ error: { message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`, type: 'provider_error' } });
},
- onRoutingExhausted: (lastError, routeErr) => {
- const exhausted = lastError ? exhaustedRetryError(lastError) : null;
- const status = exhausted?.status ?? routeErr.status ?? 503;
- const message = exhausted?.message ?? routeErr.message;
- const type = exhausted?.type ?? 'routing_error';
+ onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
+ const status = exhaustion?.status ?? routeErr.status ?? 503;
+ const message = exhaustion?.message ?? routeErr.message;
+ const type = exhaustion?.type ?? 'routing_error';
if (streamStarted) {
sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message, type } } });
res.end();
} else {
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
res.status(status).json({ error: { message, type } });
}
},
- onExhausted: (lastError) => {
+ onExhausted: (exhaustion, info) => {
// The streaming skeleton may already be on the wire — close the SSE stream
// with a failed event instead of writing JSON onto a committed response.
- const exhausted = exhaustedRetryError(lastError, MAX_RETRIES);
if (streamStarted) {
- sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhausted.message, type: exhausted.type } } });
+ sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhaustion.message, type: exhaustion.type } } });
res.end();
} else {
- res.status(exhausted.status).json({ error: { message: exhausted.message, type: exhausted.type } });
+ if (info.attempts.length > 0) res.setHeader('X-Fallback-Attempts', String(info.attempts.length));
+ res.status(exhaustion.status).json({ error: { message: exhaustion.message, type: exhaustion.type } });
}
},
});