Skip to content

Commit 865ae0d

Browse files
author
f0-1528
committed
fix(openai-native): gate the readiness waits, keep the status when the error body read fails
Thread 4509766237 - the five readiness gates at spec 522/550/569/1271/2050 did not gate. vitest 4.1.12 keeps vi.waitFor live beside vi.waitUntil, but in dist/chunks/test.DNmyFkvJ.js waitFor hands a non-thenable result straight to onResolve and returns, so a predicate that evaluates false resolves the wait on the first check; waitUntil's onResolve starts with if (!result) return and polls until the timeout. The five sites now use vi.waitUntil with the predicates, timeouts and intervals unchanged, so the abort on the following line is placed mid-request as the comments already claimed. Thread 4509766269 - a body read that fails after the 429/503 headers arrived lost the numeric status, because the read at :765 sat outside the guarded parse and the outer catch had no status to recover. The read is guarded now: a cancelled read still surfaces as the contract AbortError, and a failed read carries the reason as the body text so the friendly status message and the status-carrying throw at the end of the block still apply. Control: the new 429 test is red without the guard (Tests 1 failed | 129 passed) and green with it (130 passed). Thread 4509766254 - spec 1542 now asserts the captured ApiProviderError's operation. Mutating the SDK-path operation literal to another value fails that assertion and nothing else (Tests 1 failed | 129 passed at :1542:53), which is what the old expect.any(ApiProviderError) could not do.
1 parent b13d8c9 commit 865ae0d

2 files changed

Lines changed: 83 additions & 6 deletions

File tree

‎src/api/providers/__tests__/openai-native.spec.ts‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ describe("OpenAiNativeHandler", () => {
519519
// The abort must land mid-request, so poll the observable that the request
520520
// exists - the fetch double having been called - instead of a wall-clock delay.
521521
// The explicit timeout is what makes a condition that never fires fail the test.
522-
await vi.waitFor(() => mockFetch.mock.calls.length > 0, { timeout: 2000, interval: 25 })
522+
await vi.waitUntil(() => mockFetch.mock.calls.length > 0, { timeout: 2000, interval: 25 })
523523
controller.abort()
524524

525525
await expect(collected).rejects.toMatchObject({ name: "AbortError" })
@@ -547,7 +547,7 @@ describe("OpenAiNativeHandler", () => {
547547
const firstCollected = collectStream(firstStream)
548548
// Observable: the first request has registered an in-flight stream. The
549549
// explicit timeout keeps a condition that never fires from idling to green.
550-
await vi.waitFor(() => openStreams.length >= 1, { timeout: 2000, interval: 25 })
550+
await vi.waitUntil(() => openStreams.length >= 1, { timeout: 2000, interval: 25 })
551551
requireController(0).enqueue(
552552
new TextEncoder().encode('data: {"type":"response.text.delta","delta":"one"}\n\n'),
553553
)
@@ -566,7 +566,7 @@ describe("OpenAiNativeHandler", () => {
566566
const secondCollected = collectStream(secondStream)
567567
// Observable: both requests are in flight; the length assertion stays because
568568
// polling replaces the sleep, not the assertion.
569-
await vi.waitFor(() => openStreams.length >= 2, { timeout: 2000, interval: 25 })
569+
await vi.waitUntil(() => openStreams.length >= 2, { timeout: 2000, interval: 25 })
570570
expect(openStreams).toHaveLength(2)
571571

572572
// Aborting the FIRST request's signal must not leak into the second request.
@@ -1268,7 +1268,7 @@ describe("OpenAiNativeHandler", () => {
12681268
// Abort first, then let the stream fail: the failure is the real outcome.
12691269
// Observable: the reader has entered pull and is parked on the gate. Polling it, then
12701270
// flushing one macrotask so the pending read is registered, replaces the fixed 10ms sleep.
1271-
await vi.waitFor(() => pullStarted, { timeout: 2000, interval: 10 })
1271+
await vi.waitUntil(() => pullStarted, { timeout: 2000, interval: 10 })
12721272
await flushMacrotasks()
12731273
controller.abort()
12741274
releaseStream()
@@ -1537,6 +1537,9 @@ describe("OpenAiNativeHandler", () => {
15371537
// from error reporting just because the abort won the race.
15381538
expect(mockCaptureException).toHaveBeenCalledTimes(1)
15391539
expect(mockCaptureException).toHaveBeenCalledWith(expect.any(ApiProviderError))
1540+
// The attribution is the reason for capturing it: retry and the error surface read
1541+
// operation, so an empty or missing one has to fail here rather than pass quietly.
1542+
expect(mockCaptureException.mock.calls[0]?.[0]).toMatchObject({ operation: "createMessage" })
15401543
})
15411544

15421545
it("should keep a streaming request's controller when completePrompt uses its own signal", async () => {
@@ -2047,7 +2050,7 @@ describe("OpenAiNativeHandler", () => {
20472050
const pending = handler.completePrompt("Test prompt", { abortSignal: controller.signal })
20482051
// Observable: the SDK call has been issued with the request signal, so the abort now
20492052
// arrives mid-request instead of after a wall-clock delay.
2050-
await vi.waitFor(() => sdkRequestStarted, { timeout: 2000, interval: 25 })
2053+
await vi.waitUntil(() => sdkRequestStarted, { timeout: 2000, interval: 25 })
20512054
controller.abort()
20522055

20532056
await expect(pending).rejects.toMatchObject({
@@ -3247,6 +3250,64 @@ describe("OpenAiNativeHandler", () => {
32473250
beforeEach(() => {
32483251
mockCaptureException.mockClear()
32493252
})
3253+
it("should keep the numeric status when the error-response body read fails on a 429", async () => {
3254+
// The 429 headers are already in hand and only the body read fails. A connection
3255+
// failure that drops the status would leave retry and backoff without the number
3256+
// they act on, so the synthesized failure has to carry it.
3257+
const mockFetch = vitest.fn().mockResolvedValue({
3258+
ok: false,
3259+
status: 429,
3260+
statusText: "Too Many Requests",
3261+
text: () => Promise.reject(new Error("socket hang up while reading the error body")),
3262+
})
3263+
global.fetch = mockFetch as typeof fetch
3264+
3265+
// Mock SDK to fail so it falls back to fetch
3266+
mockResponsesCreate.mockRejectedValue(new Error("SDK not available"))
3267+
3268+
handler = new OpenAiNativeHandler({ ...mockOptions, apiModelId: "gpt-5.1" })
3269+
3270+
const error = await collectStream(handler.createMessage(errorSystemPrompt, errorMessages)).then(
3271+
() => undefined,
3272+
(e: unknown) => e,
3273+
)
3274+
3275+
expect(error).toMatchObject({ status: 429 })
3276+
expect(error).toBeInstanceOf(Error)
3277+
expect((error as Error).message).toContain("Rate limit exceeded")
3278+
expect((error as Error).message).toContain("could not be read")
3279+
// Captured once, as every other terminal failure is: the read failure must not
3280+
// double-report the request just because the body never arrived.
3281+
expect(mockCaptureException).toHaveBeenCalledTimes(1)
3282+
expect(mockCaptureException).toHaveBeenCalledWith(expect.any(ApiProviderError))
3283+
deleteGlobalFetch()
3284+
})
3285+
3286+
it("should keep the contract AbortError when the caller aborts during the error body read", async () => {
3287+
// The cancellation is the caller's act, not a failed read: it must still surface as
3288+
// the AbortError the abort contract promises, with no status invented for it.
3289+
const mockFetch = vitest.fn().mockResolvedValue({
3290+
ok: false,
3291+
status: 503,
3292+
statusText: "Service Unavailable",
3293+
text: () =>
3294+
Promise.reject(Object.assign(new Error("The operation was aborted"), { name: "AbortError" })),
3295+
})
3296+
global.fetch = mockFetch as typeof fetch
3297+
3298+
mockResponsesCreate.mockRejectedValue(new Error("SDK not available"))
3299+
3300+
handler = new OpenAiNativeHandler({ ...mockOptions, apiModelId: "gpt-5.1" })
3301+
3302+
const error = await collectStream(handler.createMessage(errorSystemPrompt, errorMessages)).then(
3303+
() => undefined,
3304+
(e: unknown) => e,
3305+
)
3306+
3307+
expect(error).toMatchObject({ name: "AbortError" })
3308+
expect((error as { status?: unknown }).status).toBeUndefined()
3309+
deleteGlobalFetch()
3310+
})
32503311

32513312
it("should capture telemetry on createMessage error", async () => {
32523313
// Mock fetch to return error

‎src/api/providers/openai-native.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,23 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio
762762
})
763763

764764
if (!response.ok) {
765-
const errorText = await response.text()
765+
// The status is already in hand, so a body read that fails must not lose it:
766+
// retry, backoff and the UI read the numeric status, not the message text. A
767+
// cancelled read is the other case: it keeps surfacing as the contract
768+
// AbortError through the catch below. A failed-but-not-cancelled read keeps the
769+
// status by carrying on with the reason as the body text, which the parse below
770+
// turns into error details so the friendly status message and the
771+
// status-carrying throw at the end of this block still apply.
772+
let errorText: string
773+
try {
774+
errorText = await response.text()
775+
} catch (bodyReadError) {
776+
if (bodyReadError instanceof Error && bodyReadError.name === "AbortError") {
777+
throw bodyReadError
778+
}
779+
const reason = bodyReadError instanceof Error ? bodyReadError.message : String(bodyReadError)
780+
errorText = `the error response body could not be read (${reason})`
781+
}
766782

767783
let errorMessage = `OpenAI Responses API request failed (${response.status})`
768784
let errorDetails = ""

0 commit comments

Comments
 (0)