Skip to content

fix(core): abort Google GenAI requests and forward streamed usage - #5377

Merged
sailist merged 1 commit into
mainfrom
bug-450-11-25-google-genai-abort-usage
Nov 25, 2026
Merged

sailist merged 1 commit into
mainfrom
bug-450-11-25-google-genai-abort-usage

Conversation

@sailist

@sailist sailist commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Resolve #5063

使用 Gemini / Vertex(google-genai 协议)时,用户按 Esc 或调用 loop.cancel() 取消生成后,底层 HTTP 请求不会真正中断,仍在后台继续生成和计费;若流式响应卡住,请求会一直挂起到网络超时。同时,取消前已经收到的 token 用量因为没有和 finishReason 出现在同一个数据块而被丢弃。本 PR 修复这两个问题,使取消能立即关闭底层连接,并保留取消前已收到的用量。

Bug Reproduction Steps

See linked issue.

补充的回归测试在修复前可稳定复现:

  • 流式响应在发出首个带 usageMetadata(无 finishReason)的数据块后卡住,收到首个文本片段时触发取消,修复前测试超时且用量事件缺失;
  • 流式响应只返回响应头后卡住、非流式响应只返回响应头后卡住,触发取消后服务端连接在修复前不会关闭。

Root Cause

这是针对根因的修复(fundamental fix),不是绕过:

  1. 取消信号未到达传输层:google-genai 的 send / sendStream 只用 Promise.race 包裹 SDK 调用,没有设置 params.config.abortSignal。Promise.race 只让调用方停止等待;abortableStream 只在收到下一个数据块后才检查 signal.aborted,所以底层 @google/genai 的 fetch 从未收到取消信号。
  2. 用量上报被结束原因门控:decode.ts 要求同一数据块同时带有非空 finishReason 才调用 sink.onUsage。Gemini 流式响应在每个数据块都返回累计 usageMetadata,但只有最后一个数据块才带 finishReason,中途取消时最后一个数据块收不到,此前的用量就全部丢失。

Code Changes

传输层把取消信号透传给 @google/genai SDK(SDK 会将其桥接到 fetch 的 RequestInit.signal,且不会序列化进请求体);解码层在收到用量元数据时立即上报,与同目录 OpenAI / Anthropic 协议保持一致。

 googleGenAIProtocol
   send(client, request, signal)
-    generateContent(request.params)
+    generateContent({ ...request.params, config: { ...request.params.config, abortSignal: signal } })
     race with abortPromise(signal)
   sendStream(client, request, signal)
-    generateContentStream(request.params)
+    generateContentStream({ ...request.params, config: { ...request.params.config, abortSignal: signal } })
     race with abortPromise(signal)
     abortableStream(stream, signal)

 createDecoder.push(chunk)
-  if (usage !== undefined && rawFinish !== undefined && rawFinish !== null)
+  if (usage !== undefined)
     sink.onUsage(usage)
  • 为什么保留 Promise.race 与 abortableStream:@google/[email protected] 在挂载 abort 监听前没有检查 abortSignal.aborted,如果信号在调用前就已取消,SDK 仍会发出 HTTP 请求。保留 Promise.race 可以在预取消或 SDK 前置异步阶段(如 Vertex ADC 凭证解析)直接短路;abortableStream 继续作为兜底,for await 提前退出时会沿生成器链自动调用 return() 释放 reader 锁。
  • 为什么多个数据块重复上报用量是安全的:Gemini 的 usageMetadata 是累计值,core 的 mergeUsagePatch 用最新值覆盖旧值,正常结束时最终结果不变,取消时则保留取消前最后一次收到的用量。
  • 范围说明:issue 中第 4 点可选建议(FINISH_REASON_UNSPECIFIED 归一化为 NO_FINISH 后仍触发 onFinish)在 OpenAI / Anthropic 解码器中存在相同行为,属于独立的跨协议语义问题,本 PR 未改动。

阅读顺序:先看 packages/core/src/llm/builtin/protocol/google-genai/index.ts(传输层取消透传),再看 decode.ts(用量上报条件);abort.test.ts 与 usage-without-finish.ts 为回归测试。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
取消 Gemini / Vertex 流式与非流式请求(TUI、print、Desktop/Web、ACP、Node SDK) 仅调用方停止等待,底层 HTTP 请求继续运行并计费;流卡住时需等下一个数据块或网络超时才能结束 取消信号传入 SDK,底层 HTTP 连接立即关闭,卡住的请求立即以 aborted 结束 无(旧行为导致取消后请求泄漏和额外计费) 无需逃生口
Gemini / Vertex 流式响应的 llm.delta.usage 事件时机 仅当数据块同时携带非空 finishReason 时才发出,中途取消时丢弃全部已收用量 每个携带 usageMetadata 的数据块到达即发出(累计覆盖),取消结果保留已收用量 无(正常完成的最终 TokenUsage 数值不变) 无需逃生口
预取消信号(调用 send / sendStream 前 signal 已 aborted) Promise.race 直接抛出 AbortError 保持不变 — —

受影响模块与测试覆盖:

  • packages/core/src/llm/builtin/protocol/google-genai/index.ts:由 abort.test.ts 覆盖首包后取消并保留用量、首包前卡住取消、非流式卡住取消三种真实 HTTP 场景,均断言服务端连接被关闭且请求体不含 abortSignal。
  • packages/core/src/llm/builtin/protocol/google-genai/decode.ts:由 usage-without-finish.ts 夹具覆盖无 finishReason 的多数据块累计用量上报,原有 decode / encode / transport 夹具全部保持通过。
  • 未验证项:未连接真实 Google / Vertex 线上端点(测试通过本地真实 HTTP mock 服务验证传输层断连);Windows 专项未运行(纯 TypeScript 协议层改动,无平台相关路径)。
验证记录
  • 修复前运行新增测试:4 个用例全部失败(3 个取消用例超时,usage-without-finish 缺少 2 个 usage 事件)。
  • 修复后 Linux 远程环境:
    • corepack pnpm exec tsc -p packages/core/tsconfig.json --noEmit 通过;
    • corepack pnpm exec vitest run --reporter=agent packages/core/test packages/testkit/test/protocols.test.ts:38 个测试文件、431 个用例全部通过。
  • 本地干净 git worktree:pnpm lint(注释检查、oxlint type-aware、导入边界、guards、ratchet、instructions 等)与 pnpm run check:duplication 全部通过,0 警告 0 错误。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 0d8816b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/core Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T04:14:52.256407Z 0d8816b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@0d8816b
npx https://pkg.pr.new/@moonshot-ai/kimi-code@0d8816b

commit: 0d8816b

@sailist
sailist merged commit 87011ba into main Nov 25, 2026
24 checks passed
@sailist
sailist deleted the bug-450-11-25-google-genai-abort-usage branch November 25, 2026 04:23
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
…onshotAI#5377)

Port upstream 87011ba. Both generateContent and generateContentStream
now carry the request signal as config.abortSignal, so cancelling a turn
closes the underlying HTTP request instead of leaving it running. The
stream decoder reports usage metadata as soon as a chunk carries it rather
than waiting for a finish reason.

The decode fixture usage-without-finish pins usage arriving across chunks
with no finish reason. The upstream abort test depends on the aimock
transport harness this fork does not carry and is not ported.

Verified: google-genai 15 pass, core typecheck clean.
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.

[Bug] google-genai: cancellation never reaches the SDK request, and streamed usage is dropped without a finish reason

2 participants