Skip to content

fix(ai): preserve telemetry stream replacements during credential redaction - #25135

Merged
aayush-kapoor merged 1 commit into
mainfrom
fix/telemetry-stream-redaction
Nov 16, 2026
Merged

aayush-kapoor merged 1 commit into
mainfrom
fix/telemetry-stream-redaction

Conversation

@aayush-kapoor

@aayush-kapoor aayush-kapoor commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Background

Credential redaction created result copies that shared the original stream. When Sentry or another telemetry integration wrapped that stream, core retained the locked original and failed with ReadableStream is locked.

Fixes #24970

Summary

Forward stream replacements from redacted copies to the original result while preserving credential redaction. Add regression coverage for multiple subscribers and nested integrations, plus a patch changeset.

Validation: all 96 telemetry tests pass in both Node and Edge; full workspace type checking, lint, and formatting pass.

End-to-End Verification

Verified by running the Azure Responses reproduction against locally built packages before and after the fix.

Reproduction, commands, and results

Requires Node.js 22.13+ and installed workspace dependencies (pnpm install --frozen-lockfile). Uses fake SSE responses through the actual Azure provider; no API credentials or network access are needed to run the reproduction.

Save the script below as /tmp/ai-sdk-24970.mjs, then run these commands from each checkout. The workspace links in examples/ai-functions resolve the local package builds:

pnpm exec turbo build --filter=ai... --filter=@ai-sdk/azure...
cd examples/ai-functions
node --input-type=module < /tmp/ai-sdk-24970.mjs
import { tracingChannel } from 'node:diagnostics_channel';
import { streamText, tool } from 'ai';
import { createAzure } from '@ai-sdk/azure';
import { z } from 'zod';

const events = [
  { 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 } },
  } },
];
const azure = createAzure({
  resourceName: 'example', apiKey: 'test',
  fetch: async () => new Response(
    events.map(e => `data: ${JSON.stringify(e)}\n\n`).join('') + 'data: [DONE]\n\n',
    { headers: { 'content-type': 'text/event-stream' } },
  ),
});
const channel = tracingChannel('ai:telemetry');
for (const withTools of [false, true]) {
  for (const withSubscriber of [false, true]) {
    let providerStream;
    let streamObservation;
    const errors = [];
    const model = azure.responses('test-deployment');
    const doStream = model.doStream.bind(model);
    model.doStream = async options => {
      const result = await doStream(options);
      providerStream = result.stream;
      return result;
    };
    const subscribers = {
      start() {}, end() {}, asyncStart() {}, error() {},
      asyncEnd(ctx) {
        if (!ctx.result?.stream) return;
        streamObservation = { sharedWithProvider: ctx.result.stream === providerStream, lockedBefore: providerStream.locked };
        ctx.result.stream = ctx.result.stream.pipeThrough(new TransformStream());
        streamObservation.lockedAfter = providerStream.locked;
      },
    };
    if (withSubscriber) channel.subscribe(subscribers);
    try {
      const result = streamText({
        model, prompt: 'Hello',
        ...(withTools ? { tools: { getWeather: tool({
          description: 'Get the weather', inputSchema: z.object({ city: z.string() }),
          execute: async () => 'sunny',
        }) } } : {}),
        onError: ({ error }) => errors.push(error.message),
      });
      let text = '';
      for await (const delta of result.textStream) text += delta;
      console.log(JSON.stringify({ withTools, withSubscriber, text, errors, streamObservation }));
    } finally {
      if (withSubscriber) channel.unsubscribe(subscribers);
    }
  }
}

Before: Tools plus a wrapping subscriber produced empty text and Invalid state: The ReadableStream is locked. The other three combinations returned "Hello world".

After: All four combinations returned "Hello world" without errors.

This verifies the provider flow with simulated Azure responses, rather than a live Azure service or installed Sentry/Datadog integration.

@vercel

vercel Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
ai-tarballs Ready Ready Preview, v0 Nov 16, 2026 8:24pm UTC

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Published in:

Package Version
ai 7.0.174 github npm
@ai-sdk/alibaba 2.0.92 github npm
@ai-sdk/amazon-bedrock 5.0.143 github npm
@ai-sdk/angular 3.0.174 github npm
@ai-sdk/anthropic 4.0.106 github npm
@ai-sdk/anthropic-aws 2.0.99 github npm
@ai-sdk/assemblyai 3.0.83 github npm
@ai-sdk/azure 4.0.127 github npm
@ai-sdk/baseten 2.1.72 github npm
@ai-sdk/black-forest-labs 2.0.86 github npm
@ai-sdk/bytedance 2.0.87 github npm
@ai-sdk/cartesia 3.0.77 github npm
@ai-sdk/cerebras 3.0.94 github npm
@ai-sdk/code-mode 1.0.131 github npm
@ai-sdk/cohere 4.0.85 github npm
@ai-sdk/deepgram 3.1.54 github npm
@ai-sdk/deepinfra 3.0.94 github npm
@ai-sdk/deepseek 3.0.88 github npm
@ai-sdk/devtools 1.0.77 github npm
@ai-sdk/elevenlabs 3.0.87 github npm
@ai-sdk/fal 3.0.85 github npm
@ai-sdk/fireworks 3.0.97 github npm
@ai-sdk/fish-audio 3.0.60 github npm
@ai-sdk/gateway 4.0.147 github npm
@ai-sdk/gladia 3.0.83 github npm
@ai-sdk/gmicloud 3.0.65 github npm
@ai-sdk/google 4.0.122 github npm
@ai-sdk/google-vertex 5.0.142 github npm
@ai-sdk/groq 4.0.85 github npm
@ai-sdk/harness 1.0.185 github npm
@ai-sdk/harness-acp 1.0.125 github npm
@ai-sdk/harness-claude-code 1.0.189 github npm
@ai-sdk/harness-cline 1.0.113 github npm
@ai-sdk/harness-codex 1.0.187 github npm
@ai-sdk/harness-cursor 1.0.100 github npm
@ai-sdk/harness-deepagents 1.0.185 github npm
@ai-sdk/harness-fx 1.0.101 github npm
@ai-sdk/harness-github-copilot 1.0.82 github npm
@ai-sdk/harness-grok-build 1.0.124 github npm
@ai-sdk/harness-opencode 1.0.188 github npm
@ai-sdk/harness-pi 1.0.188 github npm
@ai-sdk/heygen 3.0.26 github npm
@ai-sdk/huggingface 2.0.94 github npm
@ai-sdk/hume 3.0.82 github npm
@ai-sdk/klingai 4.0.86 github npm
@ai-sdk/langchain 3.0.174 github npm
@ai-sdk/llamaindex 3.0.174 github npm
@ai-sdk/luma 3.0.85 github npm
@ai-sdk/mcp 2.0.100 github npm
@ai-sdk/minimax 3.0.83 github npm
@ai-sdk/mistral 4.0.88 github npm
@ai-sdk/moonshotai 3.0.94 github npm
@ai-sdk/open-responses 2.0.88 github npm
@ai-sdk/openai 4.0.119 github npm
@ai-sdk/openai-compatible 3.0.93 github npm
@ai-sdk/otel 1.0.174 github npm
@ai-sdk/parallel 3.0.10 github npm
@ai-sdk/perplexity 5.0.36 github npm
@ai-sdk/policy-opa 1.0.174 github npm
@ai-sdk/prodia 2.0.85 github npm
@ai-sdk/provider 4.0.39 github npm
@ai-sdk/provider-utils 5.0.82 github npm
@ai-sdk/quiverai 2.0.84 github npm
@ai-sdk/react 4.0.178 github npm
@ai-sdk/replicate 3.0.85 github npm
@ai-sdk/revai 3.0.82 github npm
@ai-sdk/rsc 3.0.174 github npm
@ai-sdk/sandbox-just-bash 1.0.185 github npm
@ai-sdk/sandbox-vercel 1.0.185 github npm
@ai-sdk/scaledown 3.0.2 github npm
@ai-sdk/svelte 5.0.174 github npm
@ai-sdk/tencent 3.0.4 github npm
@ai-sdk/togetherai 3.0.95 github npm
@ai-sdk/tool-bash 1.0.28 github npm
@ai-sdk/tool-web-fetch 1.0.24 github npm
@ai-sdk/topaz 3.0.29 github npm
@ai-sdk/tui 1.0.175 github npm
@ai-sdk/typesafe-ai 3.0.41 github npm
@ai-sdk/valibot 3.0.82 github npm
@ai-sdk/voyage 2.0.84 github npm
@ai-sdk/vue 4.0.174 github npm
@ai-sdk/workflow 2.0.106 github npm
@ai-sdk/workflow-harness 1.0.185 github npm
@ai-sdk/xai 5.0.47 github npm
@ai-sdk/zai 3.0.56 github npm

RulaKhaled added a commit to getsentry/sentry-javascript that referenced this pull request Nov 18, 2026
## What

Adds a node integration scenario that runs `streamText` with tools
through `@ai-sdk/openai` (Responses API, fake SSE `fetch`, no network)
with tracing sampled and unsampled. The caller must get the streamed
text, and the model and tool spans must be recorded.

## Why

`ai` 7.0.168–7.0.173 broke this call with `ReadableStream is locked`
whenever Sentry was loaded (#26403). Our existing scenarios use
`MockLanguageModelV3`, which sends no request body, so `ai` never makes
the redacted result copy that triggers the bug. `@ai-sdk/openai`
attaches a telemetry redactor to the body when tools are sent, so it
does.

The suite requires `ai: '^7.0.174'`, the first release with the upstream
fix (vercel/ai#25135).

Refs #26403

<!-- junior-request-attribution:start -->
via **Rola Abuhasna**.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AD0C848BQ509%3A1794901557.524269 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/slack%3AD0C848BQ509%3A1794901557.524269)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AD0C848BQ509%3A1794901557.524269/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: Rola Abuhasna <[email protected]>
melgarafael pushed a commit to melgarafael/DeskcommCRM that referenced this pull request Nov 18, 2026
…I SDK (#4798)

Com o provedor `openai-assinatura`, toda chamada "Responder o cliente"
falhava em ~1 s com `Invalid state: The ReadableStream is locked`, e a aba
Teste do agente dava `preview_failed`. Chamada curta do mesmo provedor
passava; Gemini e OpenAI por chave não eram afetados.

Causa, medida no código e nas dependências instaladas:

- o ramo da assinatura é o único que monta `streamText` com tools
  (lib/agent-engine/edge/llm/run-model-call.ts:1131); os outros provedores vão
  por `generateText` (linha 1182);
- com a integração `VercelAI` do Sentry instalada, o SDK assina o canal
  `ai:telemetry` e, no `asyncEnd`, troca `result.stream` por um stream espiado
  (`deferStreamedModelCallEnd` → `tapModelCallStream`,
  @sentry/server-utils/integrations/vercel-ai/vercel-ai-dc-subscriber.js:339).
  O `pipeThrough` trava o `ReadableStream` original; a partir do `ai` 7.0.168 o
  SDK publica uma CÓPIA (`redactTelemetryCredentials`) que compartilha o mesmo
  stream, então o laço de ferramentas volta ao original já travado
  (getsentry/sentry-javascript#26403, vercel/ai#24970). Sem tools não há
  segunda volta — por isso só a assinatura caía;
- e isso atingia toda instalação porque `resolveSentryDsn` (lib/sentry/dsn.ts:19)
  mandava o vazio para o DSN da comunidade, então o `Sentry.init` rodava por
  padrão no app (sentry.server.config.ts:12), no edge (sentry.edge.config.ts:10),
  no worker (workers/agent-worker/main.ts:48) e no navegador.

Conserto:

- DSN vazio (ou ausente) = telemetria DESLIGADA: sai o fallback para o DSN da
  comunidade. O aceite virou token explícito (`SENTRY_DSN=comunidade`), que o
  install.sh grava no lugar do vazio — consentimento registrado, sem a chave do
  ingest no `.env` do cliente;
- sem DSN, nenhum `Sentry.init` roda (nem cliente é criado, nem integração é
  instalada);
- com DSN, `integrations: integracoesDoServidor` tira a integração `VercelAI`
  dos três inits de servidor. Tradeoff declarado em `lib/sentry/dsn.ts`: quem
  aponta para o próprio Sentry perde spans de IA, mantém a captura de erro (e a
  alternativa — não iniciar Sentry no worker — apagaria o erro de todos os
  provedores, porque o processo é o mesmo).

Não muda versão do `ai` nem do SDK do Sentry: a correção do vercel/ai#25135 só
chega no 7.0.174.

Testes: tests/unit/sentry-e-assinatura-do-chatgpt.test.ts (quatro casos, com
controle negativo do dublê), contrato do `SENTRY_DSN` vazio atualizado em
tests/unit/sentry-comunidade-so-erro.test.ts, e o cenário de aceite do
install.sh em hostgator-setup-kit/test-validators.sh.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants