GeezerVison is showing github.com — fix(session): retry transient transport failures · anomalyco/opencode@2c7f73b
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/session/message-v2.ts +115-15Lines changed: 115 additions & 15 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -603,17 +603,101 @@ function isAfter(info: Info, other?: Info) { | 603 | 603 | return info.id > other.id | 604 | 604 | } | 605 | 605 |
| | 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 | + | 606 | 674 | export function fromError( | 607 | 675 | e: unknown, | 608 | 676 | ctx: { providerID: ProviderV2.ID; aborted?: boolean }, | 609 | 677 | ): 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 | 610 | 693 | switch (true) { | 611 | 694 | 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 }, | 617 | 701 | ).toObject() | 618 | 702 | case OutputLengthError.isInstance(e): | 619 | 703 | return e | @@ -625,23 +709,23 @@ export function fromError( | 625 | 709 | }, | 626 | 710 | { cause: e }, | 627 | 711 | ).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): | 629 | 716 | return new APIError( | 630 | 717 | { | 631 | | - message: "Connection reset by server", | | 718 | + message: sysCode === "ECONNRESET" ? "Connection reset by server" : `Network error (${sysCode})`, | 632 | 719 | isRetryable: true, | 633 | 720 | 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 ?? "", | 637 | 724 | }, | 638 | 725 | }, | 639 | 726 | { cause: e }, | 640 | 727 | ).toObject() | 641 | 728 | case e instanceof Error && (e as FetchDecompressionError).code === "ZlibError": | 642 | | - if (ctx.aborted) { | 643 | | - return new AbortedError({ message: e.message }, { cause: e }).toObject() | 644 | | - } | 645 | 729 | return new APIError( | 646 | 730 | { | 647 | 731 | message: "Response decompression failed", | @@ -691,17 +775,33 @@ export function fromError( | 691 | 775 | ).toObject() | 692 | 776 | } | 693 | 777 |
| | 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 | 694 | 782 | return new APIError( | 695 | 783 | { | 696 | 784 | message: parsed.message, | 697 | 785 | statusCode: parsed.statusCode, | 698 | | - isRetryable: parsed.isRetryable, | | 786 | + isRetryable: permanent ? false : transient !== undefined || parsed.isRetryable, | 699 | 787 | responseHeaders: parsed.responseHeaders, | 700 | 788 | 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, | 702 | 797 | }, | 703 | 798 | { cause: e }, | 704 | 799 | ).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() | 705 | 805 | case e instanceof Error: | 706 | 806 | return new NamedError.Unknown({ message: errorMessage(e) }, { cause: e }).toObject() | 707 | 807 | default: | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/session/processor.ts +33-3Lines changed: 33 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -72,6 +72,15 @@ interface ProcessorContext extends Input { | 72 | 72 | needsCompaction: boolean | 73 | 73 | currentText: SessionV1.TextPart | undefined | 74 | 74 | 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"][] | 75 | 84 | } | 76 | 85 |
| 77 | 86 | type StreamEvent = LLMEvent | @@ -111,6 +120,8 @@ const layer = Layer.effect( | 111 | 120 | needsCompaction: false, | 112 | 121 | currentText: undefined, | 113 | 122 | reasoningMap: {}, | | 123 | + executed: false, | | 124 | + attemptParts: [], | 114 | 125 | } | 115 | 126 | let aborted = false | 116 | 127 |
| @@ -243,6 +254,7 @@ const layer = Layer.effect( | 243 | 254 | state: { status: "pending", input: {}, raw: "" }, | 244 | 255 | metadata: input.providerExecuted ? { providerExecuted: true } : undefined, | 245 | 256 | } satisfies SessionV1.ToolPart) | | 257 | + ctx.attemptParts.push(part.id) | 246 | 258 | ctx.toolcalls[input.id] = { | 247 | 259 | done: yield* Deferred.make<void>(), | 248 | 260 | partID: part.id, | @@ -288,6 +300,7 @@ const layer = Layer.effect( | 288 | 300 | time: { start: Date.now() }, | 289 | 301 | metadata: value.providerMetadata, | 290 | 302 | } | | 303 | + ctx.attemptParts.push(ctx.reasoningMap[value.id].id) | 291 | 304 | yield* session.updatePart(ctx.reasoningMap[value.id]) | 292 | 305 | return | 293 | 306 |
| @@ -334,6 +347,8 @@ const layer = Layer.effect( | 334 | 347 | } | 335 | 348 | yield* ensureToolCall(value) | 336 | 349 | 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 | 337 | 352 | yield* updateToolCall(value.id, (match) => ({ | 338 | 353 | ...match, | 339 | 354 | tool: value.name, | @@ -493,6 +508,7 @@ const layer = Layer.effect( | 493 | 508 | time: { start: Date.now() }, | 494 | 509 | metadata: value.providerMetadata, | 495 | 510 | } | | 511 | + ctx.attemptParts.push(ctx.currentText.id) | 496 | 512 | yield* session.updatePart(ctx.currentText) | 497 | 513 | return | 498 | 514 |
| @@ -634,6 +650,17 @@ const layer = Layer.effect( | 634 | 650 |
| 635 | 651 | return yield* Effect.gen(function* () { | 636 | 652 | 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 = [] | 637 | 664 | ctx.currentText = undefined | 638 | 665 | ctx.reasoningMap = {} | 639 | 666 | yield* status.set(ctx.sessionID, { type: "busy" }) | @@ -657,8 +684,8 @@ const layer = Layer.effect( | 657 | 684 | (cause) => !Cause.hasInterruptsOnly(cause), | 658 | 685 | (cause) => Effect.fail(Cause.squash(cause)), | 659 | 686 | ), | 660 | | - Effect.retry( | 661 | | - SessionRetry.policy({ | | 687 | + Effect.retry({ | | 688 | + schedule: SessionRetry.policy({ | 662 | 689 | provider: input.model.providerID, | 663 | 690 | parse, | 664 | 691 | set: (info) => { | @@ -671,7 +698,10 @@ const layer = Layer.effect( | 671 | 698 | }) | 672 | 699 | }, | 673 | 700 | }), | 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 | + }), | 675 | 705 | Effect.catch(halt), | 676 | 706 | Effect.ensuring(cleanup()), | 677 | 707 | ) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/session/retry.ts +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -85,6 +85,7 @@ export function retryable(error: Err, provider: string) { | 85 | 85 | // context overflow errors should not be retried | 86 | 86 | if (SessionV1.ContextOverflowError.isInstance(error)) return undefined | 87 | 87 | if (SessionV1.APIError.isInstance(error)) { | | 88 | + if (MessageV2.isPermanentTransportCode(error.data.metadata?.code)) return undefined | 88 | 89 | const status = error.data.statusCode | 89 | 90 | // 5xx errors are transient server failures and should always be retried, | 90 | 91 | // even when the provider SDK doesn't explicitly mark them as retryable. | |
|