From fa40623c5444a6a9fe05b4b23fefb607888f5052 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:49:20 +0000 Subject: [PATCH 1/3] fix(server-utils): Mark Mistral and Workers AI spans as cancelled when the caller aborts Co-Authored-By: Rola Abuhasna --- .../suites/tracing/mistral/scenario-abort.mjs | 57 +++++++++++++++++++ .../suites/tracing/mistral/test.ts | 25 ++++++++ packages/server-utils/src/ai/mistral/index.ts | 22 ++++--- packages/server-utils/src/ai/mistral/utils.ts | 13 ++++- .../server-utils/src/ai/workers-ai/index.ts | 25 +++++--- .../server-utils/src/integrations/mistral.ts | 7 ++- .../test/ai/lib/tracing/caller-abort.test.ts | 30 ++++++++++ 7 files changed, 160 insertions(+), 19 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs diff --git a/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs new file mode 100644 index 000000000000..5a824e3f478f --- /dev/null +++ b/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs @@ -0,0 +1,57 @@ +import { Mistral } from '@mistralai/mistralai'; +import * as Sentry from '@sentry/node'; +import express from 'express'; + +function startMockServer() { + const app = express(); + app.use(express.json()); + + // Never responds, so each request only ends when the client gives up on it. + app.post('/v1/chat/completions', () => {}); + + return new Promise(resolve => { + const server = app.listen(0, () => { + resolve(server); + }); + }); +} + +function abortAfter(ms) { + const controller = new AbortController(); + setTimeout(() => controller.abort(), ms); + return controller.signal; +} + +async function run() { + const server = await startMockServer(); + + await Sentry.startSpan({ op: 'function', name: 'main' }, async () => { + const client = new Mistral({ + apiKey: 'mock-api-key', + serverURL: `http://localhost:${server.address().port}`, + retryConfig: { strategy: 'none' }, + }); + const messages = [{ role: 'user', content: 'Aborted by the caller' }]; + + const requests = [ + ['stream', 'abort-before-stream', { signal: abortAfter(50) }], + ['complete', 'abort-non-streaming', { fetchOptions: { signal: abortAfter(50) } }], + ['stream', 'timeout-before-stream', { timeoutMs: 50 }], + ['complete', 'timeout-non-streaming', { timeoutMs: 50 }], + ]; + for (const [method, model, requestOptions] of requests) { + try { + await client.chat[method]({ model, messages }, requestOptions); + } catch { + // Error expected + } + } + }); + + await Sentry.flush(2000); + + server.closeAllConnections(); + server.close(); +} + +run(); diff --git a/dev-packages/node-integration-tests/suites/tracing/mistral/test.ts b/dev-packages/node-integration-tests/suites/tracing/mistral/test.ts index 8b5373b22921..51fd5b80a3bf 100644 --- a/dev-packages/node-integration-tests/suites/tracing/mistral/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/mistral/test.ts @@ -314,4 +314,29 @@ describe('Mistral integration', () => { .completed(); }); }); + + createEsmTests(__dirname, 'scenario-abort.mjs', 'instrument.mjs', (createRunner, test) => { + test('ends a call the caller aborts as cancelled, but an SDK timeout as an error', async () => { + await createRunner() + .unordered() + .expect({ + span: container => { + const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === ORIGIN); + expect(spans).toHaveLength(4); + const statusByModel = Object.fromEntries( + spans.map(span => [span.attributes[GEN_AI_REQUEST_MODEL]?.value, span.status]), + ); + // Span streaming sends `cancelled` as `ok`. + expect(statusByModel).toEqual({ + 'abort-before-stream': 'ok', + 'abort-non-streaming': 'ok', + 'timeout-before-stream': 'error', + 'timeout-non-streaming': 'error', + }); + }, + }) + .start() + .completed(); + }); + }); }); diff --git a/packages/server-utils/src/ai/mistral/index.ts b/packages/server-utils/src/ai/mistral/index.ts index 4f6ba7b25f7e..270667239c53 100644 --- a/packages/server-utils/src/ai/mistral/index.ts +++ b/packages/server-utils/src/ai/mistral/index.ts @@ -1,4 +1,4 @@ -import { SPAN_STATUS_ERROR, startSpan, startSpanManual, stringify } from '@sentry/core'; +import { startSpan, startSpanManual, stringify } from '@sentry/core'; import type { Span, SpanAttributeValue } from '@sentry/core'; import { GEN_AI_AGENT_NAME, @@ -14,6 +14,7 @@ import type { InstrumentedMethodEntry } from '../core/utils'; import { buildMethodPath, extractSystemInstructions, + getErrorStatus, getGenAiSpanOp, resolveAIRecordingOptions, wrapPromiseWithMethods, @@ -22,7 +23,7 @@ import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes'; import { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants'; import { instrumentEventStream } from './streaming'; import type { MistralOptions } from './types'; -import { addResponseAttributes, extractRequestParameters, getSpanName } from './utils'; +import { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from './utils'; /** * Serialize tool definitions from request parameters, if present. @@ -113,6 +114,7 @@ function instrumentMethod( const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs, isStreamRequested); const params = args[0] as Record | undefined; + const abortSignal = getMistralRequestSignal(args[1]); const spanConfig = { name: getSpanName(operationName, requestAttributes), @@ -140,7 +142,7 @@ function instrumentMethod( return result; }, error => { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); span.end(); throw error; }, @@ -159,10 +161,16 @@ function instrumentMethod( addRequestAttributes(span, params, operationName); } - return originalResult.then(result => { - addResponseAttributes(span, result, options.recordOutputs); - return result; - }); + return originalResult.then( + result => { + addResponseAttributes(span, result, options.recordOutputs); + return result; + }, + error => { + span.setStatus(getErrorStatus(abortSignal)); + throw error; + }, + ); }); return wrapPromiseWithMethods(originalResult, instrumentedPromise); diff --git a/packages/server-utils/src/ai/mistral/utils.ts b/packages/server-utils/src/ai/mistral/utils.ts index e1786582a2ef..086f40655cec 100644 --- a/packages/server-utils/src/ai/mistral/utils.ts +++ b/packages/server-utils/src/ai/mistral/utils.ts @@ -1,7 +1,7 @@ /* eslint-disable typescript-eslint/no-deprecated */ import type { Span, SpanAttributeValue } from '@sentry/core'; import type { GenAiOutputMessage } from '../core/utils'; -import { setOutputMessagesAttribute } from '../core/utils'; +import { getRequestSignal, setOutputMessagesAttribute } from '../core/utils'; import { GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, @@ -53,6 +53,17 @@ export function getSpanName(operationName: string, attributes: Record { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); span.end(); throw error; }; @@ -95,12 +96,18 @@ function instrumentRun( addRequestAttributes(span, inputs, operationName); } - return originalResult.then(result => { - if (!returnsRawResponse) { - addResponseAttributes(span, result, options.recordOutputs, operationName); - } - return result; - }); + return originalResult.then( + result => { + if (!returnsRawResponse) { + addResponseAttributes(span, result, options.recordOutputs, operationName); + } + return result; + }, + error => { + span.setStatus(getErrorStatus(abortSignal)); + throw error; + }, + ); }); }; } diff --git a/packages/server-utils/src/integrations/mistral.ts b/packages/server-utils/src/integrations/mistral.ts index 2092a689df77..4fb281c056df 100644 --- a/packages/server-utils/src/integrations/mistral.ts +++ b/packages/server-utils/src/integrations/mistral.ts @@ -2,12 +2,12 @@ import { SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import * as diagnosticsChannel from '../utils/diagnosticsChannel'; import type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core'; import { defineIntegration, startInactiveSpan } from '@sentry/core'; -import { getGenAiSpanOp, resolveAIRecordingOptions } from '../ai/core/utils'; +import { getGenAiSpanOp, markCancelledIfAborted, resolveAIRecordingOptions } from '../ai/core/utils'; import { addRequestAttributes, extractRequestAttributes } from '../ai/mistral'; import { MISTRAL_INTEGRATION_NAME, MISTRAL_ORIGIN } from '../ai/mistral/constants'; import { instrumentEventStream } from '../ai/mistral/streaming'; import type { MistralOptions } from '../ai/mistral/types'; -import { addResponseAttributes, getSpanName } from '../ai/mistral/utils'; +import { addResponseAttributes, getMistralRequestSignal, getSpanName } from '../ai/mistral/utils'; import { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers'; import type { OrchestrionChannelContext } from '../orchestrion/types'; import { CHANNELS } from '../orchestrion/channels'; @@ -43,6 +43,9 @@ function instrumentMistral(options: MistralOptions): void { data => createGenAiSpan(data, operation, streaming, options), { beforeSpanEnd: (span, data) => { + if ('error' in data) { + markCancelledIfAborted(span, getMistralRequestSignal(data.arguments?.[1])); + } addResponseAttributes(span, data.result, resolveAIRecordingOptions(options).recordOutputs); }, // Streaming: the result is an `EventStream` consumed later, so instrument it and let it end the span. diff --git a/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts b/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts index e9e999e1b2fe..d6deff64250e 100644 --- a/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/caller-abort.test.ts @@ -3,7 +3,9 @@ import { getMainCarrier, setCurrentClient, spanToStaticSpanJSON } from '@sentry/ import type { Span } from '@sentry/core'; import { instrumentAnthropicAiClient } from '../../../../src/ai/anthropic-ai'; import { instrumentGoogleGenAIClient } from '../../../../src/ai/google-genai'; +import { instrumentMistralAiClient } from '../../../../src/ai/mistral'; import { instrumentOpenAiClient } from '../../../../src/ai/openai'; +import { instrumentWorkersAiClient } from '../../../../src/ai/workers-ai'; import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; type Call = (signal: AbortSignal, stream: boolean) => Promise; @@ -41,6 +43,34 @@ const providers: Array<{ name: string; call: () => Call }> = [ }; }, }, + { + name: 'mistral', + call: () => { + const client = instrumentMistralAiClient({ chat: { complete: rejectingMethod(), stream: rejectingMethod() } }); + return (signal, stream) => { + const params = { model: 'mistral-small-latest', messages: [] }; + return stream ? client.chat.stream(params, { signal }) : client.chat.complete(params, { signal }); + }; + }, + }, + { + name: 'mistral with fetchOptions.signal', + call: () => { + const client = instrumentMistralAiClient({ chat: { complete: rejectingMethod(), stream: rejectingMethod() } }); + return (signal, stream) => { + const params = { model: 'mistral-small-latest', messages: [] }; + const requestOptions = { fetchOptions: { signal } }; + return stream ? client.chat.stream(params, requestOptions) : client.chat.complete(params, requestOptions); + }; + }, + }, + { + name: 'workers-ai', + call: () => { + const client = instrumentWorkersAiClient({ run: rejectingMethod() }); + return (signal, stream) => client.run('@cf/meta/llama-3.1-8b-instruct', { prompt: 'Hello', stream }, { signal }); + }, + }, ]; describe.each(providers)('$name caller aborts', ({ call }) => { From 2974b42cead9ba9548eb2f54341172baf5241bb7 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:26:40 +0000 Subject: [PATCH 2/3] fix(server-utils): Mark Mistral and Workers AI streams as cancelled when the caller aborts mid-stream Co-Authored-By: Rola Abuhasna --- .../tracing/anthropic/scenario-abort.mjs | 16 ++--- .../suites/tracing/mistral/scenario-abort.mjs | 10 +-- .../suites/tracing/openai/scenario-abort.mjs | 10 +-- packages/server-utils/src/ai/mistral/index.ts | 2 +- .../server-utils/src/ai/mistral/streaming.ts | 12 ++-- .../server-utils/src/ai/workers-ai/index.ts | 2 +- .../src/ai/workers-ai/streaming.ts | 6 +- .../server-utils/src/integrations/mistral.ts | 8 ++- .../test/ai/lib/tracing/stream-errors.test.ts | 61 +++++++++++++++++++ 9 files changed, 99 insertions(+), 28 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs index 8a15d662c231..cf79de7d125b 100644 --- a/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/anthropic/scenario-abort.mjs @@ -34,26 +34,26 @@ async function run() { const messages = [{ role: 'user', content: 'Aborted by the caller' }]; const requests = [ - [{ model: 'abort-before-stream', stream: true }, { signal: abortAfter(50) }], - [{ model: 'abort-non-streaming' }, { signal: abortAfter(50) }], - [{ model: 'timeout-before-stream', stream: true }, { timeout: 50 }], - [{ model: 'timeout-non-streaming' }, { timeout: 50 }], + [{ model: 'abort-before-stream', stream: true }, () => ({ signal: abortAfter(50) })], + [{ model: 'abort-non-streaming' }, () => ({ signal: abortAfter(50) })], + [{ model: 'timeout-before-stream', stream: true }, () => ({ timeout: 50 })], + [{ model: 'timeout-non-streaming' }, () => ({ timeout: 50 })], ]; for (const [params, requestOptions] of requests) { try { - await client.messages.create({ ...params, max_tokens: 100, messages }, requestOptions); + await client.messages.create({ ...params, max_tokens: 100, messages }, requestOptions()); } catch { // Error expected } } const streamRequests = [ - [{ model: 'stream-helper-abort' }, { signal: abortAfter(50) }], - [{ model: 'stream-helper-signal-timeout' }, { signal: AbortSignal.timeout(50) }], + [{ model: 'stream-helper-abort' }, () => ({ signal: abortAfter(50) })], + [{ model: 'stream-helper-signal-timeout' }, () => ({ signal: AbortSignal.timeout(50) })], ]; for (const [params, requestOptions] of streamRequests) { try { - await client.messages.stream({ ...params, max_tokens: 100, messages }, requestOptions).finalMessage(); + await client.messages.stream({ ...params, max_tokens: 100, messages }, requestOptions()).finalMessage(); } catch { // Error expected } diff --git a/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs index 5a824e3f478f..6d4d128b5571 100644 --- a/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/mistral/scenario-abort.mjs @@ -34,14 +34,14 @@ async function run() { const messages = [{ role: 'user', content: 'Aborted by the caller' }]; const requests = [ - ['stream', 'abort-before-stream', { signal: abortAfter(50) }], - ['complete', 'abort-non-streaming', { fetchOptions: { signal: abortAfter(50) } }], - ['stream', 'timeout-before-stream', { timeoutMs: 50 }], - ['complete', 'timeout-non-streaming', { timeoutMs: 50 }], + ['stream', 'abort-before-stream', () => ({ signal: abortAfter(50) })], + ['complete', 'abort-non-streaming', () => ({ fetchOptions: { signal: abortAfter(50) } })], + ['stream', 'timeout-before-stream', () => ({ timeoutMs: 50 })], + ['complete', 'timeout-non-streaming', () => ({ timeoutMs: 50 })], ]; for (const [method, model, requestOptions] of requests) { try { - await client.chat[method]({ model, messages }, requestOptions); + await client.chat[method]({ model, messages }, requestOptions()); } catch { // Error expected } diff --git a/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs b/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs index 5f225f4b7908..1f9ef3df0823 100644 --- a/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/openai/scenario-abort.mjs @@ -34,14 +34,14 @@ async function run() { const messages = [{ role: 'user', content: 'Aborted by the caller' }]; const requests = [ - [{ model: 'abort-before-stream', stream: true }, { signal: abortAfter(50) }], - [{ model: 'abort-non-streaming' }, { signal: abortAfter(50) }], - [{ model: 'timeout-before-stream', stream: true }, { timeout: 50 }], - [{ model: 'timeout-non-streaming' }, { timeout: 50 }], + [{ model: 'abort-before-stream', stream: true }, () => ({ signal: abortAfter(50) })], + [{ model: 'abort-non-streaming' }, () => ({ signal: abortAfter(50) })], + [{ model: 'timeout-before-stream', stream: true }, () => ({ timeout: 50 })], + [{ model: 'timeout-non-streaming' }, () => ({ timeout: 50 })], ]; for (const [params, requestOptions] of requests) { try { - await client.chat.completions.create({ ...params, messages }, requestOptions); + await client.chat.completions.create({ ...params, messages }, requestOptions()); } catch { // Error expected } diff --git a/packages/server-utils/src/ai/mistral/index.ts b/packages/server-utils/src/ai/mistral/index.ts index 270667239c53..f48dcb8334ec 100644 --- a/packages/server-utils/src/ai/mistral/index.ts +++ b/packages/server-utils/src/ai/mistral/index.ts @@ -136,7 +136,7 @@ function instrumentMethod( result => { // Patched in place so the caller keeps the real `EventStream`; `instrumentEventStream` // takes over ending the span once the stream is drained. - if (!instrumentEventStream(result, span, options.recordOutputs ?? false)) { + if (!instrumentEventStream(result, span, options.recordOutputs ?? false, abortSignal)) { span.end(); } return result; diff --git a/packages/server-utils/src/ai/mistral/streaming.ts b/packages/server-utils/src/ai/mistral/streaming.ts index 74acc6e43b70..47ff72038867 100644 --- a/packages/server-utils/src/ai/mistral/streaming.ts +++ b/packages/server-utils/src/ai/mistral/streaming.ts @@ -1,6 +1,5 @@ import type { Span } from '@sentry/core'; -import { SPAN_STATUS_ERROR } from '@sentry/core'; -import { endStreamSpan, setOutputMessagesAttribute } from '../core/utils'; +import { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils'; import type { MistralCompletionChunk, MistralToolCall } from './types'; import { contentToString } from './utils'; @@ -234,7 +233,12 @@ function instrumentedSource(readable: ReadableStreamLike): ReadableStream { if (isReadableStream(result)) { - return instrumentWorkersAiStream(result, span, options.recordOutputs); + return instrumentWorkersAiStream(result, span, options.recordOutputs, abortSignal); } // The model did not actually return a stream — finalize the span eagerly. diff --git a/packages/server-utils/src/ai/workers-ai/streaming.ts b/packages/server-utils/src/ai/workers-ai/streaming.ts index 93884ffbbb94..3eed14d5384b 100644 --- a/packages/server-utils/src/ai/workers-ai/streaming.ts +++ b/packages/server-utils/src/ai/workers-ai/streaming.ts @@ -1,7 +1,6 @@ -import { SPAN_STATUS_ERROR } from '@sentry/core'; import type { Span } from '@sentry/core'; import { getToolCallKey } from '../core/streaming-tool-calls'; -import { endStreamSpan, type StreamResponseState } from '../core/utils'; +import { endStreamSpan, getErrorStatus, type StreamResponseState } from '../core/utils'; import type { WorkersAiUsage } from './types'; import { setOutputMessagesAttribute } from './utils'; @@ -164,6 +163,7 @@ export function instrumentWorkersAiStream( stream: ReadableStream, span: Span, recordOutputs: boolean, + abortSignal?: AbortSignal, ): ReadableStream { const reader = stream.getReader(); const decoder = new TextDecoder(); @@ -236,7 +236,7 @@ export function instrumentWorkersAiStream( flushBuffer(false); controller.enqueue(value); } catch (error) { - span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + span.setStatus(getErrorStatus(abortSignal)); finish(); controller.error(error); } diff --git a/packages/server-utils/src/integrations/mistral.ts b/packages/server-utils/src/integrations/mistral.ts index 4fb281c056df..4a6fe4a765a7 100644 --- a/packages/server-utils/src/integrations/mistral.ts +++ b/packages/server-utils/src/integrations/mistral.ts @@ -50,7 +50,13 @@ function instrumentMistral(options: MistralOptions): void { }, // Streaming: the result is an `EventStream` consumed later, so instrument it and let it end the span. deferSpanEnd: ({ span, data }) => - streaming && instrumentEventStream(data.result, span, resolveAIRecordingOptions(options).recordOutputs), + streaming && + instrumentEventStream( + data.result, + span, + resolveAIRecordingOptions(options).recordOutputs, + getMistralRequestSignal(data.arguments?.[1]), + ), }, ); } diff --git a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts index 8e7d1f490169..71a93354535c 100644 --- a/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts +++ b/packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts @@ -6,7 +6,9 @@ import { EventEmitter } from 'node:events'; import { instrumentAsyncIterableStream, instrumentMessageStream } from '../../../../src/ai/anthropic-ai/streaming'; import { instrumentStream as instrumentGoogleGenAIStream } from '../../../../src/ai/google-genai/streaming'; import type { GoogleGenAIResponse } from '../../../../src/ai/google-genai/types'; +import { instrumentEventStream as instrumentMistralStream } from '../../../../src/ai/mistral/streaming'; import { instrumentStream as instrumentOpenAIStream } from '../../../../src/ai/openai/streaming'; +import { instrumentWorkersAiStream } from '../../../../src/ai/workers-ai/streaming'; function createMockSpan(): { span: Span; attributes: Record; setStatus: ReturnType } { const attributes: Record = {}; @@ -199,3 +201,62 @@ describe('google-genai stream aborts', () => { expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); }); }); + +const midStreamAbortError = new DOMException('This operation was aborted', 'AbortError'); + +const midStreamAbortProviders: Array<{ + name: string; + drainAborted: (span: Span, signal: AbortSignal) => Promise; +}> = [ + { + name: 'mistral', + drainAborted: (span, signal) => { + const stream = { + async *[Symbol.asyncIterator]() { + yield { data: { id: 'cmpl-1', choices: [{ index: 0, delta: { content: 'Hi' } }] } }; + throw midStreamAbortError; + }, + }; + instrumentMistralStream(stream, span, false, signal); + return drain(stream); + }, + }, + { + name: 'workers-ai', + drainAborted: (span, signal) => { + let sentChunk = false; + const source = new ReadableStream({ + pull(controller) { + if (sentChunk) { + controller.error(midStreamAbortError); + return; + } + sentChunk = true; + controller.enqueue(new TextEncoder().encode('data: {"response":"Hi"}\n\n')); + }, + }); + return drain(instrumentWorkersAiStream(source, span, false, signal) as unknown as AsyncIterable); + }, + }, +]; + +describe.each(midStreamAbortProviders)('$name mid-stream aborts', ({ drainAborted }) => { + it("marks the span as cancelled when the caller's signal fired", async () => { + const { span, setStatus } = createMockSpan(); + + await expect(drainAborted(span, AbortSignal.abort())).rejects.toBe(midStreamAbortError); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'cancelled' }); + }); + + it("marks the span as errored when the caller's own timeout fired", async () => { + const { span, setStatus } = createMockSpan(); + const timeoutSignal = AbortSignal.abort(new DOMException('The operation timed out', 'TimeoutError')); + + await expect(drainAborted(span, timeoutSignal)).rejects.toBe(midStreamAbortError); + + expect(setStatus).toHaveBeenCalledTimes(1); + expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + }); +}); From ac6c4d42a77862300bbb09bd064866c99b82086d Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:46:29 +0000 Subject: [PATCH 3/3] ref(server-utils): Simplify getMistralRequestSignal Co-Authored-By: Rola Abuhasna --- packages/server-utils/src/ai/mistral/utils.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/server-utils/src/ai/mistral/utils.ts b/packages/server-utils/src/ai/mistral/utils.ts index 086f40655cec..d112870f2377 100644 --- a/packages/server-utils/src/ai/mistral/utils.ts +++ b/packages/server-utils/src/ai/mistral/utils.ts @@ -1,7 +1,7 @@ /* eslint-disable typescript-eslint/no-deprecated */ import type { Span, SpanAttributeValue } from '@sentry/core'; import type { GenAiOutputMessage } from '../core/utils'; -import { getRequestSignal, setOutputMessagesAttribute } from '../core/utils'; +import { setOutputMessagesAttribute } from '../core/utils'; import { GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, @@ -58,10 +58,8 @@ export function getSpanName(operationName: string, attributes: Record