22
33import dev .braintrust .api .BraintrustOpenApiClient ;
44import dev .braintrust .config .BraintrustConfig ;
5+ import io .opentelemetry .api .common .AttributeKey ;
6+ import io .opentelemetry .api .common .Attributes ;
7+ import io .opentelemetry .api .trace .SpanContext ;
8+ import io .opentelemetry .api .trace .SpanKind ;
9+ import io .opentelemetry .api .trace .TraceFlags ;
10+ import io .opentelemetry .api .trace .TraceState ;
511import io .opentelemetry .exporter .otlp .http .trace .OtlpHttpSpanExporter ;
612import io .opentelemetry .sdk .common .CompletableResultCode ;
13+ import io .opentelemetry .sdk .common .InstrumentationLibraryInfo ;
14+ import io .opentelemetry .sdk .common .InstrumentationScopeInfo ;
15+ import io .opentelemetry .sdk .resources .Resource ;
716import io .opentelemetry .sdk .trace .data .DelegatingSpanData ;
17+ import io .opentelemetry .sdk .trace .data .EventData ;
18+ import io .opentelemetry .sdk .trace .data .LinkData ;
819import io .opentelemetry .sdk .trace .data .SpanData ;
20+ import io .opentelemetry .sdk .trace .data .StatusData ;
921import io .opentelemetry .sdk .trace .export .SpanExporter ;
1022import java .util .Collection ;
1123import java .util .List ;
1224import java .util .Map ;
1325import java .util .Objects ;
1426import java .util .concurrent .ConcurrentHashMap ;
27+ import java .util .concurrent .atomic .AtomicBoolean ;
1528import java .util .function .UnaryOperator ;
1629import java .util .stream .Collectors ;
30+ import lombok .Getter ;
1731import lombok .extern .slf4j .Slf4j ;
1832
1933/**
2236 */
2337@ Slf4j
2438class BraintrustSpanExporter implements SpanExporter {
39+ private static final AtomicBoolean customizerFailureLogged = new AtomicBoolean ();
40+ private static final AttributeKey <String > CUSTOMIZER_CONTEXT =
41+ AttributeKey .stringKey ("braintrust.context_json" );
2542 private final BraintrustConfig config ;
2643 private final String tracesEndpoint ;
2744 private final Map <String , SpanExporter > exporterCache = new ConcurrentHashMap <>();
@@ -51,17 +68,11 @@ public CompletableResultCode export(Collection<SpanData> spans) {
5168 }
5269
5370 // Finish customization for the entire batch before any attachment or span upload.
54- Map <String , List <SpanData >> spansByParent ;
55- try {
56- var exportSpans = spans .stream ();
57- if (!config .spanCustomizers ().isEmpty ()) {
58- exportSpans = exportSpans .map (this ::customizeSpan );
59- }
60- spansByParent = exportSpans .collect (Collectors .groupingBy (this ::getParentFromSpan ));
61- } catch (Exception e ) {
62- log .error ("Failed to customize spans for export" , e );
63- return CompletableResultCode .ofFailure ();
71+ var exportSpans = spans .stream ();
72+ if (!config .spanCustomizers ().isEmpty ()) {
73+ exportSpans = exportSpans .map (this ::customizeSpan );
6474 }
75+ var spansByParent = exportSpans .collect (Collectors .groupingBy (this ::getParentFromSpan ));
6576
6677 // Export each group with the appropriate x-bt-parent header
6778 var results =
@@ -86,24 +97,97 @@ private SpanData customizeSpan(SpanData span) {
8697 var traceId = span .getTraceId ();
8798 var spanId = span .getSpanId ();
8899 var parentSpanId = span .getParentSpanId ();
100+ var parentTraceId = span .getParentSpanContext ().getTraceId ();
101+ var startEpochNanos = span .getStartEpochNanos ();
102+ var endEpochNanos = span .getEndEpochNanos ();
103+ var parent = span .getAttributes ().get (BraintrustSpanProcessor .PARENT );
89104 var current = span ;
90- for (var customizer : config .spanCustomizers ()) {
91- current = customizer .onSpanExport (current );
92- if (current == null ) {
93- throw new IllegalStateException ("SpanCustomizer.onSpanExport must not return null" );
105+ try {
106+ for (var customizer : config .spanCustomizers ()) {
107+ current = customizer .onSpanExport (current );
108+ if (current == null
109+ || !traceId .equals (current .getTraceId ())
110+ || !spanId .equals (current .getSpanId ())
111+ || !parentSpanId .equals (current .getParentSpanId ())
112+ || !traceId .equals (current .getSpanContext ().getTraceId ())
113+ || !spanId .equals (current .getSpanContext ().getSpanId ())
114+ || !parentTraceId .equals (current .getParentSpanContext ().getTraceId ())
115+ || !parentSpanId .equals (current .getParentSpanContext ().getSpanId ())) {
116+ current = null ;
117+ break ;
118+ }
94119 }
95- if (!traceId .equals (current .getTraceId ())
96- || !spanId .equals (current .getSpanId ())
97- || !parentSpanId .equals (current .getParentSpanId ())
98- || !traceId .equals (current .getSpanContext ().getTraceId ())
99- || !spanId .equals (current .getSpanContext ().getSpanId ())
100- || !parentSpanId .equals (current .getParentSpanContext ().getSpanId ())) {
101- throw new IllegalStateException (
102- "SpanCustomizer.onSpanExport must not change trace ID, span ID, or parent"
103- + " span ID" );
120+ if (current != null ) {
121+ return current ;
104122 }
123+ } catch (Exception ignored ) {
124+ // Never log hook exceptions: even their messages and stacks may contain span content.
125+ }
126+ if (customizerFailureLogged .compareAndSet (false , true )) {
127+ log .error (
128+ "Span customization failed; exporting only span identity and duration with"
129+ + " context.customizer_error=true. Further failures will not be logged." );
130+ }
131+ var attributes =
132+ Attributes .builder ().put (CUSTOMIZER_CONTEXT , "{\" customizer_error\" :true}" );
133+ if (parent != null ) {
134+ attributes .put (BraintrustSpanProcessor .PARENT , parent );
135+ }
136+ return new StrippedSpanData (
137+ SpanContext .create (
138+ traceId , spanId , TraceFlags .getDefault (), TraceState .getDefault ()),
139+ SpanContext .create (
140+ parentTraceId ,
141+ parentSpanId ,
142+ TraceFlags .getDefault (),
143+ TraceState .getDefault ()),
144+ startEpochNanos ,
145+ endEpochNanos ,
146+ attributes .build ());
147+ }
148+
149+ /** Allowlist only: never delegate content access back to the original or customized span. */
150+ @ Getter
151+ private static final class StrippedSpanData implements SpanData {
152+ private final SpanContext spanContext ;
153+ private final SpanContext parentSpanContext ;
154+ private final long startEpochNanos ;
155+ private final long endEpochNanos ;
156+ private final Attributes attributes ;
157+ private final int totalAttributeCount ;
158+ private final String name = "" ;
159+ private final SpanKind kind = SpanKind .INTERNAL ;
160+ private final StatusData status = StatusData .unset ();
161+ private final List <EventData > events = List .of ();
162+ private final List <LinkData > links = List .of ();
163+ private final int totalRecordedEvents = 0 ;
164+ private final int totalRecordedLinks = 0 ;
165+ private final Resource resource = Resource .empty ();
166+ private final InstrumentationScopeInfo instrumentationScopeInfo =
167+ InstrumentationScopeInfo .empty ();
168+
169+ @ SuppressWarnings ("deprecation" )
170+ private final InstrumentationLibraryInfo instrumentationLibraryInfo =
171+ InstrumentationLibraryInfo .empty ();
172+
173+ private StrippedSpanData (
174+ SpanContext spanContext ,
175+ SpanContext parentSpanContext ,
176+ long startEpochNanos ,
177+ long endEpochNanos ,
178+ Attributes attributes ) {
179+ this .spanContext = spanContext ;
180+ this .parentSpanContext = parentSpanContext ;
181+ this .startEpochNanos = startEpochNanos ;
182+ this .endEpochNanos = endEpochNanos ;
183+ this .attributes = attributes ;
184+ this .totalAttributeCount = attributes .size ();
185+ }
186+
187+ @ Override
188+ public boolean hasEnded () {
189+ return true ;
105190 }
106- return current ;
107191 }
108192
109193 private SpanData convertAttachments (SpanData span ) {
0 commit comments