From c6f18d3e15febd1fb0d89055f6ff15aefe16a81a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:43:42 +0800 Subject: [PATCH] feat(api): add the shared abort, timeout and error plumbing (#1311 split u0) Unit u0 of the split plan in #2799. It carries the shared helpers that the provider units of #1311 consume, and nothing provider-specific. - abort-signal.ts: mergeAbortSignalAndTimeout, rejectOnAbort, and the timeout classification helpers (isTimeoutAbort, createTimeoutError). - error-handler.ts: handleOpenAIRequestError keeps an HTTP failure's identity over a racing abort and reports a deadline as TimeoutError. - request-timeout.ts: getRequestTimeoutMs for the per-request SDK timeout. - test-utils/errors.ts: captureError, used by the cancellation rows of the provider units. Evidence: 643 rows across the utils and test-utils specs pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. --- .../utils/__tests__/abort-signal.spec.ts | 19 +++ .../utils/__tests__/error-handler.spec.ts | 123 +++++++++++++++++- .../utils/__tests__/request-timeout.spec.ts | 11 ++ src/api/providers/utils/abort-signal.ts | 11 +- src/api/providers/utils/error-handler.ts | 44 +++++++ src/api/providers/utils/request-timeout.ts | 14 +- src/eslint-suppressions.json | 7 +- src/test-utils/__tests__/errors.spec.ts | 22 ++++ src/test-utils/errors.ts | 17 +++ 9 files changed, 250 insertions(+), 18 deletions(-) create mode 100644 src/test-utils/__tests__/errors.spec.ts create mode 100644 src/test-utils/errors.ts diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..7159732c59e 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -600,6 +600,25 @@ describe("abort-signal utilities", () => { expect(createAbortError("Qwen Code").message).toBe("The Qwen Code request was aborted") }) + it("keeps the supplied cause under the contract name and message", () => { + const cause = new Error("socket reset by peer") + const error = createAbortError("OpenAI", cause) + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + expect(error.cause).toBe(cause) + }) + + it("leaves the cause unset when the caller supplies none", () => { + const error = createAbortError("OpenAI") + + expect(error.name).toBe("AbortError") + expect(error.message).toBe("The OpenAI request was aborted") + // A bare new Error(message, { cause: undefined }) defines the property, so the absence is + // asserted rather than compared with undefined. + expect("cause" in error).toBe(false) + }) + it("returns a fresh error on each call", () => { expect(createAbortError("X")).not.toBe(createAbortError("X")) }) diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 3e6bfc9271a..436f05d86a6 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -1,4 +1,13 @@ -import { getNumericHttpStatus, handleOpenAIError, handleProviderError, hasNumericHttpStatus } from "../error-handler" +import { APIUserAbortError } from "openai" + +import { + getNumericHttpStatus, + handleOpenAIError, + handleOpenAIRequestError, + handleProviderError, + hasNumericHttpStatus, +} from "../error-handler" +import { isTimeoutAbort, mergeAbortSignals } from "../abort-signal" describe("handleProviderError", () => { const providerName = "TestProvider" @@ -424,3 +433,115 @@ describe("getNumericHttpStatus", () => { expect(getNumericHttpStatus(Object.assign(() => undefined, { statusCode: 429 }))).toBeUndefined() }) }) + +describe("handleOpenAIRequestError (abort awareness)", () => { + it("normalizes a generic error to a fresh AbortError when the caller signal aborted", () => { + const controller = new AbortController() + controller.abort() + const original = new Error("network failure") + + const result = handleOpenAIRequestError(original, "OpenAI", controller.signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("normalizes the SDK user-abort error when no signal was passed", () => { + const result = handleOpenAIRequestError(new APIUserAbortError(), "Zai") + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Zai request was aborted") + }) + + it("keeps a timeout-triggered SDK abort classified as a timeout when the caller did not abort", () => { + const original = new APIUserAbortError() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(original, "OpenAI", undefined, requestSignal) + + expect(result.name).toBe("TimeoutError") + expect(result.message).toBe("The OpenAI completion request timed out") + expect((result as Error & { cause?: unknown }).cause).toBe(original) + }) + + it("keeps the abort contract when the request signal has not aborted", () => { + // The guard must not assume a reason exists: an SDK abort can arrive while the + // merged request signal is still live, and reading .name on an undefined reason + // would turn a cancellation into a TypeError. + const result = handleOpenAIRequestError( + new APIUserAbortError(), + "OpenAI", + undefined, + new AbortController().signal, + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps a caller cancellation classified as an abort even when the request signal timed out", () => { + const controller = new AbortController() + controller.abort() + const requestSignal = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", controller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + it("keeps the abort contract for a caller that stops after a real merged signal timed out", () => { + // The row above approximates this interleaving with a signal it builds by hand. This one merges the + // way the providers merge: mergeAbortSignals is AbortSignal.any([caller, timeout]) (abort-signal.ts:67), + // reached from mergeAbortSignalAndTimeout (abort-signal.ts:52) and from + // config-builder/request-config-builder.ts:94 - the composition that produces the requestSignal handed + // to the guard at base-openai-compatible-provider.ts:344 and openai.ts:617. The timeout signal is + // already aborted when the merge is built, so "the deadline fired first" is a property of the fixture + // and not a race; the caller then stops its own controller, and the aggregate keeps the TimeoutError + // reason. Only the !abortSignal?.aborted term at error-handler.ts:186 can route this call to the abort + // contract, so this row is what pins "the caller's stop wins" for a genuine merged signal. + const caller = new AbortController() + const timedOut = AbortSignal.abort(new DOMException("The operation was aborted", "TimeoutError")) + const requestSignal = mergeAbortSignals(caller.signal, timedOut) + caller.abort() + + // These three assertions are the premise the classification rests on. A merged signal that stopped + // carrying a TimeoutError reason would make isTimeoutAbort false, and the fall-through at + // error-handler.ts:196-201 would then answer AbortError for the wrong reason - this row would stay + // green while the guard meant nothing. + expect(requestSignal.aborted, "the merge is already aborted by the timeout").toBe(true) + expect((requestSignal.reason as { name?: string } | undefined)?.name).toBe("TimeoutError") + expect(isTimeoutAbort(requestSignal), "the predicate the guard consults").toBe(true) + + const result = handleOpenAIRequestError(new APIUserAbortError(), "OpenAI", caller.signal, requestSignal) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The OpenAI request was aborted") + }) + + it("normalizes a native fetch-level AbortError when no signal was passed", () => { + const result = handleOpenAIRequestError( + Object.assign(new Error("aborted"), { name: "AbortError" }), + "Fireworks", + ) + + expect(result.name).toBe("AbortError") + expect(result.message).toBe("The Fireworks request was aborted") + }) + + it("keeps the provider-prefix wrap for a non-abort failure", () => { + const original = new Error("rate limited") + + const result = handleOpenAIRequestError(original, "OpenAI", new AbortController().signal) + + expect(result).not.toBe(original) + expect(result.name).toBe("Error") + expect(result.message).toBe("OpenAI completion error: rate limited") + }) + + it("falls back to the provider-prefix wrap when no signal is available", () => { + const result = handleOpenAIRequestError(new Error("boom"), "Kimi Code") + + expect(result.message).toBe("Kimi Code completion error: boom") + }) +}) diff --git a/src/api/providers/utils/__tests__/request-timeout.spec.ts b/src/api/providers/utils/__tests__/request-timeout.spec.ts index 8190faebe36..c9763e759d2 100644 --- a/src/api/providers/utils/__tests__/request-timeout.spec.ts +++ b/src/api/providers/utils/__tests__/request-timeout.spec.ts @@ -1,3 +1,4 @@ +import { MAX_TIMEOUT_MS } from "../abort-signal" import { createTimeoutError, getRequestTimeoutMs } from "../request-timeout" describe("getRequestTimeoutMs", () => { @@ -35,6 +36,16 @@ describe("getRequestTimeoutMs", () => { // (e.g. user settings); the double cast exercises the typeof guard. expect(getRequestTimeoutMs("5000" as unknown as number)).toBeUndefined() }) + + it("caps timeouts past the maximum timer delay instead of letting Node clamp them", () => { + // A delay above 2^31-1 ms is not a legal timer value: Node clamps it to ~1 ms, so an + // oversized setting would abort the request almost immediately rather than wait. The + // cap belongs here because this value also goes to the SDK's own timeout option. + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(MAX_TIMEOUT_MS + 1)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(2 ** 32)).toBe(MAX_TIMEOUT_MS) + expect(getRequestTimeoutMs(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIMEOUT_MS) + }) }) describe("createTimeoutError", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc124371..05fa373ae9f 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -159,8 +159,8 @@ export function isRequestAborted(error: unknown, signal?: AbortSignal): boolean * message "Request was aborted."), so raw SDK abort errors must be * normalized instead of rethrown. */ -export function createAbortError(providerName: string): Error { - const abortError = new Error(`The ${providerName} request was aborted`) +export function createAbortError(providerName: string, cause?: unknown): Error { + const abortError = new Error(`The ${providerName} request was aborted`, cause === undefined ? undefined : { cause }) abortError.name = "AbortError" return abortError } @@ -312,9 +312,10 @@ export function createTimeoutError(providerName: string): Error { * caller's stop signal. */ export function isTimeoutAbort(requestSignal: AbortSignal | undefined): boolean { - // Classify by the merged signal's retained abort reason: if its own timeout fired first, the - // reason stays the TimeoutError even when the caller aborts later, so the failure must still be - // reported as a deadline. A caller-first abort retains the caller's reason instead. + // Classify by the merged signal's retained abort reason: a deadline that fired first keeps the + // TimeoutError reason even if the caller stops later, so this answers only which signal fired + // first. handleOpenAIRequestError answers a caller that also pressed stop with the abort + // contract - error-handler.spec.ts:483-492 pins that answer for the interleaving. return Boolean( requestSignal?.aborted && (requestSignal.reason as { name?: string } | undefined)?.name === "TimeoutError", ) diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 2247ed182c4..96ce8e1fbd8 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -9,7 +9,11 @@ * - Enables telemetry and debugging with complete error context */ +import { APIUserAbortError } from "openai" + import i18n from "../../../i18n/setup" +import { createAbortError, isTimeoutAbort } from "./abort-signal" +import { createTimeoutError } from "./request-timeout" /** * Handles API provider errors and transforms them into user-friendly messages @@ -163,3 +167,43 @@ export function handleProviderError( export function handleOpenAIError(error: unknown, providerName: string): Error { return handleProviderError(error, providerName, { messagePrefix: "completion" }) } + +/** + * Handles errors from OpenAI Node SDK request sites with abort awareness. + * + * An abort failure (the external signal already aborted, the SDK's + * APIUserAbortError, or a fetch-level AbortError) is normalized to a fresh + * Error with name "AbortError" and a message ending in "aborted" (the Task.ts + * contract) instead of being wrapped as a regular completion error, which a + * plain rethrow of the SDK abort error would produce. + */ +export function handleOpenAIRequestError( + error: unknown, + providerName: string, + abortSignal?: AbortSignal, + requestSignal?: AbortSignal, +): Error { + // A terminal HTTP failure keeps its own identity even when the caller stops in the same tick: + // backoff reads the top-level status, so masking a 401/429 as AbortError hides the provider error. + if (hasNumericHttpStatus(error)) return handleOpenAIError(error, providerName) + + // The deadline, not the caller's stop, ended this request. Classified before the abort branch so a + // native AbortError raised by the SDK's JSON body read is reported as a timeout as well. + if (!abortSignal?.aborted && isTimeoutAbort(requestSignal)) { + // The abort came from this merged signal's own deadline, not the caller's stop: a timeout + // must stay distinguishable from a user cancellation, so the shared helper's name and + // message are used and the SDK abort is attached as the cause. A caller that pressed stop + // never reaches here - error-handler.spec.ts:483-492 pins the abort for that interleaving. + const timeoutError = createTimeoutError(providerName, "completion request") + timeoutError.cause = error + return timeoutError + } + + if ( + abortSignal?.aborted || + (error instanceof Error && (error.name === "AbortError" || error instanceof APIUserAbortError)) + ) { + return createAbortError(providerName, error) + } + return handleOpenAIError(error, providerName) +} diff --git a/src/api/providers/utils/request-timeout.ts b/src/api/providers/utils/request-timeout.ts index 672922415a5..89067ac80fd 100644 --- a/src/api/providers/utils/request-timeout.ts +++ b/src/api/providers/utils/request-timeout.ts @@ -1,17 +1,19 @@ +import { hasUsableTimeout, toSdkTimeoutMs } from "./abort-signal" + /** * Returns the value to pass as a client/SDK request timeout option, or undefined. * * Per the abort-signal series contract, timeoutMs <= 0, non-finite values * (or undefined) mean 'no per-request timeout': the option is omitted * entirely, because some SDKs (e.g. the OpenAI Node SDK) treat timeout: 0 as - * an IMMEDIATE timeout. Finite values are rounded up to whole milliseconds: - * downstream AbortSignal.timeout() validates its delay as uint32 and throws - * for fractions. + * an IMMEDIATE timeout. Values that do survive validation are handed to + * toSdkTimeoutMs, which rounds fractions up (AbortSignal.timeout validates its + * delay as uint32 and throws for fractions) and caps them at the maximum timer + * delay: a Node timer clamps anything past 2^31-1 ms to ~1 ms, which would + * abort the request almost immediately instead of honouring the timeout. */ export function getRequestTimeoutMs(timeoutMs?: number): number | undefined { - return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 - ? Math.ceil(timeoutMs) - : undefined + return hasUsableTimeout(timeoutMs) ? toSdkTimeoutMs(timeoutMs) : undefined } /** diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..2c46065d858 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -74,11 +74,6 @@ "count": 1 } }, - "api/providers/__tests__/kimi-code.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "api/providers/__tests__/lite-llm.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 26 @@ -191,7 +186,7 @@ }, "api/providers/base-openai-compatible-provider.ts": { "@typescript-eslint/no-explicit-any": { - "count": 6 + "count": 5 } }, "api/providers/base-provider.ts": { diff --git a/src/test-utils/__tests__/errors.spec.ts b/src/test-utils/__tests__/errors.spec.ts new file mode 100644 index 00000000000..c666b5e9774 --- /dev/null +++ b/src/test-utils/__tests__/errors.spec.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { captureError } from "../errors" + +describe("error capture utility", () => { + it("returns the rejecting Error instance untouched", async () => { + const original = new Error("provider failed") + + expect(await captureError(Promise.reject(original))).toBe(original) + }) + + it("re-wraps a non-Error rejection so the original failure message stays visible", async () => { + const captured = await captureError(Promise.reject("plain string failure")) + + expect(captured).toBeInstanceOf(Error) + expect(captured.message).toBe("plain string failure") + }) + + it("rejects when the operation resolves, because resolving violates the contract", async () => { + await expect(captureError(Promise.resolve("value"))).rejects.toThrow("Expected the operation to reject") + }) +}) diff --git a/src/test-utils/errors.ts b/src/test-utils/errors.ts new file mode 100644 index 00000000000..67d897b2423 --- /dev/null +++ b/src/test-utils/errors.ts @@ -0,0 +1,17 @@ +/** + * Captures the rejection of an operation as an `Error`. + * + * Provider abort normalization always throws an `Error`, but an awaited + * operation is typed `unknown`, so the guard keeps strict typing without + * casts. A non-Error rejection is re-wrapped so the original failure message + * stays visible, and a resolving operation — the contract violation the + * surrounding test exists to catch — becomes a failing assertion. + */ +export async function captureError(operation: Promise): Promise { + try { + await operation + } catch (error) { + return error instanceof Error ? error : new Error(String(error)) + } + throw new Error("Expected the operation to reject") +}