Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import Anthropic from '@anthropic-ai/sdk';
import * as Sentry from '@sentry/node';
import express from 'express';

function startMockAnthropicServer() {
const app = express();
app.use(express.json());

app.post('/anthropic/v1/messages', (req, res) => {
// Never respond, so the caller aborts before the response arrives.
if (req.body.model === 'abort-before-response') {
return;
}

res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});

// Send part of a message and keep the connection open, so the caller aborts mid-stream.
const events = [
{
type: 'message_start',
message: {
id: 'msg_abort_midway_1',
type: 'message',
role: 'assistant',
model: req.body.model,
content: [],
usage: { input_tokens: 5 },
},
},
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'This stream will ' } },
];
for (const event of events) {
res.write(`event: ${event.type}\n`);
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
});

return new Promise(resolve => {
const server = app.listen(0, () => {
resolve(server);
});
});
}

async function run() {
const server = await startMockAnthropicServer();

await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
const client = new Anthropic({
apiKey: 'mock-api-key',
baseURL: `http://localhost:${server.address().port}/anthropic`,
});

// 1) Abort before the response arrives
const beforeResponse = client.messages.stream({
model: 'abort-before-response',
messages: [{ role: 'user', content: 'This will be aborted before the response' }],
});
setTimeout(() => beforeResponse.abort(), 50);
try {
await beforeResponse.done();
} catch {
// Abort expected
}

// 2) Abort midway through streaming
const midway = client.messages.stream({
model: 'abort-midway',
messages: [{ role: 'user', content: 'This will be aborted midway' }],
});
midway.on('text', () => midway.abort());
try {
await midway.done();
} catch {
// Abort expected
}
});

await Sentry.flush(2000);

server.closeAllConnections();
server.close();
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,31 @@ describe('Anthropic integration', () => {
});
});

createEsmAndCjsTests(__dirname, 'scenario-stream-abort.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
test('sends messages.stream() spans that were aborted', async () => {
await createRunner()
.ignore('event')
.expect({
span: container => {
const spans = container.items.filter(span => span.attributes[SENTRY_ORIGIN]?.value === 'auto.ai.anthropic');
expect(spans).toHaveLength(2);

// `cancelled` is sent as `ok` under span streaming.
const beforeResponseSpan = spans.find(span => span.name === 'chat abort-before-response');
expect(beforeResponseSpan!.status).toBe('ok');

const midwaySpan = spans.find(span => span.name === 'chat abort-midway');
expect(midwaySpan!.status).toBe('ok');
expect(midwaySpan!.attributes[GEN_AI_RESPONSE_STREAMING].value).toBe(true);
expect(midwaySpan!.attributes[GEN_AI_RESPONSE_ID].value).toBe('msg_abort_midway_1');
expect(midwaySpan!.attributes[GEN_AI_RESPONSE_TEXT].value).toBe('This stream will ');
},
})
.start()
.completed();
});
});

createEsmAndCjsTests(__dirname, 'scenario-errors.mjs', 'instrument-with-pii.mjs', (createRunner, test) => {
test('handles tool errors correctly', async () => {
await createRunner()
Expand Down
11 changes: 10 additions & 1 deletion packages/server-utils/src/ai/anthropic-ai/streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ export async function* instrumentAsyncIterableStream(
/**
* Instruments a MessageStream by registering event handlers and preserving the original stream API.
*/
export function instrumentMessageStream<R extends { on: (...args: unknown[]) => void }>(
export function instrumentMessageStream<R extends { on: (...args: unknown[]) => void; aborted?: boolean }>(
stream: R,
span: Span,
recordOutputs: boolean,
Expand Down Expand Up @@ -303,5 +303,14 @@ export function instrumentMessageStream<R extends { on: (...args: unknown[]) =>
}
});

// An aborted stream emits only `abort` and `end`. We don't listen for `abort`: doing so would stop the SDK from
// raising an unhandled rejection when the caller never awaits the aborted stream.
stream.on('end', () => {
if (stream.aborted && span.isRecording()) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });
}
endStreamSpan(span, state, recordOutputs);
});

return stream;
}
46 changes: 45 additions & 1 deletion packages/server-utils/test/ai/lib/tracing/stream-errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest';
import type { Span } from '@sentry/core';
import { SPAN_STATUS_ERROR } from '@sentry/core';
import { GEN_AI_RESPONSE_STREAMING, GEN_AI_USAGE_INPUT_TOKENS } from '@sentry/conventions/attributes';
import { instrumentAsyncIterableStream } from '../../../../src/ai/anthropic-ai/streaming';
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 { instrumentStream as instrumentOpenAIStream } from '../../../../src/ai/openai/streaming';
Expand Down Expand Up @@ -111,6 +112,49 @@ describe.each(providers)('$name stream errors', ({ instrument, chunks }) => {
});
});

describe('anthropic message stream aborts', () => {
it('leaves the status alone and ends the span once when the stream completes', () => {
const { span, setStatus } = createMockSpan();
const end = vi.spyOn(span, 'end');
const stream = Object.assign(new EventEmitter(), { aborted: false });
instrumentMessageStream(stream, span, false);

stream.emit('message', {});
stream.emit('end');

expect(setStatus).not.toHaveBeenCalled();
expect(end).toHaveBeenCalledTimes(1);
});

it('marks the span as cancelled and keeps the partial usage when the stream is aborted', () => {
const { span, attributes, setStatus } = createMockSpan();
const stream = Object.assign(new EventEmitter(), { aborted: false });
instrumentMessageStream(stream, span, false);

stream.emit('streamEvent', {
type: 'message_start',
message: { id: 'msg_1', model: 'claude-sonnet-4-5', usage: { input_tokens: 8 } },
});
stream.aborted = true;
stream.emit('abort', new Error('Request was aborted.'));
stream.emit('end');

expect(setStatus).toHaveBeenCalledTimes(1);
expect(setStatus).toHaveBeenCalledWith({ code: SPAN_STATUS_ERROR, message: 'cancelled' });
expect(span.isRecording()).toBe(false);
expect(attributes[GEN_AI_RESPONSE_STREAMING]).toBe(true);
expect(attributes[GEN_AI_USAGE_INPUT_TOKENS]).toBe(8);
});

it('does not listen for abort, so an unobserved abort still raises an unhandled rejection', () => {
const { span } = createMockSpan();
const stream = new EventEmitter();
instrumentMessageStream(stream, span, false);

expect(stream.listenerCount('abort')).toBe(0);
});
});

describe('google-genai stream aborts', () => {
const abortError = new DOMException('This operation was aborted', 'AbortError');

Expand Down
Loading