Skip to content
12 changes: 10 additions & 2 deletions src/api/providers/__tests__/friendli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})

Expand Down
28 changes: 28 additions & 0 deletions src/api/providers/__tests__/qwen-code.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Comment thread
easonLiangWorldedtech marked this conversation as resolved.
Resolved
})

it("passes the merged signal through and nothing without options", async () => {
Expand Down
47 changes: 13 additions & 34 deletions src/api/providers/bedrock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

/************************************************************************************
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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()
}
}

Expand Down
10 changes: 7 additions & 3 deletions src/api/providers/friendli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
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"
Expand Down Expand Up @@ -109,7 +109,8 @@
} catch {
// Classified below: only a cut-short wait is fatal.
}
if (isTimeoutAbort(signal)) throw createTimeoutError(this.providerName)
// The wait is the model catalog load, so a deadline seen here is model discovery.
if (isTimeoutAbort(signal)) throw createTimeoutError(this.providerName, "model discovery")
if (signal?.aborted) throw createAbortError(this.providerName)
}

Expand Down Expand Up @@ -272,7 +273,10 @@
const deadline = hasUsableTimeout(timeoutMs) ? Date.now() + timeoutMs : undefined
await this.waitForCatalog(options?.abortSignal, timeoutMs)
const remainingMs = deadline === undefined ? undefined : deadline - Date.now()
if (remainingMs !== undefined && remainingMs <= 0) throw createTimeoutError(this.providerName)
// The wait succeeded but spent the shared deadline: the completion never got a turn.
if (remainingMs !== undefined && remainingMs <= 0) {

Check warning on line 277 in src/api/providers/friendli.ts

View workflow job for this annotation

GitHub Actions / mutation-diff

Mutation test advisory

src/api/providers/friendli.ts:277: Survived ConditionalExpression mutant (replacement: true). See the job summary for the complete list and resolution guidance.
throw createTimeoutError(this.providerName, "completion request")
}
const { id: modelId } = this.getModel()
const friendliExtra = this.buildFriendliReasoningParams()

Expand Down
6 changes: 4 additions & 2 deletions src/api/providers/lm-studio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ import {
mergeAbortSignalAndTimeout,
throwIfAborted,
createAbortError,
createTimeoutError,
isRequestAborted,
isTimeoutAbort,
settleOnAbort,
type OpenAiRequestOptions,
} from "./utils/abort-signal"
import { createTimeoutError } from "./utils/request-timeout"
import { handleOpenAIError } from "./utils/error-handler"
import { extractReasoningFromDelta } from "./utils/extract-reasoning"

Expand Down Expand Up @@ -330,7 +330,9 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan
* and the outer completion catch, so it lives in one helper.
*/
private toCompletionAbortError(requestSignal: AbortSignal | undefined): Error {
return isTimeoutAbort(requestSignal) ? createTimeoutError("LM Studio") : createAbortError("LM Studio")
return isTimeoutAbort(requestSignal)
? createTimeoutError("LM Studio", "completion request")
: createAbortError("LM Studio")
}

async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
Expand Down
6 changes: 4 additions & 2 deletions src/api/providers/qwen-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
Expand Down
98 changes: 88 additions & 10 deletions src/api/providers/utils/__tests__/abort-signal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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)
})
})

Expand All @@ -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)
Expand All @@ -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)
})
Expand Down
24 changes: 24 additions & 0 deletions src/api/providers/utils/__tests__/request-timeout.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
Loading
Loading