Skip to content

feat(api): honour caller cancellation in zai (#1311 split u2) - #2802

Open
easonLiangWorldedtech wants to merge 3 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:split/1311-u2-zai
Open

easonLiangWorldedtech wants to merge 3 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:split/1311-u2-zai

Conversation

@easonLiangWorldedtech

@easonLiangWorldedtech easonLiangWorldedtech commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Part of #2799 (split plan for #1311). Unit u2 of 4. Base for review: u1 (#2801).

This unit's own diff (provider-only)

zai.ts and zai.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; tsc clean; eslint --prune-suppressions --max-warnings=0 clean; prettier clean.

Merge order

u0 (#2800) -> u1 (#2801) -> u2 -> u3 (#2803); u3 depends on u0+u1 only and may merge before u2.

…-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.
…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.

- The two abort contracts stay apart: the caller's signal goes to the request 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.
- A stream failure is a flag beside its value, so a rejection carrying `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.
- The Responses completion forwards the merged caller and deadline signal, 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.

Evidence: openai, base-provider and cancellation rows 725 pass; tsc --noEmit clean;
eslint --prune-suppressions --max-warnings=0 clean; prettier clean.
… 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.
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Review status

Thanks 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. community-approved is managed the same way — do not add or remove it manually. It signals a fresh community code approval for the current head as an advisory priority only; maintainer review is still required.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor
Pre-merge checks: Passed 2 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Regression Evidence Warning Scope: this unit's own delta is src/api/providers/zai.ts and src/api/providers/__tests__/zai.spec.ts (git diff 91c6af4..HEAD, 549 insertions, 28 deletions). The primary PR is #2802 by easonLiang… Add tests to src/api/providers/__tests__/zai.spec.ts for the GLM-5.3 completePrompt path: 1. A mock create that never settles, even after the signal aborts (matching the 429 backoff case in the code comment). Call completePrompt wit…
Lifecycle Resource Cleanup Warning 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 … 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 …
Passed Passed checks: 2 passed

Check name Status Explanation
Security Boundaries Passed 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 Passed 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 base createMessage normalizes errors. - completePrompt for GLM-5.3 calls throwIfAborted. It builds a per-request bridged signal merged with timeoutMs, passes a timeout through getRequestTimeoutMs, and races the request with rejectOnAbort. It also discards answers that arrive after caller cancellation and disposes the bridge in finally. 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. timeoutMs goes through hasUsableTimeout and toSdkTimeoutMs. 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 in handleProviderError is 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.ts and src/api/providers/__tests__/zai.spec.ts (git diff 91c6af4..HEAD, 549 insertions, 28 deletions). The primary PR is #2802 by easonLiangWorldedtech, base main, head split/1311-u2-zai. Changed behavior with covered tests: - createStreamWithThinking now forwards requestOptions, 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. - completePrompt for GLM-5.3 gained throwIfAborted, a per-request bridge, a merged timeout signal, rejectOnAbort, a post-response aborted check, and error mapping through handleOpenAIRequestError. 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. rejectOnAbort race (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.ts tests rejectOnAbort in isolation, but no zai test shows that GLM-5.3 completePrompt rejects 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.3 completePrompt path. The catch block now calls handleOpenAIRequestError (zai.ts line 219) instead of handleOpenAIError. The only non-abort error test (should handle errors in completePrompt, spec line 527) uses the default model, which delegates to super.completePrompt. No test covers a plain Error or 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.ts for the GLM-5.3 completePrompt path: 1. A mock create that never settles, even after the signal aborts (matching the 429 backoff case in the code comment). Call completePrompt with abortSignal, abort the controller, and assert that the promise rejects with name: "AbortError" and the message ending in "aborted" without waiting for the mock. 2. A non-abort failure, for example new Error("boom"), and an HTTP-status error (for example an object with numeric status: 429). Assert the expected Z.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.

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.

Share

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Changed-code mutation testing

Report for PR head 847f898155eb.

Surviving / uncovered mutants Advisories
0 1
Details: mutants, guidance, and reproduction

Changed-code mutation testing

PackageChanged executable linesValidKilledTimeoutSurvivedNo coverageResult
extension27400000Advisory incomplete

Focused tests

  • extension (cwd src): The mutation run was incomplete; selected test file names were not recorded. See Advisory findings for the failure.

Reproduce locally

From a full checkout containing both commits:

pnpm install --frozen-lockfile
node scripts/stryker-diff.mjs ci --base 9f8e4836680277425d36b47866b65b1b78b8b55c --head 7e04c49206e3457bd6ac9d6a11cef3a0c7aa3e75

Mutation reports

  • extension: reports/mutation/extension/mutation.html

The workflow uploads generated reports in the changed-code-mutation-report artifact. A direct artifact link appears below after upload.

Advisory findings

  • extension Stryker preflight failed: 18:20:14 (2696) INFO ProjectReader Found 6 of 1454 file(s) to be mutated. 18:20:14 (2696) INFO Instrumenter Instrumented 6 source file(s) with 245 mutant(s) 18:20:14 (2696) INFO ConcurrencyTokenProvider Creating 2 test runner process(es). 18:20:15 (2696) INFO DryRunExecutor Note: running the dry-run only. No mutations will be tested. 18:20:15 (2696) INFO DryRunExecutor Starting initial test run (vitest test runner with "perTest" coverage analysis). This may take a while. 18:23:26 (2696) ERROR DryRunExecutor One or more tests failed in the initial test run: coding eval host command boundary rejects an outside-workspace git diff in clamp-range before command execution Cannot find module '../../../../scripts/agent-evals/coding-fixtures' imported from /home/runner/work/Zoo-Code/Zoo-Code/.stryker-tmp/sandbox-2c9M4r/core/tools/__tests__/coding-eval-boundary.spec.ts 18:23:26 (2696) ERROR Stryker There were failed tests in the initial test run. file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65 throw new ConfigError('There were failed tests in the initial test run.'); ^ ConfigError: There were failed tests in the initial test run. at DryRunExecutor.validateResultCompleted (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65:27) at DryRunExecutor.executeDryRun (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:100:14) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async WorkItem.execute (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:32:28) at async file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:69:13 { innerError: undefined } Node.js v22.23.4

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant