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

fix(fallback): log the routing disposition on every surface, not just /v1/*/completions (#1203)

Chong Jia Zhen6304566d1ddd
diff --git a/server/src/__tests__/lib/fallback-loop.test.ts b/server/src/__tests__/lib/fallback-loop.test.ts
index b3f2c129..a02a151d 100644
--- a/server/src/__tests__/lib/fallback-loop.test.ts
+++ b/server/src/__tests__/lib/fallback-loop.test.ts
@@ -758,3 +758,86 @@ describe('runFallbackLoop: client disconnect + attempt log', () => {
expect(attemptLog[0].errorClass).toBe('rate_limited');
});
});
+
+// The diagnostics line used to live in each surface's onRoutingExhausted hook,
+// and only routes/proxy.ts ever implemented it — so an opaque routing_error on
+// /v1/messages, /v1/responses or an inbound wire recorded nothing about WHY the
+// pool was empty. It belongs to the loop: these tests pin it there, for every
+// surface, including one that supplies no identity at all.
+describe('runFallbackLoop: routing-exhaustion diagnostics belong to the loop', () => {
+ const routeError = (diagnostics: string[]) =>
+ Object.assign(new Error('all candidates exhausted'), { status: 429, diagnostics });
+
+ const warnedLine = (warn: ReturnType<typeof vi.spyOn>): string | undefined =>
+ warn.mock.calls.map(c => String(c[0])).find(l => l.includes('routing exhausted'));
+
+ it('logs the router per-candidate disposition when no upstream was tried', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ await runFallbackLoop(hooksSkeleton({
+ logIdentity: { surface: 'anthropic messages', requestId: 'abcdef12-3456-7890', requestedModel: 'claude-x' },
+ route: () => { throw routeError(['glm-4.7 @zai: cooldown 42s', 'llama @groq: rpd 0 left']); },
+ }));
+ const line = warnedLine(warn);
+ expect(line).toBeDefined();
+ expect(line).toContain('anthropic messages');
+ expect(line).toContain('req=abcdef'); // hyphens stripped, 6 chars
+ expect(line).toContain('requested=claude-x');
+ expect(line).toContain('candidates=2');
+ expect(line).toContain('glm-4.7 @zai: cooldown 42s');
+ expect(line).toContain('llama @groq: rpd 0 left');
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('still fires for a surface that supplies no logIdentity', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ await runFallbackLoop(hooksSkeleton({
+ route: () => { throw routeError(['solo @fake: no usable key']); },
+ }));
+ const line = warnedLine(warn);
+ expect(line).toBeDefined();
+ expect(line).toContain('unidentified surface');
+ expect(line).toContain('candidates=1');
+ expect(line).toContain('solo @fake: no usable key');
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('handles a RouteError carrying no diagnostics at all', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ await runFallbackLoop(hooksSkeleton({
+ logIdentity: { surface: 'inbound chat' },
+ route: () => { throw Object.assign(new Error('nothing routable'), { status: 429 }); },
+ }));
+ const line = warnedLine(warn);
+ expect(line).toBeDefined();
+ expect(line).toContain('inbound chat');
+ expect(line).toContain('candidates=0');
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('stays silent when attempts already ran — the attempt trail explains those', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ let call = 0;
+ await runFallbackLoop(hooksSkeleton({
+ logIdentity: { surface: 'chat completions' },
+ route: () => {
+ if (call++ === 0) return fakeRoute();
+ throw routeError(['everything @fake: cooldown']);
+ },
+ dispatch: async () => { throw Object.assign(new Error('Too Many Requests'), { status: 429 }); },
+ }));
+ expect(warnedLine(warn)).toBeUndefined();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.ts
index 4625246b..edb2208a 100644
--- a/server/src/lib/fallback-loop.ts
+++ b/server/src/lib/fallback-loop.ts
@@ -938,6 +938,26 @@ export function routingExhaustionBody(routeErr: any): ExhaustionBody {
};
}
+/** Log the router's per-candidate disposition for a zero-attempt exhaustion.
+ * Lives in the loop, not the surfaces: routing gave up before any upstream was
+ * tried, so nothing else records WHY the pool was empty, and an opaque
+ * routing_error is indistinguishable from a genuinely dry pool (issue _1).
+ * Every surface used to be responsible for logging this itself and only
+ * routes/proxy.ts ever did, so /v1/messages, /v1/responses and the inbound
+ * wires logged nothing. The loop owns the format; surfaces only name
+ * themselves via FallbackHooks.logIdentity. */
+function logRoutingExhaustion(routeErr: any, identity?: FallbackHooks['logIdentity']): void {
+ const disposition: string[] = Array.isArray(routeErr?.diagnostics) ? routeErr.diagnostics : [];
+ const surface = identity?.surface ?? 'unidentified surface';
+ const req = identity?.requestId ? ` req=${identity.requestId.replace(/-/g, '').slice(0, 6)}` : '';
+ const requested = identity?.requestedModel ? ` requested=${identity.requestedModel}` : '';
+ console.warn(
+ `[FallbackLoop] ${surface} routing exhausted (no upstream tried)${req}${requested} ` +
+ `candidates=${disposition.length}` +
+ (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
+ );
+}
+
// What a surface's dispatch() returns to signal the response is finished and the
// loop must stop:
// 'done' — the attempt succeeded and the full response was sent.
@@ -976,6 +996,11 @@ export interface FallbackHooks {
// is the same array used for exhaustion bodies), so the surface can stamp
// X-Fallback-Trail on successful responses too.
attemptLog?: AttemptRecord[];
+ // Names this surface in the shared routing-exhaustion diagnostics line the
+ // loop logs when route() gave up before any upstream was tried (see
+ // logRoutingExhaustion). Absent = the line still fires, without identifying
+ // the surface or the request.
+ logIdentity?: { surface: string; requestId?: string; requestedModel?: string };
// Returns true once the client has hung up. Checked before STARTING each
// retry: a chain nobody is waiting for must not keep burning provider
// quota. Surfaces additionally thread a client-disconnect AbortSignal into
@@ -1141,6 +1166,10 @@ async function runFallbackLoopAttempts(hooks: FallbackHooks, trace: RequestTrace
const exhaustion = lastError
? exhaustedRetryError(lastError, undefined, { attempts })
: routingExhaustionBody(routeErr);
+ // Zero attempts ran: log the router's per-candidate disposition, the only
+ // record of why the pool was empty. With prior attempts the trail in the
+ // exhaustion body already explains the failure.
+ if (!lastError) logRoutingExhaustion(routeErr, hooks.logIdentity);
hooks.onRoutingExhausted(lastError, routeErr, exhaustion, { attempts, timedOut: false });
return;
}
diff --git a/server/src/lib/inbound-chat.ts b/server/src/lib/inbound-chat.ts
index 624877db..54487a8b 100644
--- a/server/src/lib/inbound-chat.ts
+++ b/server/src/lib/inbound-chat.ts
@@ -233,6 +233,7 @@ export async function runInboundChat(
await runFallbackLoop({
state,
attemptLog,
+ logIdentity: { surface: 'inbound chat', requestedModel: input.model ?? 'auto' },
clientGone: () => clientGone,
route: () => routeRequest(
estimatedTotal,
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index 5aaa267e..9ac1e142 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -612,6 +612,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
maxRetries: MAX_RETRIES,
state,
attemptLog,
+ logIdentity: { surface: 'anthropic messages', requestedModel },
clientGone: () => clientGone,
abortInFlight: () => hedgeAbort.abort(newHedgeAbortError()),
route: () => {
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index e6e2e903..98f29909 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -1155,6 +1155,7 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
maxRetries: MAX_RETRIES,
state,
attemptLog,
+ logIdentity: { surface: 'legacy completions', requestId: requestGroupId, requestedModel: requestedModelLabel },
clientGone: () => clientGone,
abortInFlight: () => hedgeAbort.abort(newHedgeAbortError()),
route: () => routeRequest(
@@ -1405,16 +1406,6 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
});
},
onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
- if (!lastError) {
- // Synchronous exhaustion: the router rejected every candidate before
- // any upstream was tried — log the per-candidate disposition.
- const disposition: string[] = Array.isArray(routeErr.diagnostics) ? routeErr.diagnostics : [];
- console.warn(
- `[Proxy] legacy completions routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
- `requested=${requestedModelLabel} candidates=${disposition.length}` +
- (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
- );
- }
setFallbackHeaders(res, info.attempts.length, info.attempts);
setExhaustionHeaders(res, exhaustion);
res.status(exhaustion.status).json({ error: exhaustionErrorPayload(exhaustion), execution_id: requestGroupId });
@@ -2063,6 +2054,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
maxRetries: MAX_RETRIES,
state,
attemptLog,
+ logIdentity: { surface: 'chat completions', requestId: requestGroupId, requestedModel: requestedModelLabel },
clientGone: () => clientGone,
abortInFlight: () => hedgeAbort.abort(newHedgeAbortError()),
route: () => {
@@ -2854,18 +2846,6 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
},
onRoutingExhausted: (lastError, routeErr, exhaustion, info) => {
// No more models available.
- if (!lastError) {
- // Synchronous exhaustion: the router rejected every candidate before any
- // upstream was tried, so this is the ONLY place the per-model disposition
- // is recorded. Without it the exhaustion status is opaque — you can't tell
- // a genuinely dry pool from cooldowns/quota/context narrowing (issue _1).
- const disposition: string[] = Array.isArray(routeErr.diagnostics) ? routeErr.diagnostics : [];
- console.warn(
- `[Proxy] routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
- `requested=${requestedModelLabel} candidates=${disposition.length}` +
- (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
- );
- }
setFallbackHeaders(res, info.attempts.length, info.attempts);
setExhaustionHeaders(res, exhaustion);
res.status(exhaustion.status).json({ error: exhaustionErrorPayload(exhaustion), execution_id: requestGroupId });
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index 3e36f1e3..615eb619 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -770,6 +770,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
maxRetries: MAX_RETRIES,
state,
attemptLog,
+ logIdentity: { surface: 'responses', requestId: requestGroupId, requestedModel: requestedModelLabel },
clientGone: () => clientGone,
abortInFlight: () => hedgeAbort.abort(newHedgeAbortError()),
route: () => {