Skip to content

Commit b3007ac

Browse files
committed
span customizer error handling
1 parent b835d7b commit b3007ac

4 files changed

Lines changed: 336 additions & 59 deletions

File tree

‎braintrust-sdk/src/main/java/dev/braintrust/trace/BraintrustSpanExporter.java‎

Lines changed: 108 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,32 @@
22

33
import dev.braintrust.api.BraintrustOpenApiClient;
44
import 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;
511
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter;
612
import 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;
716
import io.opentelemetry.sdk.trace.data.DelegatingSpanData;
17+
import io.opentelemetry.sdk.trace.data.EventData;
18+
import io.opentelemetry.sdk.trace.data.LinkData;
819
import io.opentelemetry.sdk.trace.data.SpanData;
20+
import io.opentelemetry.sdk.trace.data.StatusData;
921
import io.opentelemetry.sdk.trace.export.SpanExporter;
1022
import java.util.Collection;
1123
import java.util.List;
1224
import java.util.Map;
1325
import java.util.Objects;
1426
import java.util.concurrent.ConcurrentHashMap;
27+
import java.util.concurrent.atomic.AtomicBoolean;
1528
import java.util.function.UnaryOperator;
1629
import java.util.stream.Collectors;
30+
import lombok.Getter;
1731
import lombok.extern.slf4j.Slf4j;
1832

1933
/**
@@ -22,6 +36,9 @@
2236
*/
2337
@Slf4j
2438
class 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) {

‎braintrust-sdk/src/main/java/dev/braintrust/trace/SpanCustomizer.java‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,33 @@
33
import io.opentelemetry.sdk.trace.data.SpanData;
44

55
/**
6-
* A callback hook for altering span data. This is primarly used by SDK users who wish to customize
7-
* auto-instrumented spans.
6+
* Optional hooks for transforming all spans reaching the Braintrust exporter, including manually
7+
* created and auto-instrumented spans.
88
*/
99
public interface SpanCustomizer {
1010
/**
11-
* called just before a span is exported. You may add/remove/delete most fields on the span.
11+
* Transforms completed span data before destination grouping, attachment uploads, and
12+
* serialization. Hooks run synchronously in registration order, each receiving the preceding
13+
* hook's result, and may run off the application thread. Keep hooks fast and avoid blocking
14+
* I/O.
1215
*
13-
* <p>The follow fields may NOT be altered: trace id, span id, parent id
16+
* <p>Return the original span or a replacement, preserving trace ID, span ID, and parent span
17+
* ID, including their corresponding span-context values. The {@code braintrust.parent}
18+
* destination attribute may change.
19+
*
20+
* <p>If a hook throws an exception, returns {@code null}, or changes a protected ID, remaining
21+
* hooks for that span are skipped. The exporter retains only the original IDs, start/end
22+
* timestamps, and destination routing, plus {@code braintrust.context_json} containing {@code
23+
* {"customizer_error":true}}. All other content, including partial changes from earlier hooks,
24+
* is discarded; no attachments from that span are uploaded. Unrelated spans continue exporting,
25+
* and a hook failure alone does not fail the export.
26+
*
27+
* <p>A payload-free diagnostic is logged at most once per process, without exception details.
28+
* Every stripped span receives the error marker regardless of logging. Submitting a batch to
29+
* the exporter again runs the hooks again. To recover without stripping content, handle errors
30+
* inside the hook and return valid span data.
31+
*
32+
* @return the non-null span data to export; returning {@code null} cannot drop a span
1433
*/
1534
default SpanData onSpanExport(SpanData span) {
1635
return span;

‎braintrust-sdk/src/test/java/dev/braintrust/trace/AttachmentProcessorTest.java‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ public int getTotalAttributeCount() {
346346
}
347347

348348
@Test
349-
void rejectedBatchDoesNotUploadEarlierSpansAttachments() throws Exception {
349+
void failedCustomizationSkipsOnlyAffectedSpansAttachments() throws Exception {
350350
configBuilder.addSpanCustomizer(
351351
new SpanCustomizer() {
352352
@Override
@@ -371,6 +371,12 @@ public SpanData onSpanExport(SpanData span) {
371371
source.get("test")
372372
.spanBuilder("reject")
373373
.setAttribute("braintrust.parent", "project_name:second")
374+
.setAttribute(
375+
INPUT_JSON,
376+
"{\"url\":\"data:application/pdf;base64," + BASE64_PDF + "\"}")
377+
.setAttribute(
378+
BraintrustSpanProcessor.OUTPUT_JSON,
379+
"{\"url\":\"data:application/pdf;base64," + BASE64_PDF + "\"}")
374380
.startSpan();
375381
first.end();
376382
second.end();
@@ -381,10 +387,58 @@ public SpanData onSpanExport(SpanData span) {
381387
((ReadableSpan) second).toSpanData()))
382388
.join(5, TimeUnit.SECONDS);
383389
assertTrue(result.isDone());
384-
assertFalse(result.isSuccess());
385-
assertNull(attachmentRequests.poll(300, TimeUnit.MILLISECONDS));
386-
assertTrue(exports.isEmpty());
390+
assertTrue(result.isSuccess());
391+
assertArrayEquals(
392+
java.util.Base64.getDecoder().decode(BASE64_PNG),
393+
uploads.poll(5, TimeUnit.SECONDS));
394+
assertNotNull(completedUploads.poll(5, TimeUnit.SECONDS));
395+
for (int i = 0; i < 2; i++) {
396+
var body = exports.poll(5, TimeUnit.SECONDS);
397+
assertNotNull(body, "Expected an OTLP export");
398+
var exported =
399+
ExportTraceServiceRequest.parseFrom(body)
400+
.getResourceSpans(0)
401+
.getScopeSpans(0)
402+
.getSpans(0);
403+
if (exported.getName().equals("accept")) {
404+
var input =
405+
exported.getAttributesList().stream()
406+
.filter(a -> a.getKey().equals(INPUT_JSON.getKey()))
407+
.findFirst()
408+
.orElseThrow()
409+
.getValue()
410+
.getStringValue();
411+
assertAttachmentRef(
412+
BraintrustJsonMapper.get().readTree(input).get("url"), "image/png");
413+
} else {
414+
assertEquals("", exported.getName());
415+
assertFalse(
416+
exported.getAttributesList().stream()
417+
.anyMatch(
418+
a ->
419+
a.getKey().equals(INPUT_JSON.getKey())
420+
|| a.getKey()
421+
.equals(
422+
BraintrustSpanProcessor
423+
.OUTPUT_JSON
424+
.getKey())));
425+
assertEquals(
426+
"{\"customizer_error\":true}",
427+
exported.getAttributesList().stream()
428+
.filter(a -> a.getKey().equals("braintrust.context_json"))
429+
.findFirst()
430+
.orElseThrow()
431+
.getValue()
432+
.getStringValue());
433+
}
434+
}
387435
}
436+
// Closing the exporter drains uploads, so absence here cannot race a pending upload.
437+
assertTrue(uploads.isEmpty(), "No attachment from the stripped span may be uploaded");
438+
assertEquals(
439+
List.of("/api/apikey/login", "/attachment", "/upload", "/attachment/status"),
440+
List.copyOf(attachmentRequests));
441+
assertTrue(exports.isEmpty());
388442
}
389443

390444
@Test

0 commit comments

Comments
 (0)