|
| 1 | +"""Detached OTel export snapshots for the shared span customizer hook.""" |
| 2 | + |
| 3 | +from collections.abc import Mapping |
| 4 | +from copy import deepcopy |
| 5 | +from types import SimpleNamespace |
| 6 | + |
| 7 | +from braintrust.span_customizer import _run_span_export_customizers |
| 8 | +from opentelemetry.sdk.resources import Resource |
| 9 | +from opentelemetry.sdk.util.instrumentation import InstrumentationScope |
| 10 | +from opentelemetry.trace import SpanContext, SpanKind, StatusCode, TraceFlags |
| 11 | + |
| 12 | + |
| 13 | +try: |
| 14 | + from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans |
| 15 | +except ImportError: |
| 16 | + # OpenTelemetry 1.16 predates the shared HTTP/gRPC encoder package. |
| 17 | + from opentelemetry.exporter.otlp.proto.http.trace_exporter.encoder import _ProtobufEncoder |
| 18 | + |
| 19 | + encode_spans = _ProtobufEncoder.encode |
| 20 | + |
| 21 | + |
| 22 | +class _ExportSpan(SimpleNamespace): |
| 23 | + def get_span_context(self): |
| 24 | + return self.context |
| 25 | + |
| 26 | + |
| 27 | +def _copy_value(value): |
| 28 | + if isinstance(value, Mapping): |
| 29 | + return {key: _copy_value(item) for key, item in value.items()} |
| 30 | + if isinstance(value, (tuple, list)): |
| 31 | + return [_copy_value(item) for item in value] |
| 32 | + if value is None or type(value) in (str, bool, int, float, bytes): |
| 33 | + return value |
| 34 | + raise TypeError("Invalid OTel snapshot value") |
| 35 | + |
| 36 | + |
| 37 | +def _context_data(context): |
| 38 | + if context is None: |
| 39 | + return None |
| 40 | + return { |
| 41 | + "trace_id": context.trace_id, |
| 42 | + "span_id": context.span_id, |
| 43 | + "is_remote": context.is_remote, |
| 44 | + "trace_flags": int(context.trace_flags), |
| 45 | + "trace_state": dict(context.trace_state.items()), |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | +def _snapshot(span): |
| 50 | + scope = span.instrumentation_scope |
| 51 | + return { |
| 52 | + "name": span.name, |
| 53 | + "context": _context_data(span.context), |
| 54 | + "parent": _context_data(span.parent), |
| 55 | + "start_time": span.start_time, |
| 56 | + "end_time": span.end_time, |
| 57 | + "kind": span.kind.value, |
| 58 | + "attributes": _copy_value(span.attributes or {}), |
| 59 | + "events": [ |
| 60 | + { |
| 61 | + "name": event.name, |
| 62 | + "timestamp": event.timestamp, |
| 63 | + "attributes": _copy_value(event.attributes or {}), |
| 64 | + "dropped_attributes": getattr(event, "dropped_attributes", getattr(event.attributes, "dropped", 0)), |
| 65 | + } |
| 66 | + for event in span.events |
| 67 | + ], |
| 68 | + "links": [ |
| 69 | + { |
| 70 | + "context": _context_data(link.context), |
| 71 | + "attributes": _copy_value(link.attributes or {}), |
| 72 | + "dropped_attributes": getattr(link, "dropped_attributes", getattr(link.attributes, "dropped", 0)), |
| 73 | + } |
| 74 | + for link in span.links |
| 75 | + ], |
| 76 | + "status": {"status_code": span.status.status_code.value, "description": span.status.description}, |
| 77 | + "resource": {"attributes": _copy_value(span.resource.attributes), "schema_url": span.resource.schema_url}, |
| 78 | + "instrumentation_scope": { |
| 79 | + "name": scope.name, |
| 80 | + "version": scope.version, |
| 81 | + "schema_url": scope.schema_url, |
| 82 | + "attributes": _copy_value(getattr(scope, "attributes", None) or {}), |
| 83 | + } |
| 84 | + if scope |
| 85 | + else None, |
| 86 | + "dropped_attributes": span.dropped_attributes, |
| 87 | + "dropped_events": span.dropped_events, |
| 88 | + "dropped_links": span.dropped_links, |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +def _attributes(data): |
| 93 | + if not isinstance(data, dict): |
| 94 | + raise TypeError("OTel attributes must be a dict") |
| 95 | + for key, value in data.items(): |
| 96 | + if type(key) is not str: |
| 97 | + raise TypeError("OTel attribute keys must be strings") |
| 98 | + key.encode("utf-8") |
| 99 | + values = value if isinstance(value, (list, tuple)) else (value,) |
| 100 | + for item in values: |
| 101 | + if type(item) not in (str, bool, int, float): |
| 102 | + raise TypeError("Invalid OTel attribute value") |
| 103 | + if type(item) is int and not -(2**63) <= item < 2**63: |
| 104 | + raise ValueError("OTel integer attribute out of range") |
| 105 | + if type(item) is str: |
| 106 | + item.encode("utf-8") |
| 107 | + if values and any(type(item) is not type(values[0]) for item in values): |
| 108 | + raise TypeError("OTel attribute arrays must be homogeneous") |
| 109 | + return data |
| 110 | + |
| 111 | + |
| 112 | +def _context(data): |
| 113 | + if data is None: |
| 114 | + return None |
| 115 | + state = data.get("trace_state", {}) |
| 116 | + if not isinstance(state, dict) or any(type(k) is not str or type(v) is not str for k, v in state.items()): |
| 117 | + raise TypeError("Invalid OTel trace state") |
| 118 | + return SpanContext( |
| 119 | + trace_id=data["trace_id"], |
| 120 | + span_id=data["span_id"], |
| 121 | + is_remote=data.get("is_remote", False), |
| 122 | + trace_flags=TraceFlags(data.get("trace_flags", 0)), |
| 123 | + trace_state=state, |
| 124 | + ) |
| 125 | + |
| 126 | + |
| 127 | +def _scope(data): |
| 128 | + if data is None: |
| 129 | + return None |
| 130 | + attributes = _attributes(data.get("attributes", {})) |
| 131 | + kwargs = {} |
| 132 | + if hasattr(InstrumentationScope, "attributes"): |
| 133 | + kwargs["attributes"] = attributes |
| 134 | + elif attributes: |
| 135 | + raise ValueError("Scope attributes require a newer OpenTelemetry SDK") |
| 136 | + return InstrumentationScope( |
| 137 | + name=data.get("name", ""), version=data.get("version"), schema_url=data.get("schema_url", ""), **kwargs |
| 138 | + ) |
| 139 | + |
| 140 | + |
| 141 | +def _export_span(data): |
| 142 | + resource = data.get("resource", {}) |
| 143 | + scope = data.get("instrumentation_scope") |
| 144 | + status = data.get("status", {}) |
| 145 | + return _ExportSpan( |
| 146 | + name=data.get("name", ""), |
| 147 | + context=_context(data["context"]), |
| 148 | + parent=_context(data["parent"]), |
| 149 | + start_time=data["start_time"], |
| 150 | + end_time=data["end_time"], |
| 151 | + kind=SpanKind(data.get("kind", 0)), |
| 152 | + attributes=_attributes(data.get("attributes", {})), |
| 153 | + events=[ |
| 154 | + SimpleNamespace( |
| 155 | + name=event["name"], |
| 156 | + timestamp=event["timestamp"], |
| 157 | + attributes=_attributes(event.get("attributes", {})), |
| 158 | + dropped_attributes=event.get("dropped_attributes", 0), |
| 159 | + ) |
| 160 | + for event in data.get("events", []) |
| 161 | + ], |
| 162 | + links=[ |
| 163 | + SimpleNamespace( |
| 164 | + context=_context(link["context"]), |
| 165 | + attributes=_attributes(link.get("attributes", {})), |
| 166 | + dropped_attributes=link.get("dropped_attributes", 0), |
| 167 | + ) |
| 168 | + for link in data.get("links", []) |
| 169 | + ], |
| 170 | + status=SimpleNamespace( |
| 171 | + status_code=StatusCode(status.get("status_code", 0)), description=status.get("description") |
| 172 | + ), |
| 173 | + resource=Resource(_attributes(resource.get("attributes", {})), schema_url=resource.get("schema_url", "")), |
| 174 | + instrumentation_scope=_scope(scope), |
| 175 | + dropped_attributes=data.get("dropped_attributes", 0), |
| 176 | + dropped_events=data.get("dropped_events", 0), |
| 177 | + dropped_links=data.get("dropped_links", 0), |
| 178 | + ) |
| 179 | + |
| 180 | + |
| 181 | +def customize_otel_span(span, customizers): |
| 182 | + """Customize exactly once at the Braintrust exporter, never other consumers.""" |
| 183 | + data = _snapshot(span) |
| 184 | + protected = {key: deepcopy(data[key]) for key in ("context", "parent", "start_time", "end_time")} |
| 185 | + routing = {key: data["attributes"][key] for key in ("braintrust.parent",) if key in data["attributes"]} |
| 186 | + |
| 187 | + def restore(result): |
| 188 | + result = _copy_value(result) |
| 189 | + result.update(deepcopy(protected)) |
| 190 | + attributes = result.setdefault("attributes", {}) |
| 191 | + if not isinstance(attributes, dict): |
| 192 | + raise TypeError("OTel attributes must be a dict") |
| 193 | + attributes.pop("braintrust.parent", None) |
| 194 | + attributes.update(routing) |
| 195 | + # Validate every hook result before the next hook runs. The upstream encoder |
| 196 | + # silently skips invalid attributes (and logs their values), so validate those |
| 197 | + # first; protobuf then checks all remaining wire types and numeric bounds. |
| 198 | + candidate = _export_span(result) |
| 199 | + encode_spans([candidate]).SerializeToString() |
| 200 | + return result |
| 201 | + |
| 202 | + def stripped_record(): |
| 203 | + stripped = deepcopy(protected) |
| 204 | + for field in ("context", "parent"): |
| 205 | + if stripped[field] is not None: |
| 206 | + stripped[field]["trace_state"] = {} |
| 207 | + stripped["attributes"] = {**routing, "braintrust.context_json": '{"customizer_error":true}'} |
| 208 | + return stripped |
| 209 | + |
| 210 | + return _export_span(_run_span_export_customizers(data, customizers, restore, stripped_record)) |
0 commit comments