Skip to content

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

Done

Description

@vastStage

What version of Kimi Code is running?

2.6.3 (source main snapshot, 2026-11-18). Confirmed by reading the code paths below and by checking the installed @google/[email protected] package.

Which open platform/subscription were you using?

None involved (code-level audit).

Which model were you using?

None involved (code-level audit). The issue is specific to the google-genai protocol (Gemini and Vertex).

What platform is your computer?

Windows 11 x64.

What issue are you seeing?

The google-genai protocol never forwards the request abort signal to the SDK, so cancelling a Gemini/Vertex request does not abort the underlying HTTP request. Streaming is worse: a stalled stream cannot be cancelled until the next chunk arrives.

packages/core/src/llm/builtin/protocol/google-genai/index.ts:111-124:

send: async (client, request, signal) => {
  const response = await Promise.race([
    modelsOf(client).generateContent(request.params),
    abortPromise(signal),
  ]);
  ...
},
sendStream: async (client, request, signal) => {
  const stream = await Promise.race([
    modelsOf(client).generateContentStream(request.params),
    abortPromise(signal),
  ]);
  return { body: abortableStream(stream, signal) as AsyncIterable<unknown> };
},

Promise.race only stops waiting. The params built in lower.ts:339 never set config.abortSignal, and abortableStream (index.ts:94-104) checks signal.aborted only after the next chunk is pulled:

for await (const chunk of stream) {
  if (signal.aborted) throw createAbortException();
  yield chunk;
}

The installed SDK already supports cancellation:

  • GenerateContentConfig.abortSignal?: AbortSignal in @google/genai/dist/genai.d.ts:4345.
  • generateContentInternal / generateContentStreamInternal forward it to request() / requestStream() in @google/genai/dist/node/index.cjs (around lines 14950 and 15017).

So after Esc / loop.cancel(), the request keeps streaming and billing in the background, and a stalled response cannot be interrupted at all.

A second, related gap: streamed usage is only forwarded when the same chunk also carries a finish reason. packages/core/src/llm/builtin/protocol/google-genai/decode.ts:118-121:

const usage = parseUsage(response);
if (usage !== undefined && rawFinish !== undefined && rawFinish !== null) {
  sink.onUsage(usage);
}

The other protocols forward usage as soon as it appears (openai decode.ts:323-326, anthropic decode.ts:166-173). With the gate, an aborted Gemini stream (exactly the cancellation case above) drops every usageMetadata it did receive, so the request contributes no usage and no measured token anchor.

What steps can reproduce the bug?

  1. Configure a google-genai model.
  2. Start a long streaming response and press Esc while it is generating.
  3. Observe that the UI turn ends after the abort grace period, but the HTTP request keeps running (and billing) instead of being closed.
  4. For a stalled provider, start a stream that stops sending chunks and then cancel: abortableStream never runs, so the request is held until a network timeout.
  5. Inspect the request usage for the cancelled turn: no usage is recorded from any usageMetadata received before the cancellation.

What is the expected behavior?

Cancellation should close the HTTP request, not just stop the caller from waiting. The abort signal should be passed to the SDK (config.abortSignal) so both generateContent and generateContentStream abort the transport, and the stream should be closed on abort. Usage received before an abort should still be forwarded to the caller.

Additional information

Suggested fixes:

  1. In both send and sendStream, pass { ...request.params, config: { ...request.params.config, abortSignal: signal } } to the SDK. abortableStream can stay as a belt-and-braces check, but the SDK is what actually cancels the transport.
  2. On abort, close the stream (stream.return()) so the response body is released deterministically.
  3. In decode.ts, call sink.onUsage(usage) whenever parseUsage returns a value. Gemini's usageMetadata is cumulative, and mergeUsagePatch keeps the latest value, so the finish-reason gate is not needed.
  4. Optionally treat a normalized NO_FINISH finish (null finishReason and null rawFinishReason) as missing for streaming in settleLlmRequest, so the existing "stream ended without a finish event" check is not bypassed by sink.onFinish(NO_FINISH).

Contribution

  • I am willing to submit a PR for this bug fix myself (please wait for maintainer approval in this issue first)

Activity

  1. vastStage commented on Nov 18, 2026

    @vastStage
    Author

    I confirmed both points with temporary failing tests against this snapshot (2.6.3 source, main), then reverted them. No network or credentials are needed.

    Abort signal not forwarded

    const controller = new AbortController();
    let captured: any;
    const client = {
      models: {
        generateContentStream: async (params: any) => {
          captured = params;
          return (async function* () {})();
        },
      },
    };
    await googleGenAIProtocol.sendStream(
      client as any,
      { params: { model: 'gemini-test', contents: [], config: {} } } as any,
      controller.signal,
    );
    expect(captured.config.abortSignal).toBe(controller.signal);

    Observed: AssertionError: expected undefined to be AbortSignal { aborted: false }.

    The SDK receives config without abortSignal, while @google/[email protected] forwards config.abortSignal to requestStream in generateContentStreamInternal (dist/node/index.cjs). So the race only abandons the caller; the HTTP request is never told to stop.

    Usage dropped without a finish reason

    const events: string[] = [];
    const decoder = createDecoder({
      onDelta: () => undefined,
      onFinish: () => events.push('finish'),
      onMessageId: () => undefined,
      onUsage: () => events.push('usage'),
      onToolCallEnd: () => undefined,
      onError: () => events.push('error'),
    } as any);
    decoder.push({
      candidates: [{ content: { parts: [{ text: 'hi' }] } }],
      usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 2 },
    });
    expect(events).toContain('usage');

    Observed: DECODER_EVENTS_WITHOUT_FINISH [] — neither usage nor finish is emitted. For contrast, the openai decoder emits usage as soon as parseUsage returns a value, so an aborted request still contributes the input tokens it received.

    I will include both regression tests in the PR.

  2. vastStage commented on Nov 18, 2026

    @vastStage
    Author

    Live stream observation from a real Google GenAI endpoint (gemini-4-argon, 1M context). Request: "Count from 1 to 40, one number per line", maxOutputTokens: 200, then parse the SSE chunks:

    chunk finishReason usageMetadata
    1 absent promptTokenCount=18, candidatesTokenCount=4
    2 absent promptTokenCount=18, candidatesTokenCount=20
    3 absent promptTokenCount=18, candidatesTokenCount=44
    4 absent promptTokenCount=18, candidatesTokenCount=68
    5 absent promptTokenCount=18, candidatesTokenCount=92
    6 absent promptTokenCount=18, candidatesTokenCount=110
    7 STOP promptTokenCount=49, candidatesTokenCount=114

    Summary: usageMetadata was present on 7/7 chunks; finishReason only on 1/7. The decoder at packages/core/src/llm/builtin/protocol/google-genai/decode.ts:118-121 requires both on the same chunk before calling sink.onUsage, so:

    • in a successful stream, usage is taken only from the final chunk;
    • in an aborted/cancelled stream (the cancellation case in this issue), the final chunk never arrives and every usage value already delivered on the earlier chunks is discarded.

    This makes the gate consequential in real traffic, not just a theoretical asymmetry.

    For the abort-forwarding part, the SDK evidence is in the issue body (GenerateContentConfig.abortSignal is forwarded to requestStream), and the failing unit test in the previous comment shows Kimi never sets it. A transport-level live observation would need a proxy or a local mock server to watch when the HTTP request actually closes; I can add that as an integration test in the PR if you prefer.

    I also confirmed a real kimi -p turn works end-to-end over this google-genai endpoint (Reply with exactly OK -> OK), so the protocol path itself is live-verified.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions