Skip to main content

saluki_components/common/otlp/traces/
translator.rs

1use std::collections::hash_map::IntoIter;
2use std::collections::HashMap;
3use std::num::NonZeroUsize;
4use std::sync::Arc;
5
6use datadog_agent_apm::semantics::{Registry, SemanticRegistryProvider};
7use otlp_protos::opentelemetry::proto::common::v1::{self as otlp_common, any_value::Value as OtlpValue};
8use otlp_protos::opentelemetry::proto::resource::v1::Resource as OtlpResource;
9use otlp_protos::opentelemetry::proto::trace::v1::ResourceSpans;
10use saluki_common::collections::FastHashMap;
11use saluki_common::strings::StringBuilder;
12use saluki_core::data_model::event::trace::{
13    AttributeValue, AttributeValueExt, Span as DdSpan, Trace, TraceIngestInfo,
14};
15use saluki_core::data_model::event::Event;
16use saluki_core::data_model::origin::OriginTagCardinality;
17use stringtheory::interning::GenericMapInterner;
18use stringtheory::MetaString;
19
20use crate::common::datadog::SAMPLING_PRIORITY_METRIC_KEY;
21use crate::common::otlp::origin::OtlpOriginTagResolver;
22use crate::common::otlp::source::resolve_source_from_attributes;
23use crate::common::otlp::traces::transform::{
24    bytes_to_hex_lowercase, get_otel_container_id, get_otel_env, get_otel_version, normalize_peer_service_tags,
25    otel_span_to_dd_span, otel_span_to_dd_span_v1, SpanConversion, SpanNaming,
26};
27use crate::common::otlp::util::{
28    get_string_attribute, is_datadog_container_tag_attribute, resolve_otlp_trace_container_tags,
29    set_resource_attributes, write_infra_tag_attributes, SourceKind,
30};
31use crate::common::otlp::value::otlp_value_to_string;
32use crate::common::otlp::Metrics;
33
34const DATADOG_HOSTNAME_ATTR: &str = "datadog.host.name";
35const TELEMETRY_SDK_LANGUAGE: &str = "telemetry.sdk.language";
36const TELEMETRY_SDK_VERSION: &str = "telemetry.sdk.version";
37
38pub fn convert_trace_id(trace_id: &[u8]) -> u64 {
39    if trace_id.len() < 8 {
40        return 0;
41    }
42    u64::from_be_bytes((&trace_id[(trace_id.len() - 8)..]).try_into().unwrap_or_default())
43}
44
45/// Extracts the high 8 bytes of a 128-bit OTLP trace ID as a big-endian u64.
46///
47/// Returns 0 if the trace ID is shorter than 16 bytes (for example, a 64-bit-only ID).
48pub fn convert_trace_id_high(trace_id: &[u8]) -> u64 {
49    if trace_id.len() < 16 {
50        return 0;
51    }
52    u64::from_be_bytes((&trace_id[..8]).try_into().unwrap_or_default())
53}
54
55pub fn convert_span_id(span_id: &[u8]) -> u64 {
56    if span_id.len() != 8 {
57        return 0;
58    }
59    u64::from_be_bytes(span_id.try_into().unwrap_or_default())
60}
61
62/// Metadata extracted from OTLP resource attributes for the unified `Trace` fields.
63///
64/// Built once per `ResourceSpans` batch and shared across all traces derived from
65/// the same resource.
66struct OtlpResourceMeta {
67    /// Resolved environment name.
68    env: MetaString,
69    /// Resolved hostname.
70    hostname: MetaString,
71    /// Resolved container ID.
72    container_id: MetaString,
73    /// Resolved application version.
74    app_version: MetaString,
75    /// Resolved tracer language name.
76    language_name: MetaString,
77    /// Resolved tracer SDK version.
78    tracer_version: MetaString,
79    /// All resource attributes as a typed map (for `Trace::attributes`).
80    attributes: Arc<FastHashMap<MetaString, AttributeValue>>,
81    /// Container tags resolved from the resource attributes and the enriched tags, as `key:value` tags.
82    container_tags: Option<Arc<Vec<MetaString>>>,
83    /// Enriched tags that span conversion must see as resource attributes, so they reach every span's meta.
84    span_attributes: Vec<otlp_common::KeyValue>,
85}
86
87/// Extracts unified trace-level fields from OTLP resource attributes.
88///
89/// Mirrors the field extraction performed by `receiveResourceSpansV2` in the Go trace agent
90/// (`pkg/trace/api/otlp.go`): env from deployment environment semantic conventions, container ID from
91/// container semantic conventions, hostname from the resource source, language/version from telemetry SDK attributes.
92/// All known fields are also inserted into the returned `attributes` map so that downstream code
93/// can use a single map lookup regardless of whether a field is explicitly modelled on `Trace`.
94fn extract_resource_meta(
95    attributes: &[otlp_common::KeyValue], ignore_missing_fields: bool, default_hostname: &MetaString,
96    infra_attributes: Option<(&OtlpOriginTagResolver, ContainerTagPromotion)>, interner: &GenericMapInterner,
97    string_builder: &mut StringBuilder<GenericMapInterner>,
98) -> OtlpResourceMeta {
99    // Reuse the existing normalizing helpers (span_attrs = empty, resource_attrs = full).
100    let empty: &[otlp_common::KeyValue] = &[];
101
102    let env = get_otel_env(attributes, empty, ignore_missing_fields, interner, string_builder);
103    let app_version = get_otel_version(attributes, empty, ignore_missing_fields, interner, string_builder);
104    let container_id = get_otel_container_id(attributes, empty, ignore_missing_fields, interner, string_builder);
105
106    let hostname = resolve_hostname(attributes, ignore_missing_fields, default_hostname, interner);
107
108    let language_name = get_string_attribute(attributes, TELEMETRY_SDK_LANGUAGE)
109        .filter(|s| !s.is_empty())
110        .map(|s| MetaString::from_interner(s, interner))
111        .unwrap_or_default();
112
113    let tracer_version = get_string_attribute(attributes, TELEMETRY_SDK_VERSION)
114        .filter(|s| !s.is_empty())
115        .map(|s| MetaString::from_interner(s, interner))
116        .unwrap_or_default();
117    // language_version is intentionally not populated for OTLP traces: OTLP has no standardised
118    // attribute for the language runtime version, so we leave it empty rather than guess.
119
120    // Build the typed attributes map from all resource attributes.
121    let mut attr_map: FastHashMap<MetaString, AttributeValue> = FastHashMap::default();
122    attr_map.reserve(attributes.len());
123    for kv in attributes {
124        if kv.key.is_empty() {
125            continue;
126        }
127        let Some(wrapper) = &kv.value else { continue };
128        let Some(value) = &wrapper.value else { continue };
129
130        // Scalar types are stored in their native AttributeValue variant so downstream
131        // code (e.g. the encoder) can coerce at the output boundary. Arrays and KVLists
132        // are stringified via JSON because no wire format accepts them natively.
133        // TODO: when implementing the new indexed format this will no longer be necessary.
134        let attr_value = match value {
135            OtlpValue::StringValue(s) => AttributeValue::String(MetaString::from_interner(s.as_str(), interner)),
136            OtlpValue::IntValue(i) => AttributeValue::Int(*i),
137            OtlpValue::DoubleValue(d) => AttributeValue::Float(*d),
138            OtlpValue::BoolValue(b) => AttributeValue::Bool(*b),
139            OtlpValue::BytesValue(b) => AttributeValue::Bytes(b.clone()),
140            _ => {
141                // Arrays and KVLists are stringified via JSON.
142                if let Some(s) = otlp_value_to_string(value) {
143                    AttributeValue::String(MetaString::from_interner(s.as_str(), interner))
144                } else {
145                    continue;
146                }
147            }
148        };
149
150        let key = MetaString::from_interner(kv.key.as_str(), interner);
151        attr_map.insert(key, attr_value);
152    }
153
154    // Entity and global tags resolve at low cardinality: higher tiers multiply the tags on every
155    // span's stats buckets, and no setting raises the tier yet.
156    let mut span_attributes = Vec::new();
157    if let Some((resolver, promotion)) = infra_attributes {
158        let infra_tags = resolver.resolve_resource_tags(attributes, OriginTagCardinality::Low);
159        span_attributes = write_infra_tag_attributes(infra_tags, promotion, interner, &mut attr_map);
160    }
161
162    // Container tags need the order and the arrays of the sender's attributes, which `attr_map` has lost.
163    let container_tags = Some(resolve_otlp_trace_container_tags(attributes, &attr_map))
164        .filter(|tags| !tags.is_empty())
165        .map(Arc::new);
166
167    OtlpResourceMeta {
168        env,
169        hostname,
170        container_id,
171        app_version,
172        language_name,
173        tracer_version,
174        attributes: Arc::new(attr_map),
175        container_tags,
176        span_attributes,
177    }
178}
179
180/// Resolves the payload hostname from the resource's source.
181///
182/// A hostname source gives its identifier, a serverless source gives no hostname, and a resource with no source gets
183/// `default_hostname`. When missing Datadog fields are ignored, only an explicit `datadog.host.name` counts.
184fn resolve_hostname(
185    attributes: &[otlp_common::KeyValue], ignore_missing_fields: bool, default_hostname: &MetaString,
186    interner: &GenericMapInterner,
187) -> MetaString {
188    if ignore_missing_fields {
189        return get_string_attribute(attributes, DATADOG_HOSTNAME_ATTR)
190            .filter(|s| !s.is_empty())
191            .map(|s| MetaString::from_interner(s, interner))
192            .unwrap_or_default();
193    }
194
195    match resolve_source_from_attributes(attributes) {
196        Some(source) if source.kind == SourceKind::Hostname => MetaString::from_interner(&source.identifier, interner),
197        Some(_) => MetaString::default(),
198        None => default_hostname.clone(),
199    }
200}
201
202struct TraceEntry {
203    spans: Vec<DdSpan>,
204    priority: Option<i32>,
205    trace_id_hex: Option<MetaString>,
206    /// High 8 bytes of the 128-bit trace ID (captured from the first span).
207    trace_id_high: u64,
208    /// Set when any span in the trace has a span ID of zero. Mirrors `normalizeV1`
209    /// (`pkg/trace/agent/normalizer.go`), which drops such a span along with the chunk containing it.
210    dropped: bool,
211    /// Whether the group failed the full trace ID consistency check and must be dropped whole.
212    rejected: bool,
213}
214
215/// Settings of OTLP trace translation.
216#[derive(Clone, Debug, PartialEq)]
217pub struct OtlpTracesSettings {
218    /// Size of the string interner backing translated traces, in bytes.
219    pub string_interner_size: NonZeroUsize,
220
221    /// Percentage of traces the OTLP receiver keeps, stamped on translated traces as their sampling rate. A value of
222    /// `0` or below, or `100` or above, stamps a rate of `1.0`.
223    pub probabilistic_sampler_sampling_percentage: f64,
224
225    /// Whether spans are marked top-level by their span kind.
226    pub enable_compute_top_level_by_span_kind: bool,
227
228    /// Whether spans missing intake-required fields are translated rather than rejected.
229    pub ignore_missing_datadog_fields: bool,
230
231    /// Whether entity and global tags from the workload metadata store are enriched onto traces.
232    pub infra_attributes_enabled: bool,
233
234    /// How custom infrastructure tags are promoted into container tags.
235    pub container_tag_promotion: ContainerTagPromotion,
236
237    /// Whether the span name becomes the operation name of a span without `operation.name`.
238    ///
239    /// `true` selects V1 operation and resource naming.
240    pub span_name_as_resource_name: bool,
241
242    /// Preferred operation names, keyed by the operation name V1 naming derives.
243    ///
244    /// A non-empty map selects V1 operation and resource naming.
245    pub span_name_remappings: HashMap<String, String>,
246
247    /// Whether operation and resource names are derived with V1 naming.
248    pub disable_operation_and_resource_name_logic_v2: bool,
249
250    /// Whether spans are converted on the V1 receive path.
251    pub disable_receive_resource_spans_v2: bool,
252
253    /// Whether the `otel.scope.*` tags are left off spans.
254    pub disable_otel_scope_convention: bool,
255}
256
257/// How custom infrastructure tags are promoted into container tags on OTLP traces.
258#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
259pub enum ContainerTagPromotion {
260    /// Writes tags as-is. Only convention keys reach container tags; custom keys remain plain resource attributes.
261    #[default]
262    Off,
263
264    /// Writes both the original key and a `datadog.container.tag.` prefixed copy.
265    Duplicate,
266
267    /// Writes only the `datadog.container.tag.` form.
268    Rename,
269}
270
271/// Returns trace translation settings carrying the configuration defaults.
272#[cfg(test)]
273pub(crate) fn traces_settings() -> OtlpTracesSettings {
274    OtlpTracesSettings {
275        string_interner_size: NonZeroUsize::new(512 * 1024).unwrap(),
276        probabilistic_sampler_sampling_percentage: 0.0,
277        enable_compute_top_level_by_span_kind: true,
278        ignore_missing_datadog_fields: false,
279        infra_attributes_enabled: true,
280        container_tag_promotion: ContainerTagPromotion::Off,
281        span_name_as_resource_name: false,
282        span_name_remappings: HashMap::new(),
283        disable_operation_and_resource_name_logic_v2: false,
284        disable_receive_resource_spans_v2: false,
285        disable_otel_scope_convention: false,
286    }
287}
288
289pub struct OtlpTracesTranslator {
290    config: OtlpTracesSettings,
291    /// Receiver sampling rate stamped on every translated trace.
292    receiver_sampling_rate: f64,
293    /// How spans are converted, derived from `config` once.
294    conversion: SpanConversion,
295    /// Resolves entity and global tags for a resource's container.
296    origin_tag_resolver: OtlpOriginTagResolver,
297    interner: GenericMapInterner,
298    string_builder: StringBuilder<GenericMapInterner>,
299    /// Supplies one registry snapshot per `ResourceSpans` batch, so mappings cannot change midway through a batch.
300    registry: SemanticRegistryProvider,
301    /// Hostname of traces whose resource carries no source.
302    default_hostname: MetaString,
303}
304
305impl OtlpTracesTranslator {
306    /// Creates a translator using `registry` for embedded or remotely updated attribute mappings.
307    ///
308    /// Reads the current registry at the start of each [`Self::translate_spans`] call, not at construction.
309    ///
310    /// The configured sampling percentage becomes the receiver sampling rate stamped on every trace. Rates outside
311    /// `(0, 1)` and NaN normalize to `1.0`. This matches `OTLPReceiver.samplingRate` in the Go trace agent, except
312    /// that the Go trace agent propagates NaN.
313    pub fn new(
314        config: OtlpTracesSettings, max_resource_len: usize, registry: SemanticRegistryProvider,
315        origin_tag_resolver: OtlpOriginTagResolver,
316    ) -> Self {
317        let interner = GenericMapInterner::new(config.string_interner_size);
318        let string_builder = StringBuilder::new().with_interner(interner.clone());
319        let rate = config.probabilistic_sampler_sampling_percentage / 100.0;
320        let receiver_sampling_rate = if rate > 0.0 && rate < 1.0 { rate } else { 1.0 };
321        let conversion = SpanConversion {
322            ignore_missing_fields: config.ignore_missing_datadog_fields,
323            compute_top_level_by_span_kind: config.enable_compute_top_level_by_span_kind,
324            max_resource_len,
325            naming: SpanNaming::select(
326                config.span_name_as_resource_name,
327                &config.span_name_remappings,
328                config.disable_operation_and_resource_name_logic_v2,
329            ),
330            emit_otel_scope: !config.disable_otel_scope_convention,
331        };
332        Self {
333            config,
334            receiver_sampling_rate,
335            conversion,
336            origin_tag_resolver,
337            interner,
338            string_builder,
339            registry,
340            default_hostname: MetaString::default(),
341        }
342    }
343
344    /// Sets the hostname of traces whose resource carries no source, such as the host the data plane runs on.
345    ///
346    /// Defaults to an empty hostname.
347    pub fn with_default_hostname(mut self, default_hostname: MetaString) -> Self {
348        self.default_hostname = default_hostname;
349        self
350    }
351
352    pub fn translate_spans(&mut self, resource_spans: ResourceSpans, metrics: &Metrics) -> impl Iterator<Item = Event> {
353        let mut resource: OtlpResource = resource_spans.resource.unwrap_or_default();
354        let ignore_missing_fields = self.config.ignore_missing_datadog_fields;
355        let receive_v1 = self.config.disable_receive_resource_spans_v2;
356        let conversion = &self.conversion;
357        let interner = &self.interner;
358        let string_builder = &mut self.string_builder;
359        let registry = self.registry.snapshot();
360        let registry: &Registry = &registry;
361
362        // Build unified resource metadata for the new Trace fields.
363        let infra_attributes = self
364            .config
365            .infra_attributes_enabled
366            .then_some((&self.origin_tag_resolver, self.config.container_tag_promotion));
367        let mut resource_meta = extract_resource_meta(
368            &resource.attributes,
369            ignore_missing_fields,
370            &self.default_hostname,
371            infra_attributes,
372            interner,
373            string_builder,
374        );
375
376        // Datadog-convention container tag keys, such as `kube_namespace`, are consumed as container tags before span
377        // conversion, so they never reach span meta. `resource_meta` already holds them for the trace's container
378        // tags, so only the resource that span conversion sees drops them. The V1 receive path doesn't consume them.
379        if !receive_v1 {
380            resource
381                .attributes
382                .retain(|attribute| !is_datadog_container_tag_attribute(attribute));
383        }
384
385        // Span conversion maps resource attributes onto every span, so it must see the enriched custom tags too.
386        set_resource_attributes(
387            &mut resource.attributes,
388            std::mem::take(&mut resource_meta.span_attributes),
389        );
390
391        let mut traces_by_id: FastHashMap<u64, TraceEntry> = FastHashMap::default();
392        let trace_count_hint = resource_spans.scope_spans.len();
393        traces_by_id.reserve(trace_count_hint);
394
395        // The sender's SDK identity, from before enrichment could replace those attributes with its own tags.
396        let spans_received = metrics
397            .spans_received()
398            .for_client(&resource_meta.language_name, &resource_meta.tracer_version);
399
400        for scope_spans in resource_spans.scope_spans {
401            let scope = scope_spans.scope;
402            let scope_ref = scope.as_ref();
403            spans_received.increment(scope_spans.spans.len() as u64);
404            for span in scope_spans.spans {
405                let trace_id = convert_trace_id(&span.trace_id);
406                let trace_id_high = convert_trace_id_high(&span.trace_id);
407                let entry = traces_by_id.entry(trace_id).or_insert_with(|| TraceEntry {
408                    spans: Vec::new(),
409                    priority: None,
410                    trace_id_hex: None,
411                    trace_id_high,
412                    dropped: false,
413                    rejected: false,
414                });
415
416                // Once a trace is headed for the drop bin, skip the remaining spans entirely rather
417                // than paying for their conversion only to discard the results at emit time.
418                if entry.dropped {
419                    metrics.spans_dropped_span_id_zero().increment(1);
420                    continue;
421                }
422
423                // Trace ID validity: a trace ID is either empty or exactly 16 bytes, and its
424                // low half must be nonzero. An invalid ID rejects the whole group.
425                if (!span.trace_id.is_empty() && span.trace_id.len() != 16) || trace_id == 0 {
426                    entry.rejected = true;
427                }
428
429                // Full trace ID consistency: spans in a group must carry the same full trace ID
430                // as the group's first span.
431                if entry.trace_id_high != trace_id_high {
432                    entry.rejected = true;
433                }
434
435                if entry.trace_id_hex.is_none() {
436                    entry.trace_id_hex = trace_id_hex_meta(&span.trace_id);
437                }
438
439                let dd_span = if receive_v1 {
440                    otel_span_to_dd_span_v1(
441                        &span,
442                        &resource,
443                        scope_ref,
444                        conversion,
445                        interner,
446                        string_builder,
447                        entry.trace_id_hex.as_ref(),
448                    )
449                } else {
450                    otel_span_to_dd_span(
451                        &span,
452                        &resource,
453                        scope_ref,
454                        conversion,
455                        registry,
456                        interner,
457                        string_builder,
458                        entry.trace_id_hex.as_ref(),
459                    )
460                };
461
462                // Malformed self-parented spans (parent == span == trace ID) get their parent
463                // cleared so root selection treats them as roots.
464                let mut dd_span = if dd_span.parent_id() == trace_id && dd_span.parent_id() == dd_span.span_id() {
465                    dd_span.with_parent_id(0)
466                } else {
467                    dd_span
468                };
469
470                // A zero span ID rejects the whole group; a wrong-length OTLP span ID also
471                // decodes to zero.
472                if dd_span.span_id() == 0 {
473                    entry.rejected = true;
474                }
475
476                // Track last-seen priority for this trace (overwrites previous values)
477                if let Some(priority) = dd_span
478                    .attributes
479                    .get(SAMPLING_PRIORITY_METRIC_KEY)
480                    .and_then(AttributeValue::as_num)
481                {
482                    entry.priority = Some(priority as i32);
483                }
484
485                // A span ID of zero is malformed: drop the span and, like the reference normalizer,
486                // the entire chunk containing it.
487                if dd_span.span_id() == 0 {
488                    if !entry.dropped {
489                        entry.dropped = true;
490                        metrics.traces_dropped_span_id_zero().increment(1);
491                        // Matches the Go trace-agent's separate `SpansDropped += len(chunk)`: count
492                        // every span already accepted into this trace plus the zero-ID span itself.
493                        metrics
494                            .spans_dropped_span_id_zero()
495                            .increment(entry.spans.len() as u64 + 1);
496                        entry.spans.clear();
497                    }
498                    continue;
499                }
500
501                normalize_peer_service_tags(&mut dd_span, registry, interner, string_builder, metrics);
502                entry.spans.push(dd_span);
503            }
504        }
505
506        OtlpTraceEventsIter {
507            ingest_info: TraceIngestInfo::Otlp {
508                receiver_sampling_rate: self.receiver_sampling_rate,
509            },
510            resource_meta,
511            entries: traces_by_id.into_iter(),
512            metrics: metrics.clone(),
513        }
514    }
515}
516
517struct OtlpTraceEventsIter {
518    ingest_info: TraceIngestInfo,
519    resource_meta: OtlpResourceMeta,
520    entries: IntoIter<u64, TraceEntry>,
521    metrics: Metrics,
522}
523
524impl Iterator for OtlpTraceEventsIter {
525    type Item = Event;
526
527    fn next(&mut self) -> Option<Self::Item> {
528        for (trace_id_low, entry) in self.entries.by_ref() {
529            if entry.dropped {
530                continue;
531            }
532
533            if entry.rejected {
534                // Two different traces glued together by a shared low half: drop the group whole.
535                self.metrics
536                    .spans_dropped_foreign_trace()
537                    .increment(entry.spans.len() as u64);
538                continue;
539            }
540
541            if entry.spans.is_empty() {
542                continue;
543            }
544
545            let mut trace = Trace::new(entry.spans, self.ingest_info);
546
547            // Populate unified Trace fields here — after grouping spans by trace ID — because
548            // this is the first point where a complete (spans + resource metadata + priority)
549            // picture is available for a single trace. Resource metadata is shared across all
550            // traces in a ResourceSpans batch, so it lives on the iterator rather than per-entry.
551            trace.trace_id_low = trace_id_low;
552            trace.trace_id_high = entry.trace_id_high;
553            trace.priority = entry.priority;
554            trace.payload.env = self.resource_meta.env.clone();
555            trace.payload.hostname = self.resource_meta.hostname.clone();
556            trace.payload.container_id = self.resource_meta.container_id.clone();
557            trace.payload.app_version = self.resource_meta.app_version.clone();
558            trace.payload.language_name = self.resource_meta.language_name.clone();
559            trace.payload.tracer_version = self.resource_meta.tracer_version.clone();
560            trace.payload.container_tags = self.resource_meta.container_tags.clone();
561            trace.attributes = Arc::clone(&self.resource_meta.attributes);
562
563            return Some(Event::Trace(trace));
564        }
565
566        None
567    }
568}
569
570fn trace_id_hex_meta(trace_id: &[u8]) -> Option<MetaString> {
571    if trace_id.is_empty() {
572        return None;
573    }
574
575    let hex = bytes_to_hex_lowercase(trace_id);
576    if hex.is_empty() {
577        return None;
578    }
579
580    Some(MetaString::from(Arc::<str>::from(hex)))
581}
582
583/// Translates a span with `custom.status_code` and returns its `http.status_code`.
584///
585/// The embedded registry does not map `custom.status_code`; [`custom_status_code_registry`] does.
586#[cfg(test)]
587pub(crate) fn translate_custom_status_code(translator: &mut OtlpTracesTranslator, metrics: &Metrics) -> Option<f64> {
588    use otlp_protos::opentelemetry::proto::trace::v1::{ScopeSpans, Span as OtlpSpan};
589
590    let span = OtlpSpan {
591        trace_id: vec![1; 16],
592        span_id: vec![1; 8],
593        name: "span".to_owned(),
594        end_time_unix_nano: 2,
595        attributes: vec![otlp_common::KeyValue {
596            key: "custom.status_code".to_owned(),
597            value: Some(otlp_common::AnyValue {
598                value: Some(OtlpValue::IntValue(418)),
599            }),
600        }],
601        ..Default::default()
602    };
603    let resource_spans = ResourceSpans {
604        scope_spans: vec![ScopeSpans {
605            spans: vec![span],
606            ..Default::default()
607        }],
608        ..Default::default()
609    };
610    let traces: Vec<Trace> = translator
611        .translate_spans(resource_spans, metrics)
612        .filter_map(Event::try_into_trace)
613        .collect();
614    traces[0].spans()[0]
615        .attributes
616        .get("http.status_code")
617        .and_then(AttributeValue::as_num)
618}
619
620/// Returns a registry document that maps `http.status_code` from `custom.status_code`.
621#[cfg(test)]
622pub(crate) fn custom_status_code_registry() -> String {
623    datadog_agent_apm::semantics::test_util::registry_json(
624        r#"{"http.status_code":{"fallbacks":[{"name":"custom.status_code","provider":"otel","type":"int64"}]}}"#,
625    )
626}
627
628#[cfg(test)]
629mod tests {
630    use std::sync::Arc;
631
632    use datadog_agent_apm::semantics::test_util::{registry_json, TestRegistryPublisher};
633    use otlp_protos::opentelemetry::proto::common::v1::any_value::Value;
634    use otlp_protos::opentelemetry::proto::common::v1::{AnyValue, ArrayValue, KeyValue};
635    use otlp_protos::opentelemetry::proto::resource::v1::Resource;
636    use otlp_protos::opentelemetry::proto::trace::v1::{ResourceSpans, ScopeSpans, Span as OtlpSpan};
637    use saluki_core::components::ComponentContext;
638    use saluki_core::data_model::tags::TagSet;
639    use saluki_env::workload::{providers::TestWorkloadProvider, EntityId};
640    use saluki_metrics::test::TestRecorder;
641
642    use super::*;
643    use crate::common::otlp::origin::OtlpOriginTagResolver;
644    use crate::common::otlp::util::extract_container_tags_from_attributes_map;
645    use crate::common::otlp::{build_metrics, Metrics};
646
647    /// Default maximum resource name length, in bytes.
648    const MAX_RESOURCE_LEN: usize = 5000;
649
650    fn string_kv(key: &str, value: &str) -> KeyValue {
651        KeyValue {
652            key: key.to_string(),
653            value: Some(AnyValue {
654                value: Some(Value::StringValue(value.to_string())),
655            }),
656        }
657    }
658
659    fn int_kv(key: &str, value: i64) -> KeyValue {
660        KeyValue {
661            key: key.to_string(),
662            value: Some(AnyValue {
663                value: Some(Value::IntValue(value)),
664            }),
665        }
666    }
667
668    fn span(trace_id: [u8; 16], span_id: [u8; 8], attributes: Vec<KeyValue>) -> OtlpSpan {
669        span_raw(trace_id.to_vec(), span_id, attributes)
670    }
671
672    fn span_with_parent(
673        trace_id: [u8; 16], span_id: [u8; 8], parent_span_id: [u8; 8], attributes: Vec<KeyValue>,
674    ) -> OtlpSpan {
675        OtlpSpan {
676            trace_id: trace_id.to_vec(),
677            span_id: span_id.to_vec(),
678            parent_span_id: parent_span_id.to_vec(),
679            name: "span".to_string(),
680            end_time_unix_nano: 2,
681            attributes,
682            ..Default::default()
683        }
684    }
685
686    fn span_raw(trace_id: Vec<u8>, span_id: [u8; 8], attributes: Vec<KeyValue>) -> OtlpSpan {
687        OtlpSpan {
688            trace_id,
689            span_id: span_id.to_vec(),
690            name: "span".to_string(),
691            end_time_unix_nano: 2,
692            attributes,
693            ..Default::default()
694        }
695    }
696
697    /// Builds a 16-byte big-endian trace ID from its high and low u64 halves.
698    fn trace_id16(high: u64, low: u64) -> [u8; 16] {
699        let mut id = [0u8; 16];
700        id[..8].copy_from_slice(&high.to_be_bytes());
701        id[8..].copy_from_slice(&low.to_be_bytes());
702        id
703    }
704
705    fn build_resource_spans(resource_attrs: Vec<KeyValue>, spans: Vec<OtlpSpan>) -> ResourceSpans {
706        ResourceSpans {
707            resource: Some(Resource {
708                attributes: resource_attrs,
709                ..Default::default()
710            }),
711            scope_spans: vec![ScopeSpans {
712                spans,
713                ..Default::default()
714            }],
715            ..Default::default()
716        }
717    }
718
719    fn translator_config() -> OtlpTracesSettings {
720        OtlpTracesSettings {
721            string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
722            enable_compute_top_level_by_span_kind: true,
723            ..traces_settings()
724        }
725    }
726
727    fn translate(resource_spans: ResourceSpans) -> Vec<Trace> {
728        let mut translator = OtlpTracesTranslator::new(
729            OtlpTracesSettings {
730                string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
731                enable_compute_top_level_by_span_kind: true,
732                ..traces_settings()
733            },
734            MAX_RESOURCE_LEN,
735            SemanticRegistryProvider::default(),
736            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
737        );
738        let metrics = Metrics::for_tests();
739        translator
740            .translate_spans(resource_spans, &metrics)
741            .filter_map(Event::try_into_trace)
742            .collect()
743    }
744
745    fn translate_with_enrichment(
746        provider: TestWorkloadProvider, promotion: ContainerTagPromotion, enabled: bool, resource_spans: ResourceSpans,
747    ) -> Vec<Trace> {
748        let config = OtlpTracesSettings {
749            infra_attributes_enabled: enabled,
750            container_tag_promotion: promotion,
751            ..translator_config()
752        };
753        let mut translator = OtlpTracesTranslator::new(
754            config,
755            MAX_RESOURCE_LEN,
756            SemanticRegistryProvider::default(),
757            OtlpOriginTagResolver::new(Arc::new(provider)),
758        );
759        let metrics = Metrics::for_tests();
760        translator
761            .translate_spans(resource_spans, &metrics)
762            .filter_map(Event::try_into_trace)
763            .collect()
764    }
765
766    /// Returns the string value of a trace attribute, or `None` when the key is absent or non-string.
767    fn attr(trace: &Trace, key: &str) -> Option<String> {
768        trace
769            .attributes
770            .get(key)
771            .and_then(|value| value.as_string())
772            .map(|value| value.as_ref().to_string())
773    }
774
775    #[test]
776    fn translate_spans_selects_the_conversion_from_the_settings() {
777        use otlp_protos::opentelemetry::proto::common::v1::InstrumentationScope;
778        use otlp_protos::opentelemetry::proto::trace::v1::span::SpanKind;
779
780        let translate_span = |settings: OtlpTracesSettings| {
781            let mut client_span = span([1; 16], [2; 8], vec![string_kv("db.system", "redis")]);
782            client_span.kind = SpanKind::Client as i32;
783            let resource_spans = ResourceSpans {
784                resource: Some(Resource::default()),
785                scope_spans: vec![ScopeSpans {
786                    scope: Some(InstrumentationScope {
787                        name: "lib".to_string(),
788                        ..Default::default()
789                    }),
790                    spans: vec![client_span],
791                    ..Default::default()
792                }],
793                ..Default::default()
794            };
795            let mut translator = OtlpTracesTranslator::new(
796                settings,
797                MAX_RESOURCE_LEN,
798                SemanticRegistryProvider::default(),
799                OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
800            );
801            let mut traces: Vec<Trace> = translator
802                .translate_spans(resource_spans, &Metrics::for_tests())
803                .filter_map(Event::try_into_trace)
804                .collect();
805            assert_eq!(traces.len(), 1);
806            traces.remove(0).spans().first().cloned().expect("one span")
807        };
808        let scope_name = |span: &DdSpan| span.attributes.get("otel.scope.name").cloned();
809
810        let default = translate_span(translator_config());
811        assert_eq!(default.span_type(), "redis");
812        assert_eq!(default.name(), "redis.query");
813        assert!(scope_name(&default).is_some());
814
815        let v1_receive = translate_span(OtlpTracesSettings {
816            disable_receive_resource_spans_v2: true,
817            ..translator_config()
818        });
819        assert_eq!(v1_receive.span_type(), "cache");
820        assert_eq!(scope_name(&v1_receive), None);
821
822        let no_scope_convention = translate_span(OtlpTracesSettings {
823            disable_otel_scope_convention: true,
824            ..translator_config()
825        });
826        assert_eq!(no_scope_convention.span_type(), "redis");
827        assert_eq!(scope_name(&no_scope_convention), None);
828
829        let v1_naming = translate_span(OtlpTracesSettings {
830            disable_operation_and_resource_name_logic_v2: true,
831            ..translator_config()
832        });
833        assert_eq!(v1_naming.name(), "lib.client");
834
835        let remapped = translate_span(OtlpTracesSettings {
836            span_name_remappings: HashMap::from([("lib.client".to_string(), "renamed".to_string())]),
837            ..translator_config()
838        });
839        assert_eq!(remapped.name(), "renamed");
840    }
841
842    #[test]
843    fn translate_spans_uses_registry_published_after_construction() {
844        let (publisher, provider) = TestRegistryPublisher::new();
845        let mut translator = OtlpTracesTranslator::new(
846            OtlpTracesSettings {
847                string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
848                ..traces_settings()
849            },
850            MAX_RESOURCE_LEN,
851            provider,
852            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
853        );
854        let metrics = Metrics::for_tests();
855        let mut http_status_code = || {
856            let rs = build_resource_spans(
857                vec![],
858                vec![span([1u8; 16], [1u8; 8], vec![int_kv("custom.status_code", 418)])],
859            );
860            let traces: Vec<Trace> = translator
861                .translate_spans(rs, &metrics)
862                .filter_map(Event::try_into_trace)
863                .collect();
864            traces[0].spans()[0]
865                .attributes
866                .get("http.status_code")
867                .and_then(AttributeValue::as_num)
868        };
869
870        assert_eq!(
871            http_status_code(),
872            None,
873            "the embedded registry does not map `custom.status_code`"
874        );
875
876        let remapped = registry_json(
877            r#"{
878                "http.status_code": {
879                    "fallbacks": [{"name": "custom.status_code", "provider": "otel", "type": "int64"}]
880                }
881            }"#,
882        );
883        publisher.accept_registry(
884            Registry::from_json(&remapped).expect("remapped registry should parse"),
885            "remapped",
886        );
887
888        assert_eq!(
889            http_status_code(),
890            Some(418.0),
891            "the next batch must resolve with the published registry"
892        );
893    }
894
895    #[test]
896    fn translate_spans_resolves_peer_service_with_registry_published_after_construction() {
897        let (publisher, provider) = TestRegistryPublisher::new();
898        let mut translator = OtlpTracesTranslator::new(
899            OtlpTracesSettings {
900                string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
901                ..traces_settings()
902            },
903            MAX_RESOURCE_LEN,
904            provider,
905            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
906        );
907        let metrics = Metrics::for_tests();
908        let mut peer_service = || {
909            let rs = build_resource_spans(
910                vec![],
911                vec![span([1u8; 16], [1u8; 8], vec![string_kv("custom.peer", "Checkouts")])],
912            );
913            let traces: Vec<Trace> = translator
914                .translate_spans(rs, &metrics)
915                .filter_map(Event::try_into_trace)
916                .collect();
917            traces[0].spans()[0]
918                .attributes
919                .get("peer.service")
920                .and_then(AttributeValue::as_string)
921                .map(|value| value.to_string())
922        };
923
924        assert_eq!(peer_service(), None, "the embedded registry does not map `custom.peer`");
925
926        let remapped = registry_json(
927            r#"{"peer.service": {"fallbacks": [{"name": "custom.peer", "provider": "otel", "type": "string"}]}}"#,
928        );
929        publisher.accept_registry(
930            Registry::from_json(&remapped).expect("remapped registry should parse"),
931            "remapped",
932        );
933
934        assert_eq!(
935            peer_service().as_deref(),
936            Some("checkouts"),
937            "the next batch must normalize `peer.service` with the published registry"
938        );
939    }
940
941    /// Ported from `OTLPReceiver.samplingRate` in the Go trace agent, except that NaN normalizes to `1.0` rather
942    /// than propagating:
943    /// https://github.com/DataDog/datadog-agent/blob/c6f7e0bc2d5744601a10f231751948ac7a4ee781/pkg/trace/api/otlp.go#L249-L258
944    #[test]
945    fn translate_spans_stamps_normalized_receiver_sampling_rate_on_every_trace() {
946        let cases = [
947            (50.0, 0.5),
948            (12.5, 0.125),
949            (100.0, 1.0),
950            (150.0, 1.0),
951            (0.0, 1.0),
952            (-10.0, 1.0),
953            (f64::NAN, 1.0),
954            (f64::INFINITY, 1.0),
955            (f64::NEG_INFINITY, 1.0),
956        ];
957        for (percentage, expected) in cases {
958            let mut translator = OtlpTracesTranslator::new(
959                OtlpTracesSettings {
960                    probabilistic_sampler_sampling_percentage: percentage,
961                    string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
962                    ..traces_settings()
963                },
964                MAX_RESOURCE_LEN,
965                SemanticRegistryProvider::default(),
966                OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
967            );
968            let rs = build_resource_spans(
969                vec![],
970                vec![span([0xAA; 16], [1u8; 8], vec![]), span([0xBB; 16], [2u8; 8], vec![])],
971            );
972            let traces: Vec<Trace> = translator
973                .translate_spans(rs, &Metrics::for_tests())
974                .filter_map(Event::try_into_trace)
975                .collect();
976
977            assert_eq!(traces.len(), 2);
978            for trace in &traces {
979                assert_eq!(
980                    trace.ingest_info(),
981                    TraceIngestInfo::Otlp {
982                        receiver_sampling_rate: expected
983                    },
984                    "sampling percentage {percentage}"
985                );
986            }
987        }
988    }
989
990    fn translate_hostname(settings: OtlpTracesSettings, resource_attrs: Vec<KeyValue>) -> String {
991        let mut translator = OtlpTracesTranslator::new(
992            settings,
993            MAX_RESOURCE_LEN,
994            SemanticRegistryProvider::default(),
995            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
996        )
997        .with_default_hostname(MetaString::from("agent-host"));
998        let rs = build_resource_spans(resource_attrs, vec![span([1u8; 16], [1u8; 8], vec![])]);
999        let traces: Vec<Trace> = translator
1000            .translate_spans(rs, &Metrics::for_tests())
1001            .filter_map(Event::try_into_trace)
1002            .collect();
1003        assert_eq!(traces.len(), 1);
1004        traces[0].payload.hostname.to_string()
1005    }
1006
1007    #[test]
1008    fn translate_spans_resolves_hostname_from_datadog_host_name() {
1009        let hostname = translate_hostname(traces_settings(), vec![string_kv("datadog.host.name", "my-host")]);
1010        assert_eq!(hostname, "my-host");
1011    }
1012
1013    #[test]
1014    fn translate_spans_resolves_hostname_with_the_agent_cascade() {
1015        // `datadog.host.name` outranks every cloud and host attribute.
1016        let hostname = translate_hostname(
1017            traces_settings(),
1018            vec![
1019                string_kv("datadog.host.name", "custom"),
1020                string_kv("host.name", "other"),
1021            ],
1022        );
1023        assert_eq!(hostname, "custom");
1024
1025        // Cloud provider attributes take the provider-specific form.
1026        let hostname = translate_hostname(
1027            traces_settings(),
1028            vec![
1029                string_kv("cloud.provider", "gcp"),
1030                string_kv("cloud.account.id", "project"),
1031                string_kv("host.name", "vm.internal"),
1032            ],
1033        );
1034        assert_eq!(hostname, "vm.internal.project");
1035
1036        // Kubernetes node names come before `host.id` and `host.name`.
1037        let hostname = translate_hostname(
1038            traces_settings(),
1039            vec![
1040                string_kv("k8s.node.name", "node-1"),
1041                string_kv("host.id", "i-1"),
1042                string_kv("host.name", "other"),
1043            ],
1044        );
1045        assert_eq!(hostname, "node-1");
1046
1047        let hostname = translate_hostname(traces_settings(), vec![string_kv("host.name", "my-host")]);
1048        assert_eq!(hostname, "my-host");
1049    }
1050
1051    #[test]
1052    fn translate_spans_falls_back_to_the_default_hostname_without_a_source() {
1053        assert_eq!(translate_hostname(traces_settings(), vec![]), "agent-host");
1054        // Loopback names are not valid hostnames.
1055        let hostname = translate_hostname(traces_settings(), vec![string_kv("host.name", "localhost")]);
1056        assert_eq!(hostname, "agent-host");
1057    }
1058
1059    #[test]
1060    fn translate_spans_leaves_hostname_empty_for_serverless_sources() {
1061        let lambda = vec![
1062            string_kv("cloud.provider", "aws"),
1063            string_kv("cloud.platform", "aws_lambda"),
1064            string_kv("faas.id", "arn:aws:lambda:us-east-1:123456789012:function:orders"),
1065            string_kv("host.name", "ip-10-0-0-1"),
1066        ];
1067        assert_eq!(translate_hostname(traces_settings(), lambda), "");
1068
1069        let fargate = vec![
1070            string_kv("aws.ecs.launchtype", "fargate"),
1071            string_kv("aws.ecs.task.arn", "arn:task"),
1072            string_kv("host.name", "ignored"),
1073        ];
1074        assert_eq!(translate_hostname(traces_settings(), fargate), "");
1075    }
1076
1077    #[test]
1078    fn translate_spans_honors_only_datadog_host_name_when_ignoring_missing_fields() {
1079        let settings = OtlpTracesSettings {
1080            ignore_missing_datadog_fields: true,
1081            ..traces_settings()
1082        };
1083        assert_eq!(
1084            translate_hostname(settings.clone(), vec![string_kv("host.name", "ignored")]),
1085            ""
1086        );
1087        assert_eq!(translate_hostname(settings.clone(), vec![]), "");
1088        assert_eq!(
1089            translate_hostname(settings, vec![string_kv("datadog.host.name", "my-host")]),
1090            "my-host"
1091        );
1092    }
1093
1094    #[test]
1095    fn translate_spans_groups_spans_by_trace_id() {
1096        let trace_a = [0xAAu8; 16];
1097        let trace_b = [0xBBu8; 16];
1098        let rs = build_resource_spans(
1099            vec![],
1100            vec![
1101                span(trace_a, [1u8; 8], vec![]),
1102                span(trace_a, [2u8; 8], vec![]),
1103                span(trace_b, [3u8; 8], vec![]),
1104            ],
1105        );
1106
1107        let mut traces = translate(rs);
1108        assert_eq!(traces.len(), 2, "expected one trace per distinct trace ID");
1109
1110        traces.sort_by_key(|t| t.spans().len());
1111        assert_eq!(traces[0].spans().len(), 1);
1112
1113        let grouped = &traces[1];
1114        assert_eq!(grouped.spans().len(), 2, "spans sharing a trace ID group together");
1115        // Trace ID low/high bytes are captured from the 16-byte OTLP trace ID.
1116        assert_eq!(grouped.trace_id_low, u64::from_be_bytes([0xAA; 8]));
1117        assert_eq!(grouped.trace_id_high, u64::from_be_bytes([0xAA; 8]));
1118    }
1119
1120    #[test]
1121    fn translate_spans_tracks_last_seen_sampling_priority() {
1122        let trace = [0xCCu8; 16];
1123        let rs = build_resource_spans(
1124            vec![],
1125            vec![
1126                span(trace, [1u8; 8], vec![int_kv("sampling.priority", 1)]),
1127                span(trace, [2u8; 8], vec![int_kv("sampling.priority", 2)]),
1128            ],
1129        );
1130
1131        let traces = translate(rs);
1132        assert_eq!(traces.len(), 1);
1133        assert_eq!(traces[0].priority, Some(2), "the last span's sampling priority wins");
1134    }
1135
1136    #[test]
1137    fn translate_spans_populates_resource_metadata() {
1138        let rs = build_resource_spans(
1139            vec![
1140                string_kv("deployment.environment", "prod"),
1141                string_kv("service.version", "1.2.3"),
1142                string_kv("container.id", "abc123"),
1143                string_kv("telemetry.sdk.language", "go"),
1144                string_kv("telemetry.sdk.version", "1.0"),
1145            ],
1146            vec![span([1u8; 16], [1u8; 8], vec![])],
1147        );
1148
1149        let traces = translate(rs);
1150        assert_eq!(traces.len(), 1);
1151        let payload = &traces[0].payload;
1152        assert_eq!(payload.env.as_ref(), "prod");
1153        assert_eq!(payload.app_version.as_ref(), "1.2.3");
1154        assert_eq!(payload.container_id.as_ref(), "abc123");
1155        assert_eq!(payload.language_name.as_ref(), "go");
1156        assert_eq!(payload.tracer_version.as_ref(), "1.0");
1157    }
1158
1159    fn array_kv(key: &str, values: Vec<Value>) -> KeyValue {
1160        KeyValue {
1161            key: key.to_string(),
1162            value: Some(AnyValue {
1163                value: Some(Value::ArrayValue(ArrayValue {
1164                    values: values
1165                        .into_iter()
1166                        .map(|value| AnyValue { value: Some(value) })
1167                        .collect(),
1168                })),
1169            }),
1170        }
1171    }
1172
1173    fn string_array_kv(key: &str, values: &[&str]) -> KeyValue {
1174        array_kv(
1175            key,
1176            values
1177                .iter()
1178                .map(|value| Value::StringValue((*value).to_string()))
1179                .collect(),
1180        )
1181    }
1182
1183    /// Returns the container tags of the only trace translated from a resource with `attributes`, sorted.
1184    fn container_tags(attributes: Vec<KeyValue>) -> Vec<String> {
1185        let rs = build_resource_spans(attributes, vec![span([1u8; 16], [1u8; 8], vec![])]);
1186        let traces = translate(rs);
1187        assert_eq!(traces.len(), 1);
1188        let mut tags: Vec<String> = traces[0]
1189            .payload
1190            .resolved_container_tags()
1191            .iter()
1192            .map(|tag| tag.as_ref().to_string())
1193            .collect();
1194        tags.sort();
1195        tags
1196    }
1197
1198    #[test]
1199    fn translate_spans_maps_container_image_tags_to_the_image_tag_container_tag() {
1200        let tags = container_tags(vec![
1201            string_array_kv("container.image.tags", &["v1", "latest"]),
1202            string_kv("container.name", "web"),
1203        ]);
1204        assert_eq!(tags, vec!["container_name:web", "image_tag:v1"]);
1205    }
1206
1207    #[test]
1208    fn translate_spans_resolves_the_image_tag_like_the_reference() {
1209        let image_tags = |values: &[&str]| string_array_kv("container.image.tags", values);
1210        let custom = || string_kv("datadog.container.tag.image_tag", "custom");
1211        let pre_mapped = || string_kv("image_tag", "pre-mapped");
1212        let old = || string_kv("container.image.tag", "old");
1213
1214        // (resource attributes in order, expected `image_tag` value)
1215        let cases: Vec<(&str, Vec<KeyValue>, Option<&str>)> = vec![
1216            (
1217                "first of several elements",
1218                vec![image_tags(&["v1", "latest"])],
1219                Some("v1"),
1220            ),
1221            (
1222                "scalar string",
1223                vec![string_kv("container.image.tags", "v1")],
1224                Some("v1"),
1225            ),
1226            ("empty array", vec![image_tags(&[])], None),
1227            ("empty scalar", vec![string_kv("container.image.tags", "")], None),
1228            (
1229                "empty first element is not skipped",
1230                vec![image_tags(&["", "latest"])],
1231                None,
1232            ),
1233            (
1234                "non-string first element is not skipped",
1235                vec![array_kv(
1236                    "container.image.tags",
1237                    vec![Value::IntValue(1), Value::StringValue("latest".to_string())],
1238                )],
1239                None,
1240            ),
1241            (
1242                "older tag first wins over later tags",
1243                vec![old(), image_tags(&["new"])],
1244                Some("old"),
1245            ),
1246            (
1247                "tags first wins over later older tag",
1248                vec![image_tags(&["new"]), old()],
1249                Some("new"),
1250            ),
1251            (
1252                "tags beat custom, custom first",
1253                vec![custom(), image_tags(&["v1"])],
1254                Some("v1"),
1255            ),
1256            (
1257                "tags beat custom, tags first",
1258                vec![image_tags(&["v1"]), custom()],
1259                Some("v1"),
1260            ),
1261            (
1262                "tags beat pre-mapped, pre-mapped first",
1263                vec![pre_mapped(), image_tags(&["v1"])],
1264                Some("v1"),
1265            ),
1266            (
1267                "tags beat pre-mapped, tags first",
1268                vec![image_tags(&["v1"]), pre_mapped()],
1269                Some("v1"),
1270            ),
1271            ("custom beats pre-mapped", vec![pre_mapped(), custom()], Some("custom")),
1272            (
1273                "invalid tags leave the pre-mapped tag",
1274                vec![image_tags(&[""]), pre_mapped()],
1275                Some("pre-mapped"),
1276            ),
1277            (
1278                "invalid tags leave the custom tag",
1279                vec![image_tags(&[]), custom()],
1280                Some("custom"),
1281            ),
1282            (
1283                "invalid tags leave a later older tag",
1284                vec![image_tags(&[""]), old()],
1285                Some("old"),
1286            ),
1287        ];
1288
1289        for (name, attributes, expected) in cases {
1290            let image_tag = container_tags(attributes)
1291                .into_iter()
1292                .find_map(|tag| tag.strip_prefix("image_tag:").map(str::to_string));
1293            assert_eq!(image_tag.as_deref(), expected, "{name}");
1294        }
1295    }
1296
1297    #[test]
1298    fn translate_spans_keeps_container_image_tags_on_spans_and_in_trace_attributes() {
1299        let rs = build_resource_spans(
1300            vec![string_array_kv("container.image.tags", &["v1", "latest"])],
1301            vec![span([1u8; 16], [1u8; 8], vec![])],
1302        );
1303
1304        let traces = translate(rs);
1305        assert_eq!(traces.len(), 1);
1306
1307        // Selecting the first element for the container tag doesn't rewrite the attribute itself.
1308        let span_value = span_attr(&traces[0], "container.image.tags").expect("the span keeps the attribute");
1309        assert!(
1310            span_value.contains("v1") && span_value.contains("latest"),
1311            "got {span_value}"
1312        );
1313        let trace_value = attr(&traces[0], "container.image.tags").expect("the trace keeps the attribute");
1314        assert!(
1315            trace_value.contains("v1") && trace_value.contains("latest"),
1316            "got {trace_value}"
1317        );
1318    }
1319
1320    #[test]
1321    fn translate_spans_keeps_the_enriched_value_of_an_overwritten_convention_tag() {
1322        // A workload tag can take the name of a semantic-convention key, replacing the sender's value in the typed
1323        // attributes. The resolved container tags must keep the enriched value, so they can't disagree with
1324        // `Trace::attributes`.
1325        let provider = TestWorkloadProvider::with_entity(
1326            EntityId::Container(MetaString::from("abc123")),
1327            &["cloud.region:enriched"],
1328        );
1329        let rs = build_resource_spans(
1330            vec![
1331                string_kv("container.id", "abc123"),
1332                string_kv("cloud.region", "sender-r"),
1333            ],
1334            vec![span([1u8; 16], [1u8; 8], vec![])],
1335        );
1336
1337        let traces = translate_with_enrichment(provider, ContainerTagPromotion::Off, true, rs);
1338        assert_eq!(traces.len(), 1);
1339
1340        assert_eq!(attr(&traces[0], "cloud.region").as_deref(), Some("enriched"));
1341        let tags: Vec<&str> = traces[0]
1342            .payload
1343            .resolved_container_tags()
1344            .iter()
1345            .map(AsRef::as_ref)
1346            .collect();
1347        assert!(tags.contains(&"region:enriched"), "got {tags:?}");
1348        assert!(
1349            !tags.iter().any(|tag| tag.starts_with("region:sender-r")),
1350            "got {tags:?}"
1351        );
1352    }
1353
1354    #[test]
1355    fn translate_spans_keeps_an_enriched_image_tag_at_its_attribute_position() {
1356        // Enrichment replaces the value of `container.image.tag`, not its place among the sender's attributes, so
1357        // the first valid image tag still wins in attribute order.
1358        let enrich_image_tag = || {
1359            TestWorkloadProvider::with_entity(
1360                EntityId::Container(MetaString::from("abc123")),
1361                &["container.image.tag:enriched"],
1362            )
1363        };
1364        let image_tag_of = |attributes: Vec<KeyValue>| {
1365            let rs = build_resource_spans(attributes, vec![span([1u8; 16], [1u8; 8], vec![])]);
1366            let traces = translate_with_enrichment(enrich_image_tag(), ContainerTagPromotion::Off, true, rs);
1367            assert_eq!(traces.len(), 1);
1368            traces[0]
1369                .payload
1370                .resolved_container_tags()
1371                .iter()
1372                .find_map(|tag| tag.as_ref().strip_prefix("image_tag:").map(str::to_string))
1373        };
1374        let container = || string_kv("container.id", "abc123");
1375
1376        // The enriched tag took the place of the sender's, which came before the array.
1377        assert_eq!(
1378            image_tag_of(vec![
1379                container(),
1380                string_kv("container.image.tag", "sender"),
1381                string_array_kv("container.image.tags", &["later"]),
1382            ])
1383            .as_deref(),
1384            Some("enriched")
1385        );
1386        // The array came first, so it still wins.
1387        assert_eq!(
1388            image_tag_of(vec![
1389                container(),
1390                string_array_kv("container.image.tags", &["first"]),
1391                string_kv("container.image.tag", "sender"),
1392            ])
1393            .as_deref(),
1394            Some("first")
1395        );
1396    }
1397
1398    #[test]
1399    fn translate_spans_keeps_an_enriched_replacement_of_the_image_tags_array() {
1400        // With promotion Off or Duplicate, a workload tag named `container.image.tags` replaces the sender's
1401        // array in the typed attributes and on spans. The replacement is a scalar string, so it must win over the
1402        // sender's first element and agree with `Trace::attributes`.
1403        let provider = TestWorkloadProvider::with_entity(
1404            EntityId::Container(MetaString::from("abc123")),
1405            &["container.image.tags:enriched"],
1406        );
1407        let rs = build_resource_spans(
1408            vec![
1409                string_kv("container.id", "abc123"),
1410                string_array_kv("container.image.tags", &["sender", "latest"]),
1411            ],
1412            vec![span([1u8; 16], [1u8; 8], vec![])],
1413        );
1414
1415        let traces = translate_with_enrichment(provider, ContainerTagPromotion::Off, true, rs);
1416        assert_eq!(traces.len(), 1);
1417        // The typed attributes hold the replacement, not the stringified array.
1418        assert_eq!(attr(&traces[0], "container.image.tags").as_deref(), Some("enriched"));
1419        let tags: Vec<&str> = traces[0]
1420            .payload
1421            .resolved_container_tags()
1422            .iter()
1423            .map(AsRef::as_ref)
1424            .collect();
1425        assert!(tags.contains(&"image_tag:enriched"), "got {tags:?}");
1426        assert!(
1427            !tags.iter().any(|tag| tag.starts_with("image_tag:sender")),
1428            "got {tags:?}"
1429        );
1430    }
1431
1432    /// Returns a provider holding one convention tag and one custom tag for the given container.
1433    fn provider_for_container() -> TestWorkloadProvider {
1434        TestWorkloadProvider::with_entity(
1435            EntityId::Container(MetaString::from("abc123")),
1436            &["kube_namespace:payments", "team:checkout"],
1437        )
1438    }
1439
1440    /// Returns the string value of the first span's attribute, or `None` when the key is absent or non-string.
1441    fn span_attr(trace: &Trace, key: &str) -> Option<String> {
1442        trace.spans()[0]
1443            .attributes
1444            .get(key)
1445            .and_then(|value| value.as_string())
1446            .map(|value| value.as_ref().to_string())
1447    }
1448
1449    #[test]
1450    fn translate_spans_enriches_resource_attributes_with_workload_tags() {
1451        let rs = build_resource_spans(
1452            vec![string_kv("container.id", "abc123")],
1453            vec![span([1u8; 16], [1u8; 8], vec![])],
1454        );
1455
1456        let traces = translate_with_enrichment(provider_for_container(), ContainerTagPromotion::Off, true, rs);
1457        assert_eq!(traces.len(), 1);
1458        assert_eq!(attr(&traces[0], "kube_namespace").as_deref(), Some("payments"));
1459        assert_eq!(attr(&traces[0], "team").as_deref(), Some("checkout"));
1460
1461        // The custom tag stays a plain resource attribute, so span conversion maps it onto the span. The recognized
1462        // convention key is consumed as a container tag and must not be duplicated onto spans.
1463        assert_eq!(span_attr(&traces[0], "team").as_deref(), Some("checkout"));
1464        assert_eq!(span_attr(&traces[0], "kube_namespace"), None);
1465
1466        // The enriched convention tag is a container tag, and the plain custom tag is not.
1467        let tags: Vec<&str> = traces[0]
1468            .payload
1469            .resolved_container_tags()
1470            .iter()
1471            .map(AsRef::as_ref)
1472            .collect();
1473        assert!(tags.contains(&"kube_namespace:payments"), "got {tags:?}");
1474        assert!(!tags.iter().any(|tag| tag.starts_with("team:")), "got {tags:?}");
1475    }
1476
1477    /// Resource attributes holding the same container identity under Datadog and OTel convention keys.
1478    fn container_convention_resource_attributes() -> Vec<KeyValue> {
1479        vec![
1480            string_kv("kube_namespace", "payments"),
1481            string_kv("pod_name", "web-1"),
1482            string_kv("container_id", "abc123"),
1483            string_kv("container.id", "abc123"),
1484            string_kv("k8s.namespace.name", "payments"),
1485        ]
1486    }
1487
1488    fn translate_with_settings(settings: OtlpTracesSettings, resource_spans: ResourceSpans) -> Vec<Trace> {
1489        let mut translator = OtlpTracesTranslator::new(
1490            settings,
1491            MAX_RESOURCE_LEN,
1492            SemanticRegistryProvider::default(),
1493            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
1494        );
1495        translator
1496            .translate_spans(resource_spans, &Metrics::for_tests())
1497            .filter_map(Event::try_into_trace)
1498            .collect()
1499    }
1500
1501    #[test]
1502    fn translate_spans_consumes_datadog_convention_container_keys_before_span_conversion() {
1503        let mut resource_attributes = container_convention_resource_attributes();
1504        // Generic-looking names are Datadog-convention keys too, so a string value is consumed like any other.
1505        resource_attributes.push(string_kv("region", "us-east-1"));
1506        resource_attributes.push(string_kv("zone", "us-east-1a"));
1507        // Only non-empty string values are consumed as container tags.
1508        resource_attributes.push(int_kv("cloud_provider", 7));
1509        resource_attributes.push(string_kv("kube_node", ""));
1510        let rs = build_resource_spans(resource_attributes, vec![span([1u8; 16], [1u8; 8], vec![])]);
1511
1512        let traces = translate(rs);
1513        assert_eq!(traces.len(), 1);
1514
1515        // Datadog convention keys stay out of span meta, while OTel convention keys still reach it.
1516        assert_eq!(span_attr(&traces[0], "kube_namespace"), None);
1517        assert_eq!(span_attr(&traces[0], "pod_name"), None);
1518        assert_eq!(span_attr(&traces[0], "container_id"), None);
1519        assert_eq!(span_attr(&traces[0], "container.id").as_deref(), Some("abc123"));
1520        assert_eq!(span_attr(&traces[0], "k8s.namespace.name").as_deref(), Some("payments"));
1521        assert_eq!(span_attr(&traces[0], "region"), None);
1522        assert_eq!(span_attr(&traces[0], "zone"), None);
1523        assert_eq!(span_attr(&traces[0], "cloud_provider").as_deref(), Some("7"));
1524        assert_eq!(span_attr(&traces[0], "kube_node").as_deref(), Some(""));
1525
1526        // The trace's own attributes keep them, so the encoder still emits them as container tags.
1527        assert_eq!(attr(&traces[0], "kube_namespace").as_deref(), Some("payments"));
1528        assert_eq!(attr(&traces[0], "pod_name").as_deref(), Some("web-1"));
1529        assert_eq!(attr(&traces[0], "container_id").as_deref(), Some("abc123"));
1530        let mut tags = TagSet::default();
1531        extract_container_tags_from_attributes_map(&traces[0].attributes, &mut tags);
1532        let tags: Vec<_> = tags.into_iter().map(|tag| tag.as_str().to_string()).collect();
1533        assert!(tags.contains(&"kube_namespace:payments".to_string()), "got {tags:?}");
1534        assert!(tags.contains(&"pod_name:web-1".to_string()), "got {tags:?}");
1535    }
1536
1537    #[test]
1538    fn translate_spans_leaves_container_keys_on_spans_on_the_v1_receive_path() {
1539        let rs = build_resource_spans(
1540            container_convention_resource_attributes(),
1541            vec![span([1u8; 16], [1u8; 8], vec![])],
1542        );
1543
1544        let traces = translate_with_settings(
1545            OtlpTracesSettings {
1546                disable_receive_resource_spans_v2: true,
1547                ..translator_config()
1548            },
1549            rs,
1550        );
1551        assert_eq!(traces.len(), 1);
1552        assert_eq!(span_attr(&traces[0], "kube_namespace").as_deref(), Some("payments"));
1553        assert_eq!(span_attr(&traces[0], "pod_name").as_deref(), Some("web-1"));
1554        assert_eq!(span_attr(&traces[0], "container_id").as_deref(), Some("abc123"));
1555    }
1556
1557    #[test]
1558    fn translate_spans_applies_duplicate_promotion_to_custom_tags() {
1559        let rs = build_resource_spans(
1560            vec![string_kv("container.id", "abc123")],
1561            vec![span([1u8; 16], [1u8; 8], vec![])],
1562        );
1563
1564        let traces = translate_with_enrichment(provider_for_container(), ContainerTagPromotion::Duplicate, true, rs);
1565        assert_eq!(traces.len(), 1);
1566
1567        assert_eq!(attr(&traces[0], "kube_namespace").as_deref(), Some("payments"));
1568        assert!(traces[0]
1569            .attributes
1570            .get("datadog.container.tag.kube_namespace")
1571            .is_none());
1572
1573        assert_eq!(attr(&traces[0], "team").as_deref(), Some("checkout"));
1574        assert_eq!(
1575            attr(&traces[0], "datadog.container.tag.team").as_deref(),
1576            Some("checkout")
1577        );
1578
1579        // The unprefixed form reaches span meta; the prefixed copy is consumed as a container tag.
1580        let tags: Vec<&str> = traces[0]
1581            .payload
1582            .resolved_container_tags()
1583            .iter()
1584            .map(AsRef::as_ref)
1585            .collect();
1586        assert!(tags.contains(&"team:checkout"), "got {tags:?}");
1587        assert_eq!(span_attr(&traces[0], "team").as_deref(), Some("checkout"));
1588        assert_eq!(span_attr(&traces[0], "datadog.container.tag.team"), None);
1589    }
1590
1591    #[test]
1592    fn translate_spans_applies_rename_promotion_to_custom_tags() {
1593        let rs = build_resource_spans(
1594            vec![string_kv("container.id", "abc123")],
1595            vec![span([1u8; 16], [1u8; 8], vec![])],
1596        );
1597
1598        let traces = translate_with_enrichment(provider_for_container(), ContainerTagPromotion::Rename, true, rs);
1599        assert_eq!(traces.len(), 1);
1600
1601        assert_eq!(attr(&traces[0], "kube_namespace").as_deref(), Some("payments"));
1602        assert_eq!(
1603            attr(&traces[0], "datadog.container.tag.team").as_deref(),
1604            Some("checkout")
1605        );
1606        assert!(traces[0].attributes.get("team").is_none());
1607
1608        // Only the prefixed form exists, and it is consumed as a container tag, so nothing reaches span meta.
1609        assert_eq!(span_attr(&traces[0], "team"), None);
1610        assert_eq!(span_attr(&traces[0], "datadog.container.tag.team"), None);
1611    }
1612
1613    #[test]
1614    fn translate_spans_preserves_sender_provided_prefixed_attributes() {
1615        let rs = build_resource_spans(
1616            vec![
1617                string_kv("container.id", "abc123"),
1618                string_kv("datadog.container.tag.env", "prod"),
1619            ],
1620            vec![span([1u8; 16], [1u8; 8], vec![])],
1621        );
1622
1623        let traces = translate_with_enrichment(provider_for_container(), ContainerTagPromotion::Duplicate, true, rs);
1624        assert_eq!(traces.len(), 1);
1625
1626        assert_eq!(attr(&traces[0], "datadog.container.tag.env").as_deref(), Some("prod"));
1627    }
1628
1629    #[test]
1630    fn translate_spans_skips_enrichment_when_disabled() {
1631        let rs = build_resource_spans(
1632            vec![string_kv("container.id", "abc123")],
1633            vec![span([1u8; 16], [1u8; 8], vec![])],
1634        );
1635
1636        let traces = translate_with_enrichment(provider_for_container(), ContainerTagPromotion::Duplicate, false, rs);
1637        assert_eq!(traces.len(), 1);
1638
1639        assert!(traces[0].attributes.get("kube_namespace").is_none());
1640        assert!(traces[0].attributes.get("team").is_none());
1641        assert!(traces[0].attributes.get("datadog.container.tag.team").is_none());
1642    }
1643
1644    /// A span whose span ID converts to zero is dropped along with the trace containing it, mirroring
1645    /// `normalizeV1` (`pkg/trace/agent/normalizer.go`). https://github.com/DataDog/saluki/issues/2382
1646    #[test]
1647    fn translate_spans_drops_trace_containing_zero_span_id() {
1648        let recorder = TestRecorder::default();
1649        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1650
1651        let mut translator = OtlpTracesTranslator::new(
1652            OtlpTracesSettings {
1653                string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
1654                ..traces_settings()
1655            },
1656            5000,
1657            SemanticRegistryProvider::default(),
1658            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
1659        );
1660        let metrics = build_metrics(&ComponentContext::test_source("otlp_test"));
1661
1662        let trace = [0xDDu8; 16];
1663        let rs = build_resource_spans(
1664            vec![],
1665            vec![
1666                span(trace, [1u8; 8], vec![]),
1667                span(trace, [0u8; 8], vec![]), // zero span ID drops the whole trace
1668                span(trace, [2u8; 8], vec![]),
1669            ],
1670        );
1671
1672        let traces: Vec<Trace> = translator
1673            .translate_spans(rs, &metrics)
1674            .filter_map(Event::try_into_trace)
1675            .collect();
1676        assert!(
1677            traces.is_empty(),
1678            "the trace containing the zero-ID span must be dropped"
1679        );
1680
1681        // Exactly one trace-level drop is counted, but all three spans in that trace are counted at
1682        // the span level, mirroring the Go trace-agent's separate `TracesDropped`/`SpansDropped`
1683        // counters.
1684        let trace_tags: &[(&str, &str)] = &[
1685            ("component_id", "otlp_test"),
1686            ("component_type", "source"),
1687            ("intentional", "true"),
1688            ("drop_reason", "span_id_zero"),
1689        ];
1690        assert_eq!(
1691            recorder.counter(("component_events_dropped_total", trace_tags)),
1692            Some(1)
1693        );
1694
1695        let span_tags: &[(&str, &str)] = &[
1696            ("component_id", "otlp_test"),
1697            ("component_type", "source"),
1698            ("intentional", "true"),
1699            ("drop_reason", "span_id_zero"),
1700            ("message_type", "otlp_spans"),
1701        ];
1702        assert_eq!(recorder.counter(("component_events_dropped_total", span_tags)), Some(3));
1703    }
1704
1705    /// Translates a batch of two spans from a resource with the given attributes and returns the span counts recorded
1706    /// for the given client tags.
1707    fn spans_received_for(
1708        resource_attrs: Vec<KeyValue>, client_tags: &'static [(&'static str, &'static str)],
1709    ) -> Option<u64> {
1710        let recorder = TestRecorder::default();
1711        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1712
1713        let mut translator = OtlpTracesTranslator::new(
1714            OtlpTracesSettings {
1715                string_interner_size: std::num::NonZeroUsize::new(64 * 1024).unwrap(),
1716                ..traces_settings()
1717            },
1718            5000,
1719            SemanticRegistryProvider::default(),
1720            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
1721        );
1722        let metrics = build_metrics(&ComponentContext::test_source("otlp_test"));
1723
1724        let trace = [0xAAu8; 16];
1725        let rs = build_resource_spans(
1726            resource_attrs,
1727            vec![span(trace, [1u8; 8], vec![]), span(trace, [2u8; 8], vec![])],
1728        );
1729        let _ = translator.translate_spans(rs, &metrics).count();
1730
1731        recorder.counter(("component_events_received_total", client_tags))
1732    }
1733
1734    /// The span counter carries the sending client's language and `otlp-`-prefixed SDK version.
1735    /// https://github.com/DataDog/saluki/issues/2391
1736    #[test]
1737    fn translate_spans_tags_received_spans_with_the_client_language_and_version() {
1738        let received = spans_received_for(
1739            vec![
1740                string_kv("telemetry.sdk.language", "Go"),
1741                string_kv("telemetry.sdk.version", "1.2.3"),
1742            ],
1743            &[
1744                ("component_id", "otlp_test"),
1745                ("component_type", "source"),
1746                ("message_type", "otlp_spans"),
1747                ("lang", "go"),
1748                ("tracer_version", "otlp-1.2.3"),
1749                ("endpoint_version", "opentelemetry_grpc_v1"),
1750            ],
1751        );
1752        assert_eq!(received, Some(2));
1753    }
1754
1755    /// Infrastructure enrichment can write a tag under the same key as an SDK attribute, replacing the sender's value
1756    /// on the resource. The counter must still name the sender.
1757    #[test]
1758    fn translate_spans_tags_received_spans_with_the_sender_sdk_when_enrichment_uses_the_same_keys() {
1759        let recorder = TestRecorder::default();
1760        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1761
1762        let provider = TestWorkloadProvider::with_entity(
1763            EntityId::Container(MetaString::from("abc123")),
1764            &["telemetry.sdk.language:enriched", "telemetry.sdk.version:9.9.9"],
1765        );
1766        let mut translator = OtlpTracesTranslator::new(
1767            OtlpTracesSettings {
1768                infra_attributes_enabled: true,
1769                container_tag_promotion: ContainerTagPromotion::Off,
1770                ..translator_config()
1771            },
1772            MAX_RESOURCE_LEN,
1773            SemanticRegistryProvider::default(),
1774            OtlpOriginTagResolver::new(Arc::new(provider)),
1775        );
1776        let metrics = build_metrics(&ComponentContext::test_source("otlp_test"));
1777
1778        let trace = [0xBBu8; 16];
1779        let rs = build_resource_spans(
1780            vec![
1781                string_kv("container.id", "abc123"),
1782                string_kv("telemetry.sdk.language", "go"),
1783                string_kv("telemetry.sdk.version", "1.2.3"),
1784            ],
1785            vec![span(trace, [1u8; 8], vec![]), span(trace, [2u8; 8], vec![])],
1786        );
1787        let _ = translator.translate_spans(rs, &metrics).count();
1788
1789        let sender: &[(&str, &str)] = &[
1790            ("component_id", "otlp_test"),
1791            ("component_type", "source"),
1792            ("message_type", "otlp_spans"),
1793            ("lang", "go"),
1794            ("tracer_version", "otlp-1.2.3"),
1795            ("endpoint_version", "opentelemetry_grpc_v1"),
1796        ];
1797        let enriched: &[(&str, &str)] = &[
1798            ("component_id", "otlp_test"),
1799            ("component_type", "source"),
1800            ("message_type", "otlp_spans"),
1801            ("lang", "enriched"),
1802            ("tracer_version", "otlp-9.9.9"),
1803            ("endpoint_version", "opentelemetry_grpc_v1"),
1804        ];
1805        assert_eq!(recorder.counter(("component_events_received_total", sender)), Some(2));
1806        assert_eq!(recorder.counter(("component_events_received_total", enriched)), None);
1807    }
1808
1809    /// Without `telemetry.sdk.language` the `lang` tag is left off.
1810    #[test]
1811    fn translate_spans_omits_lang_without_an_sdk_language() {
1812        let received = spans_received_for(
1813            vec![string_kv("telemetry.sdk.version", "1.2.3")],
1814            &[
1815                ("component_id", "otlp_test"),
1816                ("component_type", "source"),
1817                ("message_type", "otlp_spans"),
1818                ("tracer_version", "otlp-1.2.3"),
1819                ("endpoint_version", "opentelemetry_grpc_v1"),
1820            ],
1821        );
1822        assert_eq!(received, Some(2));
1823    }
1824
1825    /// Without `telemetry.sdk.version` the tracer version is still emitted, as a bare `otlp-`.
1826    #[test]
1827    fn translate_spans_keeps_the_otlp_tracer_version_prefix_without_an_sdk_version() {
1828        let received = spans_received_for(
1829            vec![string_kv("telemetry.sdk.language", "go")],
1830            &[
1831                ("component_id", "otlp_test"),
1832                ("component_type", "source"),
1833                ("message_type", "otlp_spans"),
1834                ("lang", "go"),
1835                ("tracer_version", "otlp-"),
1836                ("endpoint_version", "opentelemetry_grpc_v1"),
1837            ],
1838        );
1839        assert_eq!(received, Some(2));
1840    }
1841
1842    /// A zero-ID span in one trace must not affect a well-formed trace in the same batch.
1843    #[test]
1844    fn translate_spans_keeps_well_formed_trace_alongside_dropped_trace() {
1845        let bad_trace = [0xEEu8; 16];
1846        let good_trace = [0xFFu8; 16];
1847        let rs = build_resource_spans(
1848            vec![],
1849            vec![span(bad_trace, [0u8; 8], vec![]), span(good_trace, [1u8; 8], vec![])],
1850        );
1851
1852        let traces = translate(rs);
1853        assert_eq!(traces.len(), 1, "only the well-formed trace survives");
1854        assert_eq!(traces[0].trace_id_low, u64::from_be_bytes([0xFF; 8]));
1855        assert_eq!(traces[0].spans().len(), 1);
1856    }
1857
1858    #[test]
1859    fn convert_trace_id_uses_agent_grouping_key() {
1860        // Pins the grouping key we derive from the upstream OTLP ingest: the low 8 bytes of the
1861        // 16-byte big-endian trace ID.
1862        let id: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
1863        assert_eq!(
1864            convert_trace_id(&id),
1865            u64::from_be_bytes([8, 9, 10, 11, 12, 13, 14, 15])
1866        );
1867        assert_eq!(convert_trace_id_high(&id), u64::from_be_bytes([0, 1, 2, 3, 4, 5, 6, 7]));
1868
1869        // A zero-padded 64-bit trace ID: its value lives entirely in the low half.
1870        let id64 = trace_id16(0, 0x1234_5678_9abc_def0);
1871        assert_eq!(convert_trace_id(&id64), 0x1234_5678_9abc_def0);
1872        assert_eq!(convert_trace_id_high(&id64), 0);
1873
1874        assert_eq!(convert_trace_id(&[1, 2, 3]), 0);
1875        assert_eq!(convert_trace_id_high(&[0xAA; 8]), 0);
1876    }
1877
1878    #[test]
1879    fn translate_spans_rejects_groups_with_mixed_full_trace_ids() {
1880        let low = u64::from_be_bytes([0xAA; 8]);
1881        let rs = build_resource_spans(
1882            vec![],
1883            vec![
1884                span(trace_id16(0x0101_0101_0101_0101, low), [1u8; 8], vec![]),
1885                span(trace_id16(0x0202_0202_0202_0202, low), [2u8; 8], vec![]),
1886                span(trace_id16(0, 0x0BBB_BBBB_BBBB_BBBB), [3u8; 8], vec![]),
1887            ],
1888        );
1889
1890        let traces = translate(rs);
1891        assert_eq!(
1892            traces.len(),
1893            1,
1894            "the mixed group is dropped; the unrelated trace survives"
1895        );
1896        assert_eq!(traces[0].trace_id_low, 0x0BBB_BBBB_BBBB_BBBB);
1897    }
1898
1899    #[test]
1900    fn translate_spans_rejects_mixed_zero_and_nonzero_high_halves() {
1901        // A zero high half and a nonzero high half are different full trace IDs, in either span
1902        // order. Both IDs are canonical 16-byte OTLP IDs here; the OTLP spans always carry the
1903        // full 128-bit ID, so unlike legacy tracer chunks the high halves are always compared.
1904        let id_zero_high = trace_id16(0, u64::from_be_bytes([0xAA; 8])).to_vec();
1905        let id_full = trace_id16(0x0101_0101_0101_0101, u64::from_be_bytes([0xAA; 8])).to_vec();
1906
1907        let zero_high_first = build_resource_spans(
1908            vec![],
1909            vec![
1910                span_raw(id_zero_high.clone(), [1u8; 8], vec![]),
1911                span_raw(id_full.clone(), [2u8; 8], vec![]),
1912            ],
1913        );
1914        assert_eq!(translate(zero_high_first).len(), 0);
1915
1916        let full_first = build_resource_spans(
1917            vec![],
1918            vec![
1919                span_raw(id_full, [1u8; 8], vec![]),
1920                span_raw(id_zero_high, [2u8; 8], vec![]),
1921            ],
1922        );
1923        assert_eq!(translate(full_first).len(), 0);
1924    }
1925
1926    #[test]
1927    fn translate_spans_accepts_consistent_zero_high_halves() {
1928        // Two 16-byte IDs with the same zero high half and same low half are one trace.
1929        let id_zero_high = trace_id16(0, u64::from_be_bytes([0xAA; 8]));
1930
1931        let rs = build_resource_spans(
1932            vec![],
1933            vec![
1934                span(id_zero_high, [1u8; 8], vec![]),
1935                span(id_zero_high, [2u8; 8], vec![]),
1936            ],
1937        );
1938        let traces = translate(rs);
1939        assert_eq!(traces.len(), 1);
1940        assert_eq!(traces[0].spans().len(), 2);
1941        assert_eq!(traces[0].trace_id_high, 0);
1942    }
1943
1944    #[test]
1945    fn translate_spans_rejects_non_canonical_length_trace_ids() {
1946        // A trace ID is valid only when it is empty or exactly 16 bytes; anything else is
1947        // decode-invalid, and the trace is dropped.
1948        for raw_id in [vec![0xAA; 8], vec![0xAA; 12], vec![0xAA; 20]] {
1949            let rs = build_resource_spans(vec![], vec![span_raw(raw_id.clone(), [1u8; 8], vec![])]);
1950            assert_eq!(
1951                translate(rs).len(),
1952                0,
1953                "non-canonical length {} is dropped",
1954                raw_id.len()
1955            );
1956        }
1957
1958        // A short ID in a group also rejects the whole group, not just the malformed span.
1959        let rs = build_resource_spans(
1960            vec![],
1961            vec![
1962                span_raw(vec![0xAA; 8], [1u8; 8], vec![]),
1963                span(trace_id16(0, u64::from_be_bytes([0xAA; 8])), [2u8; 8], vec![]),
1964            ],
1965        );
1966        assert_eq!(
1967            translate(rs).len(),
1968            0,
1969            "the group containing a short trace ID is dropped whole"
1970        );
1971    }
1972
1973    #[test]
1974    fn translate_spans_rejects_zero_trace_ids() {
1975        // A zero low half is invalid regardless of the high half: a 16-byte ID with a zero
1976        // low half is zero, and an empty ID decodes to zero.
1977        for raw_id in [
1978            trace_id16(0x0101_0101_0101_0101, 0).to_vec(),
1979            trace_id16(0, 0).to_vec(),
1980            Vec::new(),
1981        ] {
1982            let rs = build_resource_spans(vec![], vec![span_raw(raw_id, [1u8; 8], vec![])]);
1983            assert_eq!(translate(rs).len(), 0, "zero trace IDs are dropped");
1984        }
1985    }
1986
1987    #[test]
1988    fn translate_spans_rejects_zero_span_ids() {
1989        // A zero span ID drops the whole trace; a wrong-length OTLP span ID also decodes to
1990        // zero. Duplicate span IDs, by contrast, are only counted as malformed, so they stay
1991        // accepted.
1992        let rs = build_resource_spans(vec![], vec![span(trace_id16(0, 1), [0u8; 8], vec![])]);
1993        assert_eq!(translate(rs).len(), 0, "an all-zero span ID drops the trace");
1994
1995        let mut zero_len_span = span(trace_id16(0, 1), [1u8; 8], vec![]);
1996        zero_len_span.span_id = vec![];
1997        let rs = build_resource_spans(vec![], vec![zero_len_span]);
1998        assert_eq!(
1999            translate(rs).len(),
2000            0,
2001            "an empty span ID decodes to zero and drops the trace"
2002        );
2003
2004        let rs = build_resource_spans(
2005            vec![],
2006            vec![
2007                span(trace_id16(0, 1), [1u8; 8], vec![]),
2008                span(trace_id16(0, 1), [1u8; 8], vec![]),
2009            ],
2010        );
2011        let traces = translate(rs);
2012        assert_eq!(traces.len(), 1, "duplicate span IDs are tolerated");
2013        assert_eq!(traces_spans_len(&traces), 2);
2014    }
2015
2016    fn traces_spans_len(traces: &[Trace]) -> usize {
2017        traces.iter().map(|t| t.spans().len()).sum()
2018    }
2019
2020    #[test]
2021    fn translate_spans_repairs_self_parented_spans() {
2022        // parent == span == trace ID gets the parent cleared so the malformed span becomes a
2023        // root; other spans keep their parents.
2024        let trace = trace_id16(0, 1);
2025        let self_parented = span_with_parent(trace, [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 1], vec![]);
2026        let child = span_with_parent(trace, [0, 0, 0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0, 0, 1], vec![]);
2027
2028        let rs = build_resource_spans(vec![], vec![self_parented, child]);
2029        let traces = translate(rs);
2030        assert_eq!(traces.len(), 1);
2031
2032        let spans = traces[0].spans();
2033        let repaired = spans
2034            .iter()
2035            .find(|s| s.span_id() == 1)
2036            .expect("self-parented span is present");
2037        assert_eq!(repaired.parent_id(), 0, "the self-parented span's parent is cleared");
2038
2039        let child = spans.iter().find(|s| s.span_id() == 2).expect("child is present");
2040        assert_eq!(child.parent_id(), 1, "the child's parent is untouched");
2041    }
2042}