#21819·ai

streamText: in-stream provider `error` part leaves the doStream span without ERROR status, and unended if the consumer stops reading

Author: Lorenzo45Created Sep 30, 2026Updated Sep 30, 2026
Labelstask-identify-issue-type-donetask-bug-reproduction-successfactory-activefactory-automatictask-identify-harness-labels-done

Description

When a provider returns HTTP 200 and then sends an in-stream error part (for example, OpenAI server_error forwarded by the AI Gateway), the ai.streamText.doStream span from @ai-sdk/otel's LegacyOpenTelemetry does not record the failure:

  1. No ERROR status, even when the stream finishes normally. The step flush sets ai.response.finishReason = "error", but span status stays UNSET and there is no status message. OTEL backends and error views that filter on span status never see these failures.
  2. The span stays open if the consumer stops reading at the error part. Stopping at the first error part is common: the part carries the terminal error, and callers throw it to their own retry or error handling. If the provider body is still open at that point, the span never ends, so it is never exported. If the caller aborts, nothing ends it either.

This is related to, but not covered by, #20586 / #20870 (released in 7.0.106). That fix handles the provider response body failing while it is being read. Here the body delivers a well-formed error part.

Expected

  • An error part sets SpanStatusCode.ERROR on the step (doStream) span, with the error message. onStepEnd already knows finishReason === "error".
  • When the consumer cancels the result stream, or the abort signal fires while nobody is pulling, telemetry ends the open step and root spans (onAbort or onError), so they are exported.

Actual (ai 7.0.123, @ai-sdk/otel 1.0.123, @ai-sdk/gateway 4.0.101)

What happens after the error part doStream span
Consumer keeps reading; provider closes the body ends: status UNSET, finishReason=error
Consumer stops reading, then aborts never ends (not exported)
Consumer stops reading; body stays open never ends (not exported)

The behavior is the same on ai 7.0.66 and @ai-sdk/otel 1.0.66.

Reproduction

javascript
// bun add [email protected] @ai-sdk/[email protected] @ai-sdk/[email protected] @opentelemetry/api @opentelemetry/sdk-trace-base
import { AsyncLocalStorage } from "node:async_hooks";
import { LegacyOpenTelemetry } from "@ai-sdk/otel";
import { createGateway } from "@ai-sdk/gateway";
import { ROOT_CONTEXT, context } from "@opentelemetry/api";
import { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { streamText } from "ai";

const als = new AsyncLocalStorage();
context.setGlobalContextManager({
  active: () => als.getStore() ?? ROOT_CONTEXT,
  with: (c, fn, t, ...a) => als.run(c, () => fn.apply(t, a)),
  bind: (_c, t) => t, enable() { return this; }, disable() { return this; },
});

async function run(mode) {
  const exporter = new InMemorySpanExporter();
  const provider = new BasicTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] });
  let body;
  // HTTP 200, then one in-stream provider error part. The body stays open.
  const fetch = async () => new Response(new ReadableStream({
    start(c) {
      body = c;
      c.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({
        type: "error",
        error: { type: "server_error", message: "An error occurred while processing your request." },
      })}\n\n`));
    },
  }), { status: 200, headers: { "content-type": "text/event-stream" } });

  const abort = new AbortController();
  const result = streamText({
    model: createGateway({ apiKey: "x", fetch })("openai/gpt-5"),
    prompt: "hi",
    abortSignal: abort.signal,
    telemetry: { isEnabled: true, integrations: [new LegacyOpenTelemetry({ tracer: provider.getTracer("ai") })] },
    onError: () => {},
  });

  for await (const part of result.stream) if (part.type === "error") break; // stop at the error part
  if (mode === "close") body.close();
  if (mode === "abort") abort.abort();
  await new Promise((r) => setTimeout(r, 200));

  const spans = exporter.getFinishedSpans()
    .map((s) => `${s.name} status=${s.status.code} finishReason=${s.attributes["ai.response.finishReason"]}`);
  console.log(mode, spans.length ? spans.join(" ; ") : "(no spans ended)");
}

for (const mode of ["close", "abort", "open"]) await run(mode);
process.exit(0);

Output:

close ai.streamText.doStream status=0 finishReason=error
abort (no spans ended)
open (no spans ended)

Workaround we use today: keep a handle to the span that is active when the provider fetch starts (the doStream step span). When the adapter sees an error part, it sets finishReason=error and ERROR status on that span.

AI SDK Version

  • ai: 7.0.123 (also 7.0.66)
  • @ai-sdk/otel: 1.0.123 (also 1.0.66)
  • @ai-sdk/gateway: 4.0.101 (also 4.0.52)

Code of Conduct

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