Repository navigation
feat(api): honour caller cancellation in the openai family (#1311 split u1) - #2801
easonLiangWorldedtech wants to merge 4 commits into
Conversation
…-Org#1311 split u0) Unit u0 of the split plan in Zoo-Code-Org#2799. It carries the shared helpers that the provider units of Zoo-Code-Org#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.
Review statusThanks for contributing. This comment tracks the review sequence and the next action. Current step: Wait for required CI checks; awaiting-maintainer requires CI and automated review completion. Review-state labels are managed by this workflow; do not edit them manually. |
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Regression Evidence | Unit u1 (HEAD 91c6af4 vs u0 head c6f18d3) changes OpenAiHandler.completePrompt on the Responses route. The new code merges the caller signal with the deadline and classifies timeouts (src/api/provid… |
Add a provider-level test in src/api/providers/tests/openai.spec.ts for the Responses route. Set openAiUseResponsesApi: true, then call completePrompt("...", { timeoutMs: <small value> }) with no caller signal. Park the `mockRespons… |

Passed checks: 3 passed
-
Check name Status Explanation Security Boundaries The Security boundaries check fails only for a concrete defect in a changed path: an exposed secret or personal data, unvalidated input that is trusted or executed, or a bypassed approval or allowlist… Persistence Integrity The check applies only to changed persistence paths. PR #2801(head split/1311-u1-openai-family, base main, author easonLiangWorldedtech) changes OpenAI-family provider request and stream handling. Th…Lifecycle Resource Cleanup Checked the lifecycle paths changed in this unit (commit 91c6af4 against base c6f18d3) in openai.tsandbase-openai-compatible-provider.ts. No changed path leaks a listener, watcher, provider, tim…Full details: Security Boundaries
-
Explanation
The Security boundaries check fails only for a concrete defect in a changed path: an exposed secret or personal data, unvalidated input that is trusted or executed, or a bypassed approval or allowlist control. I found no such defect. Scope reviewed: - PR
#2801(Zoo-Code-Org/Zoo-Code, head split/1311-u1-openai-family, base main). Author: easonLiangWorldedtech. - The u1 commit (c6f18d3..91c6af4) changes openai.ts, base-openai-compatible-provider.ts, and their spec files. - The u0 commit (dd30249..c6f18d3), which the PR diff against main also includes, adds error-handler.ts, abort-signal.ts, request-timeout.ts, and config-builder helpers. What the changes do: - They add caller-cancellation and deadline plumbing. They use AbortSignal checks, a per-request SDK timeout, and error normalization to an AbortError or TimeoutError. - The Azure AI Inference path option is still set under the same condition. It is now built through setOption, which omits undefined values, so the request options are equivalent. - No new logging of request bodies, headers, or API keys appears in the diff. The only new key-like value is the placeholder "test-api-key" in the spec files. - No approval, allowlist, or permission gate is removed or skipped. Abort checks only stop work earlier. - The eslint-suppressions.json change removes one suppression and lowers another count. It does not add a suppression. - Error text from handleOpenAIRequestError reuses the existing handleOpenAIError path. Pre-existing logging in handleProviderError is unchanged. The check does not match these changes to any explicit failure condition.
Full details: Persistence Integrity
-
Explanation
The check applies only to changed persistence paths. PR
#2801(head split/1311-u1-openai-family, base main, author easonLiangWorldedtech) changes OpenAI-family provider request and stream handling. The 19 changed files cover openai.ts, base-openai-compatible-provider.ts, the utils abort/timeout/error helpers, test-utils, eslint-suppressions.json, and provider specs. Evidence gathered: - Added lines were scanned for disk, settings, secret, globalState/workspaceState, database, and flush or commit operations (writeFile, appendFile, rename, unlink, globalState, secrets, persist, save). No matches. The only.update(hits are in-memory stream parsers (matcher.update, signatureReader.update). - No fs or fs/promises calls were added, so no unawaited disk write was introduced. - ThoughtSignatureReader is an in-memory per-instance helper (openai.ts:167-168). The diff reorders its update call inside the stream loop, but it does not write to storage. - The utils changes (error-handler.ts, abort-signal.ts, request-timeout.ts) change error classification and timeout value computation. They do not touch stored state. No changed path writes persistent state, so no path can lose or corrupt persisted state under this check's criteria. The PR fails none of the listed conditions: un-awaited writes, non-atomic writes, missing rollback, or defaults that do not reach consumers.
Full details: Lifecycle Resource Cleanup
-
Explanation
Checked the lifecycle paths changed in this unit (commit 91c6af4 against base c6f18d3) in
openai.tsandbase-openai-compatible-provider.ts. No changed path leaks a listener, watcher, provider, timer, or task, and none repeats work after cancellation. - Listeners: The only listeners the changed code creates go throughrejectOnAbort/raceAbort(utils/abort-signal.ts:180-215). That helper detaches the abort listener when the pending promise settles or the abort fires, whichever comes first. The already-aborted branch attaches no listener.openai.tscompletePromptandbase-openai-compatible-provider.tscreateMessageboth use it. - Timers:mergeAbortSignalAndTimeout(openai.tsbuildCompletePromptRequestConfig,base-openai-compatible-provider.tscompletePrompt) usesAbortSignal.timeout(), which the code comment says manages its own timer.AbortSignal.anyis used for merging. NosetTimeout/setIntervalappears in the changed non-test code. - Early cancellation:throwIfAbortedruns before the merged signal or timeout is built in bothcompletePromptmethods, so a pre-aborted call creates no timer. - Streams: Abort checks usebreakinsidefor awaitloops (openai.tscreateMessageandhandleStreamResponse; basecreateMessage). Leaving the loop calls the SDK iteratorreturn(), which closes the response. Generator yields are re-checked against the signal, so a cancelled caller does not receive further content. - Abandoned in-flight requests: WhenrejectOnAbortwins the race, the SDK call still receives the same signal (requestConfig.signal), so the SDK aborts the request.friendli.tscreateStreamalso forwardsrequestOptions. No orphaned stream was found. - Duplicate work: No retry or re-issue path was added. The non-streaming branches only add checks before each yield. - Pre-existing code: The Responses-routebridgeExternalAbortSignal(openai.ts~481-526) is unchanged by this unit and disposes infinally. Residual risk:rejectOnAbortleaves the underlying SDK promise running. Its settlement is handled, so this does not cause an unhandled rejection. The SDK receives the same signal, so the request still ends.
-
Full details: Regression Evidence
-
Explanation
Unit u1 (HEAD 91c6af4 vs u0 head c6f18d3) changes
OpenAiHandler.completePrompton the Responses route. The new code merges the caller signal with the deadline and classifies timeouts (src/api/providers/openai.ts, Responses branch, themergeAbortSignalAndTimeoutcall and the catch that testsisTimeoutAbort(requestSignal)). The code comment says the deadline "only stays armed if it is forwarded as this request's signal." Test coverage for this changed behavior is incomplete: - Covered: the chat-path deadline (openai.spec.ts ~1511-1555 expectsTimeoutErrorand the message "The OpenAI completion request timed out"). - Covered: the Responses route forwardstimeout: 1234, and the merged signal is not aborted before the caller aborts (openai.spec.ts ~3375-3394). - Covered: caller-cancel on the Responses route (openai.spec.ts ~1793-1828). - Missing: no ResponsescompletePrompttest letstimeoutMselapse. Nothing asserts that the merged signal aborts on the deadline. Nothing asserts that the Responses catch returns theTimeoutErrorcontract instead of a raw or user-cancel abort. ThetimeoutMs: 1234test never fires a timer. A regression that drops the timeout from the merged signal, or removes|| isTimeoutAbort(requestSignal), would leave the suite green. The timeout test for the chat route would not catch it, because it covers a different code path. The lowest valid layer for this gap is the provider specopenai.spec.ts, next to the existing chat-path timeout tests. Other changed behavior in this unit has direct provider-level tests (abort pre-check, mid-stream abort, usage-before-verdict, o3 family, base provider, and the timeout spec). I found no test copying the implementation.Resolution
Add a provider-level test in src/api/providers/tests/openai.spec.ts for the Responses route. Set
openAiUseResponsesApi: true, then callcompletePrompt("...", { timeoutMs: <small value> })with no caller signal. Park themockResponsesCreatemock untiloptions.signalaborts, following the chat-path test at ~1524-1555. Assert that the merged signal aborts. Assert that the result hasname"TimeoutError" and message "The OpenAI completion request timed out". Optionally add a case where the caller signal stays live, and assert the same classification.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Changed-code mutation testingReport for PR head
Details: mutants, guidance, and reproductionChanged-code mutation testing
Focused tests
Reproduce locallyFrom a full checkout containing both commits: Mutation reports
The workflow uploads generated reports in the Advisory findings
|
…1311 split u0) The shared abort, timeout and error helpers landed with two required checks red: compile (eslint) and knip. This commit clears both without re-inflating suppressions, and adds the test that the guard was missing. compile: ESLint 9.39.5 count-based suppressions are all-or-nothing. In suppressions-service.js:171 a file is suppressed only while violationsCount <= suppressionsCount, and :177 rewrites the remainder only when violationsCount < suppressionsCount, so a file that is over its count reports every violation rather than the excess. The previous commit lowered base-openai-compatible-provider.ts from 6 to 5 while the file still held 6 assertions, and deleted the kimi-code.spec.ts entry while that file still held 1, which turned all 7 into reported errors. The fix retypes only what costs nothing. modelInfo goes from any to ModelInfo: the type is already imported in this file and calculateApiCostOpenAI in shared/cost.ts is its only consumer, so the assertion disappears without new machinery and the file drops to exactly its remaining count of 5. The kimi mock reaches the handler's protected client by bracket access, with the seam narrowed to the one create call it replaces - the shape anthropic-vertex.spec.ts:277 and :581 already use. Bracket access alone was not enough: it produced a fresh TS2739 on the ChatCompletionMessage mock literal, so the seam type is load-bearing and not decoration. Its suppression entry stays deleted because the file now asserts nothing, so a count of zero is the honest count rather than an allowance. The other five assertions stay suppressed on purpose: they sit on lines the suite never executes. Coverage over the 18 provider and api specs reports zero hits for both thinking assignments (lines 103 and 225) and for both base_resp throws (lines 136 and 234). Retyping an unexecuted line only moves it into the mutation cell, where no existing test could kill a mutant, and the file is upstream-owned (blame 6cfa82f, #11462) rather than part of this unit, as is the mock's owner (78c1410, Zoo-Code-Org#945). Type-checking adds nothing here either way: tsc over src reports the same diagnostics before and after this change. knip: handleOpenAIRequestError has no production importer in this unit - only error-handler.spec.ts imports it, and the request sites arrive with the later splits - so knip --production reports it while dev knip does not, which is the difference between the two runs rather than a finding about the code being wrong. Marked @internal with the reason: an intentional direct-test seam, the exception docs/development-quality-checks.md sanctions and abort-signal.ts:254 already uses in this same directory. The new row is coverage-closing, not a red-first repro: the status-first guard already behaved correctly, but no row reached it because none of the abort-awareness inputs carries a numeric status, so its early return had nothing executing it. It is not free-standing either: deleting the guard fails exactly this row - "expected 'AbortError' to be 'Error'" - while the other 49 rows keep passing. Suppression debt moves down, and the baseline is the merge-base dd30249, which is what AGENTS.md states the rule against - not the PR head: 261 entries and 2844 suppressed occurrences there, 260 and 2842 here. The provider entry stays at 5 and the kimi entry stays gone, so a prune run leaves the count map unchanged and only reflows indentation. Cost against that same base, on the mutation gate's own measure: this cell reports 19 changed executable lines against a cap of 500, one more than the 18 the previous commit measured, and that one line is the retyped signature. Not closed by this commit: - the five remaining provider assertions, which are worth typing only once tests execute the thinking and base_resp paths, and only next to the splits that make them live code - production importers for handleOpenAIRequestError, which arrive with split/1311-u1-openai-family and its siblings - the whole-file typed removal for the provider, sketched during this investigation: it clears all 5 remaining assertions but raises the cell from 18 to 33 changed executable lines, so it should land after the two unexecuted paths have tests of their own
91c6af4 to
16439b1
Compare
…Org#1311 split u1) Unit u1 of the split plan in Zoo-Code-Org#2799. It carries openai.ts and the OpenAI-compatible base, with their cancellation rows. undefined- The two abort contracts stay apart: the caller's signal goes to the undefinedrequest each route issues, and a mid-flight abort or a raw SDK abort becomes the provider's contract error with the failure kept as the cause. Each request site normalizes its own failure, including the Responses completion. undefined- A stream failure is a flag beside its value, so a rejection carrying undefined`undefined` still reaches the handler, and the recorded usage is yielded before the error. A usage frame the SDK already returned is recorded before the abort break. undefined- The Responses completion forwards the merged caller and deadline undefinedsignal, so the deadline stays armed while the SDK reads the JSON body. - Request creation is raced against the request signal, so a 429 backoff sleep cannot outlast a deadline. undefinedEvidence: openai, base-provider and cancellation rows 725 pass; tsc undefined--noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean. This commit also drops the provider entry in src/eslint-suppressions.json from five to four, because rewriting the provider is what made the fifth count stale: the earlier cell fixed one of the six positions the merge-base entry covered, and this commit's rewrite removes another, so four violations remain against an entry that still says five. eslint treats a surplus entry as an error in its own right: suppressions-service.js line 171 suppresses a file when its violations are at most its count, line 177 rewrites the remainder when they are strictly fewer, and once nothing is left to suppress the run exits two with the message about suppressions that no longer occur, which is what the lint step would have reported as soon as the other error was gone. The count moves down and is the only change in the file. The file is written with the single-tab indentation the committed copy uses, because the writer's own output is two-space and would have churned every line; prettier --check on the file exits 0, and a prune run afterwards changes no count - its writer reformats indentation, so the check that matters compares the parsed counts rather than the bytes.
The api coverage lane fails at this head (CI job 143658284755, ubuntu test:coverage:api; the same failure repeats for Zoo-Code-Org#2803 at job 143661531345) on api/providers/__tests__/zai.spec.ts > ZAiHandler > API Methods > "should handle errors in completePrompt": the mock factory at zai.spec.ts:21-28 returns only a default export, while this unit's error path reads the named export APIUserAbortError (api/providers/base-openai-compatible-provider.ts:136, api/providers/openai.ts:706), so vitest's missing-export error replaces the asserted Z.ai message. This unit already stubbed that export in the four sibling specs it touched (fireworks +2/-0, friendli +8/-0, sambanova +2/-0, mimo +31/-5), but zai.spec.ts belongs to u2, so its mock stayed incomplete; u3 inherits this head and repeats the same failure. Fix: add the same two lines the sibling specs already use. Test-only; no production behaviour changes, and no suppression count moves. Gates (both sides): - before: vitest run --config vitest.api.config.ts --coverage in src/ -> RC=1, Test Files 1 failed | 128 passed (129), Tests 1 failed | 6245 passed | 2 skipped (6248), 19s (local Windows). CI ubuntu collected 1 failed | 6278 passed | 2 skipped (6281) in 80.86s for the same head; CI sits 33 tests higher on both heads with the same 129 files and the same 2 skipped. - after: the same command -> RC=0, Test Files 129 passed (129), Tests 6246 passed | 2 skipped (6248), 18s. - eslint --max-warnings=0 --no-warn-ignored on the changed file: RC=0. - prettier --check on the changed file: RC=0. - the compile lane is deliberately untouched: its single error (kimi-code.spec.ts:141 Unexpected any) is rooted in u0's suppression hunks (c6f18d3) and is held for the Zoo-Code-Org#2800 menu. Mutation-gate calibers (scripts/stryker-diff.mjs primitives, cap 500): - cell, base=91c6af4bb0c46f69333372125763ab0c2207da59 (this PR head): changedExecutableLines total 0, readSource=checkout and readSource=commit agree, because src/api/providers/__tests__/ paths are excluded from the manifest. - unit delta, base=c6f18d3e15febd1fb0d89055f6ff15aefe16a81a (u0 head, upstream): extension 228 -> 228, identical under both readSource values. - cumulative, base=dd30249147159dad2d410845527a14a8e55d1463 (merge-base with upstream main): extension 246 -> 246, identical under both readSource values. src/eslint-suppressions.json is byte-identical to the parent commit (git blob sha1 unchanged): no suppression entry was added, lowered or pruned here. Not closed by this commit: - local api-lane totals sit 33 tests below CI on both heads; the mechanism is unverified, and the CI job log carries no per-file test counts, so a file-by-file comparison cannot be made from it. - Zoo-Code-Org#2802's ancestry relative to u0 and u1 is unverified: fetching refs/pull/2802/head collided with a pre-existing stale refs/tmp/u2 ref. - whether these two lines auto-merge when u2 rebases its rewritten zai.spec.ts onto them is unverified.
16439b1 to
d6e0af3
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…esh (Zoo-Code-Org#1311 split u3) Unit u3 of the split plan in Zoo-Code-Org#2799. Stacked on u1 (Zoo-Code-Org#2801). - The Kimi Code handler forwards the caller's signal through model discovery and the completion request, and retries once after a 401 refresh. - The OAuth refresh keeps the pair the server rotated: a cancelled waiter no longer rolls back the write it was making, the shared POST is never aborted once sent, an older refresh cannot clear a newer one's commit marker, and every credential write runs on one chain. A store failure after a rotation keeps the pair in memory. - The invalid_grant clear runs on that chain with the generation re-checked inside. Evidence: kimi provider, oauth, fetcher and model-catalog rows 201 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
Part of #2799 (split plan for #1311). Unit u1 of 4. Base for review: u0 (#2800).
This unit's own diff (provider-only)
openai.ts,base-openai-compatible-provider.tsand their rows:openai.spec.ts,base-openai-compatible-provider.spec.ts,base-openai-compatible-provider-timeout.spec.ts,openai.cancellation.spec.ts,mimo.spec.ts,friendli.spec.ts,sambanova.spec.ts,fireworks.spec.ts, plus the suppression prune.GitHub currently shows the ancestor's files too, because this branch is based on u0's head. Once #2800 merges, the diff above is all this pull shows.
Why not independent right now
Two compile-time dependencies block a provider-only branch today:
handleOpenAIRequestErroris defined in u0, and every provider request site calls it. A branch that carries only this provider fails the repository's pre-push typecheck (tsc), so it cannot be pushed, let alone be green. Once #2800 lands, this branch rebases to a provider-only, independently mergeable pull.Budget (own delta vs u0's head
c6f18d3e15)Changed executable lines: 228 (cap 500): openai.ts 140, base 88. a+d 2346/132 - the soft 400 screen is exceeded because the focused specs travel with the unit.
Verification
725 rows pass (openai, base, cancellation);
tscclean;eslint --prune-suppressions --max-warnings=0clean; prettier clean.Cross-unit contract points
Consumes u0's helpers; adds no copy. u2 and u3 extend these classes.
Merge order
u0 (#2800) -> u1 -> u2 (#2802) -> u3 (#2803).