ai icon indicating copy to clipboard operation
ai copied to clipboard

streamText: a stable hook awaited before the result settles

Open robelest opened this issue 3 weeks ago • 1 comments

The gap

A library that persists a generation (we save every step to a database) needs to finish its write for the last step before anyone can observe that the generation ended: before fullStream yields finish, and before text, steps and finishReason resolve. If the write fails, the caller should see that failure where it sees other stream errors.

No stable callback gives this today (ai 7.0.153):

  • onEnd runs after text, steps and finishReason have resolved, isn't called when the stream is aborted or no step finished, and a throw in it doesn't reject anything.
  • onChunk is awaited before the result settles, but the part is forwarded first, so fullStream readers see finish before the write ends. A throw in it doesn't reject anything either.
  • onStepEnd runs before stopWhen, so it can't know whether this step is the last one.

The one thing that works is an experimental_transform that awaits the write when it sees finish and only then enqueues it. That puts a core persistence path on an experimental API.

A related gap: transforms run once per retry segment, and a transform's flush can't tell a segment that ended because a transform called stopStream from one that ended at a retry boundary. To fail a step that stopStream cut off, before text resolves, we wrap every transform's stopStream to record that it was called.

Minimal repro

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

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const model = () =>
  new MockLanguageModelV4({
    doStream: async () => ({
      stream: simulateReadableStream({
        chunks: [
          { type: "stream-start", warnings: [] },
          { type: "text-start", id: "1" },
          { type: "text-delta", id: "1", delta: "Hello" },
          { type: "text-end", id: "1" },
          {
            type: "finish",
            finishReason: { unified: "stop", raw: "stop" },
            usage: {
              inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
              outputTokens: { total: 1, text: 1, reasoning: 0 },
            },
          },
        ],
      }),
    }),
  });

// onEnd: `text` resolves while the write is still running.
let saved = false;
const a = streamText({
  model: model(),
  prompt: "Hi",
  onEnd: async () => {
    await sleep(100);
    saved = true;
  },
});
console.log(await a.text, saved); // "Hello" false

// onChunk: `fullStream` yields `finish` before the write ends.
saved = false;
const b = streamText({
  model: model(),
  prompt: "Hi",
  onChunk: async ({ chunk }) => {
    if (chunk.type !== "finish") return;
    await sleep(100);
    saved = true;
  },
});
for await (const part of b.fullStream) {
  if (part.type === "finish") console.log(saved); // false
}

// A failed write can't fail the result.
const c = streamText({
  model: model(),
  prompt: "Hi",
  onEnd: async () => {
    throw new Error("save failed");
  },
});
console.log(await c.text); // "Hello", no rejection

Only an experimental_transform that awaits before enqueueing finish makes saved true in both places.

The hook we'd want

Either of these would let us drop the transform:

  1. Stabilise experimental_transform as transform, documenting that parts reach fullStream and the result only after the transform passes them on, that it runs per retry segment, and that flush runs at a segment's end. Pass flush the reason the segment ended ("finish", "stop", "error" or "retry").

  2. An onBeforeEnd callback, awaited once after the last onStepEnd and before finish is emitted and the result promises settle, including when the stream ends without finish:

    onBeforeEnd?: (event: {
      reason: "finish" | "stop" | "error" | "abort";
      steps: StepResult<TOOLS>[];
      error?: unknown;
    }) => PromiseLike<void> | void;
    

    A throw in it would error the stream and reject text, steps and the other result promises with that error.

Option 2 is narrower and covers both gaps: reason: "stop" replaces our stopStream wrapper, and the throw semantics replace our own error plumbing.

robelest avatar Nov 09 '26 21:11 robelest

Identify issue type

Identified as Feature
Confidence: High

Rationale

The issue requests a new lifecycle capability and stronger completion/error semantics, rather than reporting a failure of existing promised behavior.

Evidence

  • Requests either stabilizing experimental_transform with segment-end metadata or adding an awaited onBeforeEnd callback.
  • Needs persistence to complete before finish is emitted and result promises resolve, with write failures propagated to callers.
  • Describes limitations of existing callbacks without claiming they violate documented guarantees.

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