GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(session): retry transient transport failures · anomalyco/opencode@2c7f73b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/opencode
    • src/session
      • message-v2.ts
      • processor.ts
      • retry.ts
    • test/session
      • message-v2.test.ts
      • processor-effect.test.ts
      • retry.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/opencode/src/session/message-v2.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/message-v2.ts
+115-15Lines changed: 115 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -603,17 +603,101 @@ function isAfter(info: Info, other?: Info) {
603603
return info.id > other.id
604604
}
605605

606+
// Transport failures that can recover without changing the request. Every code
607+
// here is still bounded by the global retry limit (~60s of backoff) and then
608+
// surfaces, so a genuinely broken endpoint still reports within a minute.
609+
//
610+
// Bun's native fetch collapses DNS failure, refused connection, TLS mismatch,
611+
// and unroutable network into a single ConnectionRefused with one shared
612+
// message, so it cannot be treated as permanent without also giving up retries
613+
// for wifi flaps, VPN reconnects, and sleep/wake. Bounded retry is the only
614+
// classification that serves both.
615+
const TRANSIENT_SYS_CODES = new Set([
616+
"ECONNRESET",
617+
"ETIMEDOUT",
618+
"EAI_AGAIN",
619+
"EHOSTUNREACH",
620+
"ENETUNREACH",
621+
"EPIPE",
622+
"UND_ERR_CONNECT_TIMEOUT",
623+
"UND_ERR_HEADERS_TIMEOUT",
624+
"UND_ERR_BODY_TIMEOUT",
625+
"UND_ERR_SOCKET",
626+
"ConnectionClosed",
627+
"ConnectionRefused",
628+
"FailedToOpenSocket",
629+
"Timeout",
630+
])
631+
// Node and undici report these only for a genuinely unresolvable or refused
632+
// endpoint, so they stay permanent and surface immediately. They are reachable
633+
// through a custom fetch implementation rather than Bun's own.
634+
const PERMANENT_SYS_CODES = new Set(["ENOTFOUND", "ECONNREFUSED", "DNSResolveFailed", "DNSResolutionFailed"])
635+
const TRANSIENT_ERROR_CODES = new Set([
636+
"TimeoutError",
637+
"NETWORK_ERROR",
638+
"ZlibError",
639+
"ProviderHeaderTimeoutError",
640+
"ProviderResponseStreamError",
641+
])
642+
const CAUSE_MAX_DEPTH = 8
643+
644+
export function isPermanentTransportCode(code: unknown) {
645+
return typeof code === "string" && PERMANENT_SYS_CODES.has(code)
646+
}
647+
648+
export function isTransientTransportCode(code: unknown) {
649+
return typeof code === "string" && (TRANSIENT_SYS_CODES.has(code) || TRANSIENT_ERROR_CODES.has(code))
650+
}
651+
652+
// Exact messages emitted for a prematurely closed transport. Generic text
653+
// such as "network error" or "fetch failed" cannot distinguish a transient
654+
// disconnect from a permanent DNS, TLS, authentication, or endpoint failure.
655+
const TRANSIENT_MESSAGES = new Set(["socket hang up", "sse read timed out", "other side closed", "terminated"])
656+
657+
// Walks the cause chain, which is where a transport fault ends up once the
658+
// provider SDK wraps it. CAUSE_MAX_DEPTH bounds the walk, so a self-referential
659+
// cause cannot spin.
660+
function classifyTransportError(error: unknown) {
661+
let current = error
662+
let transient: SystemError | undefined
663+
for (let depth = 0; depth < CAUSE_MAX_DEPTH; depth++) {
664+
if (!(current instanceof Error)) break
665+
const code = "code" in current && typeof current.code === "string" ? current.code : undefined
666+
if (isPermanentTransportCode(code)) return { type: "permanent" as const, error: current as SystemError }
667+
if (!transient && code && TRANSIENT_SYS_CODES.has(code)) transient = current as SystemError
668+
current = current.cause
669+
}
670+
if (transient) return { type: "transient" as const, error: transient }
671+
return undefined
672+
}
673+
606674
export function fromError(
607675
e: unknown,
608676
ctx: { providerID: ProviderV2.ID; aborted?: boolean },
609677
): NonNullable<Assistant["error"]> {
678+
const error = classify(e, ctx)
679+
// A cancelled request must never be retried. Abort can surface as a
680+
// transport-shaped failure instead of an interrupt when it races the read, so
681+
// rather than guarding each transport branch, refuse every retryable
682+
// classification once the turn is known to be aborted.
683+
if (ctx.aborted && APIError.isInstance(error) && error.data.isRetryable)
684+
return new AbortedError({ message: error.data.message }, { cause: e }).toObject()
685+
return error
686+
}
687+
688+
function classify(e: unknown, ctx: { providerID: ProviderV2.ID; aborted?: boolean }): NonNullable<Assistant["error"]> {
689+
const transport = classifyTransportError(e)
690+
const transient = transport?.type === "transient" ? transport.error : undefined
691+
const permanent = transport?.type === "permanent" ? transport.error : undefined
692+
const sysCode = transient?.code
610693
switch (true) {
611694
case e instanceof DOMException && e.name === "AbortError":
612-
return new AbortedError(
613-
{ message: e.message },
614-
{
615-
cause: e,
616-
},
695+
// Controlled timeouts carry their own error types. A bare AbortError is a cancellation.
696+
return new AbortedError({ message: e.message }, { cause: e }).toObject()
697+
case e instanceof DOMException && e.name === "TimeoutError":
698+
return new APIError(
699+
{ message: e.message || "Request timed out", isRetryable: true, metadata: { code: "TimeoutError" } },
700+
{ cause: e },
617701
).toObject()
618702
case OutputLengthError.isInstance(e):
619703
return e
@@ -625,23 +709,23 @@ export function fromError(
625709
},
626710
{ cause: e },
627711
).toObject()
628-
case (e as SystemError)?.code === "ECONNRESET":
712+
// An APICallError carrying a transport fault is handled in its own branch
713+
// below so the response envelope survives; this branch is for a bare
714+
// transport error with no response.
715+
case sysCode !== undefined && !APICallError.isInstance(e):
629716
return new APIError(
630717
{
631-
message: "Connection reset by server",
718+
message: sysCode === "ECONNRESET" ? "Connection reset by server" : `Network error (${sysCode})`,
632719
isRetryable: true,
633720
metadata: {
634-
code: (e as SystemError).code ?? "",
635-
syscall: (e as SystemError).syscall ?? "",
636-
message: (e as SystemError).message ?? "",
721+
code: sysCode,
722+
syscall: transient?.syscall ?? "",
723+
message: transient?.message ?? "",
637724
},
638725
},
639726
{ cause: e },
640727
).toObject()
641728
case e instanceof Error && (e as FetchDecompressionError).code === "ZlibError":
642-
if (ctx.aborted) {
643-
return new AbortedError({ message: e.message }, { cause: e }).toObject()
644-
}
645729
return new APIError(
646730
{
647731
message: "Response decompression failed",
@@ -691,17 +775,33 @@ export function fromError(
691775
).toObject()
692776
}
693777

778+
// Keep the response envelope even when a transport fault is the root
779+
// cause: retry-after headers and the body are the useful diagnostics, and
780+
// replacing them with a bare network error loses both.
781+
const transportError = permanent ?? transient
694782
return new APIError(
695783
{
696784
message: parsed.message,
697785
statusCode: parsed.statusCode,
698-
isRetryable: parsed.isRetryable,
786+
isRetryable: permanent ? false : transient !== undefined || parsed.isRetryable,
699787
responseHeaders: parsed.responseHeaders,
700788
responseBody: parsed.responseBody,
701-
metadata: parsed.metadata,
789+
metadata: transportError
790+
? {
791+
...parsed.metadata,
792+
code: transportError.code ?? "",
793+
syscall: transportError.syscall ?? "",
794+
message: transportError.message ?? "",
795+
}
796+
: parsed.metadata,
702797
},
703798
{ cause: e },
704799
).toObject()
800+
case e instanceof Error && TRANSIENT_MESSAGES.has(e.message.toLowerCase()):
801+
return new APIError(
802+
{ message: e.message, isRetryable: true, metadata: { code: "NETWORK_ERROR", message: e.message } },
803+
{ cause: e },
804+
).toObject()
705805
case e instanceof Error:
706806
return new NamedError.Unknown({ message: errorMessage(e) }, { cause: e }).toObject()
707807
default:
Collapse file

‎packages/opencode/src/session/processor.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/processor.ts
+33-3Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ interface ProcessorContext extends Input {
7272
needsCompaction: boolean
7373
currentText: SessionV1.TextPart | undefined
7474
reasoningMap: Record<string, SessionV1.ReasoningPart>
75+
// Sticky once a tool has started executing. A retry replays the same request,
76+
// so the model re-emits the same call and a side-effecting tool would run a
77+
// second time. Deleting the part cannot undo what already touched the disk,
78+
// so this is the one failure the turn must not replay.
79+
executed: boolean
80+
// Parts written by the attempt currently in flight. A retry removes them
81+
// first, otherwise the truncated output from the failed attempt stays in the
82+
// transcript alongside its replacement.
83+
attemptParts: SessionV1.Part["id"][]
7584
}
7685

7786
type StreamEvent = LLMEvent
@@ -111,6 +120,8 @@ const layer = Layer.effect(
111120
needsCompaction: false,
112121
currentText: undefined,
113122
reasoningMap: {},
123+
executed: false,
124+
attemptParts: [],
114125
}
115126
let aborted = false
116127

@@ -243,6 +254,7 @@ const layer = Layer.effect(
243254
state: { status: "pending", input: {}, raw: "" },
244255
metadata: input.providerExecuted ? { providerExecuted: true } : undefined,
245256
} satisfies SessionV1.ToolPart)
257+
ctx.attemptParts.push(part.id)
246258
ctx.toolcalls[input.id] = {
247259
done: yield* Deferred.make<void>(),
248260
partID: part.id,
@@ -288,6 +300,7 @@ const layer = Layer.effect(
288300
time: { start: Date.now() },
289301
metadata: value.providerMetadata,
290302
}
303+
ctx.attemptParts.push(ctx.reasoningMap[value.id].id)
291304
yield* session.updatePart(ctx.reasoningMap[value.id])
292305
return
293306

@@ -334,6 +347,8 @@ const layer = Layer.effect(
334347
}
335348
yield* ensureToolCall(value)
336349
const input = isRecord(value.input) ? value.input : { value: value.input }
350+
// The call is about to execute, so the turn can no longer be replayed.
351+
ctx.executed = true
337352
yield* updateToolCall(value.id, (match) => ({
338353
...match,
339354
tool: value.name,
@@ -493,6 +508,7 @@ const layer = Layer.effect(
493508
time: { start: Date.now() },
494509
metadata: value.providerMetadata,
495510
}
511+
ctx.attemptParts.push(ctx.currentText.id)
496512
yield* session.updatePart(ctx.currentText)
497513
return
498514

@@ -634,6 +650,17 @@ const layer = Layer.effect(
634650

635651
return yield* Effect.gen(function* () {
636652
yield* Effect.gen(function* () {
653+
// Drop whatever the previous attempt managed to write. The request is
654+
// replayed unchanged, so leaving those parts behind would show the
655+
// truncated output followed by the full replacement.
656+
yield* Effect.forEach(ctx.attemptParts, (partID) =>
657+
session.removePart({
658+
sessionID: ctx.assistantMessage.sessionID,
659+
messageID: ctx.assistantMessage.id,
660+
partID,
661+
}),
662+
)
663+
ctx.attemptParts = []
637664
ctx.currentText = undefined
638665
ctx.reasoningMap = {}
639666
yield* status.set(ctx.sessionID, { type: "busy" })
@@ -657,8 +684,8 @@ const layer = Layer.effect(
657684
(cause) => !Cause.hasInterruptsOnly(cause),
658685
(cause) => Effect.fail(Cause.squash(cause)),
659686
),
660-
Effect.retry(
661-
SessionRetry.policy({
687+
Effect.retry({
688+
schedule: SessionRetry.policy({
662689
provider: input.model.providerID,
663690
parse,
664691
set: (info) => {
@@ -671,7 +698,10 @@ const layer = Layer.effect(
671698
})
672699
},
673700
}),
674-
),
701+
// Text and reasoning written by a failed attempt are removed before
702+
// the next one, but a tool that already ran cannot be undone.
703+
while: () => !ctx.executed,
704+
}),
675705
Effect.catch(halt),
676706
Effect.ensuring(cleanup()),
677707
)
Collapse file

‎packages/opencode/src/session/retry.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/session/retry.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ export function retryable(error: Err, provider: string) {
8585
// context overflow errors should not be retried
8686
if (SessionV1.ContextOverflowError.isInstance(error)) return undefined
8787
if (SessionV1.APIError.isInstance(error)) {
88+
if (MessageV2.isPermanentTransportCode(error.data.metadata?.code)) return undefined
8889
const status = error.data.statusCode
8990
// 5xx errors are transient server failures and should always be retried,
9091
// even when the provider SDK doesn't explicitly mark them as retryable.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.