Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(routing): hold the chain when a stream retry cannot reach the provider

Jack Rudenko0f2c5e14e93c
diff --git a/ai-docs/architecture/adapters.md b/ai-docs/architecture/adapters.md
index c76a17c9..b25249f9 100644
--- a/ai-docs/architecture/adapters.md
+++ b/ai-docs/architecture/adapters.md
@@ -429,6 +429,12 @@ The exclusion rested on "a 503 cannot silently switch the user off a pinned mode
outage on this machine still holds the chain.
- Changed on purpose: the stream sniffers' exhaustion 503 (overloaded after 3s → 15s → 30s of
retries) now advances a bare-name chain instead of returning to Claude Code.
+- Except when a retry could not REACH the provider. `settleResponsesStreamHead` and
+ `settleDevinStreamHead` return `exhausted` with `unreachable: true` when `reissue()` throws,
+ and the caller adds `x-claudish-connection-error` to that 503, so the chain holds. Without it a
+ DNS or connection failure on a Codex subscription hop advanced onto a metered OpenAI hop
+ (found by the 10.3.0 release review, source-traced; the status alone could not tell a
+ connection fault from an overload).
## The catalog's endpoint contract has two halves (v9.0.7)
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index d6046649..f9694841 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -1928,7 +1928,8 @@ export class ComposedHandler implements ModelHandler {
// the provider's words.
return c.json(
wrapAnthropicError(503, surfaced, "overloaded_error", undefined, settled.message),
- 503 as any
+ 503 as any,
+ settled.unreachable ? connectionFaultHeaders() : undefined
);
}
response = settled.response;
@@ -2001,7 +2002,10 @@ export class ComposedHandler implements ModelHandler {
)
: c.json(
wrapAnthropicError(503, surfaced, "overloaded_error", undefined, settled.message),
- 503 as any
+ 503 as any,
+ settled.kind === "exhausted" && settled.unreachable
+ ? connectionFaultHeaders()
+ : undefined
);
}
response = settled.response;
@@ -2110,7 +2114,7 @@ export class ComposedHandler implements ModelHandler {
reissue: () => Promise<Response>
): Promise<
| { kind: "ok"; response: Response }
- | { kind: "exhausted"; code: string; message: string; attempts: number }
+ | { kind: "exhausted"; code: string; message: string; attempts: number; unreachable?: true }
> {
let response = initial;
@@ -2148,6 +2152,10 @@ export class ComposedHandler implements ModelHandler {
code: verdict.code,
message: `${verdict.message} (retry could not reach the provider: ${error})`,
attempts: attempt + 1,
+ // A connection fault, not the provider's answer. The caller marks the
+ // 503 with the connection-fault header, so a routing chain HOLDS here
+ // instead of advancing onto the next (possibly metered) candidate.
+ unreachable: true,
};
}
@@ -2189,7 +2197,7 @@ export class ComposedHandler implements ModelHandler {
): Promise<
| { kind: "ok"; response: Response }
| { kind: "terminal"; code: string; message: string }
- | { kind: "exhausted"; code: string; message: string; attempts: number }
+ | { kind: "exhausted"; code: string; message: string; attempts: number; unreachable?: true }
> {
// Optional-method probe rather than a `ProviderTransport` member: this whole
// branch is Devin-specific by construction, and widening the shared
@@ -2240,6 +2248,10 @@ export class ComposedHandler implements ModelHandler {
code: verdict.code,
message: `${verdict.message} (retry could not reach the provider: ${error})`,
attempts: attempt + 1,
+ // A connection fault, not the provider's answer. The caller marks the
+ // 503 with the connection-fault header, so a routing chain HOLDS here
+ // instead of advancing onto the next (possibly metered) candidate.
+ unreachable: true,
};
}
diff --git a/packages/cli/src/handlers/stream-head-unreachable.test.ts b/packages/cli/src/handlers/stream-head-unreachable.test.ts
new file mode 100644
index 00000000..b377d99c
--- /dev/null
+++ b/packages/cli/src/handlers/stream-head-unreachable.test.ts
@@ -0,0 +1,137 @@
+import { afterEach, expect, test } from "bun:test";
+import { type Context, Hono } from "hono";
+import type { ProviderTransport } from "../providers/transport/types.js";
+import { ComposedHandler } from "./composed-handler.js";
+import { FallbackHandler, isRetryableError } from "./fallback-handler.js";
+import { CONNECTION_FAULT_HEADER, RECOVERY_MARKER_VALUE } from "./shared/recovery-marker.js";
+import type { ModelHandler } from "./types.js";
+
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+function makeTransport(): ProviderTransport {
+ return {
+ name: "sakana",
+ displayName: "Codex",
+ streamFormat: "openai-responses-sse",
+ overrideStreamFormat: () => "openai-responses-sse",
+ getEndpoint: () => "https://api.sakana.example/v1/responses",
+ getHeaders: async () => ({}),
+ } as unknown as ProviderTransport;
+}
+
+function makeContext(): Context {
+ return {
+ req: {
+ header: (name?: string) =>
+ name === undefined ? {} : name === "x-claudish-no-recovery" ? "1" : undefined,
+ },
+ header: () => {},
+ body: (body: BodyInit | null, init?: ResponseInit) => new Response(body, init),
+ // Preserve the third argument: it carries the connection-fault verdict.
+ json: (body: unknown, status = 200, headers?: HeadersInit) =>
+ new Response(JSON.stringify(body), { status, headers }),
+ } as unknown as Context;
+}
+
+const PAYLOAD = {
+ model: "fugu-ultra",
+ max_tokens: 16,
+ messages: [{ role: "user", content: "hi" }],
+};
+
+function makeHandler(): ComposedHandler {
+ return new ComposedHandler(makeTransport(), PAYLOAD.model, PAYLOAD.model, 8080, {});
+}
+
+function overloadedStream(): Response {
+ const events = [
+ { type: "response.created", response: { id: "resp_test", status: "in_progress" } },
+ { type: "response.in_progress", response: { id: "resp_test", status: "in_progress" } },
+ {
+ type: "error",
+ error: { code: "server_is_overloaded", message: "Server is overloaded" },
+ sequence_number: 2,
+ },
+ ];
+ return new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+}
+
+function stubFetch(unreachable: boolean): () => number {
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls++;
+ if (calls === 1) return overloadedStream();
+ if (calls !== 2) throw new Error(`Unexpected fetch call ${calls}`);
+ if (unreachable) {
+ throw Object.assign(new TypeError("fetch failed"), { code: "ConnectionRefused" });
+ }
+ return new Response('{"error":{"message":"upstream overloaded"}}', { status: 503 });
+ }) as typeof fetch;
+ return () => calls;
+}
+
+async function runInChain(first: ModelHandler) {
+ let nextCalls = 0;
+ const second = {
+ async handle() {
+ nextCalls++;
+ return new Response('{"content":[{"type":"text","text":"ok"}]}', {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ },
+ shutdown: async () => {},
+ } as ModelHandler;
+ const handler = new FallbackHandler([
+ { name: "Codex", handler: first },
+ { name: "Metered candidate", handler: second },
+ ]);
+ const app = new Hono();
+ app.post("/test", (c) => handler.handle(c, PAYLOAD));
+ const response = await app.request("/test", {
+ method: "POST",
+ headers: { "x-claudish-no-recovery": "1" },
+ body: "{}",
+ });
+ return { response, nextCalls };
+}
+
+test("a re-issue that cannot reach the provider answers 503 with the connection-fault header", async () => {
+ const calls = stubFetch(true);
+ const response = await makeHandler().handle(makeContext(), PAYLOAD);
+ const body = await response.text();
+ expect(calls()).toBe(2);
+ expect(response.status).toBe(503);
+ expect(response.headers.get(CONNECTION_FAULT_HEADER)).toBe(RECOVERY_MARKER_VALUE);
+ expect(JSON.parse(body).error.type).toBe("overloaded_error");
+ expect(isRetryableError(503, body, "Codex", response.headers)).toBe(false);
+}, 20_000);
+
+test("a routing chain holds on that 503 and never calls the next candidate", async () => {
+ const calls = stubFetch(true);
+ const { response, nextCalls } = await runInChain(makeHandler());
+ expect(calls()).toBe(2);
+ expect(response.status).toBe(503);
+ expect(response.headers.get(CONNECTION_FAULT_HEADER)).toBe(RECOVERY_MARKER_VALUE);
+ expect(nextCalls).toBe(0);
+}, 20_000);
+
+test("a re-issue that gets an HTTP answer stays unmarked, so the chain advances", async () => {
+ const singleCalls = stubFetch(false);
+ const single = await makeHandler().handle(makeContext(), PAYLOAD);
+ expect(singleCalls()).toBe(2);
+ expect(single.status).toBe(503);
+ expect(single.headers.has(CONNECTION_FAULT_HEADER)).toBe(false);
+
+ const chainCalls = stubFetch(false);
+ const { response, nextCalls } = await runInChain(makeHandler());
+ expect(chainCalls()).toBe(2);
+ expect(nextCalls).toBe(1);
+ expect(response.status).toBe(200);
+}, 20_000);