ai icon indicating copy to clipboard operation
ai copied to clipboard

toUIMessageStream onError is invoked twice per upstream error

Open tigranl opened this issue 7 months ago • 2 comments

Summary

A single onError callback passed to result.toUIMessageStream({ onError }) is invoked twice per upstream error. The public reference only specifies the signature ((error: unknown) => string) and says it's "invoked when an error occurs during stream processing" – call frequency is not documented.

How to reproduce

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

const model = new MockLanguageModelV3({
  doStream: async () => ({
    stream: simulateReadableStream({
      chunks: [
        { type: "stream-start", warnings: [] },
        { type: "error", error: new Error("simulated upstream error") },
      ],
    }),
  }),
});

let calls = 0;

const result = streamText({
  model,
  prompt: "trigger error",
});

const uiStream = result.toUIMessageStream({
  onError: (err) => {
    calls += 1;
    console.log(`\n=== onError call #${calls} ===`);
    console.trace("stack");
    return (err as Error)?.message ?? String(err);
  },
  // Removing onFinish (and onStepFinish) makes handleUIMessageStreamFinish
  // early-return, which skips processUIMessageStream — onError then fires
  // only once. Keep it here to reproduce the double call.
  onFinish: () => {},
});

async function main() {
  for await (const chunk of uiStream) {
    console.log("chunk:", JSON.stringify(chunk));
  }
  console.log(`\nTotal onError calls: ${calls}`);
}

main();

Run:

pnpm tsx repro.ts

Results:

  Observed output

  === onError call #1 ===
  Trace: stack
      at onError (repro.ts:…)
      at Object.transform (…/ai/src/generate-text/stream-text.ts:2402:28)

  === onError call #2 ===
  Trace: stack
      at onError (repro.ts:…)
      at <anonymous> (…/ai/src/ui/process-ui-message-stream.ts:710:15)
      at runUpdateMessageJob (…/ai/src/ui-message-stream/handle-ui-message-stream-finish.ts:97:11)
      at Object.transform (…/ai/src/ui/process-ui-message-stream.ts:104:15)

  Total onError calls: 2

Stack trace shows the handoff chain: toUIMessageStream → handleUIMessageStreamFinish (runUpdateMessageJob) → processUIMessageStream.

Results

Two distinct call sites share the same onError reference:

  1. Formatter stage in generate-text/stream-text.ts:
  case 'error': {
    controller.enqueue({
      type: 'error',
      errorText: onError(part.error),
    });
  }

Called synchronously with the original provider error; return value is written onto the outgoing chunk. 2. Notifier stage in ui/process-ui-message-stream.ts:

case 'error': {
onError?.(new Error(chunk.errorText));
}
  1. Called with a freshly constructed Error wrapping the string Stage 1 just returned; return value is discarded.

The handoff is wired in ui-message-stream/handle-ui-message-stream-finish.ts, which forwards onError from toUIMessageStream into processUIMessageStream. This path is only taken when onFinish or onStepFinish is passed to toUIMessageStream; otherwise Stage 2 is skipped.

Proposal

Docs-only change. Add a note on the onError parameter of toUIMessageStream:

May be invoked more than once per error: once by the formatter stage producing the SSE chunk's errorText, and again by the chunk walker as a notification (return value discarded). Side effects inside onError (logging, metrics, persistence) should be idempotent, or externally deduped — otherwise a single upstream error will produce duplicate records.

AI SDK Version

Versions:

Code of Conduct

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

tigranl avatar Apr 24 '26 13:04 tigranl

Identify issue type

{
  "evidence": [
    "The description says the public reference only specifies the onError signature and does not document call frequency.",
    "The proposal explicitly says “Docs-only change” and asks to add a note explaining that onError may be invoked more than once per error.",
    "No behavior change is requested; the issue asks users to be warned to make side effects idempotent or deduped."
  ],
  "rationale": "Although the issue demonstrates current callback behavior, it frames the requested resolution as clarifying documentation rather than changing SDK behavior.",
  "type": "documentation",
  "confidence": "high"
}

lgrammel avatar Jul 02 '26 08:07 lgrammel

Still reproduces on 6.0.272, 6.0.300 and 7.0.127, and on 7.x with onEnd as well as onFinish. The same thing happens one level up in the usual route shape: with createUIMessageStream({ execute: ({ writer }) => writer.merge(result.toUIMessageStream({ onError })), onError, onFinish }) the outer onError gets a second call with new Error(<string the inner onError returned>). So an onError that logs the real error and returns a safe message to the client also logs the safe message as a separate error, which I think needs a code fix rather than only a docs note.

I applied each PR's change to the 7.0.127 build: both bring it down to one call per error, but with #14738 readUIMessageStream({ onError, terminateOnError: true }) no longer sees error chunks at all, while #19154 leaves that path working. Which of the two do you want to move forward?

repro
// npm i [email protected]   (same output with [email protected] and [email protected])
import { streamText, createUIMessageStream } from "ai";
import { MockLanguageModelV3, convertArrayToReadableStream } from "ai/test";

const model = new MockLanguageModelV3({
  doStream: async () => ({
    stream: convertArrayToReadableStream([
      { type: "stream-start", warnings: [] },
      { type: "error", error: new Error("upstream error detail") },
    ]),
  }),
});

const onError = (label) => (error) => {
  console.log(`${label} onError:`, error.message);
  return "Something went wrong.";
};

// 1. toUIMessageStream with onFinish (onEnd on 7.x behaves the same)
const result = streamText({ model, prompt: "hi" });
for await (const _ of result.toUIMessageStream({ onError: onError("toUIMessageStream"), onFinish: () => {} }));

// 2. route shape: createUIMessageStream + writer.merge(toUIMessageStream)
const stream = createUIMessageStream({
  execute: ({ writer }) => writer.merge(streamText({ model, prompt: "hi" }).toUIMessageStream({ onError: onError("inner") })),
  onError: onError("outer"),
  onFinish: () => {},
});
for await (const _ of stream);

Output (streamText's default error log on stderr left out):

toUIMessageStream onError: upstream error detail
toUIMessageStream onError: Something went wrong.
inner onError: upstream error detail
outer onError: Something went wrong.

HardMax71 avatar Oct 02 '26 13:10 HardMax71