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
Expand Up @@ -227,10 +227,24 @@ void otelAutoconfigureProducesRealTracer() {
void tracerAfterShutdownPreservesParentWithoutRecording() throws Exception {
// Load the SDK through the actual agent loader, not the application classpath.
// A flat classpath hides the API/incubator visibility mismatch from issue #184.
var providerClass =
BraintrustBridge.getAgentClassLoader()
.loadClass("io.opentelemetry.sdk.trace.SdkTracerProvider");
var agentLoader = BraintrustBridge.getAgentClassLoader();
var providerClass = agentLoader.loadClass("io.opentelemetry.sdk.trace.SdkTracerProvider");
var builder = providerClass.getMethod("builder").invoke(null);
// OTel >= 1.67 hands out noop tracers when no span processor is registered.
var processorClass = agentLoader.loadClass("io.opentelemetry.sdk.trace.SpanProcessor");
var exporterClass = agentLoader.loadClass("io.opentelemetry.sdk.trace.export.SpanExporter");
var exporter =
exporterClass
.getMethod("composite", exporterClass.arrayType())
.invoke(
null,
(Object) java.lang.reflect.Array.newInstance(exporterClass, 0));
var processor =
agentLoader
.loadClass("io.opentelemetry.sdk.trace.export.SimpleSpanProcessor")
.getMethod("create", exporterClass)
.invoke(null, exporter);
builder.getClass().getMethod("addSpanProcessor", processorClass).invoke(builder, processor);
var provider = (TracerProvider) builder.getClass().getMethod("build").invoke(builder);
var close = providerClass.getMethod("close");
boolean closed = false;
Expand Down
3 changes: 2 additions & 1 deletion braintrust-sdk/instrumentation/anthropic_2_2_0/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ muzzle {
pass {
group = 'com.anthropic'
module = 'anthropic-java'
versions = '[2.2.0,)'
// 3.x is a breaking major (e.g. HttpRequest.body() now returns Optional); not yet supported
versions = '[2.2.0,3.0.0)'
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseRequest;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamRequest;
import software.amazon.eventstream.Message;
import software.amazon.eventstream.MessageDecoder;

/**
* AWS SDK ExecutionInterceptor that creates OpenTelemetry spans for Bedrock Converse calls,
Expand Down Expand Up @@ -230,7 +228,7 @@ private static String extractModelIdFromPath(String path) {
}

/**
* Tees the reactive byte stream into a {@link MessageDecoder}, forwarding each decoded
* Tees the reactive byte stream into an {@link EventStreamDecoder}, forwarding each decoded
* event-stream frame to a {@link ConverseStreamAccumulator}. On completion the accumulator's
* reconstructed Converse-shaped body is handed to semconv, so a streaming span carries the same
* content-block shapes — text, tool use, reasoning — as a synchronous one.
Expand All @@ -239,7 +237,7 @@ private static class TeeingSubscriber implements Subscriber<ByteBuffer> {
private final Subscriber<? super ByteBuffer> downstream;
private final Span span;
private final Tracer tracer;
private final MessageDecoder decoder = new MessageDecoder();
private final EventStreamDecoder decoder = new EventStreamDecoder();
private final ConverseStreamAccumulator accumulator = new ConverseStreamAccumulator();

private long startNanos;
Expand All @@ -262,11 +260,9 @@ public void onNext(ByteBuffer buf) {
byte[] copy = new byte[buf.remaining()];
buf.duplicate().get(copy);
try {
decoder.feed(copy);
for (Message msg : decoder.getDecodedMessages()) {
var header = msg.getHeaders().get(":event-type");
if (header == null) continue;
String eventType = header.getString();
for (EventStreamDecoder.Message msg : decoder.feed(copy)) {
String eventType = msg.headers().get(":event-type");
if (eventType == null) continue;
// First content frame marks time-to-first-token, whether the model opened with
// text, a tool call, or a reasoning block.
if (timeToFirstTokenNanos == null
Expand All @@ -275,7 +271,7 @@ public void onNext(ByteBuffer buf) {
timeToFirstTokenNanos = System.nanoTime() - startNanos;
}
accumulator.accept(
eventType, new String(msg.getPayload(), StandardCharsets.UTF_8));
eventType, new String(msg.payload(), StandardCharsets.UTF_8));
}
} catch (Exception e) {
log.debug("Failed to feed event-stream decoder", e);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package dev.braintrust.instrumentation.awsbedrock.v2_30_0;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.CRC32;

/**
* Minimal incremental decoder for the AWS event-stream framing used by Bedrock ConverseStream.
*
* <p>We own this instead of using the AWS decoder because AWS SDK 2.57.0 moved it from {@code
* software.amazon.eventstream} to {@code software.amazon.awssdk.eventstream}; depending on either
* package would break instrumentation for the other half of the supported range.
*
* <p>Frame layout (big-endian): {@code total length (4) | headers length (4) | prelude CRC32 (4) |
* headers | payload | message CRC32 (4)}. Only string-typed headers are retained.
*/
final class EventStreamDecoder {
record Message(Map<String, String> headers, byte[] payload) {}

private static final int PRELUDE_LENGTH = 12;
private static final int TRAILER_LENGTH = 4;
private static final int MAX_MESSAGE_LENGTH = 16 * 1024 * 1024;

private byte[] buf = new byte[8192];
private int len = 0;
private boolean failed = false;

/**
* Appends {@code bytes} and returns the messages they complete. Once malformed input is seen
* the decoder throws and returns no further messages, since frame boundaries are lost.
*/
List<Message> feed(byte[] bytes) {
if (failed) {
return List.of();
}
if (len + bytes.length > buf.length) {
buf = Arrays.copyOf(buf, Math.max(len + bytes.length, buf.length * 2));
}
System.arraycopy(bytes, 0, buf, len, bytes.length);
len += bytes.length;

List<Message> messages = new ArrayList<>();
ByteBuffer bb = ByteBuffer.wrap(buf);
int pos = 0;
try {
while (len - pos >= PRELUDE_LENGTH) {
int totalLength = bb.getInt(pos);
int headersLength = bb.getInt(pos + 4);
if (totalLength < PRELUDE_LENGTH + TRAILER_LENGTH
|| totalLength > MAX_MESSAGE_LENGTH
|| headersLength < 0
|| headersLength > totalLength - PRELUDE_LENGTH - TRAILER_LENGTH) {
throw new IllegalStateException("Invalid event-stream prelude");
}
if (crc32(pos, 8) != bb.getInt(pos + 8)) {
throw new IllegalStateException("Event-stream prelude CRC mismatch");
}
if (len - pos < totalLength) {
break;
}
int trailerStart = pos + totalLength - TRAILER_LENGTH;
if (crc32(pos, totalLength - TRAILER_LENGTH) != bb.getInt(trailerStart)) {
throw new IllegalStateException("Event-stream message CRC mismatch");
}
int headersStart = pos + PRELUDE_LENGTH;
int payloadStart = headersStart + headersLength;
messages.add(
new Message(
decodeHeaders(bb, headersStart, payloadStart),
Arrays.copyOfRange(buf, payloadStart, trailerStart)));
pos += totalLength;
}
} catch (RuntimeException e) {
failed = true;
buf = new byte[0];
len = 0;
throw e;
}
System.arraycopy(buf, pos, buf, 0, len - pos);
len -= pos;
return messages;
}

private int crc32(int offset, int length) {
CRC32 crc = new CRC32();
crc.update(buf, offset, length);
return (int) crc.getValue();
}

private Map<String, String> decodeHeaders(ByteBuffer bb, int start, int end) {
Map<String, String> headers = new HashMap<>();
int p = start;
while (p < end) {
int nameLength = buf[p++] & 0xFF;
String name = new String(buf, p, nameLength, StandardCharsets.UTF_8);
p += nameLength;
int type = buf[p++];
switch (type) {
case 0, 1 -> {} // boolean true / false: no value bytes
case 2 -> p += 1; // byte
case 3 -> p += 2; // short
case 4 -> p += 4; // int
case 5, 8 -> p += 8; // long, timestamp
case 9 -> p += 16; // uuid
case 6, 7 -> { // byte array, string
int valueLength = bb.getShort(p) & 0xFFFF;
p += 2;
if (type == 7) {
headers.put(name, new String(buf, p, valueLength, StandardCharsets.UTF_8));
}
p += valueLength;
}
default ->
throw new IllegalStateException("Unknown event-stream header type " + type);
}
}
if (p != end) {
throw new IllegalStateException("Event-stream headers overran their declared length");
}
return headers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public List<String> getHelperClassNames() {
MANUAL_INSTRUMENTATION_PACKAGE + "BraintrustAWSBedrock",
MANUAL_INSTRUMENTATION_PACKAGE + "BraintrustBedrockInterceptor",
MANUAL_INSTRUMENTATION_PACKAGE + "BraintrustBedrockInterceptor$TeeingSubscriber",
MANUAL_INSTRUMENTATION_PACKAGE + "EventStreamDecoder",
MANUAL_INSTRUMENTATION_PACKAGE + "EventStreamDecoder$Message",
"dev.braintrust.json.BraintrustJsonMapper",
"dev.braintrust.instrumentation.InstrumentationSemConv",
"dev.braintrust.instrumentation.ConverseStreamAccumulator");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package dev.braintrust.instrumentation.awsbedrock.v2_30_0;

import static org.junit.jupiter.api.Assertions.*;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import software.amazon.eventstream.HeaderValue;
import software.amazon.eventstream.Message;

/** Frames are produced by the AWS SDK's own encoder so the decoder is checked against the spec. */
class EventStreamDecoderTest {
private static byte[] frame(String eventType, String payload) throws Exception {
Map<String, HeaderValue> headers = new LinkedHashMap<>();
// Non-string header types, so the decoder must skip their values correctly. byte and short
// are omitted: eventstream 1.0.1's encoder writes no value bytes for them (spec: 1 and 2).
headers.put("bool-true", HeaderValue.fromBoolean(true));
headers.put("bool-false", HeaderValue.fromBoolean(false));
headers.put("int", HeaderValue.fromInteger(7));
headers.put("long", HeaderValue.fromLong(7L));
headers.put("bytes", HeaderValue.fromByteArray(new byte[] {1, 2, 3}));
headers.put("timestamp", HeaderValue.fromTimestamp(Instant.EPOCH));
headers.put("uuid", HeaderValue.fromUuid(UUID.randomUUID()));
headers.put(":event-type", HeaderValue.fromString(eventType));
var out = new ByteArrayOutputStream();
new Message(headers, payload.getBytes(StandardCharsets.UTF_8)).encode(out);
return out.toByteArray();
}

private static byte[] concat(byte[]... parts) {
var out = new ByteArrayOutputStream();
for (byte[] part : parts) out.writeBytes(part);
return out.toByteArray();
}

@Test
void decodesMultipleFramesInOneChunk() throws Exception {
var decoder = new EventStreamDecoder();
var messages =
decoder.feed(
concat(frame("messageStart", "{\"a\":1}"), frame("messageStop", "{}")));

assertEquals(2, messages.size());
assertEquals("messageStart", messages.get(0).headers().get(":event-type"));
assertEquals("{\"a\":1}", new String(messages.get(0).payload(), StandardCharsets.UTF_8));
assertEquals("messageStop", messages.get(1).headers().get(":event-type"));
assertFalse(messages.get(0).headers().containsKey("int"), "only string headers are kept");
}

@Test
void decodesFramesSplitAcrossChunks() throws Exception {
byte[] bytes =
concat(frame("contentBlockDelta", "{\"text\":\"hi\"}"), frame("messageStop", "{}"));
var decoder = new EventStreamDecoder();
List<EventStreamDecoder.Message> messages = new ArrayList<>();
for (byte b : bytes) {
messages.addAll(decoder.feed(new byte[] {b}));
}

assertEquals(2, messages.size());
assertEquals("contentBlockDelta", messages.get(0).headers().get(":event-type"));
assertEquals(
"{\"text\":\"hi\"}", new String(messages.get(0).payload(), StandardCharsets.UTF_8));
}

@Test
void decodesFramesLargerThanInitialBuffer() throws Exception {
String payload = "x".repeat(50_000);
var messages = new EventStreamDecoder().feed(frame("contentBlockDelta", payload));

assertEquals(1, messages.size());
assertEquals(payload, new String(messages.get(0).payload(), StandardCharsets.UTF_8));
}

@Test
void stopsDecodingAfterCorruptFrame() throws Exception {
byte[] corrupt = frame("messageStart", "{}");
corrupt[corrupt.length - 1] ^= 1; // break the message CRC
var decoder = new EventStreamDecoder();

assertThrows(IllegalStateException.class, () -> decoder.feed(corrupt));
assertEquals(List.of(), decoder.feed(frame("messageStop", "{}")));
}

@Test
void rejectsCorruptPrelude() throws Exception {
byte[] corrupt = Arrays.copyOf(frame("messageStart", "{}"), 12);
corrupt[0] ^= 1;

assertThrows(IllegalStateException.class, () -> new EventStreamDecoder().feed(corrupt));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import io.opentelemetry.sdk.trace.data.DelegatingSpanData;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
Expand Down Expand Up @@ -368,7 +369,12 @@ public String getName() {
return span;
}
});
try (var source = SdkTracerProvider.builder().build();
// OTel >= 1.67 hands out noop tracers when no span processor is registered.
try (var source =
SdkTracerProvider.builder()
.addSpanProcessor(
SimpleSpanProcessor.create(SpanExporter.composite()))
.build();
var exporter = new BraintrustSpanExporter(configBuilder.build())) {
var first =
source.get("test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import io.opentelemetry.sdk.trace.data.LinkData;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.data.StatusData;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
Expand Down Expand Up @@ -501,6 +503,10 @@ public SpanData onSpanExport(SpanData span) {

try (var provider =
SdkTracerProvider.builder()
// OTel >= 1.67 hands out noop tracers when no span processor is
// registered.
.addSpanProcessor(
SimpleSpanProcessor.create(SpanExporter.composite()))
.setResource(
Resource.create(Attributes.of(KEEP, "secret resource")))
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import org.junit.jupiter.api.Test;

public class FilterAISpansTest {

private final BraintrustSampler.FilterAISpans filter = new BraintrustSampler.FilterAISpans();
private final SdkTracerProvider tracerProvider = SdkTracerProvider.builder().build();
// OTel >= 1.67 hands out noop tracers when no span processor is registered.
private final SdkTracerProvider tracerProvider =
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite()))
.build();

private ReadableSpan createSpan(String name, String attrKey, String attrValue) {
var tracer = tracerProvider.get("test");
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ version = generateVersion()
group = 'dev.braintrust'

ext {
otelVersion = '1.66.0'
otelVersion = '1.67.0'
otelSemConvVersion = '1.44.0'
jacksonVersion = '2.21.7'
jacksonDatabindNullableVersion = '0.2.11'
Expand Down
Loading
Loading