Repository navigation
feat(api): honour caller cancellation in zai (#1311 split u2) - #2802
easonLiangWorldedtech wants to merge 5 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: Resolve the merge conflicts. The review sequence resumes after the branch is mergeable. 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 |
|---|---|---|
| Security Boundaries | The PR's own change is commit 847f898 on top of u1 (91c6af4). It touches only src/api/providers/zai.ts (+80/-28) and src/api/providers/tests/zai.spec.ts. I read that diff directly. The changes are… | |
| Persistence Integrity | The check applies to changed persistence paths. PR #2802 (branch split/1311-u2-zai, base main, author easonLiangWorldedtech) changes two files: src/api/providers/zai.ts (+80/-28 lines per the commit s… |
Full details: Security Boundaries
-
Explanation
The PR's own change is commit 847f898 on top of u1 (91c6af4). It touches only src/api/providers/zai.ts (+80/-28) and src/api/providers/tests/zai.spec.ts. I read that diff directly. The changes are: - The GLM thinking path now forwards per-request options (the abort signal) to
chat.completions.create. It also awaits creation, so basecreateMessagenormalizes errors. -completePromptfor GLM-5.3 callsthrowIfAborted. It builds a per-request bridged signal merged withtimeoutMs, passes atimeoutthroughgetRequestTimeoutMs, and races the request withrejectOnAbort. It also discards answers that arrive after caller cancellation and disposes the bridge infinally. Security boundary review: - No secret or personal data is newly exposed. The API key handling (apiKey: options.zaiApiKey ?? NOT_PROVIDED) is unchanged. No new logging of request content or credentials appears in the diff. - No unvalidated input is executed.timeoutMsgoes throughhasUsableTimeoutandtoSdkTimeoutMs. Non-finite and non-positive values are omitted, and large values are capped (request-timeout.ts). - No approval or allowlist control is bypassed. The diff adds cancellation checks and does not remove any gate. Forwarding the abort signal on the thinking path restores cancellation, and it does not widen access. I found no concrete defect in a changed path that matches the check's failure conditions. The error-message logging inhandleProviderErroris pre-existing and not changed by this PR.
Full details: Persistence Integrity
-
Explanation
The check applies to changed persistence paths. PR
#2802(branch split/1311-u2-zai, base main, author easonLiangWorldedtech) changes two files: src/api/providers/zai.ts (+80/-28 lines per the commit stat) and its spec file. I read the full zai.ts diff against the u1 head (91c6af4). It changes only the GLM-5.3 request path: abort-signal bridging, per-request timeout, racing the completion against the abort signal, and awaiting the SDK call in createStreamWithThinking. None of these paths writes, saves, or persists state. A grep of the diff and of zai.ts and the imported helpers found no fs, globalState, secrets, storage, persist, or rollback usage. The added awaits are on network calls to the OpenAI-compatible client, not on storage writes. The check's failure conditions (unawaited writes, non-atomic writes, missing rollback for persisted state, defaults not reaching consumers) therefore have no changed path to match. No persistence defect is introduced.
Full details: Regression Evidence
-
Explanation
Scope: this unit's own delta is
src/api/providers/zai.tsandsrc/api/providers/__tests__/zai.spec.ts(git diff 91c6af4..HEAD, 549 insertions, 28 deletions). The primary PR is#2802by easonLiangWorldedtech, basemain, headsplit/1311-u2-zai. Changed behavior with covered tests: -createStreamWithThinkingnow forwardsrequestOptions, awaits creation, and no longer wraps errors. Tests cover the signal on the thinking path, APIUserAbortError normalization (sync throw, rejected promise, mid-stream), and single wrapping of a non-abort error. -completePromptfor GLM-5.3 gainedthrowIfAborted, a per-request bridge, a merged timeout signal,rejectOnAbort, a post-response aborted check, and error mapping throughhandleOpenAIRequestError. Tests cover pre-aborted input, in-flight cancel, late-answer discard, APIUserAbortError, timeout-only TimeoutError, timeout cap, non-finite and zero timeout. Missing evidence at the zai layer: 1.rejectOnAbortrace (zai.ts lines 195-203). The code comment says the SDK waits out a 429 backoff without checking the signal. Every zai test mock honors the signal, so each one passes even if the race is removed.abort-signal.spec.tstestsrejectOnAbortin isolation, but no zai test shows that GLM-5.3completePromptrejects when the SDK call never settles after an abort. A regression that drops the race would not be caught. 2. Non-abort failures on the GLM-5.3completePromptpath. The catch block now callshandleOpenAIRequestError(zai.ts line 219) instead ofhandleOpenAIError. The only non-abort error test (should handle errors in completePrompt, spec line 527) uses the default model, which delegates tosuper.completePrompt. No test covers a plainErroror an HTTP-status error on the GLM-5.3 path. A regression in that classification would not be caught. Both gaps are at the lowest valid layer (zai.spec.ts) and each has a plausible regression case. The rest of the changed behavior has direct tests.Resolution
Add tests to
src/api/providers/__tests__/zai.spec.tsfor the GLM-5.3completePromptpath: 1. A mockcreatethat never settles, even after the signal aborts (matching the 429 backoff case in the code comment). CallcompletePromptwithabortSignal, abort the controller, and assert that the promise rejects withname: "AbortError"and the message ending in "aborted" without waiting for the mock. 2. A non-abort failure, for examplenew Error("boom"), and an HTTP-status error (for example an object with numericstatus: 429). Assert the expectedZ.ai completion error: ...or HTTP-classified error. Assert that neither is reported as AbortError or TimeoutError when no signal is aborted.
Full details: Lifecycle Resource Cleanup
-
Explanation
Summary: the changed GLM thinking path in createMessage can leave a listener on the caller's long-lived abort signal. The fix does not bridge that path. Changed path (src/api/providers/zai.ts, commit 847f898): - Before this PR, createStreamWithThinking dropped requestOptions. The SDK received no signal on this path. - The PR now passes requestOptions into createStreamWithThinking and then into this.client.chat.completions.create(params, requestOptions). That is at the thinking-path return near the end of createStreamWithThinking. - requestOptions comes from base createMessage (base-openai-compatible-provider.ts, lines 132 and 143). It is built with RequestConfigBuilder.setAbortSignal(metadata), which passes metadata.abortSignal, the caller's signal, unchanged. - No bridgeExternalAbortSignal and no dispose call exist on this path. Only the completePrompt override uses bridge.dispose() in a finally block. Input that triggers it: a GLM-4.7/5.x thinking-capable model in a task. Each createMessage call passes the task's abort signal to the SDK. A long task makes many such requests against one signal. The PR's own code says the SDK "attaches a listener to whatever signal it is given and keeps it after the request". The completePrompt override bridges the signal for that reason. The createMessage thinking path does not. The spec at zai.spec.ts ("createMessage should pass the abort signal on the GLM thinking path") asserts identity with controller.signal. That pins the unbridged design. Limits: node_modules is not present, so I could not read the installed openai SDK source. I could not confirm that the SDK keeps the listener after each request. The verdict relies on the diff, the PR's own stated rationale, and the identity assertion in the spec. The completePrompt path does not leak. Its bridge is disposed in finally, and the merged request signal is per request. The rejectOnAbort listeners are detached on each settle path. Primary author: easonLiangWorldedtech (verified). Identity was not part of the criterion.
Resolution
In createStreamWithThinking (src/api/providers/zai.ts), bridge the caller signal per request, as completePrompt already does. Call bridgeExternalAbortSignal(requestOptions?.signal), pass the bridged signal to the SDK, and call dispose() in a finally block that spans the create await and stream iteration. Alternatively, strip the caller signal from the SDK call and keep the base race for cancellation. Then update the "should pass the abort signal on the GLM thinking path" test so it checks the bridged signal's behavior, not identity with the caller's signal. Add a test that asserts the caller signal has no listener left after the request completes.
- 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
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.
…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.
… u2) Unit u2 of the split plan in Zoo-Code-Org#2799. Stacked on u1 (Zoo-Code-Org#2801). - The GLM-5.3 completion bridges the caller's signal per request and disposes the bridge in `finally`, so the SDK's listener lands on a per-request controller instead of the caller's long-lived one. - The completion is raced against the merged signal, so a 429 backoff sleep cannot outlast `timeoutMs` or delay a caller stop. Evidence: zai rows 78 pass; tsc --noEmit clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
847f898 to
8de638a
Compare
Part of #2799 (split plan for #1311). Unit u2 of 4. Base for review: u1 (#2801).
This unit's own diff (provider-only)
zai.tsandzai.spec.ts: the GLM-5.3 completion paths.GitHub currently shows the ancestors' files too, because this branch is based on u1's head. Once #2800 and #2801 merge, the diff above is all this pull shows.
Why not independent right now
zai's rows exercise the OpenAI-compatible base wiring that u1 owns and the helpers u0 owns; measured on u0 alone, 10 of its rows fail. The pre-push typecheck also rejects a branch that lacks u0. After #2800 and #2801 land, this branch rebases to a provider-only, independently mergeable pull.
Budget (own delta vs u1's head
91c6af4bb0)Changed executable lines: 28 (cap 500). a+d 550/34.
Verification
78 rows pass;
tscclean;eslint --prune-suppressions --max-warnings=0clean; prettier clean.Merge order
u0 (#2800) -> u1 (#2801) -> u2 -> u3 (#2803); u3 depends on u0+u1 only and may merge before u2.