Skip to content

Commit fe412ef

Browse files
andreiborzaclaude
andauthored
test(aws-serverless): Add Bedrock streaming integration scenario (#26190)
## What Adds a Bedrock streaming integration scenario that checks the current span behavior for ConverseStream and InvokeModelWithResponseStream streams that finish, fail, or are aborted. ## Why Before this change, no integration test covered Bedrock streams. This scenario is the base for the input and output recording PRs. Extracted from #26118. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6c6c040 commit fe412ef

4 files changed

Lines changed: 234 additions & 0 deletions

File tree

‎dev-packages/node-integration-tests/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
"@sentry/node-native": "11.11.0",
6969
"@sentry/server-runtime-injection": "11.11.0",
7070
"@sentry/server-utils": "11.11.0",
71+
"@smithy/core": "3.38.1",
7172
"@smithy/node-http-handler": "4.12.1",
7273
"@types/express": "^4.17.21",
7374
"@types/node-schedule": "^2.1.8",
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
import * as Sentry from '@sentry/aws-serverless';
2+
import {
3+
BedrockRuntimeClient,
4+
ConverseStreamCommand,
5+
InvokeModelWithResponseStreamCommand,
6+
} from '@aws-sdk/client-bedrock-runtime';
7+
// Force the HTTP/1 handler so `nock` can intercept the request instead of hitting real AWS.
8+
import { NodeHttpHandler } from '@smithy/node-http-handler';
9+
import { EventStreamCodec } from '@smithy/core/event-streams';
10+
import nock from 'nock';
11+
import { Buffer } from 'node:buffer';
12+
13+
nock.disableNetConnect();
14+
15+
const region = 'us-east-1';
16+
const credentials = { accessKeyId: 'aws-test-key', secretAccessKey: 'aws-test-secret' };
17+
const host = `https://bedrock-runtime.${region}.amazonaws.com`;
18+
const modelId = 'anthropic.claude-3-5-sonnet-20240620-v1:0';
19+
20+
// Bedrock streams responses in the binary AWS event stream format, not JSON. The SDK decodes and
21+
// checks each message (headers, payload, CRC32), so the mocked response must use the same format.
22+
// The SDK's own codec encodes the messages. It needs UTF-8 helpers to encode the header strings.
23+
// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTSelectObjectAppendix.html
24+
const codec = new EventStreamCodec(
25+
bytes => Buffer.from(bytes).toString('utf8'),
26+
text => Buffer.from(text),
27+
);
28+
29+
// The codec needs a type for each header value. All Bedrock headers are strings.
30+
function encodeMessage(headers, payload) {
31+
return codec.encode({
32+
headers: Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, { type: 'string', value }])),
33+
body: Buffer.from(JSON.stringify(payload)),
34+
});
35+
}
36+
37+
// The SDK reads `:event-type` to find the stream member (for example `messageStart` or `chunk`).
38+
function event(eventType, payload) {
39+
return encodeMessage(
40+
{ ':message-type': 'event', ':event-type': eventType, ':content-type': 'application/json' },
41+
payload,
42+
);
43+
}
44+
45+
// An exception message makes the SDK throw while the caller iterates the stream. This is how a
46+
// stream fails after the response starts.
47+
function exception(exceptionType, payload) {
48+
return encodeMessage(
49+
{ ':message-type': 'exception', ':exception-type': exceptionType, ':content-type': 'application/json' },
50+
payload,
51+
);
52+
}
53+
54+
// InvokeModelWithResponseStream wraps each model chunk as base64 JSON in a `chunk` event.
55+
function invokeModelChunk(chunk) {
56+
return event('chunk', { bytes: Buffer.from(JSON.stringify(chunk)).toString('base64') });
57+
}
58+
59+
function mockStream(path, messages) {
60+
nock(host).post(path).reply(200, Buffer.concat(messages), { 'content-type': 'application/vnd.amazon.eventstream' });
61+
}
62+
63+
function createClient() {
64+
return new BedrockRuntimeClient({ region, credentials, maxAttempts: 1, requestHandler: new NodeHttpHandler() });
65+
}
66+
67+
async function converseStream() {
68+
mockStream(/\/model\/.*\/converse-stream$/, [
69+
event('messageStart', { role: 'assistant' }),
70+
event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Hello ' } }),
71+
event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'from Bedrock' } }),
72+
event('contentBlockStop', { contentBlockIndex: 0 }),
73+
event('contentBlockStart', {
74+
contentBlockIndex: 1,
75+
start: { toolUse: { toolUseId: 'tooluse_1', name: 'get_weather' } },
76+
}),
77+
event('contentBlockDelta', { contentBlockIndex: 1, delta: { toolUse: { input: '{"city":' } } }),
78+
event('contentBlockDelta', { contentBlockIndex: 1, delta: { toolUse: { input: '"Vienna"}' } } }),
79+
event('contentBlockStop', { contentBlockIndex: 1 }),
80+
event('messageStop', { stopReason: 'tool_use' }),
81+
event('metadata', { usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, metrics: { latencyMs: 100 } }),
82+
]);
83+
84+
const response = await createClient().send(
85+
new ConverseStreamCommand({
86+
modelId,
87+
system: [{ text: 'You are a helpful assistant.' }],
88+
messages: [{ role: 'user', content: [{ text: 'Hello' }] }],
89+
}),
90+
);
91+
92+
let text = '';
93+
for await (const item of response.stream) {
94+
text += item.contentBlockDelta?.delta?.text ?? '';
95+
}
96+
if (text !== 'Hello from Bedrock') {
97+
throw new Error(`Unexpected streamed text: ${text}`);
98+
}
99+
}
100+
101+
async function invokeModelWithResponseStream() {
102+
mockStream(/\/model\/.*\/invoke-with-response-stream$/, [
103+
invokeModelChunk({
104+
type: 'message_start',
105+
message: { id: 'msg_bdrk_2', model: 'claude-3-5-sonnet-20240620', usage: { input_tokens: 15, output_tokens: 1 } },
106+
}),
107+
invokeModelChunk({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }),
108+
invokeModelChunk({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Streamed ' } }),
109+
invokeModelChunk({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'reply' } }),
110+
invokeModelChunk({ type: 'content_block_stop', index: 0 }),
111+
invokeModelChunk({ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 9 } }),
112+
invokeModelChunk({ type: 'message_stop' }),
113+
]);
114+
115+
const response = await createClient().send(
116+
new InvokeModelWithResponseStreamCommand({
117+
modelId,
118+
contentType: 'application/json',
119+
body: JSON.stringify({
120+
anthropic_version: 'bedrock-2023-05-31',
121+
max_tokens: 100,
122+
messages: [{ role: 'user', content: 'Stream please' }],
123+
}),
124+
}),
125+
);
126+
127+
let chunks = 0;
128+
for await (const item of response.body) {
129+
if (item.chunk?.bytes) {
130+
chunks++;
131+
}
132+
}
133+
if (chunks !== 7) {
134+
throw new Error(`Unexpected chunk count: ${chunks}`);
135+
}
136+
}
137+
138+
async function failingConverseStream() {
139+
mockStream(/\/model\/.*\/converse-stream$/, [
140+
event('messageStart', { role: 'assistant' }),
141+
event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Partial' } }),
142+
exception('modelStreamErrorException', { message: 'The model stream failed', originalStatusCode: 500 }),
143+
]);
144+
145+
const response = await createClient().send(
146+
new ConverseStreamCommand({
147+
modelId: 'amazon.nova-pro-v1:0',
148+
messages: [{ role: 'user', content: [{ text: 'Fail please' }] }],
149+
}),
150+
);
151+
152+
try {
153+
for await (const _ of response.stream) {
154+
// drain
155+
}
156+
} catch (error) {
157+
if (error.name !== 'ModelStreamErrorException') {
158+
throw error;
159+
}
160+
return;
161+
}
162+
throw new Error('Expected the stream to fail');
163+
}
164+
165+
async function abortedConverseStream() {
166+
mockStream(/\/model\/.*\/converse-stream$/, [
167+
event('messageStart', { role: 'assistant' }),
168+
event('contentBlockDelta', { contentBlockIndex: 0, delta: { text: 'Partial' } }),
169+
exception('modelStreamErrorException', { message: 'The model stream failed', originalStatusCode: 500 }),
170+
]);
171+
172+
const controller = new AbortController();
173+
const response = await createClient().send(
174+
new ConverseStreamCommand({
175+
modelId: 'amazon.nova-lite-v1:0',
176+
messages: [{ role: 'user', content: [{ text: 'Stop please' }] }],
177+
}),
178+
{ abortSignal: controller.signal },
179+
);
180+
181+
try {
182+
for await (const _ of response.stream) {
183+
controller.abort();
184+
}
185+
} catch {
186+
return;
187+
}
188+
throw new Error('Expected the stream to fail');
189+
}
190+
191+
async function run() {
192+
await Sentry.startSpan({ name: 'Test Transaction' }, async () => {
193+
await converseStream();
194+
await invokeModelWithResponseStream();
195+
await failingConverseStream();
196+
await abortedConverseStream();
197+
});
198+
}
199+
200+
run();

‎dev-packages/node-integration-tests/suites/aws-serverless/bedrock/test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
SENTRY_OP,
1212
SENTRY_ORIGIN,
1313
} from '@sentry/conventions/attributes';
14+
import { GEN_AI_CHAT, GEN_AI_GENERATE_CONTENT } from '@sentry/conventions/op';
1415
import type { SerializedStreamedSpanContainer } from '@sentry/core';
1516
import { afterAll, describe, expect } from 'vitest';
1617
import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner';
@@ -52,6 +53,29 @@ function assertBedrockSpans(container: SerializedStreamedSpanContainer): void {
5253
expect(invokeModelSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["end_turn"]');
5354
}
5455

56+
function assertStreamSpans(container: SerializedStreamedSpanContainer): void {
57+
const converseStreamSpan = container.items.find(span => span.name === `chat ${MODEL_ID}`);
58+
expect(converseStreamSpan!.status).toBe('ok');
59+
expect(converseStreamSpan!.attributes[SENTRY_OP].value).toBe(GEN_AI_CHAT);
60+
expect(converseStreamSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(12);
61+
expect(converseStreamSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(8);
62+
expect(converseStreamSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["tool_use"]');
63+
64+
const invokeStreamSpan = container.items.find(span => span.name === `generate_content ${MODEL_ID}`);
65+
expect(invokeStreamSpan!.status).toBe('ok');
66+
expect(invokeStreamSpan!.attributes[SENTRY_OP].value).toBe(GEN_AI_GENERATE_CONTENT);
67+
expect(invokeStreamSpan!.attributes[GEN_AI_USAGE_INPUT_TOKENS].value).toBe(15);
68+
expect(invokeStreamSpan!.attributes[GEN_AI_USAGE_OUTPUT_TOKENS].value).toBe(9);
69+
expect(invokeStreamSpan!.attributes[GEN_AI_RESPONSE_FINISH_REASONS].value).toBe('["end_turn"]');
70+
71+
const failedStreamSpan = container.items.find(span => span.name === 'chat amazon.nova-pro-v1:0');
72+
expect(failedStreamSpan!.status).toBe('error');
73+
74+
// `cancelled` is sent as `ok` under span streaming.
75+
const abortedStreamSpan = container.items.find(span => span.name === 'chat amazon.nova-lite-v1:0');
76+
expect(abortedStreamSpan!.status).toBe('ok');
77+
}
78+
5579
describe('awsIntegration - Bedrock', () => {
5680
afterAll(() => {
5781
cleanupChildProcesses();
@@ -62,4 +86,10 @@ describe('awsIntegration - Bedrock', () => {
6286
await createTestRunner().ignore('event').expect({ span: assertBedrockSpans }).start().completed();
6387
});
6488
});
89+
90+
createEsmAndCjsTests(__dirname, 'scenario-stream.mjs', 'instrument.mjs', (createTestRunner, test) => {
91+
test('ends Bedrock stream spans when the streams finish, fail, or are aborted', { timeout: 90_000 }, async () => {
92+
await createTestRunner().ignore('event').expect({ span: assertStreamSpans }).start().completed();
93+
});
94+
});
6595
});

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)