Skip to content

Commit 81f3e56

Browse files
author
dsh-agent
committed
fix(anthropic-family): forward timeoutMs only when the SDK can take it
The four completePrompt copies forwarded any defined timeoutMs. The Anthropic SDK turns timeout: 0 into an immediate abort and its request validation throws on negative, NaN and Infinity, so the series convention (timeoutMs <= 0 or non-finite means no explicit timeout) must leave the option absent. Fractional delays are rounded up, matching mergeAbortSignalAndTimeout. hasUsableTimeout is the shared predicate: it also backs mergeAbortSignalAndTimeout, so the rule is single-sourced for both the option and the signal.
1 parent efb3b4f commit 81f3e56

10 files changed

Lines changed: 109 additions & 42 deletions

File tree

‎src/api/providers/__tests__/anthropic-vertex.spec.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1089,7 +1089,7 @@ describe("VertexHandler", () => {
10891089
)
10901090
})
10911091

1092-
it("completePrompt should pass timeout when timeoutMs=0 (defined check)", async () => {
1092+
it("completePrompt should not forward an unusable timeoutMs", async () => {
10931093
handler = new AnthropicVertexHandler({
10941094
apiModelId: "claude-3-5-sonnet-v2@20241022",
10951095
vertexProjectId: "test-project",
@@ -1100,13 +1100,13 @@ describe("VertexHandler", () => {
11001100
.spyOn(handler["client"].messages, "create")
11011101
.mockResolvedValue({ content: [{ type: "text", text: "response" }] } as never)
11021102

1103-
await handler.completePrompt("test prompt", { timeoutMs: 0 })
1104-
// 0 is a defined value: it must reach the client as `timeout: 0`,
1105-
// not be dropped by a truthiness check.
1106-
expect(mockCreate).toHaveBeenCalledWith(
1107-
expect.objectContaining({ model: expect.any(String) }),
1108-
expect.objectContaining({ timeout: 0 }),
1109-
)
1103+
// The SDK turns timeout: 0 into an immediate abort and rejects
1104+
// negative/non-finite delays, so "no explicit timeout" means no option.
1105+
for (const timeoutMs of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
1106+
mockCreate.mockClear()
1107+
await handler.completePrompt("test prompt", { timeoutMs })
1108+
expect(mockCreate).toHaveBeenCalledWith(expect.any(Object), undefined)
1109+
}
11101110
})
11111111

11121112
it("should handle empty content array for Claude", async () => {

‎src/api/providers/__tests__/anthropic.spec.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,12 +1138,26 @@ describe("AnthropicHandler", () => {
11381138
expect(mockCreate).toHaveBeenCalledWith(expect.any(Object), undefined)
11391139
})
11401140

1141-
it("should pass timeout when timeoutMs=0 (defined check)", async () => {
1141+
it("should not forward an unusable timeoutMs (0, negative, non-finite)", async () => {
1142+
// The Anthropic SDK turns timeout: 0 into an immediate abort and throws
1143+
// on negative/non-finite delays, so "no explicit timeout" must mean the
1144+
// option is absent rather than 0.
1145+
for (const timeoutMs of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
1146+
mockCreate.mockClear()
1147+
mockCreate.mockResolvedValueOnce({ content: [{ type: "text", text: "response" }] })
1148+
await handler.completePrompt("test prompt", { timeoutMs })
1149+
expect(mockCreate).toHaveBeenCalledWith(
1150+
expect.objectContaining({ model: mockOptions.apiModelId }),
1151+
undefined,
1152+
)
1153+
}
1154+
})
1155+
1156+
it("should round a fractional timeoutMs up before forwarding it", async () => {
11421157
mockCreate.mockResolvedValueOnce({ content: [{ type: "text", text: "response" }] })
1143-
await handler.completePrompt("test prompt", { timeoutMs: 0 })
1144-
// timeoutMs=0 must be forwarded as an explicit 0 timeout, not dropped as if unset
1158+
await handler.completePrompt("test prompt", { timeoutMs: 12.5 })
11451159
expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: mockOptions.apiModelId }), {
1146-
timeout: 0,
1160+
timeout: 13,
11471161
})
11481162
})
11491163
})

‎src/api/providers/__tests__/minimax.spec.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -286,15 +286,18 @@ describe("MiniMaxHandler", () => {
286286
})
287287
})
288288

289-
it("should pass timeout when timeoutMs=0 (defined check)", async () => {
290-
mockCreate.mockResolvedValueOnce({
291-
content: [{ type: "text", text: "response" }],
292-
})
293-
await handler.completePrompt("test prompt", { timeoutMs: 0 })
294-
expect(mockCreate).toHaveBeenCalledWith(
295-
expect.objectContaining({ model: expect.any(String) }),
296-
{ timeout: 0 }, // !== undefined check means 0 is passed through
297-
)
289+
it("should not forward an unusable timeoutMs", async () => {
290+
// "No explicit timeout" must leave the option absent: timeout: 0 aborts
291+
// immediately and negative/non-finite delays throw inside the SDK.
292+
for (const timeoutMs of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
293+
mockCreate.mockClear()
294+
mockCreate.mockResolvedValueOnce({ content: [{ type: "text", text: "response" }] })
295+
await handler.completePrompt("test prompt", { timeoutMs })
296+
expect(mockCreate).toHaveBeenCalledWith(
297+
expect.objectContaining({ model: expect.any(String) }),
298+
undefined,
299+
)
300+
}
298301
})
299302

300303
it("completePrompt should send the configured temperature, user message and stream flag", async () => {

‎src/api/providers/__tests__/xai.spec.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -396,14 +396,18 @@ describe("XAIHandler", () => {
396396
})
397397
})
398398

399-
it("completePrompt should pass timeout when timeoutMs=0 (defined check)", async () => {
400-
mockResponsesCreate.mockResolvedValueOnce({ output_text: "response" })
401-
402-
await handler.completePrompt("test prompt", { timeoutMs: 0 })
403-
expect(mockResponsesCreate).toHaveBeenCalledWith(
404-
expect.objectContaining({ model: expect.any(String) }),
405-
{ timeout: 0 }, // !== undefined check means 0 is passed through
406-
)
399+
it("completePrompt should not forward an unusable timeoutMs", async () => {
400+
// "No explicit timeout" must leave the option absent: timeout: 0 aborts
401+
// immediately and negative/non-finite delays throw inside the SDK.
402+
for (const timeoutMs of [0, -5, Number.NaN, Number.POSITIVE_INFINITY]) {
403+
mockResponsesCreate.mockClear()
404+
mockResponsesCreate.mockResolvedValueOnce({ output_text: "response" })
405+
await handler.completePrompt("test prompt", { timeoutMs })
406+
expect(mockResponsesCreate).toHaveBeenCalledWith(
407+
expect.objectContaining({ model: expect.any(String) }),
408+
undefined,
409+
)
410+
}
407411
})
408412

409413
it("should include reasoning effort for mini models in Responses API format", async () => {

‎src/api/providers/anthropic-vertex.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
} from "../../core/prompts/tools/native-tools/converters"
2525

2626
import { BaseProvider } from "./base-provider"
27-
import { bridgeExternalAbortSignal } from "./utils/abort-signal"
27+
import { bridgeExternalAbortSignal, hasUsableTimeout } from "./utils/abort-signal"
2828
import { NOT_PROVIDED } from "./constants"
2929
import { parseVertexJsonCredentials } from "./utils/vertex-credentials"
3030
import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index"
@@ -340,8 +340,12 @@ export class AnthropicVertexHandler extends BaseProvider implements SingleComple
340340
if (options?.abortSignal) {
341341
requestOptions.signal = options.abortSignal
342342
}
343-
if (options?.timeoutMs !== undefined) {
344-
requestOptions.timeout = options.timeoutMs
343+
const timeoutMs = options?.timeoutMs
344+
// Only a usable finite positive timeout may be forwarded: the SDKs treat
345+
// timeout: 0 as an immediate abort and throw on negative/non-finite values.
346+
// Fractional delays are rounded up, matching mergeAbortSignalAndTimeout.
347+
if (hasUsableTimeout(timeoutMs)) {
348+
requestOptions.timeout = Math.ceil(timeoutMs)
345349
}
346350

347351
const response = await this.client.messages.create(

‎src/api/providers/anthropic.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import { filterNonAnthropicBlocks } from "../transform/anthropic-filter"
2121
import { getAnthropicProviderReasoning } from "../transform/reasoning"
2222

2323
import { BaseProvider } from "./base-provider"
24-
import { bridgeExternalAbortSignal } from "./utils/abort-signal"
24+
import { bridgeExternalAbortSignal, hasUsableTimeout } from "./utils/abort-signal"
2525
import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index"
2626
import { calculateApiCostAnthropic } from "../../shared/cost"
2727
import {
@@ -467,8 +467,12 @@ export class AnthropicHandler extends BaseProvider implements SingleCompletionHa
467467
if (options?.abortSignal) {
468468
requestOptions.signal = options.abortSignal
469469
}
470-
if (options?.timeoutMs !== undefined) {
471-
requestOptions.timeout = options.timeoutMs
470+
const timeoutMs = options?.timeoutMs
471+
// Only a usable finite positive timeout may be forwarded: the SDKs treat
472+
// timeout: 0 as an immediate abort and throw on negative/non-finite values.
473+
// Fractional delays are rounded up, matching mergeAbortSignalAndTimeout.
474+
if (hasUsableTimeout(timeoutMs)) {
475+
requestOptions.timeout = Math.ceil(timeoutMs)
472476
}
473477

474478
message = await this.client.messages.create(

‎src/api/providers/minimax.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { getModelParams } from "../transform/model-params"
1313
import { mergeEnvironmentDetailsForMiniMax } from "../transform/minimax-format"
1414

1515
import { BaseProvider } from "./base-provider"
16-
import { bridgeExternalAbortSignal } from "./utils/abort-signal"
16+
import { bridgeExternalAbortSignal, hasUsableTimeout } from "./utils/abort-signal"
1717
import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index"
1818
import { calculateApiCostAnthropic } from "../../shared/cost"
1919
import { convertOpenAIToolsToAnthropic } from "../../core/prompts/tools/native-tools/converters"
@@ -316,8 +316,12 @@ export class MiniMaxHandler extends BaseProvider implements SingleCompletionHand
316316
if (options?.abortSignal) {
317317
requestOptions.signal = options.abortSignal
318318
}
319-
if (options?.timeoutMs !== undefined) {
320-
requestOptions.timeout = options.timeoutMs
319+
const timeoutMs = options?.timeoutMs
320+
// Only a usable finite positive timeout may be forwarded: the SDKs treat
321+
// timeout: 0 as an immediate abort and throw on negative/non-finite values.
322+
// Fractional delays are rounded up, matching mergeAbortSignalAndTimeout.
323+
if (hasUsableTimeout(timeoutMs)) {
324+
requestOptions.timeout = Math.ceil(timeoutMs)
321325
}
322326

323327
const message = await this.client.messages.create(

‎src/api/providers/utils/__tests__/abort-signal.spec.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
createAbortError,
44
isRequestAborted,
55
mergeAbortSignalAndTimeout,
6+
hasUsableTimeout,
67
mergeAbortSignals,
78
rejectOnAbort,
89
resolveModelWithAbort,
@@ -513,3 +514,19 @@ describe("bridgeExternalAbortSignal", () => {
513514
expect(signal?.aborted).toBe(false)
514515
})
515516
})
517+
518+
describe("hasUsableTimeout", () => {
519+
it("accepts only finite positive values", () => {
520+
expect(hasUsableTimeout(1)).toBe(true)
521+
expect(hasUsableTimeout(50)).toBe(true)
522+
expect(hasUsableTimeout(12.5)).toBe(true)
523+
})
524+
525+
it("rejects values the SDK timeout option cannot take", () => {
526+
expect(hasUsableTimeout(undefined)).toBe(false)
527+
expect(hasUsableTimeout(0)).toBe(false)
528+
expect(hasUsableTimeout(-5)).toBe(false)
529+
expect(hasUsableTimeout(Number.NaN)).toBe(false)
530+
expect(hasUsableTimeout(Number.POSITIVE_INFINITY)).toBe(false)
531+
})
532+
})

‎src/api/providers/utils/abort-signal.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
/**
2+
* Whether a timeout value is usable as an SDK `timeout` option: a finite
3+
* number greater than zero.
4+
*
5+
* The value `0` means "no explicit timeout" across this series (the SDKs turn
6+
* `timeout: 0` into an immediate abort), and negative, `NaN`, `Infinity` and
7+
* fractional values make the SDK's own validation throw — so none of them may
8+
* be forwarded.
9+
*/
10+
export function hasUsableTimeout(timeoutMs?: number): timeoutMs is number {
11+
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
12+
}
13+
114
/**
215
* Merge an optional external abort signal with an optional timeout.
316
*
@@ -12,7 +25,7 @@ export function mergeAbortSignalAndTimeout(externalSignal?: AbortSignal, timeout
1225
// abort almost immediately; treat non-finite values as "no timeout",
1326
// round fractional delays up to whole milliseconds (uint32 validation
1427
// throws for 1500.5), and cap the rest.
15-
const hasTimeout = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
28+
const hasTimeout = hasUsableTimeout(timeoutMs)
1629

1730
if (!hasTimeout) {
1831
return externalSignal

‎src/api/providers/xai.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { getModelParams } from "../transform/model-params"
1313

1414
import { DEFAULT_HEADERS, NOT_PROVIDED } from "./constants"
1515
import { BaseProvider } from "./base-provider"
16-
import { bridgeExternalAbortSignal, createAbortError, isRequestAborted } from "./utils/abort-signal"
16+
import { bridgeExternalAbortSignal, createAbortError, hasUsableTimeout, isRequestAborted } from "./utils/abort-signal"
1717
import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index"
1818
import { handleOpenAIError } from "./utils/error-handler"
1919
import { isMcpTool } from "../../utils/mcp-name"
@@ -188,8 +188,12 @@ export class XAIHandler extends BaseProvider implements SingleCompletionHandler
188188
if (options?.abortSignal) {
189189
requestOptions.signal = options.abortSignal
190190
}
191-
if (options?.timeoutMs !== undefined) {
192-
requestOptions.timeout = options.timeoutMs
191+
const timeoutMs = options?.timeoutMs
192+
// Only a usable finite positive timeout may be forwarded: the SDKs treat
193+
// timeout: 0 as an immediate abort and throw on negative/non-finite values.
194+
// Fractional delays are rounded up, matching mergeAbortSignalAndTimeout.
195+
if (hasUsableTimeout(timeoutMs)) {
196+
requestOptions.timeout = Math.ceil(timeoutMs)
193197
}
194198

195199
const response = await this.client.responses.create(

0 commit comments

Comments
 (0)