diff --git a/src/api/providers/__tests__/friendli.spec.ts b/src/api/providers/__tests__/friendli.spec.ts index 1ff1b1475b..fb68ef2f78 100644 --- a/src/api/providers/__tests__/friendli.spec.ts +++ b/src/api/providers/__tests__/friendli.spec.ts @@ -337,14 +337,22 @@ describe("FriendliHandler", () => { return {} }) - await expect(handler.completePrompt("a", { timeoutMs: 3000 })).rejects.toMatchObject({ name: "TimeoutError" }) + // The wait succeeded but consumed the shared deadline: the completion never ran. + await expect(handler.completePrompt("a", { timeoutMs: 3000 })).rejects.toMatchObject({ + name: "TimeoutError", + message: "The Friendli completion request timed out", + }) expect(mockCreate).not.toHaveBeenCalled() }) it("completePrompt should time out without a chat request when the catalog wait uses the deadline", async () => { mockGetModels.mockReturnValueOnce(new Promise(() => {})) - await expect(handler.completePrompt("a", { timeoutMs: 20 })).rejects.toMatchObject({ name: "TimeoutError" }) + // The catalog wait itself hit the deadline: that is model discovery, not a completion. + await expect(handler.completePrompt("a", { timeoutMs: 20 })).rejects.toMatchObject({ + name: "TimeoutError", + message: "The Friendli model discovery timed out", + }) expect(mockCreate).not.toHaveBeenCalled() }) diff --git a/src/api/providers/__tests__/qwen-code.spec.ts b/src/api/providers/__tests__/qwen-code.spec.ts index 5d81e90230..123c784b36 100644 --- a/src/api/providers/__tests__/qwen-code.spec.ts +++ b/src/api/providers/__tests__/qwen-code.spec.ts @@ -8,6 +8,26 @@ vi.mock("node:fs", () => ({ }, })) +// callApiWithRetry normalizes any abort failure into a fresh contract AbortError before the +// provider's catch wraps it, so asserting that the TimeoutError carries *this request's* +// abort failure (not a newly invented one) requires recording the instances the contract +// helper creates. Every other export delegates to the real implementation. +const abortFailures = vi.hoisted(function (): Error[] { + return [] +}) +vi.mock("../utils/abort-signal", async (importOriginal) => { + // The factory's importOriginal is typed as unknown; recover the module's real type so + // the rest of the contract can be spread without `any`. + const actual = (await importOriginal()) as typeof import("../utils/abort-signal") + return { + ...actual, + createAbortError: function (providerName: string): Error { + const abortError = actual.createAbortError(providerName) + abortFailures.push(abortError) + return abortError + }, + } +}) const mockCreate = vi.fn() import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" @@ -793,6 +813,14 @@ describe("QwenCodeHandler abort wiring", () => { expect(caught).toBeInstanceOf(Error) expect((caught as Error).name).toBe("TimeoutError") expect((caught as Error).message).toBe("The Qwen Code completion request timed out") + // The SDK rejection is normalized into a fresh contract AbortError by callApiWithRetry + // before the provider wraps it, so the cause can only be one of the abort errors this + // request actually created - not a discarded cause, and not an unrelated error. + const cause = (caught as { cause?: unknown }).cause + expect(cause).toBeInstanceOf(Error) + expect((cause as Error).name).toBe("AbortError") + expect((cause as Error).message).toBe("The Qwen Code request was aborted") + expect(abortFailures).toContain(cause) }) it("passes the merged signal through and nothing without options", async () => { diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index d11f5f7dba..eb844e7561 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -53,7 +53,7 @@ import { shouldUseReasoningBudget } from "../../shared/api" import { normalizeToolSchema } from "../../utils/json-schema" import { getSystemProxyUrl } from "../../utils/networkProxy" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" -import { mergeAbortSignalAndTimeout } from "./utils/abort-signal" +import { bridgeExternalAbortSignal, mergeAbortSignalAndTimeout } from "./utils/abort-signal" import { OutputTokenLimitError } from "./utils/output-token-limit-error" /************************************************************************************ @@ -569,42 +569,23 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH ...(useServiceTier && { [SERVICE_TIER_KEY]: this.options.awsBedrockServiceTier }), } - // Create a request-local AbortController with 10 minute timeout. Keeping it - // request-local (and detaching the bridge listener in the finally block) means - // a completed request can never leave a stale listener on the caller's signal. + // Bridge the caller's signal onto a request-local AbortController that also carries the + // 10 minute deadline, so one controller ends the request whether the caller or the clock + // fired. The bridge registers its listener with { once: true }, and it aborts the controller + // directly when the caller's signal was already aborted at call time, so a pre-aborted + // caller cancels through a path that needs no listener. // A manual setTimeout (rather than AbortSignal.timeout()) is required here // because clearTimeout in the finally block needs a cancelable handle — // AbortSignal.timeout() self-manages its timer and cannot be cleared. - const requestController = new AbortController() + const bridge = bridgeExternalAbortSignal(metadata?.abortSignal) let timeoutId: NodeJS.Timeout | undefined - // Bridge external abort signal to the request controller using the standard - // abort bridge pattern: - // - pre-aborted guard: a listener on an already-aborted signal may never fire, - // so abort the local controller directly in that case - // - { once: true }: the listener auto-removes on first abort event - let abortListener: (() => void) | undefined - const externalAbortSignal = metadata?.abortSignal - if (externalAbortSignal) { - if (externalAbortSignal.aborted) { - requestController.abort() - } else { - abortListener = () => requestController.abort() - externalAbortSignal.addEventListener("abort", abortListener, { once: true }) - } - } - try { - timeoutId = setTimeout( - () => { - requestController.abort() - }, - 10 * 60 * 1000, - ) + timeoutId = setTimeout(() => bridge.controller.abort(), 10 * 60 * 1000) const command = new ConverseStreamCommand(payload) const response = await this.client.send(command, { - abortSignal: requestController.signal, + abortSignal: bridge.controller.signal, }) if (!response.stream) { @@ -870,12 +851,10 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // early termination by the caller (break/destroy), which bypasses the normal // timeout-clearing path after the stream completes. clearTimeout(timeoutId) - - // Detach the bridge listener once the request ends (success or error) so the - // external signal keeps no reference to this request's controller. - if (abortListener) { - externalAbortSignal?.removeEventListener("abort", abortListener) - } + // Detach the bridge listener once the request ends — completion, failure, or early + // generator exit alike — so the caller's long-lived signal keeps no reference to + // this request's controller. + bridge.dispose() } } diff --git a/src/api/providers/friendli.ts b/src/api/providers/friendli.ts index 1c8c276ce6..95c904d6e1 100644 --- a/src/api/providers/friendli.ts +++ b/src/api/providers/friendli.ts @@ -21,13 +21,13 @@ import { handleOpenAIError } from "./utils/error-handler" import { bridgeExternalAbortSignal, createAbortError, - createTimeoutError, hasUsableTimeout, isRequestAborted, isTimeoutAbort, mergeAbortSignalAndTimeout, toSdkTimeoutMs, } from "./utils/abort-signal" +import { createTimeoutError } from "./utils/request-timeout" import { NOT_PROVIDED } from "./constants" import { getModels } from "./fetchers/modelCache" import { getFriendliModels } from "./fetchers/friendli" @@ -109,7 +109,8 @@ export class FriendliHandler extends BaseOpenAiCompatibleProvider { diff --git a/src/api/providers/qwen-code.ts b/src/api/providers/qwen-code.ts index 23cb3806ef..6f3db5816e 100644 --- a/src/api/providers/qwen-code.ts +++ b/src/api/providers/qwen-code.ts @@ -21,9 +21,9 @@ import { isRequestAborted, settleOnAbort, type OpenAiRequestOptions, - createTimeoutError, isTimeoutAbort, } from "./utils/abort-signal" +import { createTimeoutError } from "./utils/request-timeout" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" const QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai" @@ -492,7 +492,9 @@ export class QwenCodeHandler extends BaseProvider implements SingleCompletionHan // TimeoutError when the merged signal ended because its own timer // elapsed. The auth wait and the request both settle through here. if (isRequestAborted(error, requestSignal) && isTimeoutAbort(requestSignal)) { - throw createTimeoutError("Qwen Code") + // The deadline was classified from an abort-shaped failure already in hand; + // keep it as cause so the report holds both the deadline and what it was seen through. + throw createTimeoutError("Qwen Code", "completion request", error) } throw error } diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550..a0cbe099b7 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -12,9 +12,9 @@ import { throwIfAborted, MAX_TIMEOUT_MS, toSdkTimeoutMs, - createTimeoutError, isTimeoutAbort, } from "../abort-signal" +import { createTimeoutError } from "../request-timeout" import { withSettleGuard } from "../../../../test-utils/settle-guard" import { flushMacrotasks } from "../../../../test-utils/timers" @@ -829,6 +829,85 @@ describe("bridgeExternalAbortSignal", () => { controller.abort() expect(signal?.aborted).toBe(false) }) + + it("hands back a request-local controller when there is no external signal", () => { + const bridge = bridgeExternalAbortSignal() + expect(bridge.signal).toBeUndefined() + // Providers like lm-studio and qwen-code need a signal for their own races even + // when the caller passed none; the controller is that signal. + expect(bridge.controller.signal.aborted).toBe(false) + bridge.controller.abort() + expect(bridge.controller.signal.aborted).toBe(true) + }) + + it("returns the signal of the controller it created", () => { + const external = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal) + expect(bridge.signal).toBe(bridge.controller.signal) + }) + + it("bridges onto a caller-supplied controller instead of creating one", () => { + const external = new AbortController() + const requestController = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal, { controller: requestController }) + // openai-native keeps its class-level controller as the stop-button handle; the + // bridge must abort that same controller, not a private one. + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBe(requestController.signal) + external.abort() + expect(requestController.signal.aborted).toBe(true) + }) + + it("runs the onAbort hook once, after the request signal aborts", () => { + const external = new AbortController() + const requestController = new AbortController() + const reason = new Error("caller stop") + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } + // Providers pass their own controller exactly this way, so the hook can observe + // it directly instead of a mutable local. + bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) + external.abort(reason) + expect(seen.calls).toBe(1) + // A hook that threw must never be the reason a request signal stays un-settled, + // so the controller aborts first. + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) + }) + + it("runs the onAbort hook when the external signal was already aborted", () => { + const external = new AbortController() + const reason = new Error("already stopped") + external.abort(reason) + const hook = vitest.fn() + // native-ollama aborts its client and vscode-lm cancels its token source on the + // same signal: a caller that stopped before we started must reach that side + // effect too, not only the live-abort path. + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + expect(bridge.controller.signal.aborted).toBe(true) + expect(hook).toHaveBeenCalledTimes(1) + expect(hook).toHaveBeenCalledWith(reason) + }) + + it("neither aborts nor runs the hook for an abort that lands after dispose", () => { + const external = new AbortController() + const hook = vitest.fn() + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + bridge.dispose() + external.abort() + expect(hook).not.toHaveBeenCalled() + expect(bridge.controller.signal.aborted).toBe(false) + }) }) describe("hasUsableTimeout", () => { @@ -859,13 +938,12 @@ describe("toSdkTimeoutMs", () => { }) }) -describe("createTimeoutError", () => { - it("builds a TimeoutError naming the provider", () => { - const error = createTimeoutError("LM Studio") - - expect(error).toBeInstanceOf(Error) - expect(error.name).toBe("TimeoutError") - expect(error.message).toBe("The LM Studio completion request timed out") +describe("abort-signal module surface", () => { + it("does not re-declare the timeout error next to the phase-aware one", async () => { + // request-timeout.ts is the error's only home. A second definition here - or a + // re-export of it - is what this unit removed, and it would let the two drift again. + const abortSignalModule = await import("../abort-signal") + expect("createTimeoutError" in abortSignalModule).toBe(false) }) }) @@ -879,7 +957,7 @@ describe("isTimeoutAbort", () => { const timeout = new AbortController() const caller = new AbortController() const merged = mergeAbortSignals(timeout.signal, caller.signal) - timeout.abort(createTimeoutError("Qwen Code")) + timeout.abort(createTimeoutError("Qwen Code", "completion request")) caller.abort() expect(isTimeoutAbort(merged)).toBe(true) @@ -890,7 +968,7 @@ describe("isTimeoutAbort", () => { const caller = new AbortController() const merged = mergeAbortSignals(timeout.signal, caller.signal) caller.abort(new Error("user stop")) - timeout.abort(createTimeoutError("Qwen Code")) + timeout.abort(createTimeoutError("Qwen Code", "completion request")) expect(isTimeoutAbort(merged)).toBe(false) }) diff --git a/src/api/providers/utils/__tests__/request-timeout.spec.ts b/src/api/providers/utils/__tests__/request-timeout.spec.ts index 8190faebe3..3d20482288 100644 --- a/src/api/providers/utils/__tests__/request-timeout.spec.ts +++ b/src/api/providers/utils/__tests__/request-timeout.spec.ts @@ -44,4 +44,28 @@ describe("createTimeoutError", () => { expect(error.name).toBe("TimeoutError") expect(error.message).toBe("The Gemini completion request timed out") }) + + it("names the phase that the phase-less build dropped", () => { + // A catalog wait is model discovery. Collapsing the duplicate definition into + // this one is what lets a caller report the phase that actually stalled. + const error = createTimeoutError("Friendli", "model discovery") + expect(error.name).toBe("TimeoutError") + expect(error.message).toBe("The Friendli model discovery timed out") + }) + + it("carries the failure the deadline was detected through", () => { + // A stalled response body or a late SDK rejection is not the deadline itself; + // cause keeps both facts in one report. + const cause = new Error("Response body stalled") + const error = createTimeoutError("Unbound", "completion request", cause) + expect(error.message).toBe("The Unbound completion request timed out") + expect(error.cause).toBe(cause) + }) + + it("leaves cause unset when the caller has no underlying failure", () => { + // A timer that elapsed on its own has nothing to attribute. Passing an + // undefined cause would make the error look attributed when it is not. + const error = createTimeoutError("Vercel AI Gateway", "model discovery") + expect("cause" in error).toBe(false) + }) }) diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc12437..09d8bfdbb6 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -67,6 +67,30 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: return AbortSignal.any([primarySignal, secondarySignal]) } +/** + * Optional hooks for {@link bridgeExternalAbortSignal}: the cancellation side effects a + * provider needs that a plain signal relay cannot express. + */ +export type AbortBridgeHooks = { + /** + * Run this when the external signal aborts - a client-level `abort()` on a transport + * that owns its own connection, a host cancellation token, or a flag recording that the + * caller rather than a timeout ended the request. + * + * It also runs when the external signal was already aborted at call time, so a + * pre-aborted caller reaches the same side effect as a live abort. The per-request + * controller aborts before the hook runs, so a hook that throws cannot leave a + * request signal that never settles. + */ + onAbort?: (reason?: unknown) => void + /** + * Bridge onto this controller instead of creating one. Providers that keep a + * class-level controller as the stop-button handle pass it here so the bridge and + * that path share one controller. + */ + controller?: AbortController +} + /** * Bridge an optional caller-owned (external) abort signal to a per-request * signal, with an explicit detach handle. @@ -78,30 +102,54 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: * left attached would outlive the request and retain the per-request * controller for every completed request. * - * With no external signal, returns `{ signal: undefined, dispose: noop }` so - * the client-level timeout remains the only cancellation mechanism. + * With no external signal, `signal` is `undefined` and `dispose` is a noop, so the + * client-level timeout remains the only cancellation mechanism; the returned + * `controller` is still a usable request-local signal for a provider that needs + * one without relaying anything. */ -export function bridgeExternalAbortSignal(externalSignal?: AbortSignal): { +export function bridgeExternalAbortSignal( + externalSignal?: AbortSignal, + hooks?: AbortBridgeHooks, +): { signal?: AbortSignal + controller: AbortController dispose: () => void } { + const controller = hooks?.controller ?? new AbortController() + // The hook is invoked from one place per abort path so a provider side effect + // cannot be run twice for the same cancellation. + const notify = (reason?: unknown): void => { + if (!hooks?.onAbort) { + return + } + hooks.onAbort(reason) + } + if (!externalSignal) { - return { signal: undefined, dispose: () => {} } + // No caller signal: the request-local controller is still handed back, so a + // provider that needs a signal for its own races or timer keeps one without + // relaying anything. + return { signal: undefined, controller, dispose: () => {} } } - const controller = new AbortController() if (externalSignal.aborted) { controller.abort() - return { signal: controller.signal, dispose: () => {} } + notify(externalSignal.reason) + return { signal: controller.signal, controller, dispose: () => {} } } // Retain the callback so the listener can be detached once this request // ends: an anonymous listener on a long-lived external signal would // outlive the request and retain the per-request controller. - const onExternalAbort = () => controller.abort() + const onExternalAbort = (): void => { + const reason = externalSignal.reason + controller.abort() + notify(reason) + } externalSignal.addEventListener("abort", onExternalAbort, { once: true }) return { signal: controller.signal, + controller, dispose: () => externalSignal.removeEventListener("abort", onExternalAbort), } } @@ -296,17 +344,6 @@ export function settleOnAbort( return signal ? rejectOnAbort(pending, signal, providerName) : pending } -/** - * A per-request timeout is not a caller cancellation: report it as the distinct TimeoutError so - * callers can tell a stalled request from a user stop. A caller stop keeps using - * {@link createAbortError}; this error is only for a deadline the request itself hit. - */ -export function createTimeoutError(providerName: string): Error { - const timeoutError = new Error(`The ${providerName} completion request timed out`) - timeoutError.name = "TimeoutError" - return timeoutError -} - /** * Whether an abort-shaped failure came from the merged signal's own timeout rather than from the * caller's stop signal. diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 672922415a..a725a19b6f 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -18,10 +18,23 @@ export function getRequestTimeoutMs(timeoutMs?: number): number | undefined { * Fresh error for a per-request deadline elapsing in a given phase. * * Distinct from the abort contract error on purpose: a timeout is not a user - * cancellation, and callers treat the two differently. + * cancellation, and callers treat the two differently. This is the only place the + * timeout error is built: `abort-signal.ts` used to carry a second, phase-less + * definition, so callers of the two modules assembled the same report from + * different code. + * + * `cause` carries the failure a deadline was detected through - a stalled response + * body, an SDK rejection raised after the timer fired - so the report keeps both + * the deadline that elapsed and what the request was waiting on. It is left unset + * when the caller has no underlying failure to report. */ -export function createTimeoutError(providerName: string, phase: "model discovery" | "completion request"): Error { - const timeoutError = new Error(`The ${providerName} ${phase} timed out`) +export function createTimeoutError( + providerName: string, + phase: "model discovery" | "completion request", + cause?: unknown, +): Error { + const message = `The ${providerName} ${phase} timed out` + const timeoutError = cause === undefined ? new Error(message) : new Error(message, { cause }) timeoutError.name = "TimeoutError" return timeoutError }