Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1371,7 +1371,10 @@ export function fromError(
return new APIError(
{
message: (e as Error).message || "Connection interrupted",
isRetryable: true,
// Per-errno: most transport disconnects are retryable, but a permanent
// one (e.g. ENOTFOUND, an unresolved host) is not — classifyRetry reads
// this so it stops instead of retrying into a stall.
isRetryable: transport.retryable,
metadata: {
code: transport.code,
message: (e as Error).message || "",
Expand Down
18 changes: 17 additions & 1 deletion packages/opencode/src/session/retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,30 @@ describe("classifyRetry — reads providerFailure.kind (slice ④)", () => {

// Transient kinds always retry, even if isRetryable is false and the status is
// not 5xx — the classification, not the SDK flag, is the source of truth.
for (const kind of ["rate_limit", "server_overload", "transport_disconnect", "decompression"] as const) {
for (const kind of ["rate_limit", "server_overload", "decompression"] as const) {
test(`transient kind ${kind} retries even when isRetryable is false and status is not 5xx`, () => {
expect(
classifyRetry(makeAPIError({ isRetryable: false, statusCode: 400, providerFailure: { kind } }))?.kind,
).toBe("unknown")
})
}

// transport_disconnect honors the per-errno isRetryable the stream classifier
// sets (#1105b): most transport errnos are transient, but a permanent one
// (e.g. ENOTFOUND — unresolved host) is marked isRetryable=false and must not
// auto-retry into a stall.
test("transport_disconnect retries when the classifier marked it retryable", () => {
expect(
classifyRetry(makeAPIError({ isRetryable: true, providerFailure: { kind: "transport_disconnect" } }))?.kind,
).toBe("unknown")
})

test("transport_disconnect does not retry when the classifier marked it non-retryable", () => {
expect(
classifyRetry(makeAPIError({ isRetryable: false, providerFailure: { kind: "transport_disconnect" } })),
).toBeUndefined()
})

test("unknown kind falls back to the legacy isRetryable + 5xx gate", () => {
expect(
classifyRetry(makeAPIError({ isRetryable: true, statusCode: 404, providerFailure: { kind: "unknown" } }))?.kind,
Expand Down
26 changes: 13 additions & 13 deletions packages/opencode/src/session/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,10 @@ export type { RetryAction } from "./retry-classification"
// always retry. classifyRetry reads these so the retry decision follows the
// canonical classification instead of re-deriving it from the provider SDK's
// isRetryable flag; `unknown` or absent kinds fall back to that legacy signal.
// transport_disconnect is handled separately: it honors the per-errno
// isRetryable the stream classifier set (most errnos transient, ENOTFOUND not).
const RETRY_TERMINAL_KINDS = new Set<ProviderFailureKind>(["auth", "invalid_request", "quota_exhausted"])
const RETRY_TRANSIENT_KINDS = new Set<ProviderFailureKind>([
"rate_limit",
"server_overload",
"transport_disconnect",
"decompression",
])
const RETRY_TRANSIENT_KINDS = new Set<ProviderFailureKind>(["rate_limit", "server_overload", "decompression"])

export const RETRY_INITIAL_DELAY = 2000
export const RETRY_BACKOFF_FACTOR = 2
Expand Down Expand Up @@ -85,16 +82,19 @@ export function classifyRetry(error: Err): RetryClassification | undefined {
const status = error.data.statusCode
const kind = error.data.providerFailure?.kind
// Retry/stop gate. Prefer the canonical providerFailure.kind: terminal kinds
// never retry, transient kinds always do. When the kind is `unknown` or the
// row predates providerFailure, fall back to the legacy signal — isRetryable,
// or a 5xx the provider SDK didn't explicitly mark retryable. The two agree
// for every classified kind today.
// never retry, transient kinds always do. transport_disconnect honors the
// per-errno isRetryable the stream classifier set (most errnos transient,
// ENOTFOUND not). When the kind is `unknown` or the row predates
// providerFailure, fall back to the legacy signal — isRetryable, or a 5xx the
// provider SDK didn't explicitly mark retryable.
const retryable =
kind && RETRY_TERMINAL_KINDS.has(kind)
? false
: kind && RETRY_TRANSIENT_KINDS.has(kind)
? true
: error.data.isRetryable || (status !== undefined && status >= 500)
: kind === "transport_disconnect"
? error.data.isRetryable
: kind && RETRY_TRANSIENT_KINDS.has(kind)
? true
: error.data.isRetryable || (status !== undefined && status >= 500)
if (!retryable) return undefined

// Strict 3-way AND: opencode provider + FreeUsageLimitError marker in body
Expand Down
71 changes: 71 additions & 0 deletions packages/opencode/src/session/stream-failure-classifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,60 @@ describe("classifyStreamFailure", () => {
code: "UND_ERR_SOCKET",
})
})

test("EAI_AGAIN (transient DNS) stays retryable", () => {
const error = Object.assign(new Error("getaddrinfo EAI_AGAIN api.example.com"), {
code: "EAI_AGAIN",
syscall: "getaddrinfo",
})
expect(classifyStreamFailure(error)).toEqual({
kind: "provider_transport_disconnect",
retryable: true,
code: "EAI_AGAIN",
})
})

test("UND_ERR_HEADERS_TIMEOUT is a retryable transport disconnect", () => {
const error = Object.assign(new Error("Headers Timeout Error"), { code: "UND_ERR_HEADERS_TIMEOUT" })
expect(classifyStreamFailure(error)).toEqual({
kind: "provider_transport_disconnect",
retryable: true,
code: "UND_ERR_HEADERS_TIMEOUT",
})
})

test("bare 'socket hang up' message (no errno code) classifies as retryable transport", () => {
const error = new Error("socket hang up")
expect(classifyStreamFailure(error)).toEqual({
kind: "provider_transport_disconnect",
retryable: true,
code: "SOCKET_HANG_UP",
})
})
})

describe("transport disconnect — non-retryable", () => {
test("ENOTFOUND (unresolved host, likely misconfigured base URL) is not retryable", () => {
const error = Object.assign(new Error("getaddrinfo ENOTFOUND api.wrong-host.invalid"), {
code: "ENOTFOUND",
syscall: "getaddrinfo",
})
expect(classifyStreamFailure(error)).toEqual({
kind: "provider_transport_disconnect",
retryable: false,
code: "ENOTFOUND",
})
})

test("ENOTFOUND nested in cause chain is not retryable", () => {
const cause = Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "ENOTFOUND" })
const error = new TypeError("fetch failed", { cause })
expect(classifyStreamFailure(error)).toEqual({
kind: "provider_transport_disconnect",
retryable: false,
code: "ENOTFOUND",
})
})
})

describe("non-transport errors — not classified", () => {
Expand All @@ -81,5 +135,22 @@ describe("classifyStreamFailure", () => {
const error = new TypeError("terminated", { cause: new Error("unrelated") })
expect(classifyStreamFailure(error)).toBeUndefined()
})

test("message fallback does not hijack an HTTP error that mentions 'socket hang up'", () => {
// An error carrying an HTTP statusCode is an API error classified by status
// downstream; a transport phrase in its message must not reclassify it.
const error = Object.assign(new Error("400 invalid request: socket hang up is not allowed"), {
statusCode: 400,
})
expect(classifyStreamFailure(error)).toBeUndefined()
})

test("HTTP error with a transport-coded cause is still classified by status, not transport", () => {
// statusCode present = HTTP response received = API error. A transport code
// on its cause must not reclassify it as a transport disconnect.
const cause = Object.assign(new Error("socket hang up"), { code: "UND_ERR_SOCKET" })
const error = Object.assign(new Error("400 invalid request"), { statusCode: 400, cause })
expect(classifyStreamFailure(error)).toBeUndefined()
})
})
})
58 changes: 54 additions & 4 deletions packages/opencode/src/session/stream-failure-classifier.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,72 @@
export type TransportDisconnect = {
kind: "provider_transport_disconnect"
retryable: true
retryable: boolean
code: string
}

const TRANSPORT_CODES = new Set(["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_SOCKET"])
// errno / undici codes that mean the connection dropped, timed out, or could
// not be established. All are transient (worth retrying) except the ones in
// NON_RETRYABLE_TRANSPORT_CODES below.
const TRANSPORT_CODES = new Set([
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"ECONNABORTED",
"EPIPE",
"EHOSTUNREACH",
"ENETUNREACH",
"EAI_AGAIN", // transient DNS lookup failure — retry
"ENOTFOUND", // permanent DNS failure (see NON_RETRYABLE_TRANSPORT_CODES)
"UND_ERR_SOCKET",
"UND_ERR_CONNECT_TIMEOUT",
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
])

// ENOTFOUND means the hostname did not resolve — usually a misconfigured base
// URL that will never resolve, so auto-retrying just stalls the turn. Kept
// distinct from EAI_AGAIN (transient DNS), which stays retryable.
const NON_RETRYABLE_TRANSPORT_CODES = new Set(["ENOTFOUND"])

// Connection-dropped signals that can arrive as a bare message with no errno
// code (undici/Node throws these in some paths). Only checked when no code
// matched. "terminated" is intentionally excluded — on its own it is undici's
// generic fetch wrapper and is only a transport failure when its cause carries
// a transport code (handled by the cause walk above).
const TRANSIENT_MESSAGE_CODES: ReadonlyArray<[RegExp, string]> = [
[/socket hang up/i, "SOCKET_HANG_UP"],
[/premature close/i, "PREMATURE_CLOSE"],
]

function disconnect(code: string): TransportDisconnect {
return { kind: "provider_transport_disconnect", retryable: !NON_RETRYABLE_TRANSPORT_CODES.has(code), code }
}

export function classifyStreamFailure(error: unknown): TransportDisconnect | undefined {
if (!(error instanceof Error)) return undefined

// An error carrying an HTTP statusCode means an HTTP response was received, so
// it is an API error classified by status downstream (the APICallError branch
// in fromError, which runs after this). It must not be reclassified as a
// transport disconnect — not by a transport-coded cause, and not by a
// transport phrase in its message.
if (typeof (error as { statusCode?: unknown }).statusCode === "number") return undefined

const topCode = (error as { code?: string }).code
if (typeof topCode === "string" && TRANSPORT_CODES.has(topCode)) {
return { kind: "provider_transport_disconnect", retryable: true, code: topCode }
return disconnect(topCode)
}

const code = findTransportCodeInCause(error.cause)
if (code) {
return { kind: "provider_transport_disconnect", retryable: true, code }
return disconnect(code)
}

// Message fallback is a last resort for raw connection errors that carry no
// errno code.
const message = typeof error.message === "string" ? error.message : ""
for (const [pattern, fallbackCode] of TRANSIENT_MESSAGE_CODES) {
if (pattern.test(message)) return { kind: "provider_transport_disconnect", retryable: true, code: fallbackCode }
}

return undefined
Expand Down
52 changes: 52 additions & 0 deletions packages/opencode/test/session/message-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2029,6 +2029,58 @@ describe("session.message-v2.fromError", () => {
})
})

test("classifies ENOTFOUND as a non-retryable transport disconnect", () => {
const error = Object.assign(new Error("getaddrinfo ENOTFOUND api.wrong-host.invalid"), {
code: "ENOTFOUND",
syscall: "getaddrinfo",
})

const result = MessageV2.fromError(error, { providerID })

expect(MessageV2.APIError.isInstance(result)).toBe(true)
expect((result as MessageV2.APIError).data.isRetryable).toBe(false)
expect((result as MessageV2.APIError).data.providerFailure).toStrictEqual({
kind: "transport_disconnect",
code: "ENOTFOUND",
})
})

test("classifies EAI_AGAIN as a retryable transport disconnect", () => {
const error = Object.assign(new Error("getaddrinfo EAI_AGAIN api.example.com"), {
code: "EAI_AGAIN",
syscall: "getaddrinfo",
})

const result = MessageV2.fromError(error, { providerID })

expect((result as MessageV2.APIError).data.isRetryable).toBe(true)
expect((result as MessageV2.APIError).data.providerFailure).toStrictEqual({
kind: "transport_disconnect",
code: "EAI_AGAIN",
})
})

test("does not let a transport phrase or transport cause on an APICallError hijack status classification", () => {
// A 400 invalid_request whose message echoes "socket hang up" AND whose cause
// carries a transport code must stay invalid_request, not be reclassified as
// a retryable transport disconnect (statusCode present = HTTP response).
const cause = Object.assign(new Error("socket hang up"), { code: "UND_ERR_SOCKET" })
const error = new APICallError({
message: "400 invalid request: socket hang up is not allowed",
url: "https://example.com",
requestBodyValues: {},
statusCode: 400,
responseHeaders: { "content-type": "application/json" },
responseBody: JSON.stringify({ error: { code: "invalid_prompt", message: "socket hang up is not allowed" } }),
isRetryable: false,
cause,
})

const result = MessageV2.fromError(error, { providerID })

expect((result as MessageV2.APIError).data.providerFailure?.kind).toBe("invalid_request")
})

test("populates providerFailure for decompression failures", () => {
const zlibError = Object.assign(
new Error('ZlibError fetching "https://opencode.cloudflare.dev/anthropic/messages".'),
Expand Down
Loading