-
Notifications
You must be signed in to change notification settings - Fork 300
feat(api): abort signal support for openai-native and openai-compatible (completePrompt + createMessage) #1291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
easonLiangWorldedtech
wants to merge
31
commits into
Zoo-Code-Org:main
Choose a base branch
from
easonLiangWorldedtech:feat/abort-r1-openai-native-compat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,882
−24
Open
Changes from 5 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
3b899ce
feat(api): abort signal support for openai-native provider (completeP…
easonliang28 d53b955
feat(api): abort signal support for openai-compatible provider (compl…
easonliang28 2296b74
fix(api): address CodeRabbit review on openai-native and openai-compa…
easonliang28 176a0fa
test(api): clear leftover guard timers in openai-compatible abort tests
easonliang28 cb153ec
refactor(api): adopt RequestConfigBuilder in feat/abort-r1-openai-nat…
easonliang28 4702738
test(api): cover primary-signal abort in builder merge regression tests
easonliang28 f371082
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech 48e30d5
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech 1c925d0
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
easonliang28 7dee99d
Merge branch 'main' into feat/abort-r1-openai-native-compat
edelauna b16d5ad
test(api): kill abort-signal mutation survivors in openai-native/open…
easonliang28 118b921
test(api): exclude proven-equivalent openai-native OptionalChaining m…
easonliang28 ba72b77
fix(api): address reviewer abort-signal findings in openai-native and…
easonliang28 dfb93de
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
easonliang28 0488a39
test(api): reuse the open-stream fetch fixture and assert listener id…
easonliang28 1e22dfe
Merge branch main into feat/abort-r1-openai-native-compat
easonliang28 ad71368
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonLiangWorldedtech d9ec5a3
Merge branch 'main' into feat/abort-r1-openai-native-compat
easonliang28 e948680
fix(api): per-request abort check in fallback SSE loop and release bo…
easonliang28 df16983
fix(api): normalize completePrompt SDK aborts to the contract AbortError
easonliang28 bfc880c
fix(api): classify SDK cancellations from the error alone, never from…
easonliang28 4a07a4e
Merge remote-tracking branch 'upstream/main' into feat/abort-r1-opena…
3717280
preflight synthetic head
f9d5d00
test: kill catch-path mutants + document equivalent streamCompleted c…
fff974d
preflight synthetic head
5e983df
chore: re-trigger CI (flaky e2e-mock restart-persistence timeout)
8389c31
test(abort-r1): assert the fallback request signal and the empty stre…
32bbf6b
test(abort-r1): pin the fallback fetch to exactly one call
c942a45
fix(abort-r1): hand back the contract AbortError on a mid-stream abort
2541747
fix(abort-r1): report the contract AbortError when the SDK iterator e…
fa62d91
Merge commit 'refs/shapes/upstream-main' into feat/abort-r1-openai-na…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,297 @@ | ||
| // npx vitest run api/providers/__tests__/openai-compatible.spec.ts | ||
|
|
||
| import { OpenAICompatibleHandler } from "../openai-compatible" | ||
| import { makeApiHandlerOptions } from "../../../test-utils/api" | ||
| import { collectStream } from "../../../test-utils/stream" | ||
|
|
||
| const mockGenerateText = vitest.fn() | ||
| const mockStreamText = vitest.fn() | ||
|
|
||
| // The factory must not touch the mock bindings at factory-execution time (vi.mock is | ||
| // hoisted above the consts), so forward lazily through wrapper functions. | ||
| vitest.mock("ai", () => ({ | ||
| generateText: (...args: unknown[]) => mockGenerateText(...(args as [])), | ||
| streamText: (...args: unknown[]) => mockStreamText(...(args as [])), | ||
| })) | ||
|
|
||
| // Concrete test implementation of the abstract OpenAI-compatible base class | ||
| class TestOpenAICompatibleHandler extends OpenAICompatibleHandler { | ||
| constructor(apiKey: string) { | ||
| super(makeApiHandlerOptions({ apiModelId: "test-model" }), { | ||
| providerName: "TestProvider", | ||
| baseURL: "https://test.example.com/v1", | ||
| apiKey, | ||
| modelId: "test-model", | ||
| modelInfo: { | ||
| maxTokens: 4096, | ||
| contextWindow: 128000, | ||
| supportsImages: false, | ||
| supportsPromptCache: false, | ||
| inputPrice: 0.5, | ||
| outputPrice: 1.5, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| override getModel() { | ||
| return { id: "test-model", info: this.config.modelInfo } | ||
| } | ||
| } | ||
|
|
||
| function makeEmptyStreamResult() { | ||
| return { | ||
| fullStream: { | ||
| [Symbol.asyncIterator]: async function* () { | ||
| // Emit no parts | ||
| yield* [] | ||
| }, | ||
| }, | ||
| usage: Promise.resolve(undefined), | ||
| } | ||
| } | ||
|
|
||
| describe("OpenAICompatibleHandler", () => { | ||
| let handler: TestOpenAICompatibleHandler | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| handler = new TestOpenAICompatibleHandler("test-api-key") | ||
| }) | ||
|
|
||
| describe("completePrompt", () => { | ||
| it("should return message content from successful response", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const result = await handler.completePrompt("test prompt") | ||
|
|
||
| expect(result).toBe("response") | ||
| expect(mockGenerateText).toHaveBeenCalledTimes(1) | ||
| expect(mockGenerateText.mock.calls[0][0].prompt).toBe("test prompt") | ||
| }) | ||
|
|
||
| it("should pass abortSignal through to generateText", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const controller = new AbortController() | ||
| await handler.completePrompt("test prompt", { abortSignal: controller.signal }) | ||
|
|
||
| expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal) | ||
| }) | ||
|
|
||
| it("should pass timeoutMs through to generateText as a working timeout abort signal", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| await handler.completePrompt("test prompt", { timeoutMs: 50 }) | ||
|
|
||
| const { abortSignal } = mockGenerateText.mock.calls[0][0] | ||
| expect(abortSignal).toBeInstanceOf(AbortSignal) | ||
| expect(abortSignal.aborted).toBe(false) | ||
|
|
||
| // A never-expiring signal (or a pre-aborted one) would fail this check: | ||
| // the signal must fire on its own ~50ms timeout without any external abort. | ||
| let guardTimer: ReturnType<typeof setTimeout> | undefined | ||
| const fired = await Promise.race([ | ||
| new Promise<boolean>((resolve) => { | ||
| abortSignal.addEventListener("abort", () => resolve(true), { once: true }) | ||
| }), | ||
| new Promise<boolean>((resolve) => { | ||
| guardTimer = setTimeout(() => resolve(false), 1000) | ||
| }), | ||
| ]) | ||
| try { | ||
| expect(fired).toBe(true) | ||
| expect(abortSignal.aborted).toBe(true) | ||
| } finally { | ||
| // Clear the guard timer so a winning abort event does not leave an | ||
| // active timer behind that delays worker teardown. | ||
| clearTimeout(guardTimer) | ||
| } | ||
| }) | ||
|
|
||
| it("should merge signal and timeout when both are provided", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const controller = new AbortController() | ||
| await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 50 }) | ||
|
|
||
| const mergedSignal = mockGenerateText.mock.calls[0][0].abortSignal as AbortSignal | ||
| expect(mergedSignal).toBeInstanceOf(AbortSignal) | ||
| expect(mergedSignal.aborted).toBe(false) | ||
|
|
||
| // Aborting the external signal must abort the merged signal synchronously | ||
| controller.abort() | ||
| expect(mergedSignal.aborted).toBe(true) | ||
| }) | ||
|
|
||
| it("should let the timeout component of a merged signal fire without the caller signal", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| await handler.completePrompt("test prompt", { abortSignal: new AbortController().signal, timeoutMs: 50 }) | ||
|
|
||
| const mergedSignal = mockGenerateText.mock.calls[0][0].abortSignal as AbortSignal | ||
| expect(mergedSignal).toBeInstanceOf(AbortSignal) | ||
| expect(mergedSignal.aborted).toBe(false) | ||
|
|
||
| // With the caller signal left untouched, only the timeout component can fire | ||
| let guardTimer: ReturnType<typeof setTimeout> | undefined | ||
| const fired = await Promise.race([ | ||
| new Promise<boolean>((resolve) => { | ||
| mergedSignal.addEventListener("abort", () => resolve(true), { once: true }) | ||
| }), | ||
| new Promise<boolean>((resolve) => { | ||
| guardTimer = setTimeout(() => resolve(false), 1000) | ||
| }), | ||
| ]) | ||
| try { | ||
| expect(fired).toBe(true) | ||
| expect(mergedSignal.aborted).toBe(true) | ||
| } finally { | ||
| // Clear the guard timer so a winning abort event does not leave an | ||
| // active timer behind that delays worker teardown. | ||
| clearTimeout(guardTimer) | ||
| } | ||
| }) | ||
|
|
||
| it("should work without options (backward compatible)", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const result = await handler.completePrompt("test prompt") | ||
|
|
||
| expect(result).toBe("response") | ||
| expect(mockGenerateText.mock.calls[0][0].abortSignal).toBeUndefined() | ||
| }) | ||
|
|
||
| it("should treat timeoutMs <= 0 as disabled", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| await handler.completePrompt("test prompt", { timeoutMs: 0 }) | ||
| expect(mockGenerateText.mock.calls[0][0].abortSignal).toBeUndefined() | ||
|
|
||
| await handler.completePrompt("test prompt", { timeoutMs: -1 }) | ||
| expect(mockGenerateText.mock.calls[1][0].abortSignal).toBeUndefined() | ||
| }) | ||
|
|
||
| it("should pass the caller signal unchanged when timeoutMs is 0", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const controller = new AbortController() | ||
| await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: 0 }) | ||
|
|
||
| // A disabled timeout must not drop the caller's cancellation signal | ||
| expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal) | ||
| }) | ||
|
|
||
| it("should pass the caller signal unchanged when timeoutMs is negative", async () => { | ||
| mockGenerateText.mockResolvedValue({ text: "response" }) | ||
|
|
||
| const controller = new AbortController() | ||
| await handler.completePrompt("test prompt", { abortSignal: controller.signal, timeoutMs: -1 }) | ||
|
|
||
| expect(mockGenerateText.mock.calls[0][0].abortSignal).toBe(controller.signal) | ||
| }) | ||
|
|
||
| it("should reject with AbortError when abortSignal is already aborted before request", async () => { | ||
| mockGenerateText.mockImplementation((options: { abortSignal?: AbortSignal }) => { | ||
| if (options.abortSignal?.aborted) { | ||
| const error = new Error("This operation was aborted") | ||
| error.name = "AbortError" | ||
| return Promise.reject(error) | ||
| } | ||
| return Promise.resolve({ text: "response" }) | ||
| }) | ||
|
|
||
| const controller = new AbortController() | ||
| controller.abort() | ||
|
|
||
| await expect( | ||
| handler.completePrompt("test prompt", { abortSignal: controller.signal }), | ||
| ).rejects.toMatchObject({ | ||
| name: "AbortError", | ||
| }) | ||
| }) | ||
|
|
||
| it("should throw handled error when API call fails", async () => { | ||
| mockGenerateText.mockRejectedValue(new Error("Network error")) | ||
|
|
||
| await expect(handler.completePrompt("test prompt")).rejects.toThrow("Network error") | ||
| }) | ||
| }) | ||
|
|
||
| describe("createMessage", () => { | ||
| it("should pass the external abortSignal to streamText", async () => { | ||
| mockStreamText.mockReturnValue(makeEmptyStreamResult()) | ||
|
|
||
| const controller = new AbortController() | ||
| const stream = handler.createMessage("You are helpful.", [], { | ||
| taskId: "test", | ||
| abortSignal: controller.signal, | ||
| }) | ||
| await collectStream(stream) | ||
|
|
||
| expect(mockStreamText).toHaveBeenCalledTimes(1) | ||
| expect(mockStreamText.mock.calls[0][0].abortSignal).toBe(controller.signal) | ||
| }) | ||
|
|
||
| it("should not set an abortSignal when metadata has none", async () => { | ||
| mockStreamText.mockReturnValue(makeEmptyStreamResult()) | ||
|
|
||
| const stream = handler.createMessage("You are helpful.", [], { taskId: "test" }) | ||
| await collectStream(stream) | ||
|
|
||
| expect(mockStreamText.mock.calls[0][0].abortSignal).toBeUndefined() | ||
| }) | ||
|
|
||
| it("should reject with AbortError when the external abortSignal is pre-aborted", async () => { | ||
| mockStreamText.mockImplementation((options: { abortSignal?: AbortSignal }) => ({ | ||
| fullStream: { | ||
| [Symbol.asyncIterator]: async function* () { | ||
| if (options.abortSignal?.aborted) { | ||
| const error = new Error("This operation was aborted") | ||
| error.name = "AbortError" | ||
| throw error | ||
| } | ||
| yield* [] | ||
| }, | ||
| }, | ||
| usage: Promise.resolve(undefined), | ||
| })) | ||
|
|
||
| const controller = new AbortController() | ||
| controller.abort() | ||
|
|
||
| const stream = handler.createMessage("You are helpful.", [], { | ||
| taskId: "test", | ||
| abortSignal: controller.signal, | ||
| }) | ||
| await expect(collectStream(stream)).rejects.toMatchObject({ name: "AbortError" }) | ||
| }) | ||
|
|
||
| it("should abort the stream when the external abortSignal is aborted mid-request", async () => { | ||
| mockStreamText.mockImplementation((options: { abortSignal?: AbortSignal }) => ({ | ||
| fullStream: { | ||
| [Symbol.asyncIterator]: async function* () { | ||
| // Emulate a slow model response that ends when the request is aborted | ||
| await new Promise<void>((resolve) => { | ||
| options.abortSignal?.addEventListener("abort", () => resolve(), { once: true }) | ||
| }) | ||
| yield* [] | ||
| const error = new Error("This operation was aborted") | ||
| error.name = "AbortError" | ||
| throw error | ||
| }, | ||
| }, | ||
| usage: Promise.resolve(undefined), | ||
| })) | ||
|
|
||
| const controller = new AbortController() | ||
| const stream = handler.createMessage("You are helpful.", [], { | ||
| taskId: "test", | ||
| abortSignal: controller.signal, | ||
| }) | ||
| const collected = collectStream(stream) | ||
| setTimeout(() => controller.abort(), 10) | ||
|
|
||
| await expect(collected).rejects.toMatchObject({ name: "AbortError" }) | ||
| }) | ||
| }) | ||
| }) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.