Skip to content

fix(ai): propagate telemetry subscriber stream replacements to execution result (#24970) - #24984

Closed
wasim-builds wants to merge 1 commit into
vercel:mainfrom
wasim-builds:fix/issue-24970-telemetry-locked-stream
Closed

wasim-builds wants to merge 1 commit into
vercel:mainfrom
wasim-builds:fix/issue-24970-telemetry-locked-stream

Conversation

@wasim-builds

Copy link
Copy Markdown
Contributor

Fixes #24970

Background & Root Cause

In @ai-sdk/ai since 7.0.169, streamText fails with:

TypeError [ERR_INVALID_STATE]: Invalid state: The ReadableStream is locked

when an ai:telemetry diagnostics channel subscriber (such as @sentry/node or dd-trace) intercepts ctx.result.stream in asyncEnd and wraps it via:

ctx.result.stream = ctx.result.stream.pipeThrough(new TransformStream(...));

Calling pipeThrough locks the original stream.

When credentials are redacted via redactTelemetryCredentials(result) before publishing the span, replaceProperties cloned the result object using property descriptors (Object.create(proto, descriptors)). Because descriptors.stream was a static value property descriptor on the cloned object, assigning ctx.result.stream = ... only updated the clone. Meanwhile, runWithTracingChannelSpan returned the original unredacted executionResult, leaving its stream referencing the original stream that was now locked by the subscriber's pipeThrough. When the SDK then attempted to read or pipe executionResult.stream, it threw TypeError [ERR_INVALID_STATE]: The ReadableStream is locked.

Changes

  1. Accessor Forwarding on Redacted Telemetry Copies: In replaceProperties (packages/ai/src/telemetry/redact-telemetry-credentials.ts), if the object has an own stream property, define getter/setter accessors targeting the underlying object so ctx.result.stream = ... directly updates executionResult.stream.
  2. Span Stream Reconciliation: In runWithTracingChannelSpan (packages/ai/src/telemetry/tracing-channel-publisher.ts), verify after tracePromise completes whether message.result.stream !== executionResult.stream (e.g. if a subscriber replaced the result object entirely), propagating the subscriber's tapped stream back to executionResult.stream.
  3. Tests:
    • Unit tests in packages/ai/src/telemetry/tracing-channel-publisher.test.ts verifying both in-place ctx.result.stream replacement via pipeThrough and entire ctx.result replacement.
    • Integration test in packages/ai/src/telemetry/tracing-channel.test.ts verifying full streamText execution with tools when an ai:telemetry subscriber taps ctx.result.stream via pipeThrough.
  4. Changeset: Added .changeset/telemetry-stream-replacement.md for ai.

Copilot AI balanced review requested due to automatic review settings November 12, 2026 18:50
@vercel

vercel Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@wasim-builds is attempting to deploy a commit to the Vercel Labs Team on Vercel.

A member of the Team first needs to authorize it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T18:54:28.295778Z b7a2c44 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@vercel-internal-security-reviewer

Copy link
Copy Markdown
Contributor

Security review details

Comment on lines +89 to +94
const streamDesc = descriptors.stream;
if (streamDesc && 'value' in streamDesc) {
descriptors.stream = {
get() {
return (value as unknown as { stream: unknown }).stream;
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A provider tool registered under the name stream exposes its unredacted credentials to telemetry because the forwarding accessor overwrites the tool's redacted descriptor.

Fix on Vercel

@jadibdev

Copy link
Copy Markdown
Contributor

Ran validation on GitHub Actions against main (8bc7652cdb) before and after merging this PR (b7a2c44bfd), building @ai-sdk/azure... and running the #24970 repro plus the telemetry unit tests.

  • streamText: "ReadableStream is locked" since 7.0.169 when an ai:telemetry subscriber replaces result.stream (breaks Sentry's and dd-trace's AI integrations) #24970 repro (Azure Responses + tools + an ai:telemetry subscriber using pipeThrough): on main, onError fires Invalid state: The ReadableStream is locked with text: "" and tappedChunks: 0. With this PR: text: "Hello world", tappedChunks: 6, onErrors: [].
  • More stream-replacement cases: two subscribers chaining pipeThrough, replacing the whole ctx.result (ctx.result = { ...ctx.result, stream: ... }), and a 2-step tool loop with a redacted request.body. All three fail with the same locked-stream error on main and pass with this PR.
  • Reproduced the credential leak flagged by the bot on redact-telemetry-credentials.ts: with tools: { stream: openai.tools.mcp({ ..., authorization: 'secret-mcp-token' }) }, an ai:telemetry start subscriber sees authorization: "[redacted]" on main but the raw "secret-mcp-token" with this PR. redactTools reuses replaceProperties, so the new stream accessor also replaces the redacted tool entry.
  • Unit tests: with only this PR's test changes applied to main, both new tests in tracing-channel-publisher.test.ts fail; with the PR merged, all 83 pass across tracing-channel-publisher.test.ts, tracing-channel.test.ts, and create-telemetry-dispatcher.test.ts.
    • The new streamText test in tracing-channel.test.ts already passes on main. Its mock request.body has no withTelemetryRedaction(...) value, so redactTelemetryCredentials returns the original result object and never clones it.

No competing open PRs for #24970, and no reproduction-only files in the diff.

Script for the extra cases and the tools.stream probe (trimmed from the run: Case 4 dropped, simpler logging)
import { tracingChannel } from 'node:diagnostics_channel';
import { stepCountIs, streamText, tool } from 'ai';
import { createAzure } from '@ai-sdk/azure';
import { openai } from '@ai-sdk/openai';
import { withTelemetryRedaction } from '@ai-sdk/provider-utils';
import { MockLanguageModelV4, convertArrayToReadableStream } from 'ai/test';
import { z } from 'zod';

const channel = tracingChannel('ai:telemetry');

const azureEvents = [
  {
    type: 'response.created',
    response: {
      id: 'resp_1',
      created_at: 1700000000,
      model: 'test-model',
      service_tier: null,
    },
  },
  {
    type: 'response.output_item.added',
    output_index: 0,
    item: { type: 'message', id: 'msg_1' },
  },
  {
    type: 'response.output_text.delta',
    item_id: 'msg_1',
    delta: 'Hello world',
    logprobs: [],
  },
  {
    type: 'response.output_item.done',
    output_index: 0,
    item: { type: 'message', id: 'msg_1' },
  },
  {
    type: 'response.completed',
    response: {
      incomplete_details: null,
      service_tier: null,
      usage: {
        input_tokens: 5,
        input_tokens_details: { cached_tokens: 0 },
        output_tokens: 2,
        output_tokens_details: { reasoning_tokens: 0 },
      },
    },
  },
];

function createFakeAzure() {
  return createAzure({
    resourceName: 'example',
    apiKey: 'test',
    fetch: async () =>
      new Response(
        azureEvents.map(e => `data: ${JSON.stringify(e)}\n\n`).join('') +
          'data: [DONE]\n\n',
        { headers: { 'content-type': 'text/event-stream' } },
      ),
  });
}

// Case 1: Two simultaneous ai:telemetry subscribers chaining pipeThrough
{
  let sub1Chunks = 0;
  let sub2Chunks = 0;
  const sub1 = {
    start() {},
    end() {},
    asyncStart() {},
    error() {},
    asyncEnd(ctx) {
      if (!ctx.result?.stream) return;
      ctx.result.stream = ctx.result.stream.pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            sub1Chunks++;
            controller.enqueue(chunk);
          },
        }),
      );
    },
  };
  const sub2 = {
    start() {},
    end() {},
    asyncStart() {},
    error() {},
    asyncEnd(ctx) {
      if (!ctx.result?.stream) return;
      ctx.result.stream = ctx.result.stream.pipeThrough(
        new TransformStream({
          transform(chunk, controller) {
            sub2Chunks++;
            controller.enqueue(chunk);
          },
        }),
      );
    },
  };

  channel.subscribe(sub1);
  channel.subscribe(sub2);
  const errors = [];
  try {
    const azure = createFakeAzure();
    const result = streamText({
      model: azure.responses('test-deployment'),
      prompt: 'Hello',
      tools: {
        getWeather: tool({
          description: 'Get the weather',
          inputSchema: z.object({ city: z.string() }),
          execute: async () => 'sunny',
        }),
      },
      onError: ({ error }) => errors.push(error?.message ?? String(error)),
    });
    let text = '';
    for await (const delta of result.textStream) text += delta;
    console.log('CASE1_TWO_SUBSCRIBERS', {
      text,
      sub1Chunks,
      sub2Chunks,
      errors,
    });
  } finally {
    channel.unsubscribe(sub1);
    channel.unsubscribe(sub2);
  }
}

// Case 2: Whole ctx.result replacement in asyncEnd
{
  let chunks = 0;
  const sub = {
    start() {},
    end() {},
    asyncStart() {},
    error() {},
    asyncEnd(ctx) {
      if (!ctx.result?.stream) return;
      ctx.result = {
        ...ctx.result,
        stream: ctx.result.stream.pipeThrough(
          new TransformStream({
            transform(chunk, controller) {
              chunks++;
              controller.enqueue(chunk);
            },
          }),
        ),
      };
    },
  };

  channel.subscribe(sub);
  const errors = [];
  try {
    const azure = createFakeAzure();
    const result = streamText({
      model: azure.responses('test-deployment'),
      prompt: 'Hello',
      tools: {
        getWeather: tool({
          description: 'Get the weather',
          inputSchema: z.object({ city: z.string() }),
          execute: async () => 'sunny',
        }),
      },
      onError: ({ error }) => errors.push(error?.message ?? String(error)),
    });
    let text = '';
    for await (const delta of result.textStream) text += delta;
    console.log('CASE2_WHOLE_RESULT_REPLACE', { text, chunks, errors });
  } finally {
    channel.unsubscribe(sub);
  }
}

// Case 3: Multi-step tool execution with redacted request.body + pipeThrough subscriber
{
  let stepCalls = 0;
  let subscriberStreamWraps = 0;
  let toolExecuted = false;
  const sub = {
    start() {},
    end() {},
    asyncStart() {},
    error() {},
    asyncEnd(ctx) {
      if (!ctx.result?.stream) return;
      subscriberStreamWraps++;
      ctx.result.stream = ctx.result.stream.pipeThrough(new TransformStream());
    },
  };

  channel.subscribe(sub);
  const errors = [];
  try {
    const model = new MockLanguageModelV4({
      doStream: async () => {
        const callIndex = stepCalls++;
        if (callIndex === 0) {
          return {
            stream: convertArrayToReadableStream([
              { type: 'stream-start', warnings: [] },
              {
                type: 'tool-call',
                toolCallId: 'tc_1',
                toolName: 'getWeather',
                input: JSON.stringify({ city: 'NYC' }),
              },
              {
                type: 'finish',
                finishReason: { unified: 'tool-calls', raw: undefined },
                usage: {
                  inputTokens: {
                    total: 5,
                    noCache: 5,
                    cacheRead: 0,
                    cacheWrite: 0,
                  },
                  outputTokens: { total: 3, text: 3, reasoning: 0 },
                },
              },
            ]),
            request: {
              body: withTelemetryRedaction({ token: 'secret-1' }, v => ({
                ...v,
                token: '[redacted]',
              })),
            },
          };
        }
        return {
          stream: convertArrayToReadableStream([
            { type: 'stream-start', warnings: [] },
            { type: 'text-start', id: '1' },
            { type: 'text-delta', id: '1', delta: 'It is sunny in NYC' },
            { type: 'text-end', id: '1' },
            {
              type: 'finish',
              finishReason: { unified: 'stop', raw: 'stop' },
              usage: {
                inputTokens: {
                  total: 5,
                  noCache: 5,
                  cacheRead: 0,
                  cacheWrite: 0,
                },
                outputTokens: { total: 5, text: 5, reasoning: 0 },
              },
            },
          ]),
          request: {
            body: withTelemetryRedaction({ token: 'secret-2' }, v => ({
              ...v,
              token: '[redacted]',
            })),
          },
        };
      },
    });

    const result = streamText({
      model,
      prompt: 'Weather in NYC?',
      stopWhen: stepCountIs(2),
      tools: {
        getWeather: tool({
          description: 'Get weather',
          inputSchema: z.object({ city: z.string() }),
          execute: async () => {
            toolExecuted = true;
            return 'sunny';
          },
        }),
      },
      onError: ({ error }) => errors.push(error?.message ?? String(error)),
    });
    let text = '';
    for await (const delta of result.textStream) text += delta;
    console.log('CASE3_MULTISTEP', {
      text,
      toolExecuted,
      subscriberStreamWraps,
      errors,
    });
  } finally {
    channel.unsubscribe(sub);
  }
}

// Case 5: Probe for tool literally named "stream" credential redaction
{
  const observedAuthValues = [];
  const sub = {
    start(ctx) {
      const streamTool = ctx?.event?.tools?.stream;
      if (streamTool && typeof streamTool === 'object') {
        observedAuthValues.push(streamTool.args?.authorization ?? null);
      }
    },
    end() {},
    asyncStart() {},
    error() {},
    asyncEnd() {},
  };
  channel.subscribe(sub);
  const errors = [];
  try {
    const azure = createFakeAzure();
    const result = streamText({
      model: azure.responses('test-deployment'),
      prompt: 'Hello',
      tools: {
        stream: openai.tools.mcp({
          serverLabel: 'remote',
          serverUrl: 'https://example.com/mcp',
          authorization: 'secret-mcp-token',
        }),
      },
      onError: ({ error }) => errors.push(error?.message ?? String(error)),
    });
    await result.consumeStream();
    console.log('CASE5_PROBE_TOOL_NAMED_STREAM', {
      observedAuthValues,
      errors,
    });
  } finally {
    channel.unsubscribe(sub);
  }
}

@aayush-kapoor aayush-kapoor left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Projects

None yet

4 participants