ai icon indicating copy to clipboard operation
ai copied to clipboard

`stopStream()` on the last `finish-step` causes an unhandled "Unable to enqueue" rejection in `streamText`

Open robelest opened this issue 3 weeks ago • 4 comments

Description

When an experimental_transform calls stopStream() on the last finish-step, streamText raises an unhandled rejection, TypeError: Invalid state: Unable to enqueue. Without an unhandledRejection handler, the Node process exits with code 1.

onStepEnd and onEnd both still run, and fullStream ends normally after finish-step. The error comes afterwards, from the step stream's flush:

TypeError [ERR_INVALID_STATE]: Invalid state: Unable to enqueue
    at transformStreamDefaultControllerEnqueue (node:internal/webstreams/transformstream:540:11)
    at TransformStreamDefaultController.enqueue (node:internal/webstreams/transformstream:339:5)
    at enqueueStepPart (node_modules/ai/dist/index.js:10348:18)
    at Object.flush (node_modules/ai/dist/index.js:10567:9) {
  code: 'ERR_INVALID_STATE'
}

Expected: stopping at a step boundary ends the stream cleanly, with no rejection. Actual: an unhandled rejection after the stream ends, which crashes the process by default.

Root cause

stopStream() calls stitchableStream.terminate(). terminate() calls reader.cancel() on the inner step stream, but doesn't await or catch it: https://github.com/vercel/ai/blob/382d0b8eaf87687fb5a404705195f6fafac38fab/packages/ai/src/util/create-stitchable-stream.ts#L31-L45

At that moment the step stream's flush has already enqueued finish-step and is waiting on stepFinish.promise: https://github.com/vercel/ai/blob/382d0b8eaf87687fb5a404705195f6fafac38fab/packages/ai/src/generate-text/stream-text.ts#L3331-L3337

The cancel promise waits on that flush. When onStepEnd resolves stepFinish, flush enqueues finish into the readable that was just cancelled, so flush throws. Nothing catches the cancel promise, so its rejection is unhandled.

Guarding that enqueue exposes a second error on the next line. self.closeStream() throws TypeError: Invalid state: Controller is already closed, because close() checks only isCancelled and not whether terminate() already closed the controller: https://github.com/vercel/ai/blob/382d0b8eaf87687fb5a404705195f6fafac38fab/packages/ai/src/util/create-stitchable-stream.ts#L149-L160

Possible fix

  • In the step stream's flush, skip enqueueStepPart and closeStream() once stopStream() has run (for example, check the existing isRunning gate).
  • Make close() a no-op after terminate().

I patched both into the 7.0.165 dist, and the repro below then completed with no rejection.

https://github.com/vercel/ai/pull/22557 also addresses this. It catches the rejected inner cancel, which swallows the flush error, but the flush still enqueues after the stream stops.

Reproduction

import { streamText } from "ai";
import { MockLanguageModelV4, convertArrayToReadableStream } from "ai/test";

process.on("unhandledRejection", (error) => console.log("unhandled:", error));

const usage = {
  inputTokens: { total: 3, noCache: 3, cacheRead: 0, cacheWrite: 0 },
  outputTokens: { total: 10, text: 10, reasoning: 0 },
};

const result = streamText({
  model: new MockLanguageModelV4({
    doStream: async () => ({
      stream: convertArrayToReadableStream([
        { type: "stream-start", warnings: [] },
        { type: "text-start", id: "t" },
        { type: "text-delta", id: "t", delta: "Hello" },
        { type: "text-end", id: "t" },
        { type: "finish", finishReason: { unified: "stop", raw: undefined }, usage },
      ]),
    }),
  }),
  prompt: "Hi",
  experimental_transform: ({ stopStream }) =>
    new TransformStream({
      transform(part, controller) {
        controller.enqueue(part);
        if (part.type === "finish-step") stopStream();
      },
    }),
  onStepEnd: () => console.log("onStepEnd"),
  onEnd: () => console.log("onEnd"),
});

for await (const part of result.fullStream) console.log(part.type);

Output on 7.0.165:

start
start-step
text-start
text-delta
text-end
onStepEnd
finish-step
onEnd
unhandled: TypeError [ERR_INVALID_STATE]: Invalid state: Unable to enqueue

AI SDK Version

  • ai: 7.0.165 (same source as main at 382d0b8) and 7.0.153
  • Node: 26.13.0

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

robelest avatar Nov 09 '26 00:11 robelest

Identify issue type

Identified as Bug
Confidence: High

Rationale

The issue describes a concrete runtime failure in existing streamText behavior: stopping the stream at a step boundary unexpectedly causes an unhandled rejection instead of clean termination.

Evidence

  • Calling stopStream() on the last finish-step produces an unhandled ERR_INVALID_STATE rejection: "Unable to enqueue".
  • The report provides a runnable reproduction on AI SDK 7.0.165 and 7.0.153; without an unhandledRejection handler, the Node process exits.
  • The reported flush path enqueues into a cancelled stream, and a proposed guard eliminates the rejection.

ai-sdk-factory[bot] avatar Nov 09 '26 00:11 ai-sdk-factory[bot]

Bug discovery clarification

@robelest, how did you discover this bug? Did you encounter it while using the AI SDK in production, find it while auditing or reviewing AI SDK source code, or discover it another way? Please describe the original discovery context.

The report establishes a reproducible bug and detailed source investigation, but not how it was originally discovered. Ask the original author whether it arose in production, during SDK source review, or through local testing.

ai-sdk-factory[bot] avatar Nov 09 '26 00:11 ai-sdk-factory[bot]

Found it while building @convex-dev/agent (https://github.com/convex/agent), not from reading the SDK source. We stop streams at step boundaries, and a regression test for that path hit this unhandled rejection. The repro above is that test cut down to plain streamText.

robelest avatar Nov 09 '26 01:11 robelest

Identify bug discovery

Discovery source: discovery:other (high confidence).

The author explicitly identified development and regression testing of @convex-dev/agent as the discovery source, not production use or auditing AI SDK code.

  • The author said: "Found it while building @convex-dev/agent ... not from reading the SDK source."
  • A regression test for stopping streams at step boundaries triggered the unhandled rejection.
  • The author clarified that the issue's reproduction was that regression test reduced to plain streamText.

ai-sdk-factory[bot] avatar Nov 09 '26 01:11 ai-sdk-factory[bot]