Skip to main content

libdd_trace_stats/span_concentrator/
aggregation.rs

1// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! This module implement the logic for stats aggregation into time buckets and stats group.
5//! This includes the aggregation key to group spans together and the computation of stats from a
6//! span.
7
8use hashbrown::{HashMap, HashSet};
9use libdd_trace_obfuscation::ip_address::quantize_peer_ip_addresses;
10use libdd_trace_protobuf::pb;
11use std::{
12    borrow::{Borrow, Cow},
13    hash::{DefaultHasher, Hash, Hasher as _},
14};
15use tracing::warn;
16
17use crate::span_concentrator::{StatSpan, cardinality_limit_telemetry::CollapsedFieldSet};
18
19use super::{
20    CardinalityLimitConfig,
21    cardinality_limit_telemetry::{self, CollapsedFieldsMetrics},
22};
23
24/// Sentinel value used for cardinality limiting.
25pub const TRACER_BLOCKED_VALUE: &str = "tracer_blocked_value";
26
27const TAG_STATUS_CODE: &str = "http.status_code";
28const TAG_METHOD: &str = "http.method";
29// OpenTelemetry HTTP semantic-convention names for the two attributes above. A tracer running in
30// OTel semantics mode (DD_TRACE_OTEL_SEMANTICS_ENABLED) emits these instead of the Datadog names,
31// so reading only the Datadog names silently drops the status and method stats dimensions: the
32// bucket reports status 0 and an empty method while the span itself is correct.
33// http.endpoint and http.route need no equivalent: http.route is already the OTel name, and
34// http.endpoint is Datadog-only and retained in that mode.
35const TAG_STATUS_CODE_OTEL: &str = "http.response.status_code";
36const TAG_METHOD_OTEL: &str = "http.request.method";
37const ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN: usize = 200;
38const TAG_SYNTHETICS: &str = "synthetics";
39const TAG_SPANKIND: &str = "span.kind";
40const TAG_BASE_SERVICE: &str = "_dd.base_service";
41const TAG_ORIGIN: &str = "_dd.origin";
42const TAG_SVC_SRC: &str = "_dd.svc_src";
43const GRPC_STATUS_CODE_FIELD: &[&str] = &[
44    "rpc.grpc.status_code",
45    "grpc.code",
46    "rpc.grpc.status.code",
47    "grpc.status.code",
48];
49
50/// Aggregation key fields shared across all concentrator implementations — everything
51/// **except** peer tags.
52///
53/// `T` is the string representation:
54/// * `&'a str`   — borrowed references used in `BorrowedAggregationKey`
55/// * `String`    — owned values used in `OwnedAggregationKey`
56#[derive(
57    Clone, Default, Hash, Eq, PartialEq, Debug, PartialOrd, serde::Serialize, serde::Deserialize,
58)]
59pub struct FixedAggregationKey<T> {
60    pub resource_name: T,
61    pub service_name: T,
62    pub operation_name: T,
63    pub span_type: T,
64    pub span_kind: T,
65    pub http_method: T,
66    pub http_endpoint: T,
67    pub service_source: T,
68    pub http_status_code: u32,
69    pub grpc_status_code: Option<u8>,
70    pub is_synthetics_request: bool,
71    pub is_trace_root: pb::Trilean,
72}
73
74impl<T> FixedAggregationKey<T> {
75    /// Map all string fields through `f`, preserving scalar fields.
76    pub fn convert<'a, V: 'a, I: ?Sized + 'a, F: Fn(&'a I) -> V>(
77        &'a self,
78        f: F,
79    ) -> FixedAggregationKey<V>
80    where
81        T: Borrow<I>,
82    {
83        FixedAggregationKey {
84            resource_name: f(self.resource_name.borrow()),
85            service_name: f(self.service_name.borrow()),
86            operation_name: f(self.operation_name.borrow()),
87            span_type: f(self.span_type.borrow()),
88            span_kind: f(self.span_kind.borrow()),
89            http_method: f(self.http_method.borrow()),
90            http_endpoint: f(self.http_endpoint.borrow()),
91            service_source: f(self.service_source.borrow()),
92            http_status_code: self.http_status_code,
93            grpc_status_code: self.grpc_status_code,
94            is_synthetics_request: self.is_synthetics_request,
95            is_trace_root: self.is_trace_root,
96        }
97    }
98}
99
100#[derive(Clone, Hash, PartialEq, Eq)]
101/// Represent a stats aggregation key borrowed from span data
102pub(super) struct BorrowedAggregationKey<'a> {
103    fixed: FixedAggregationKey<&'a str>,
104    peer_tags: Vec<(&'a str, Cow<'a, str>)>,
105    additional_metric_tags: Vec<(&'a str, &'a str)>,
106}
107
108impl hashbrown::Equivalent<OwnedAggregationKey> for BorrowedAggregationKey<'_> {
109    #[inline]
110    fn equivalent(&self, other: &OwnedAggregationKey) -> bool {
111        self.fixed == other.fixed.convert(|s| s)
112            && self.peer_tags.len() == other.peer_tags.len()
113            && self
114                .peer_tags
115                .iter()
116                .zip(other.peer_tags.iter())
117                .all(|((k1, v1), (k2, v2))| k1 == k2 && v1 == v2)
118            && self.additional_metric_tags.len() == other.additional_metric_tags.len()
119            && self
120                .additional_metric_tags
121                .iter()
122                .zip(other.additional_metric_tags.iter())
123                .all(|((k1, v1), (k2, v2))| k1 == k2 && v1 == v2)
124    }
125}
126
127#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Default)]
128/// Represents a span aggregation key with owned data
129///
130/// To be able to use BorrowedAggregationKey to index into a stats bucket hashmap two
131/// conditions must stay true:
132/// * Hashing an owned key derived from a borrowed key should produce the same hash as hashing the
133///   borrowed key
134/// * Running the Equivalent trait on an owned key derived from a borrowed key should produce true
135pub(super) struct OwnedAggregationKey {
136    fixed: FixedAggregationKey<String>,
137    peer_tags: Vec<(String, String)>,
138    additional_metric_tags: Vec<(String, String)>,
139}
140
141impl From<&BorrowedAggregationKey<'_>> for OwnedAggregationKey {
142    fn from(value: &BorrowedAggregationKey<'_>) -> Self {
143        OwnedAggregationKey {
144            fixed: value.fixed.convert(str::to_owned),
145            peer_tags: value
146                .peer_tags
147                .iter()
148                .map(|(k, v)| (k.to_string(), v.to_string()))
149                .collect(),
150            additional_metric_tags: value
151                .additional_metric_tags
152                .iter()
153                .map(|(k, v)| (k.to_string(), v.to_string()))
154                .collect(),
155        }
156    }
157}
158
159fn float_to_int(f: f64) -> Option<u8> {
160    if f.floor() != f {
161        return None;
162    }
163    if f < 0.0 || (u8::MAX as f64) < f {
164        return None;
165    }
166    Some(f as u8)
167}
168
169fn float_to_u32(f: f64) -> Option<u32> {
170    if !f.is_finite() || f.floor() != f || f < 0.0 || (u32::MAX as f64) < f {
171        return None;
172    }
173    // The checks above guarantee the finite integral value is representable without loss.
174    Some(f as u32)
175}
176
177fn is_valid_http_status_code(code: &u32) -> bool {
178    (100..600).contains(code)
179}
180
181/// The HTTP method, under either naming convention, or "" when the span carries neither.
182///
183/// The Datadog name is canonical in the Agent semantic registry and is preferred when both names
184/// are present.
185fn get_http_method<'a>(span: &'a impl StatSpan<'a>) -> &'a str {
186    for key in [TAG_METHOD, TAG_METHOD_OTEL] {
187        if let Some(value) = span.get_meta(key) {
188            if !value.is_empty() {
189                return value;
190            }
191        }
192    }
193
194    ""
195}
196
197/// The HTTP status code, under either naming convention, or 0 when the span carries neither.
198///
199/// `metrics` is checked before `meta` for each name because a numeric attribute is routed there
200/// by the tracer's own setter, and OTel types `http.response.status_code` as an int. The Datadog
201/// key retains its existing conversion and precedence behavior. Invalid OTel values are ignored.
202fn get_http_status_code<'a>(span: &'a impl StatSpan<'a>) -> u32 {
203    for key in [TAG_STATUS_CODE, TAG_STATUS_CODE_OTEL] {
204        if let Some(value) = span.get_metrics(key) {
205            if key == TAG_STATUS_CODE {
206                // Preserve the existing Datadog-key conversion behavior.
207                return value as u32;
208            }
209            if let Some(code) = float_to_u32(value).filter(is_valid_http_status_code) {
210                return code;
211            }
212        }
213
214        if let Some(value) = span.get_meta(key) {
215            if key == TAG_STATUS_CODE {
216                // Preserve the existing Datadog-key parse-or-zero behavior.
217                return value.parse().unwrap_or_default();
218            }
219            if let Some(code) = value.parse().ok().filter(is_valid_http_status_code) {
220                return code;
221            }
222        }
223    }
224
225    0
226}
227
228fn get_grpc_status_code<'a>(span: &'a impl StatSpan<'a>) -> Option<u8> {
229    for key in GRPC_STATUS_CODE_FIELD {
230        if let Some(val) = span.get_meta(key) {
231            if let Some(code) = grpc_status_str_to_int_value(val) {
232                return Some(code);
233            }
234        }
235    }
236
237    for key in GRPC_STATUS_CODE_FIELD {
238        if let Some(val) = span.get_metrics(key) {
239            if let Some(code) = float_to_int(val) {
240                return Some(code);
241            }
242        }
243    }
244
245    None
246}
247
248fn grpc_status_str_to_int_value(v: &str) -> Option<u8> {
249    if let Ok(status) = v.parse() {
250        return Some(status);
251    }
252    let mut status_uppercase = [0u8; 32];
253    let mut status = v.trim_start_matches("StatusCode.");
254
255    let mut needs_upcasing = false;
256    for b in status.as_bytes() {
257        if !b.is_ascii() {
258            return None;
259        }
260        needs_upcasing |= b.is_ascii_lowercase()
261    }
262    if needs_upcasing {
263        for (c, d) in status.as_bytes().iter().zip(&mut status_uppercase) {
264            *d = c.to_ascii_uppercase();
265        }
266        status = std::str::from_utf8(&status_uppercase[0..status.len().min(status_uppercase.len())])
267            .ok()?
268    }
269
270    match status {
271        "OK" => return Some(0),
272        "CANCELLED" | "CANCELED" => return Some(1),
273        "UNKNOWN" => return Some(2),
274        "INVALID_ARGUMENT" | "INVALIDARGUMENT" => return Some(3),
275        "DEADLINE_EXCEEDED" | "DEADLINEEXCEEDED" => return Some(4),
276        "NOT_FOUND" | "NOTFOUND" => return Some(5),
277        "ALREADY_EXISTS" | "ALREADYEXISTS" => return Some(6),
278        "PERMISSION_DENIED" | "PERMISSIONDENIED" => return Some(7),
279        "UNAUTHENTICATED" => return Some(16),
280        "RESOURCE_EXHAUSTED" | "RESOURCEEXHAUSTED" => return Some(8),
281        "FAILED_PRECONDITION" | "FAILEDPRECONDITION" => return Some(9),
282        "ABORTED" => return Some(10),
283        "OUT_OF_RANGE" | "OUTOFRANGE" => return Some(11),
284        "UNIMPLEMENTED" => return Some(12),
285        "INTERNAL" => return Some(13),
286        "UNAVAILABLE" => return Some(14),
287        "DATA_LOSS" | "DATALOSS" => return Some(15),
288        _ => {}
289    }
290    None
291}
292
293impl<'a> BorrowedAggregationKey<'a> {
294    /// Return an AggregationKey matching the given span.
295    ///
296    /// If `peer_tag_keys` is not empty then the peer tags of the span will be included in the
297    /// key.
298    /// If `additional_metric_tags` is not empty then matching span tags keys are included in the
299    /// key.
300    pub(super) fn from_span<T: StatSpan<'a>>(
301        span: &'a T,
302        peer_tag_keys: &'a [String],
303        additional_metric_tag_keys: &'a [String],
304    ) -> Self {
305        Self::from_obfuscated_span(
306            span.resource(),
307            span,
308            peer_tag_keys,
309            additional_metric_tag_keys,
310        )
311    }
312
313    pub(crate) fn from_obfuscated_span<'b, T>(
314        resource_name: &'a str,
315        span: &'b T,
316        peer_tag_keys: &'b [String],
317        additional_metric_tag_keys: &'b [String],
318    ) -> BorrowedAggregationKey<'a>
319    where
320        T: StatSpan<'b>,
321        // resource_name is a temporary string on the stack the span will outlive it
322        'b: 'a,
323    {
324        let span_kind = span.get_meta(TAG_SPANKIND).unwrap_or_default();
325        let base_service = span.get_meta(TAG_BASE_SERVICE).unwrap_or_default();
326        // Mirrors the Go trace-agent's peerTagKeysToAggregateForSpan: peer tags are collected
327        // only when peer-tag aggregation is configured, and then either from the configured
328        // keys (client/producer/consumer spans) or, for internal spans (or spans without a
329        // kind) carrying a non-empty _dd.base_service override, from _dd.base_service alone.
330        // All other kinds, including server, get no peer tags.
331        let peer_tags = if peer_tag_keys.is_empty() {
332            // Peer-tag aggregation is disabled: no span gets peer tags, even when
333            // _dd.base_service is set.
334            vec![]
335        } else if should_track_peer_tags(span_kind) {
336            // Parse the meta tags of the span and return a list of the peer tags based on the list
337            // of `peer_tag_keys`. IP address values are quantized to reduce cardinality.
338            peer_tag_keys
339                .iter()
340                .filter_map(|key| {
341                    let value = span.get_meta(key.as_str())?;
342                    Some((key.as_str(), quantize_peer_ip_addresses(value)))
343                })
344                .collect()
345        } else if (span_kind.is_empty() || span_kind.eq_ignore_ascii_case("internal"))
346            && !base_service.is_empty()
347        {
348            // Internal spans with a base service override use only _dd.base_service as peer tag
349            vec![(TAG_BASE_SERVICE, Cow::Borrowed(base_service))]
350        } else {
351            vec![]
352        };
353
354        // The Datadog name wins when both are present. An empty value counts as absent, so a
355        // tracer that writes the key unconditionally cannot shadow a real value under the other
356        // name, which is the mistake get_grpc_status_code above already avoids.
357        let http_method = get_http_method(span);
358
359        let http_endpoint = span
360            .get_meta("http.endpoint")
361            .filter(|value| !value.is_empty())
362            .or_else(|| {
363                span.get_meta("http.route")
364                    .filter(|value| !value.is_empty())
365            })
366            .unwrap_or_default();
367
368        let status_code = get_http_status_code(span);
369
370        let grpc_status_code = get_grpc_status_code(span);
371        let service_source = span.get_meta(TAG_SVC_SRC).unwrap_or_default();
372
373        let additional_metric_tags: Vec<(&'a str, &'a str)> = additional_metric_tag_keys
374            .iter()
375            .filter_map(|key| match span.get_meta(key.as_str()) {
376                Some(v) if !v.is_empty() => {
377                    // Byte length >= char count, so skip the char walk when byte length alone
378                    // is within the max character length, otherwise stop as soon as we pass the max character length.
379                    if v.len() > ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN
380                        && v.chars().nth(ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN).is_some()
381                    {
382                        warn!(
383                            "additional_metric_tags: value for key '{}' exceeds {} characters; substituting tracer_blocked_value",
384                            key, ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN,
385                        );
386                        Some((key.as_str(), TRACER_BLOCKED_VALUE))
387                    } else {
388                        Some((key.as_str(), v))
389                    }
390                }
391                _ => None,
392            })
393            .collect();
394
395        Self {
396            fixed: FixedAggregationKey {
397                resource_name,
398                service_name: span.service(),
399                operation_name: span.name(),
400                span_type: span.r#type(),
401                span_kind,
402                http_method,
403                http_endpoint,
404                service_source,
405                http_status_code: status_code,
406                grpc_status_code,
407                is_synthetics_request: span
408                    .get_meta(TAG_ORIGIN)
409                    .is_some_and(|origin| origin.starts_with(TAG_SYNTHETICS)),
410                is_trace_root: if span.is_trace_root() {
411                    pb::Trilean::True
412                } else {
413                    pb::Trilean::False
414                },
415            },
416            peer_tags,
417            additional_metric_tags,
418        }
419    }
420
421    /// Truncates string fields in accordance with the cardinality limit RFC
422    ///
423    /// This should be called only after obfuscation
424    #[cfg_attr(not(feature = "stats-obfuscation"), allow(unused))]
425    pub(crate) fn truncate(&mut self, big_resource: bool) {
426        let resource_length_limit = if big_resource { 15_000 } else { 5000 };
427        self.fixed.resource_name = slice_up_to(self.fixed.resource_name, resource_length_limit);
428        self.fixed.service_name = slice_up_to(self.fixed.service_name, 100);
429        self.fixed.operation_name = slice_up_to(self.fixed.operation_name, 100);
430        self.fixed.span_type = slice_up_to(self.fixed.span_type, 100);
431    }
432}
433
434/// Truncate `s` to at most `max_len` bytes
435fn slice_up_to(s: &str, max_len: usize) -> &str {
436    if max_len >= s.len() {
437        return s;
438    }
439    // TODO: use `floor_char_boundary` once our MSRV is 1.91 or higher
440    // (https://doc.rust-lang.org/std/primitive.str.html#method.floor_char_boundary)
441    let mut idx = max_len;
442    while !s.is_char_boundary(idx) {
443        idx -= 1;
444    }
445    &s[..idx]
446}
447
448impl OwnedAggregationKey {
449    /// Return the overflow sentinel key.
450    pub(super) fn overflow_key() -> Self {
451        OwnedAggregationKey {
452            fixed: FixedAggregationKey {
453                resource_name: TRACER_BLOCKED_VALUE.to_owned(),
454                service_name: TRACER_BLOCKED_VALUE.to_owned(),
455                operation_name: TRACER_BLOCKED_VALUE.to_owned(),
456                span_type: TRACER_BLOCKED_VALUE.to_owned(),
457                span_kind: TRACER_BLOCKED_VALUE.to_owned(),
458                http_method: TRACER_BLOCKED_VALUE.to_owned(),
459                http_endpoint: TRACER_BLOCKED_VALUE.to_owned(),
460                service_source: TRACER_BLOCKED_VALUE.to_owned(),
461                http_status_code: 0,
462                grpc_status_code: None,
463                is_synthetics_request: false,
464                is_trace_root: pb::Trilean::NotSet,
465            },
466            peer_tags: vec![(TRACER_BLOCKED_VALUE.to_owned(), "".to_owned())],
467            additional_metric_tags: vec![(TRACER_BLOCKED_VALUE.to_owned(), "".to_owned())],
468        }
469    }
470}
471
472impl From<pb::ClientGroupedStats> for OwnedAggregationKey {
473    fn from(value: pb::ClientGroupedStats) -> Self {
474        Self {
475            fixed: FixedAggregationKey {
476                resource_name: value.resource,
477                service_name: value.service,
478                operation_name: value.name,
479                span_type: value.r#type,
480                span_kind: value.span_kind,
481                http_method: value.http_method,
482                http_endpoint: value.http_endpoint,
483                service_source: value.service_source,
484                http_status_code: value.http_status_code,
485                grpc_status_code: value.grpc_status_code.parse().ok(),
486                is_synthetics_request: value.synthetics,
487                is_trace_root: pb::Trilean::try_from(value.is_trace_root)
488                    .unwrap_or(pb::Trilean::NotSet),
489            },
490            peer_tags: value
491                .peer_tags
492                .into_iter()
493                .filter_map(|t| {
494                    let (key, value) = t.split_once(':')?;
495                    Some((key.to_string(), value.to_string()))
496                })
497                .collect(),
498            additional_metric_tags: value
499                .additional_metric_tags
500                .into_iter()
501                .filter_map(|t| {
502                    let (key, value) = t.split_once(':')?;
503                    Some((key.to_string(), value.to_string()))
504                })
505                .collect(),
506        }
507    }
508}
509
510/// Return true if we care about peer tags on the span
511fn should_track_peer_tags(span_kind: &str) -> bool {
512    matches!(
513        span_kind.to_lowercase().as_str(),
514        "client" | "producer" | "consumer"
515    )
516}
517
518/// The stats computed from a group of span with the same AggregationKey
519#[derive(Debug, Default, Clone)]
520pub(super) struct GroupedStats {
521    hits: u64,
522    errors: u64,
523    duration: u64,
524    top_level_hits: u64,
525    ok_summary: libdd_ddsketch::DDSketch,
526    error_summary: libdd_ddsketch::DDSketch,
527    // Exact per-cell (ok/error) scalars used by the OTLP trace-metrics path. These are tracked
528    // separately from `duration` so the /v0.6/stats agent payload is byte-for-byte unchanged.
529    ok_duration: u64,
530    ok_min: u64,
531    ok_max: u64,
532    error_duration: u64,
533    error_min: u64,
534    error_max: u64,
535}
536
537impl GroupedStats {
538    /// Update the stats of a GroupedStats by inserting a span.
539    fn insert(&mut self, duration: i64, is_error: bool, is_top_level: bool) {
540        self.hits += 1;
541        self.duration += duration as u64;
542        let d = duration as u64;
543        if is_error {
544            self.errors += 1;
545            let _ = self.error_summary.add(duration as f64);
546            self.error_duration += d;
547            self.error_min = if self.errors == 1 {
548                d
549            } else {
550                self.error_min.min(d)
551            };
552            self.error_max = self.error_max.max(d);
553        } else {
554            let _ = self.ok_summary.add(duration as f64);
555            self.ok_duration += d;
556            let ok_count = self.hits - self.errors;
557            self.ok_min = if ok_count == 1 { d } else { self.ok_min.min(d) };
558            self.ok_max = self.ok_max.max(d);
559        }
560        if is_top_level {
561            self.top_level_hits += 1;
562        }
563    }
564}
565
566/// Exact per-cell (ok or error) scalars for one aggregation group, surfaced to the OTLP
567/// trace-metrics path. `count` is exact; `duration_ns`/`min_ns`/`max_ns` are exact when
568/// `count > 0` and meaningless otherwise (the OTLP mapper suppresses empty cells).
569#[derive(Debug, Clone, Copy, Default)]
570pub struct OtlpExactCell {
571    pub count: u64,
572    pub duration_ns: u64,
573    pub min_ns: u64,
574    pub max_ns: u64,
575}
576
577/// Exact OK/ERROR cells for one aggregation group, in the same order as the `stats` vector
578/// of the accompanying [`pb::ClientStatsBucket`].
579#[derive(Debug, Clone, Default)]
580pub struct OtlpExactGroup {
581    pub ok: OtlpExactCell,
582    pub error: OtlpExactCell,
583}
584
585/// A bucket flushed for the OTLP trace-metrics path. `exact[i]` is the exact-scalar sidecar
586/// for `bucket.stats[i]`; the protobuf bucket itself is identical to what the agent path uses.
587#[derive(Debug, Clone)]
588pub struct OtlpStatsBucket {
589    pub bucket: pb::ClientStatsBucket,
590    pub exact: Vec<OtlpExactGroup>,
591}
592
593/// A time bucket used for stats aggregation. It stores a map of GroupedStats storing the stats of
594/// spans aggregated on their AggregationKey.
595#[derive(Debug, Clone)]
596pub(super) struct StatsBucket {
597    data: HashMap<OwnedAggregationKey, GroupedStats>,
598    start: u64,
599    /// Maximum number of distinct aggregation keys this bucket will hold before collapsing new
600    /// ones into the overflow sentinel key.
601    cardinality_limits: CardinalityLimitConfig,
602    // HashSet of hashes of field values so we save memory
603    // This is not 100% accurate but the probability of getting collision is close to 0
604    // In the very rare case we get a collision, we would get one extra bucket which is totally
605    // fine
606    distinct_resources: HashSet<u64>,
607    distinct_http_endpoints: HashSet<u64>,
608    distinct_peer_tags: HashSet<u64>,
609    distinct_additional_tags: HashSet<u64>,
610    /// Number of spans collapsed into the overflow bucket due to whole-key cardinality limiting.
611    collapsed_count: u64,
612    collapsed_fields_metrics: CollapsedFieldsMetrics,
613    /// Indicates if stats obfuscated in this bucket. This is set once at creation and stays
614    /// constant per bucket
615    #[cfg(feature = "stats-obfuscation")]
616    pub(super) obfuscated: bool,
617}
618
619impl StatsBucket {
620    /// Return a new StatsBucket starting at `start_timestamp`.
621    ///
622    /// `cardinality_limits` are the values for whole-key and per-field cardinality limits
623    pub(super) fn new(
624        start_timestamp: u64,
625        cardinality_limits: CardinalityLimitConfig,
626        #[cfg(feature = "stats-obfuscation")] obfuscation_enabled: bool,
627    ) -> Self {
628        Self {
629            data: HashMap::new(),
630            start: start_timestamp,
631            cardinality_limits,
632            collapsed_count: 0,
633            #[cfg(feature = "stats-obfuscation")]
634            obfuscated: obfuscation_enabled,
635            distinct_resources: HashSet::new(),
636            distinct_http_endpoints: HashSet::new(),
637            distinct_peer_tags: HashSet::new(),
638            distinct_additional_tags: HashSet::new(),
639            collapsed_fields_metrics: cardinality_limit_telemetry::CollapsedFieldsMetrics::zero(),
640        }
641    }
642
643    /// Returns metrics on spans field collapse with reasons.
644    pub fn collapsed_fields_metrics(&self) -> cardinality_limit_telemetry::CollapsedFieldsMetrics {
645        self.collapsed_fields_metrics
646    }
647
648    /// Return the number of spans collapsed into the overflow bucket.
649    pub(super) fn collapsed_count(&self) -> u64 {
650        self.collapsed_count
651    }
652
653    /// Insert a value as stats in the group corresponding to the aggregation key, if it does not
654    /// exist it creates it.
655    ///
656    /// Keys that already exist in this bucket always merge normally. A new key is subject to the
657    /// `max_entries` limit, which collapses it into the overflow sentinel key.
658    pub(super) fn insert(
659        &mut self,
660        mut key: BorrowedAggregationKey<'_>,
661        duration: i64,
662        is_error: bool,
663        is_top_level: bool,
664    ) {
665        // Per field cardinality limiting
666        self.collapse_key_fields_cardinality(&mut key);
667
668        // The map can't change size before the entry below is resolved, so this single read
669        // covers the `max_entries` check in the vacant branch without a further lookup.
670        let len_before_insert = self.data.len();
671
672        match self.data.entry_ref(&key) {
673            // Existing key, merge
674            hashbrown::hash_map::EntryRef::Occupied(mut e) => {
675                e.get_mut().insert(duration, is_error, is_top_level);
676            }
677            hashbrown::hash_map::EntryRef::Vacant(e) => {
678                // New key over the max entry limit, collapse into the overflow
679                // sentinel.
680                if len_before_insert >= self.cardinality_limits.whole_key_limit {
681                    self.collapsed_count += 1;
682                    self.data
683                        .entry(OwnedAggregationKey::overflow_key())
684                        .or_default()
685                        .insert(duration, is_error, is_top_level);
686                    return;
687                }
688                // Within the max entry limit, admit key as a new distinct entry.
689                e.insert_with_key(OwnedAggregationKey::from(&key), GroupedStats::default())
690                    .insert(duration, is_error, is_top_level);
691            }
692        }
693    }
694
695    /// Collapse an aggregation key fields following the bucket's `CardinalityLimitConfig`
696    fn collapse_key_fields_cardinality(&mut self, key: &mut BorrowedAggregationKey<'_>) {
697        use hashbrown::hash_set::Entry;
698        fn hash(input: &impl Hash) -> u64 {
699            let mut hasher = DefaultHasher::new();
700            input.hash(&mut hasher);
701            hasher.finish()
702        }
703
704        let mut collapsed_fields = CollapsedFieldSet::empty();
705
706        let resource_hash = hash(&key.fixed.resource_name);
707        let resources_count = self.distinct_resources.len();
708        if let Entry::Vacant(slot) = self.distinct_resources.entry(resource_hash) {
709            if resources_count >= self.cardinality_limits.resource_limit {
710                key.fixed.resource_name = TRACER_BLOCKED_VALUE;
711                collapsed_fields.add(CollapsedFieldSet::RESOURCE_NAME);
712            } else {
713                slot.insert();
714            }
715        }
716
717        let http_endpoint_hash = hash(&key.fixed.http_endpoint);
718        let http_endpoints_count = self.distinct_http_endpoints.len();
719        if let Entry::Vacant(slot) = self.distinct_http_endpoints.entry(http_endpoint_hash) {
720            if http_endpoints_count >= self.cardinality_limits.http_endpoint_limit {
721                key.fixed.http_endpoint = TRACER_BLOCKED_VALUE;
722                collapsed_fields.add(CollapsedFieldSet::HTTP_ENDPOINT);
723            } else {
724                slot.insert();
725            }
726        }
727
728        let peer_tags_hash = hash(&key.peer_tags);
729        let peer_tags_count = self.distinct_peer_tags.len();
730        if let Entry::Vacant(slot) = self.distinct_peer_tags.entry(peer_tags_hash) {
731            if peer_tags_count >= self.cardinality_limits.peer_tags_limit {
732                key.peer_tags = vec![(TRACER_BLOCKED_VALUE, Cow::Borrowed(""))];
733                collapsed_fields.add(CollapsedFieldSet::PEER_TAGS);
734            } else {
735                slot.insert();
736            }
737        }
738
739        let additional_tags_hash = hash(&key.additional_metric_tags);
740        let additional_tags_count = self.distinct_additional_tags.len();
741        if let Entry::Vacant(slot) = self.distinct_additional_tags.entry(additional_tags_hash) {
742            if additional_tags_count >= self.cardinality_limits.additional_tags_limit {
743                key.additional_metric_tags = vec![(TRACER_BLOCKED_VALUE, "")];
744                collapsed_fields.add(CollapsedFieldSet::ADDITIONAL_TAGS);
745            } else {
746                slot.insert();
747            }
748        }
749        self.collapsed_fields_metrics.increment(collapsed_fields);
750    }
751
752    /// Consume the bucket and return a ClientStatsBucket containing the bucket stats.
753    /// `bucket_duration` is the size of buckets for the concentrator containing the bucket.
754    pub(super) fn flush(self, bucket_duration: u64) -> pb::ClientStatsBucket {
755        self.flush_with_otlp_exact(bucket_duration).bucket
756    }
757
758    /// Like [`Self::flush`], but additionally produces exact per-cell scalars for the OTLP
759    /// trace-metrics path. The `bucket` field is identical to what [`Self::flush`] returns.
760    pub(super) fn flush_with_otlp_exact(self, bucket_duration: u64) -> OtlpStatsBucket {
761        let mut stats = Vec::with_capacity(self.data.len());
762        let mut exact = Vec::with_capacity(self.data.len());
763        for (k, g) in self.data {
764            exact.push(OtlpExactGroup {
765                ok: OtlpExactCell {
766                    count: g.hits.saturating_sub(g.errors),
767                    duration_ns: g.ok_duration,
768                    min_ns: g.ok_min,
769                    max_ns: g.ok_max,
770                },
771                error: OtlpExactCell {
772                    count: g.errors,
773                    duration_ns: g.error_duration,
774                    min_ns: g.error_min,
775                    max_ns: g.error_max,
776                },
777            });
778            stats.push(encode_grouped_stats(k, g));
779        }
780        OtlpStatsBucket {
781            bucket: pb::ClientStatsBucket {
782                start: self.start,
783                duration: bucket_duration,
784                stats,
785                agent_time_shift: 0,
786            },
787            exact,
788        }
789    }
790}
791
792/// Create a ClientGroupedStats struct based on the given AggregationKey and GroupedStats
793fn encode_grouped_stats(key: OwnedAggregationKey, group: GroupedStats) -> pb::ClientGroupedStats {
794    let f = key.fixed;
795    pb::ClientGroupedStats {
796        service: f.service_name,
797        name: f.operation_name,
798        resource: f.resource_name,
799        http_status_code: f.http_status_code,
800        r#type: f.span_type,
801        db_type: String::new(), // db_type is not used yet (see proto definition)
802
803        hits: group.hits,
804        errors: group.errors,
805        duration: group.duration,
806
807        ok_summary: group.ok_summary.encode_to_vec(),
808        error_summary: group.error_summary.encode_to_vec(),
809        synthetics: f.is_synthetics_request,
810        top_level_hits: group.top_level_hits,
811        span_kind: f.span_kind,
812
813        peer_tags: key
814            .peer_tags
815            .into_iter()
816            .map(|(k, v)| {
817                if v.is_empty() {
818                    k.to_string()
819                } else {
820                    format!("{k}:{v}")
821                }
822            })
823            .collect(),
824        is_trace_root: f.is_trace_root.into(),
825        http_method: f.http_method,
826        http_endpoint: f.http_endpoint,
827        grpc_status_code: f
828            .grpc_status_code
829            .map(|c| c.to_string())
830            .unwrap_or_default(),
831        service_source: f.service_source,
832        span_derived_primary_tags: vec![],
833        additional_metric_tags: key
834            .additional_metric_tags
835            .into_iter()
836            .map(|(k, v)| format!("{k}:{v}"))
837            .collect(),
838    }
839}
840
841#[cfg(test)]
842mod tests {
843    use libdd_trace_utils::span::v04::{SpanBytes, SpanSlice};
844
845    use super::*;
846    use libdd_trace_protobuf::pb;
847    use std::hash::Hash;
848
849    fn get_hash(v: &impl Hash) -> u64 {
850        use std::hash::Hasher;
851        let mut hasher = std::hash::DefaultHasher::new();
852        v.hash(&mut hasher);
853        hasher.finish()
854    }
855
856    impl FixedAggregationKey<String> {
857        fn into_key(self) -> OwnedAggregationKey {
858            OwnedAggregationKey {
859                fixed: self,
860                peer_tags: vec![],
861                additional_metric_tags: vec![],
862            }
863        }
864        fn into_key_with_peers(self, peer_tags: Vec<(String, String)>) -> OwnedAggregationKey {
865            OwnedAggregationKey {
866                fixed: self,
867                peer_tags,
868                additional_metric_tags: vec![],
869            }
870        }
871    }
872
873    #[test]
874    fn test_float_to_u32_rejects_malformed_values() {
875        assert_eq!(float_to_u32(0.0), Some(0));
876        assert_eq!(float_to_u32(500.0), Some(500));
877        assert_eq!(float_to_u32(u32::MAX as f64), Some(u32::MAX));
878        assert_eq!(float_to_u32(f64::NAN), None);
879        assert_eq!(float_to_u32(f64::INFINITY), None);
880        assert_eq!(float_to_u32(-1.0), None);
881        assert_eq!(float_to_u32(1.5), None);
882        assert_eq!(float_to_u32((u32::MAX as f64) + 1.0), None);
883    }
884
885    #[test]
886    fn test_aggregation_key_from_span() {
887        let test_cases: Vec<(SpanBytes, OwnedAggregationKey)> = vec![
888            // Root span
889            (
890                SpanBytes {
891                    service: "service".into(),
892                    name: "op".into(),
893                    resource: "res".into(),
894                    span_id: 1,
895                    parent_id: 0,
896                    ..Default::default()
897                },
898                FixedAggregationKey {
899                    service_name: "service".into(),
900                    operation_name: "op".into(),
901                    resource_name: "res".into(),
902                    is_trace_root: pb::Trilean::True,
903                    ..Default::default()
904                }
905                .into_key(),
906            ),
907            // Datadog-key numeric conversion retains its existing cast behavior.
908            (
909                SpanBytes {
910                    service: "service".into(),
911                    name: "op".into(),
912                    resource: "res".into(),
913                    span_id: 1,
914                    parent_id: 0,
915                    meta: vec![("http.response.status_code".into(), "418".into())].into(),
916                    metrics: vec![("http.status_code".into(), f64::NAN)].into(),
917                    ..Default::default()
918                },
919                FixedAggregationKey {
920                    service_name: "service".into(),
921                    operation_name: "op".into(),
922                    resource_name: "res".into(),
923                    is_synthetics_request: false,
924                    is_trace_root: pb::Trilean::True,
925                    http_status_code: 0,
926                    ..Default::default()
927                }
928                .into_key(),
929            ),
930            // The Datadog key keeps its existing u32 behavior and wins over the OTel key.
931            (
932                SpanBytes {
933                    service: "service".into(),
934                    name: "op".into(),
935                    resource: "res".into(),
936                    span_id: 1,
937                    parent_id: 0,
938                    meta: vec![("http.response.status_code".into(), "418".into())].into(),
939                    metrics: vec![("http.status_code".into(), 600.0)].into(),
940                    ..Default::default()
941                },
942                FixedAggregationKey {
943                    service_name: "service".into(),
944                    operation_name: "op".into(),
945                    resource_name: "res".into(),
946                    is_synthetics_request: false,
947                    is_trace_root: pb::Trilean::True,
948                    http_status_code: 600,
949                    ..Default::default()
950                }
951                .into_key(),
952            ),
953            // Datadog-key numeric conversion keeps the existing Rust cast behavior.
954            (
955                SpanBytes {
956                    service: "service".into(),
957                    name: "op".into(),
958                    resource: "res".into(),
959                    span_id: 1,
960                    parent_id: 0,
961                    meta: vec![("http.response.status_code".into(), "418".into())].into(),
962                    metrics: vec![("http.status_code".into(), 1.5)].into(),
963                    ..Default::default()
964                },
965                FixedAggregationKey {
966                    service_name: "service".into(),
967                    operation_name: "op".into(),
968                    resource_name: "res".into(),
969                    is_synthetics_request: false,
970                    is_trace_root: pb::Trilean::True,
971                    http_status_code: 1,
972                    ..Default::default()
973                }
974                .into_key(),
975            ),
976            // The Datadog key also keeps its existing u32 behavior when stored as metadata.
977            (
978                SpanBytes {
979                    service: "service".into(),
980                    name: "op".into(),
981                    resource: "res".into(),
982                    span_id: 1,
983                    parent_id: 0,
984                    meta: vec![("http.status_code".into(), "99".into())].into(),
985                    metrics: vec![("http.response.status_code".into(), 418.0)].into(),
986                    ..Default::default()
987                },
988                FixedAggregationKey {
989                    service_name: "service".into(),
990                    operation_name: "op".into(),
991                    resource_name: "res".into(),
992                    is_synthetics_request: false,
993                    is_trace_root: pb::Trilean::True,
994                    http_status_code: 99,
995                    ..Default::default()
996                }
997                .into_key(),
998            ),
999            // An out-of-range OTel status is not a valid HTTP response status.
1000            (
1001                SpanBytes {
1002                    service: "service".into(),
1003                    name: "op".into(),
1004                    resource: "res".into(),
1005                    span_id: 1,
1006                    parent_id: 0,
1007                    metrics: vec![("http.response.status_code".into(), 600.0)].into(),
1008                    ..Default::default()
1009                },
1010                FixedAggregationKey {
1011                    service_name: "service".into(),
1012                    operation_name: "op".into(),
1013                    resource_name: "res".into(),
1014                    is_synthetics_request: false,
1015                    is_trace_root: pb::Trilean::True,
1016                    http_status_code: 0,
1017                    ..Default::default()
1018                }
1019                .into_key(),
1020            ),
1021            // Span with span kind
1022            (
1023                SpanBytes {
1024                    service: "service".into(),
1025                    name: "op".into(),
1026                    resource: "res".into(),
1027                    span_id: 1,
1028                    parent_id: 0,
1029                    meta: vec![("span.kind".into(), "client".into())].into(),
1030                    ..Default::default()
1031                },
1032                FixedAggregationKey {
1033                    service_name: "service".into(),
1034                    operation_name: "op".into(),
1035                    resource_name: "res".into(),
1036                    span_kind: "client".into(),
1037                    is_trace_root: pb::Trilean::True,
1038                    ..Default::default()
1039                }
1040                .into_key(),
1041            ),
1042            // Span with peer tags but peertags aggregation disabled
1043            (
1044                SpanBytes {
1045                    service: "service".into(),
1046                    name: "op".into(),
1047                    resource: "res".into(),
1048                    span_id: 1,
1049                    parent_id: 0,
1050                    meta: vec![
1051                        ("span.kind".into(), "client".into()),
1052                        ("aws.s3.bucket".into(), "bucket-a".into()),
1053                    ]
1054                    .into(),
1055                    ..Default::default()
1056                },
1057                FixedAggregationKey {
1058                    service_name: "service".into(),
1059                    operation_name: "op".into(),
1060                    resource_name: "res".into(),
1061                    span_kind: "client".into(),
1062                    is_trace_root: pb::Trilean::True,
1063                    ..Default::default()
1064                }
1065                .into_key(),
1066            ),
1067            // Span with multiple peer tags but peertags aggregation disabled
1068            (
1069                SpanBytes {
1070                    service: "service".into(),
1071                    name: "op".into(),
1072                    resource: "res".into(),
1073                    span_id: 1,
1074                    parent_id: 0,
1075                    meta: vec![
1076                        ("span.kind".into(), "producer".into()),
1077                        ("aws.s3.bucket".into(), "bucket-a".into()),
1078                        ("db.instance".into(), "dynamo.test.us1".into()),
1079                        ("db.system".into(), "dynamodb".into()),
1080                    ]
1081                    .into(),
1082                    ..Default::default()
1083                },
1084                FixedAggregationKey {
1085                    service_name: "service".into(),
1086                    operation_name: "op".into(),
1087                    resource_name: "res".into(),
1088                    span_kind: "producer".into(),
1089                    is_trace_root: pb::Trilean::True,
1090                    ..Default::default()
1091                }
1092                .into_key(),
1093            ),
1094            // Span with multiple peer tags but peertags aggregation disabled and span kind is
1095            // server
1096            (
1097                SpanBytes {
1098                    service: "service".into(),
1099                    name: "op".into(),
1100                    resource: "res".into(),
1101                    span_id: 1,
1102                    parent_id: 0,
1103                    meta: vec![
1104                        ("span.kind".into(), "server".into()),
1105                        ("aws.s3.bucket".into(), "bucket-a".into()),
1106                        ("db.instance".into(), "dynamo.test.us1".into()),
1107                        ("db.system".into(), "dynamodb".into()),
1108                    ]
1109                    .into(),
1110                    ..Default::default()
1111                },
1112                FixedAggregationKey {
1113                    service_name: "service".into(),
1114                    operation_name: "op".into(),
1115                    resource_name: "res".into(),
1116                    span_kind: "server".into(),
1117                    is_trace_root: pb::Trilean::True,
1118                    ..Default::default()
1119                }
1120                .into_key(),
1121            ),
1122            // Span from synthetics
1123            (
1124                SpanBytes {
1125                    service: "service".into(),
1126                    name: "op".into(),
1127                    resource: "res".into(),
1128                    span_id: 1,
1129                    parent_id: 0,
1130                    meta: vec![("_dd.origin".into(), "synthetics-browser".into())].into(),
1131                    ..Default::default()
1132                },
1133                FixedAggregationKey {
1134                    service_name: "service".into(),
1135                    operation_name: "op".into(),
1136                    resource_name: "res".into(),
1137                    is_synthetics_request: true,
1138                    is_trace_root: pb::Trilean::True,
1139                    ..Default::default()
1140                }
1141                .into_key(),
1142            ),
1143            // Span with status code in meta
1144            (
1145                SpanBytes {
1146                    service: "service".into(),
1147                    name: "op".into(),
1148                    resource: "res".into(),
1149                    span_id: 1,
1150                    parent_id: 0,
1151                    meta: vec![("http.status_code".into(), "418".into())].into(),
1152                    ..Default::default()
1153                },
1154                FixedAggregationKey {
1155                    service_name: "service".into(),
1156                    operation_name: "op".into(),
1157                    resource_name: "res".into(),
1158                    is_synthetics_request: false,
1159                    is_trace_root: pb::Trilean::True,
1160                    http_status_code: 418,
1161                    ..Default::default()
1162                }
1163                .into_key(),
1164            ),
1165            // Span with invalid status code in meta
1166            (
1167                SpanBytes {
1168                    service: "service".into(),
1169                    name: "op".into(),
1170                    resource: "res".into(),
1171                    span_id: 1,
1172                    parent_id: 0,
1173                    meta: vec![("http.status_code".into(), "x".into())].into(),
1174                    ..Default::default()
1175                },
1176                FixedAggregationKey {
1177                    service_name: "service".into(),
1178                    operation_name: "op".into(),
1179                    resource_name: "res".into(),
1180                    is_synthetics_request: false,
1181                    is_trace_root: pb::Trilean::True,
1182                    ..Default::default()
1183                }
1184                .into_key(),
1185            ),
1186            // Span with status code in metrics
1187            (
1188                SpanBytes {
1189                    service: "service".into(),
1190                    name: "op".into(),
1191                    resource: "res".into(),
1192                    span_id: 1,
1193                    parent_id: 0,
1194                    metrics: vec![("http.status_code".into(), 418.0)].into(),
1195                    ..Default::default()
1196                },
1197                FixedAggregationKey {
1198                    service_name: "service".into(),
1199                    operation_name: "op".into(),
1200                    resource_name: "res".into(),
1201                    is_synthetics_request: false,
1202                    is_trace_root: pb::Trilean::True,
1203                    http_status_code: 418,
1204                    ..Default::default()
1205                }
1206                .into_key(),
1207            ),
1208            // Span in OTel semantics mode: status code in metrics under the OTel name, which is
1209            // where the int-typed OTel attribute lands
1210            (
1211                SpanBytes {
1212                    service: "service".into(),
1213                    name: "op".into(),
1214                    resource: "res".into(),
1215                    span_id: 1,
1216                    parent_id: 0,
1217                    metrics: vec![("http.response.status_code".into(), 418.0)].into(),
1218                    ..Default::default()
1219                },
1220                FixedAggregationKey {
1221                    service_name: "service".into(),
1222                    operation_name: "op".into(),
1223                    resource_name: "res".into(),
1224                    is_synthetics_request: false,
1225                    is_trace_root: pb::Trilean::True,
1226                    http_status_code: 418,
1227                    ..Default::default()
1228                }
1229                .into_key(),
1230            ),
1231            // Span in OTel semantics mode: status code in meta under the OTel name, which is
1232            // where it lands whenever the tracer stringifies its attributes
1233            (
1234                SpanBytes {
1235                    service: "service".into(),
1236                    name: "op".into(),
1237                    resource: "res".into(),
1238                    span_id: 1,
1239                    parent_id: 0,
1240                    meta: vec![("http.response.status_code".into(), "418".into())].into(),
1241                    ..Default::default()
1242                },
1243                FixedAggregationKey {
1244                    service_name: "service".into(),
1245                    operation_name: "op".into(),
1246                    resource_name: "res".into(),
1247                    is_synthetics_request: false,
1248                    is_trace_root: pb::Trilean::True,
1249                    http_status_code: 418,
1250                    ..Default::default()
1251                }
1252                .into_key(),
1253            ),
1254            // Datadog name in meta, OTel name in metrics: the Datadog name still wins, so the
1255            // metrics-before-meta order inside one name never leaks across names
1256            (
1257                SpanBytes {
1258                    service: "service".into(),
1259                    name: "op".into(),
1260                    resource: "res".into(),
1261                    span_id: 1,
1262                    parent_id: 0,
1263                    meta: vec![("http.status_code".into(), "500".into())].into(),
1264                    metrics: vec![("http.response.status_code".into(), 418.0)].into(),
1265                    ..Default::default()
1266                },
1267                FixedAggregationKey {
1268                    service_name: "service".into(),
1269                    operation_name: "op".into(),
1270                    resource_name: "res".into(),
1271                    is_synthetics_request: false,
1272                    is_trace_root: pb::Trilean::True,
1273                    http_status_code: 500,
1274                    ..Default::default()
1275                }
1276                .into_key(),
1277            ),
1278            // An unparseable Datadog status retains its existing parse-or-zero behavior.
1279            (
1280                SpanBytes {
1281                    service: "service".into(),
1282                    name: "op".into(),
1283                    resource: "res".into(),
1284                    span_id: 1,
1285                    parent_id: 0,
1286                    meta: vec![
1287                        ("http.status_code".into(), "x".into()),
1288                        ("http.response.status_code".into(), "418".into()),
1289                    ]
1290                    .into(),
1291                    ..Default::default()
1292                },
1293                FixedAggregationKey {
1294                    service_name: "service".into(),
1295                    operation_name: "op".into(),
1296                    resource_name: "res".into(),
1297                    is_synthetics_request: false,
1298                    is_trace_root: pb::Trilean::True,
1299                    http_status_code: 0,
1300                    ..Default::default()
1301                }
1302                .into_key(),
1303            ),
1304            // Datadog metrics retain their existing precedence and cast behavior.
1305            (
1306                SpanBytes {
1307                    service: "service".into(),
1308                    name: "op".into(),
1309                    resource: "res".into(),
1310                    span_id: 1,
1311                    parent_id: 0,
1312                    meta: vec![("http.status_code".into(), "500".into())].into(),
1313                    metrics: vec![("http.status_code".into(), f64::NAN)].into(),
1314                    ..Default::default()
1315                },
1316                FixedAggregationKey {
1317                    service_name: "service".into(),
1318                    operation_name: "op".into(),
1319                    resource_name: "res".into(),
1320                    is_synthetics_request: false,
1321                    is_trace_root: pb::Trilean::True,
1322                    http_status_code: 0,
1323                    ..Default::default()
1324                }
1325                .into_key(),
1326            ),
1327            // An empty Datadog method counts as absent, so it cannot shadow the OTel name
1328            (
1329                SpanBytes {
1330                    service: "service".into(),
1331                    name: "op".into(),
1332                    resource: "res".into(),
1333                    span_id: 1,
1334                    parent_id: 0,
1335                    meta: vec![
1336                        ("http.method".into(), "".into()),
1337                        ("http.request.method".into(), "GET".into()),
1338                    ]
1339                    .into(),
1340                    ..Default::default()
1341                },
1342                FixedAggregationKey {
1343                    service_name: "service".into(),
1344                    operation_name: "op".into(),
1345                    resource_name: "res".into(),
1346                    is_synthetics_request: false,
1347                    is_trace_root: pb::Trilean::True,
1348                    http_method: "GET".into(),
1349                    ..Default::default()
1350                }
1351                .into_key(),
1352            ),
1353            // Both names present: the canonical Datadog names win.
1354            (
1355                SpanBytes {
1356                    service: "service".into(),
1357                    name: "op".into(),
1358                    resource: "res".into(),
1359                    span_id: 1,
1360                    parent_id: 0,
1361                    meta: vec![
1362                        ("http.status_code".into(), "500".into()),
1363                        ("http.response.status_code".into(), "418".into()),
1364                        ("http.method".into(), "GET".into()),
1365                        ("http.request.method".into(), "POST".into()),
1366                    ]
1367                    .into(),
1368                    ..Default::default()
1369                },
1370                FixedAggregationKey {
1371                    service_name: "service".into(),
1372                    operation_name: "op".into(),
1373                    resource_name: "res".into(),
1374                    is_synthetics_request: false,
1375                    is_trace_root: pb::Trilean::True,
1376                    http_status_code: 500,
1377                    http_method: "GET".into(),
1378                    ..Default::default()
1379                }
1380                .into_key(),
1381            ),
1382            // Span in OTel semantics mode: method under the OTel name, route unchanged because
1383            // http.route is already the OTel name
1384            (
1385                SpanBytes {
1386                    service: "service".into(),
1387                    name: "op".into(),
1388                    resource: "GET /api/v1/users".into(),
1389                    span_id: 1,
1390                    parent_id: 0,
1391                    meta: vec![
1392                        ("http.request.method".into(), "GET".into()),
1393                        ("http.route".into(), "/api/v1/users".into()),
1394                    ]
1395                    .into(),
1396                    ..Default::default()
1397                },
1398                FixedAggregationKey {
1399                    service_name: "service".into(),
1400                    operation_name: "op".into(),
1401                    resource_name: "GET /api/v1/users".into(),
1402                    is_synthetics_request: false,
1403                    is_trace_root: pb::Trilean::True,
1404                    http_method: "GET".into(),
1405                    http_endpoint: "/api/v1/users".into(),
1406                    ..Default::default()
1407                }
1408                .into_key(),
1409            ),
1410            // Span with http.method and http.route
1411            (
1412                SpanBytes {
1413                    service: "service".into(),
1414                    name: "op".into(),
1415                    resource: "GET /api/v1/users".into(),
1416                    span_id: 1,
1417                    parent_id: 0,
1418                    meta: vec![
1419                        ("http.method".into(), "GET".into()),
1420                        ("http.route".into(), "/api/v1/users".into()),
1421                    ]
1422                    .into(),
1423                    ..Default::default()
1424                },
1425                FixedAggregationKey {
1426                    service_name: "service".into(),
1427                    operation_name: "op".into(),
1428                    resource_name: "GET /api/v1/users".into(),
1429                    http_method: "GET".into(),
1430                    http_endpoint: "/api/v1/users".into(),
1431                    is_synthetics_request: false,
1432                    is_trace_root: pb::Trilean::True,
1433                    ..Default::default()
1434                }
1435                .into_key(),
1436            ),
1437            // Span with http.route and http.endpoint (http.endpoint takes precedence)
1438            (
1439                SpanBytes {
1440                    service: "service".into(),
1441                    name: "op".into(),
1442                    resource: "POST /users/create".into(),
1443                    span_id: 1,
1444                    parent_id: 0,
1445                    meta: vec![
1446                        ("http.method".into(), "POST".into()),
1447                        ("http.route".into(), "/users/create1".into()),
1448                        ("http.endpoint".into(), "/users/create2".into()),
1449                    ]
1450                    .into(),
1451                    ..Default::default()
1452                },
1453                FixedAggregationKey {
1454                    service_name: "service".into(),
1455                    operation_name: "op".into(),
1456                    resource_name: "POST /users/create".into(),
1457                    http_method: "POST".into(),
1458                    http_endpoint: "/users/create2".into(),
1459                    is_synthetics_request: false,
1460                    is_trace_root: pb::Trilean::True,
1461                    ..Default::default()
1462                }
1463                .into_key(),
1464            ),
1465            // Span with empty http.endpoint and http.route (fallback to http.route)
1466            (
1467                SpanBytes {
1468                    service: "service".into(),
1469                    name: "op".into(),
1470                    resource: "POST /users/create".into(),
1471                    span_id: 1,
1472                    parent_id: 0,
1473                    meta: vec![
1474                        ("http.method".into(), "POST".into()),
1475                        ("http.route".into(), "/users/create1".into()),
1476                        ("http.endpoint".into(), "".into()),
1477                    ]
1478                    .into(),
1479                    ..Default::default()
1480                },
1481                FixedAggregationKey {
1482                    service_name: "service".into(),
1483                    operation_name: "op".into(),
1484                    resource_name: "POST /users/create".into(),
1485                    http_method: "POST".into(),
1486                    http_endpoint: "/users/create1".into(),
1487                    is_synthetics_request: false,
1488                    is_trace_root: pb::Trilean::True,
1489                    ..Default::default()
1490                }
1491                .into_key(),
1492            ),
1493            // Span with grpc status from meta as named string
1494            (
1495                SpanBytes {
1496                    meta: vec![("rpc.grpc.status_code".into(), "OK".into())].into(),
1497                    ..Default::default()
1498                },
1499                FixedAggregationKey {
1500                    grpc_status_code: Some(0),
1501                    is_trace_root: pb::Trilean::True,
1502                    ..Default::default()
1503                }
1504                .into_key(),
1505            ),
1506            // grpc.method.name is carried in GroupedStats (for OTLP), not in the aggregation key.
1507            (
1508                SpanBytes {
1509                    meta: vec![("grpc.method.name".into(), "/pkg.Svc/Method".into())].into(),
1510                    ..Default::default()
1511                },
1512                FixedAggregationKey {
1513                    is_trace_root: pb::Trilean::True,
1514                    ..Default::default()
1515                }
1516                .into_key(),
1517            ),
1518            // Span with grpc status from meta as numeric string
1519            (
1520                SpanBytes {
1521                    meta: vec![("rpc.grpc.status_code".into(), "14".into())].into(),
1522                    ..Default::default()
1523                },
1524                FixedAggregationKey {
1525                    grpc_status_code: Some(14),
1526                    is_trace_root: pb::Trilean::True,
1527                    ..Default::default()
1528                }
1529                .into_key(),
1530            ),
1531            // Span with grpc status from meta with StatusCode. prefix
1532            (
1533                SpanBytes {
1534                    meta: vec![("grpc.code".into(), "StatusCode.UNAVAILABLE".into())].into(),
1535                    ..Default::default()
1536                },
1537                FixedAggregationKey {
1538                    grpc_status_code: Some(14),
1539                    is_trace_root: pb::Trilean::True,
1540                    ..Default::default()
1541                }
1542                .into_key(),
1543            ),
1544            // Span with grpc status from metrics takes precedence over meta
1545            (
1546                SpanBytes {
1547                    meta: vec![("rpc.grpc.status_code".into(), "PERMISSION_DENIED".into())].into(),
1548                    metrics: vec![("rpc.grpc.status_code".into(), 2.0)].into(),
1549                    ..Default::default()
1550                },
1551                FixedAggregationKey {
1552                    grpc_status_code: Some(7),
1553                    is_trace_root: pb::Trilean::True,
1554                    ..Default::default()
1555                }
1556                .into_key(),
1557            ),
1558            // Span with grpc status from metrics via secondary key
1559            (
1560                SpanBytes {
1561                    metrics: vec![("grpc.code".into(), 3.0)].into(),
1562                    ..Default::default()
1563                },
1564                FixedAggregationKey {
1565                    grpc_status_code: Some(3),
1566                    is_trace_root: pb::Trilean::True,
1567                    ..Default::default()
1568                }
1569                .into_key(),
1570            ),
1571            // Span with invalid grpc status string
1572            (
1573                SpanBytes {
1574                    meta: vec![("rpc.grpc.status_code".into(), "NOPE".into())].into(),
1575                    ..Default::default()
1576                },
1577                FixedAggregationKey {
1578                    is_trace_root: pb::Trilean::True,
1579                    ..Default::default()
1580                }
1581                .into_key(),
1582            ),
1583            // Span with service source set by integration
1584            (
1585                SpanBytes {
1586                    service: "my-service".into(),
1587                    name: "op".into(),
1588                    resource: "res".into(),
1589                    span_id: 1,
1590                    parent_id: 0,
1591                    meta: vec![("_dd.svc_src".into(), "redis".into())].into(),
1592                    ..Default::default()
1593                },
1594                FixedAggregationKey {
1595                    service_name: "my-service".into(),
1596                    operation_name: "op".into(),
1597                    resource_name: "res".into(),
1598                    is_trace_root: pb::Trilean::True,
1599                    service_source: "redis".into(),
1600                    ..Default::default()
1601                }
1602                .into_key(),
1603            ),
1604            // Span with service source set by configuration option
1605            (
1606                SpanBytes {
1607                    service: "my-service".into(),
1608                    name: "op".into(),
1609                    resource: "res".into(),
1610                    span_id: 1,
1611                    parent_id: 0,
1612                    meta: vec![("_dd.svc_src".into(), "opt.split_by_tag".into())].into(),
1613                    ..Default::default()
1614                },
1615                FixedAggregationKey {
1616                    service_name: "my-service".into(),
1617                    operation_name: "op".into(),
1618                    resource_name: "res".into(),
1619                    is_trace_root: pb::Trilean::True,
1620                    service_source: "opt.split_by_tag".into(),
1621                    ..Default::default()
1622                }
1623                .into_key(),
1624            ),
1625            // Span without service source (default service name)
1626            (
1627                SpanBytes {
1628                    service: "my-service".into(),
1629                    name: "op".into(),
1630                    resource: "res".into(),
1631                    span_id: 1,
1632                    parent_id: 0,
1633                    ..Default::default()
1634                },
1635                FixedAggregationKey {
1636                    service_name: "my-service".into(),
1637                    operation_name: "op".into(),
1638                    resource_name: "res".into(),
1639                    is_trace_root: pb::Trilean::True,
1640                    service_source: "".into(),
1641                    ..Default::default()
1642                }
1643                .into_key(),
1644            ),
1645        ];
1646
1647        let test_peer_tags = vec![
1648            "aws.s3.bucket".to_string(),
1649            "db.instance".to_string(),
1650            "db.system".to_string(),
1651        ];
1652
1653        let test_cases_with_peer_tags: Vec<(SpanSlice, OwnedAggregationKey)> = vec![
1654            // Span with peer tags with peertags aggregation enabled
1655            (
1656                SpanSlice {
1657                    service: Cow::Borrowed("service"),
1658                    name: Cow::Borrowed("op"),
1659                    resource: Cow::Borrowed("res"),
1660                    span_id: 1,
1661                    parent_id: 0,
1662                    meta: vec![
1663                        (Cow::Borrowed("span.kind"), Cow::Borrowed("client")),
1664                        (Cow::Borrowed("aws.s3.bucket"), Cow::Borrowed("bucket-a")),
1665                    ]
1666                    .into(),
1667                    ..Default::default()
1668                },
1669                FixedAggregationKey {
1670                    service_name: "service".into(),
1671                    operation_name: "op".into(),
1672                    resource_name: "res".into(),
1673                    span_kind: "client".into(),
1674                    is_trace_root: pb::Trilean::True,
1675                    ..Default::default()
1676                }
1677                .into_key_with_peers(vec![("aws.s3.bucket".into(), "bucket-a".into())]),
1678            ),
1679            // Span with multiple peer tags with peertags aggregation enabled
1680            (
1681                SpanSlice {
1682                    service: Cow::Borrowed("service"),
1683                    name: Cow::Borrowed("op"),
1684                    resource: Cow::Borrowed("res"),
1685                    span_id: 1,
1686                    parent_id: 0,
1687                    meta: vec![
1688                        (Cow::Borrowed("span.kind"), Cow::Borrowed("producer")),
1689                        (Cow::Borrowed("aws.s3.bucket"), Cow::Borrowed("bucket-a")),
1690                        (
1691                            Cow::Borrowed("db.instance"),
1692                            Cow::Borrowed("dynamo.test.us1"),
1693                        ),
1694                        (Cow::Borrowed("db.system"), Cow::Borrowed("dynamodb")),
1695                    ]
1696                    .into(),
1697                    ..Default::default()
1698                },
1699                FixedAggregationKey {
1700                    service_name: "service".into(),
1701                    operation_name: "op".into(),
1702                    resource_name: "res".into(),
1703                    span_kind: "producer".into(),
1704                    is_trace_root: pb::Trilean::True,
1705                    ..Default::default()
1706                }
1707                .into_key_with_peers(vec![
1708                    ("aws.s3.bucket".into(), "bucket-a".into()),
1709                    ("db.instance".into(), "dynamo.test.us1".into()),
1710                    ("db.system".into(), "dynamodb".into()),
1711                ]),
1712            ),
1713            // Span with multiple peer tags with peertags aggregation enabled and span kind is
1714            // server
1715            (
1716                SpanSlice {
1717                    service: Cow::Borrowed("service"),
1718                    name: Cow::Borrowed("op"),
1719                    resource: Cow::Borrowed("res"),
1720                    span_id: 1,
1721                    parent_id: 0,
1722                    meta: vec![
1723                        (Cow::Borrowed("span.kind"), Cow::Borrowed("server")),
1724                        (Cow::Borrowed("aws.s3.bucket"), Cow::Borrowed("bucket-a")),
1725                        (
1726                            Cow::Borrowed("db.instance"),
1727                            Cow::Borrowed("dynamo.test.us1"),
1728                        ),
1729                        (Cow::Borrowed("db.system"), Cow::Borrowed("dynamodb")),
1730                    ]
1731                    .into(),
1732                    ..Default::default()
1733                },
1734                FixedAggregationKey {
1735                    service_name: "service".into(),
1736                    operation_name: "op".into(),
1737                    resource_name: "res".into(),
1738                    span_kind: "server".into(),
1739                    is_trace_root: pb::Trilean::True,
1740                    ..Default::default()
1741                }
1742                .into_key(),
1743            ),
1744        ];
1745
1746        for (span, expected_key) in test_cases {
1747            let borrowed_key = BorrowedAggregationKey::from_span(&span, &[], &[]);
1748            assert_eq!(
1749                OwnedAggregationKey::from(&borrowed_key),
1750                expected_key,
1751                "for span {span:?}"
1752            );
1753            assert_eq!(
1754                get_hash(&borrowed_key),
1755                get_hash(&OwnedAggregationKey::from(&borrowed_key))
1756            );
1757        }
1758
1759        for (span, expected_key) in test_cases_with_peer_tags {
1760            let borrowed_key =
1761                BorrowedAggregationKey::from_span(&span, test_peer_tags.as_slice(), &[]);
1762            assert_eq!(OwnedAggregationKey::from(&borrowed_key), expected_key);
1763            assert_eq!(
1764                get_hash(&borrowed_key),
1765                get_hash(&OwnedAggregationKey::from(&borrowed_key))
1766            );
1767        }
1768    }
1769
1770    /// Table-driven regression test for peer-tag selection in the aggregation key, mirroring
1771    /// the Go trace-agent's `peerTagKeysToAggregateForSpan`:
1772    /// - an empty configured key list suppresses all peer tags, including _dd.base_service;
1773    /// - client/producer/consumer spans use the configured keys;
1774    /// - spans with an absent, empty, or internal kind and a non-empty _dd.base_service use only
1775    ///   _dd.base_service;
1776    /// - server and unknown kinds get no peer tags, even when _dd.base_service is configured.
1777    #[test]
1778    fn test_base_service_peer_tag_selection_in_aggregation_key() {
1779        // (span.kind (None = absent), _dd.base_service (None = absent), configured
1780        // peer_tag_keys, extra meta, expected peer tags, expected stored span kind)
1781        type PeerTagSelectionCase = (
1782            Option<&'static str>,
1783            Option<&'static str>,
1784            Vec<&'static str>,
1785            Vec<(&'static str, &'static str)>,
1786            Vec<(&'static str, &'static str)>,
1787            &'static str,
1788        );
1789        let test_cases: Vec<PeerTagSelectionCase> = vec![
1790            // Absent kind with a non-empty base service: fallback applies.
1791            (
1792                None,
1793                Some("svc-a"),
1794                vec!["db.instance"],
1795                vec![("db.instance", "i-1")],
1796                vec![("_dd.base_service", "svc-a")],
1797                "",
1798            ),
1799            // Explicitly empty kind behaves like an absent kind.
1800            (
1801                Some(""),
1802                Some("svc-a"),
1803                vec!["db.instance"],
1804                vec![],
1805                vec![("_dd.base_service", "svc-a")],
1806                "",
1807            ),
1808            // Internal kind: only _dd.base_service, the other configured key is ignored.
1809            (
1810                Some("internal"),
1811                Some("svc-a"),
1812                vec!["db.instance"],
1813                vec![("db.instance", "i-1")],
1814                vec![("_dd.base_service", "svc-a")],
1815                "internal",
1816            ),
1817            // Mixed-case internal kind is selected case-insensitively but stored as-is.
1818            (
1819                Some("InTeRnAl"),
1820                Some("svc-a"),
1821                vec!["db.instance"],
1822                vec![("db.instance", "i-1")],
1823                vec![("_dd.base_service", "svc-a")],
1824                "InTeRnAl",
1825            ),
1826            // Empty base-service value does not trigger the fallback.
1827            (
1828                Some("internal"),
1829                Some(""),
1830                vec!["db.instance"],
1831                vec![],
1832                vec![],
1833                "internal",
1834            ),
1835            // Missing base service does not trigger the fallback.
1836            (
1837                Some("internal"),
1838                None,
1839                vec!["db.instance"],
1840                vec![],
1841                vec![],
1842                "internal",
1843            ),
1844            // Server kind never gets peer tags, even with a base service and configured keys
1845            // including _dd.base_service itself.
1846            (
1847                Some("server"),
1848                Some("svc-a"),
1849                vec!["db.instance", "_dd.base_service"],
1850                vec![("db.instance", "i-1")],
1851                vec![],
1852                "server",
1853            ),
1854            // Unknown kind never gets peer tags either.
1855            (
1856                Some("gateway"),
1857                Some("svc-a"),
1858                vec!["db.instance", "_dd.base_service"],
1859                vec![],
1860                vec![],
1861                "gateway",
1862            ),
1863            // An empty configured key list suppresses the base-service fallback.
1864            (
1865                Some("internal"),
1866                Some("svc-a"),
1867                vec![],
1868                vec![],
1869                vec![],
1870                "internal",
1871            ),
1872            // ...and also suppresses the client extraction.
1873            (
1874                Some("client"),
1875                Some("svc-a"),
1876                vec![],
1877                vec![("aws.s3.bucket", "bucket-a")],
1878                vec![],
1879                "client",
1880            ),
1881            // Client span with _dd.base_service itself configured: extracted via the
1882            // configured keys, in configured order.
1883            (
1884                Some("client"),
1885                Some("svc-a"),
1886                vec!["db.instance", "_dd.base_service"],
1887                vec![("db.instance", "i-1")],
1888                vec![("db.instance", "i-1"), ("_dd.base_service", "svc-a")],
1889                "client",
1890            ),
1891            // Same for producer and consumer.
1892            (
1893                Some("producer"),
1894                Some("svc-a"),
1895                vec!["_dd.base_service"],
1896                vec![],
1897                vec![("_dd.base_service", "svc-a")],
1898                "producer",
1899            ),
1900            (
1901                Some("consumer"),
1902                Some("svc-a"),
1903                vec!["_dd.base_service"],
1904                vec![],
1905                vec![("_dd.base_service", "svc-a")],
1906                "consumer",
1907            ),
1908            // Internal span with _dd.base_service configured: the fallback still uses only
1909            // _dd.base_service.
1910            (
1911                Some("internal"),
1912                Some("svc-a"),
1913                vec!["db.instance", "_dd.base_service"],
1914                vec![("db.instance", "i-1")],
1915                vec![("_dd.base_service", "svc-a")],
1916                "internal",
1917            ),
1918            // Mixed-case client kind is selected case-insensitively but stored as-is.
1919            (
1920                Some("CLIENT"),
1921                Some("svc-a"),
1922                vec!["db.instance"],
1923                vec![("db.instance", "i-1")],
1924                vec![("db.instance", "i-1")],
1925                "CLIENT",
1926            ),
1927        ];
1928
1929        for (
1930            case_index,
1931            (kind, base_service, peer_tag_keys, extra_meta, expected_peer_tags, expected_kind),
1932        ) in test_cases.into_iter().enumerate()
1933        {
1934            let mut meta: Vec<(&str, &str)> = Vec::new();
1935            if let Some(kind) = kind {
1936                meta.push(("span.kind", kind));
1937            }
1938            if let Some(base_service) = base_service {
1939                meta.push(("_dd.base_service", base_service));
1940            }
1941            meta.extend(extra_meta);
1942            let span = SpanSlice {
1943                service: Cow::Borrowed("service"),
1944                name: Cow::Borrowed("op"),
1945                resource: Cow::Borrowed("res"),
1946                span_id: 1,
1947                parent_id: 0,
1948                meta: meta
1949                    .into_iter()
1950                    .map(|(k, v)| (Cow::Borrowed(k), Cow::Borrowed(v)))
1951                    .collect::<Vec<_>>()
1952                    .into(),
1953                ..Default::default()
1954            };
1955            let peer_tag_keys: Vec<String> =
1956                peer_tag_keys.iter().map(|key| key.to_string()).collect();
1957            let borrowed_key = BorrowedAggregationKey::from_span(&span, &peer_tag_keys, &[]);
1958            let owned_key = OwnedAggregationKey::from(&borrowed_key);
1959            let expected: Vec<(String, String)> = expected_peer_tags
1960                .into_iter()
1961                .map(|(k, v)| (k.to_string(), v.to_string()))
1962                .collect();
1963            assert_eq!(
1964                owned_key.peer_tags, expected,
1965                "unexpected peer tags for case {case_index}"
1966            );
1967            assert_eq!(
1968                owned_key.fixed.span_kind, expected_kind,
1969                "span kind must be stored with its original casing for case {case_index}"
1970            );
1971            assert_eq!(
1972                get_hash(&borrowed_key),
1973                get_hash(&owned_key),
1974                "borrowed/owned hash mismatch for case {case_index}"
1975            );
1976        }
1977    }
1978
1979    #[test]
1980    fn test_peer_tag_ip_quantization_in_aggregation_key() {
1981        let peer_tag_keys = vec!["peer.hostname".to_string(), "db.instance".to_string()];
1982
1983        // IPv4 address peer tag gets replaced with blocked-ip-address
1984        let span_ipv4 = SpanSlice {
1985            service: Cow::Borrowed("service"),
1986            name: Cow::Borrowed("op"),
1987            resource: Cow::Borrowed("res"),
1988            span_id: 1,
1989            parent_id: 0,
1990            meta: vec![
1991                (Cow::Borrowed("span.kind"), Cow::Borrowed("client")),
1992                (Cow::Borrowed("peer.hostname"), Cow::Borrowed("10.1.2.3")),
1993                (Cow::Borrowed("db.instance"), Cow::Borrowed("my-db")),
1994            ]
1995            .into(),
1996            ..Default::default()
1997        };
1998        let key = BorrowedAggregationKey::from_span(&span_ipv4, &peer_tag_keys, &[]);
1999        let owned = OwnedAggregationKey::from(&key);
2000        assert_eq!(
2001            owned.peer_tags,
2002            vec![
2003                (
2004                    "peer.hostname".to_string(),
2005                    "blocked-ip-address".to_string()
2006                ),
2007                ("db.instance".to_string(), "my-db".to_string()),
2008            ]
2009        );
2010
2011        // IPv6 address peer tag gets replaced with blocked-ip-address
2012        let span_ipv6 = SpanSlice {
2013            service: Cow::Borrowed("service"),
2014            name: Cow::Borrowed("op"),
2015            resource: Cow::Borrowed("res"),
2016            span_id: 1,
2017            parent_id: 0,
2018            meta: vec![
2019                (Cow::Borrowed("span.kind"), Cow::Borrowed("client")),
2020                (
2021                    Cow::Borrowed("peer.hostname"),
2022                    Cow::Borrowed("2001:db8:3333:4444:CCCC:DDDD:EEEE:FFFF"),
2023                ),
2024            ]
2025            .into(),
2026            ..Default::default()
2027        };
2028        let ipv6_keys = vec!["peer.hostname".to_string()];
2029        let key = BorrowedAggregationKey::from_span(&span_ipv6, &ipv6_keys, &[]);
2030        let owned = OwnedAggregationKey::from(&key);
2031        assert_eq!(
2032            owned.peer_tags,
2033            vec![(
2034                "peer.hostname".to_string(),
2035                "blocked-ip-address".to_string()
2036            )]
2037        );
2038
2039        // Non-IP peer tags pass through unchanged
2040        let span_non_ip = SpanSlice {
2041            service: Cow::Borrowed("service"),
2042            name: Cow::Borrowed("op"),
2043            resource: Cow::Borrowed("res"),
2044            span_id: 1,
2045            parent_id: 0,
2046            meta: vec![
2047                (Cow::Borrowed("span.kind"), Cow::Borrowed("client")),
2048                (
2049                    Cow::Borrowed("db.instance"),
2050                    Cow::Borrowed("dynamo.test.us1"),
2051                ),
2052            ]
2053            .into(),
2054            ..Default::default()
2055        };
2056        let non_ip_keys = vec!["db.instance".to_string()];
2057        let key = BorrowedAggregationKey::from_span(&span_non_ip, &non_ip_keys, &[]);
2058        let owned = OwnedAggregationKey::from(&key);
2059        assert_eq!(
2060            owned.peer_tags,
2061            vec![("db.instance".to_string(), "dynamo.test.us1".to_string())]
2062        );
2063    }
2064
2065    #[test]
2066    fn test_grpc_status_str_to_int_value() {
2067        // Numeric strings parse directly
2068        assert_eq!(grpc_status_str_to_int_value("0"), Some(0));
2069        assert_eq!(grpc_status_str_to_int_value("14"), Some(14));
2070        assert_eq!(grpc_status_str_to_int_value("255"), Some(255));
2071        assert_eq!(grpc_status_str_to_int_value("256"), None);
2072        assert_eq!(grpc_status_str_to_int_value("-1"), None);
2073
2074        // Named status codes (uppercase)
2075        assert_eq!(grpc_status_str_to_int_value("OK"), Some(0));
2076        assert_eq!(grpc_status_str_to_int_value("CANCELLED"), Some(1));
2077        assert_eq!(grpc_status_str_to_int_value("UNKNOWN"), Some(2));
2078        assert_eq!(grpc_status_str_to_int_value("INVALID_ARGUMENT"), Some(3));
2079        assert_eq!(grpc_status_str_to_int_value("DEADLINE_EXCEEDED"), Some(4));
2080        assert_eq!(grpc_status_str_to_int_value("NOT_FOUND"), Some(5));
2081        assert_eq!(grpc_status_str_to_int_value("ALREADY_EXISTS"), Some(6));
2082        assert_eq!(grpc_status_str_to_int_value("PERMISSION_DENIED"), Some(7));
2083        assert_eq!(grpc_status_str_to_int_value("UNAUTHENTICATED"), Some(16));
2084        assert_eq!(grpc_status_str_to_int_value("RESOURCE_EXHAUSTED"), Some(8));
2085        assert_eq!(grpc_status_str_to_int_value("FAILED_PRECONDITION"), Some(9));
2086        assert_eq!(grpc_status_str_to_int_value("ABORTED"), Some(10));
2087        assert_eq!(grpc_status_str_to_int_value("OUT_OF_RANGE"), Some(11));
2088        assert_eq!(grpc_status_str_to_int_value("UNIMPLEMENTED"), Some(12));
2089        assert_eq!(grpc_status_str_to_int_value("INTERNAL"), Some(13));
2090        assert_eq!(grpc_status_str_to_int_value("UNAVAILABLE"), Some(14));
2091        assert_eq!(grpc_status_str_to_int_value("DATA_LOSS"), Some(15));
2092
2093        // Case-insensitive matching
2094        assert_eq!(grpc_status_str_to_int_value("ok"), Some(0));
2095        assert_eq!(grpc_status_str_to_int_value("Cancelled"), Some(1));
2096        assert_eq!(grpc_status_str_to_int_value("not_found"), Some(5));
2097
2098        // StatusCode. prefix is stripped
2099        assert_eq!(grpc_status_str_to_int_value("StatusCode.OK"), Some(0));
2100        assert_eq!(
2101            grpc_status_str_to_int_value("StatusCode.UNAVAILABLE"),
2102            Some(14)
2103        );
2104        assert_eq!(
2105            grpc_status_str_to_int_value("StatusCode.not_found"),
2106            Some(5)
2107        );
2108
2109        // Alternate spellings
2110        assert_eq!(grpc_status_str_to_int_value("CANCELED"), Some(1));
2111
2112        // Unknown / empty strings
2113        assert_eq!(grpc_status_str_to_int_value("NOPE"), None);
2114        assert_eq!(grpc_status_str_to_int_value(""), None);
2115        assert_eq!(
2116            grpc_status_str_to_int_value("this_is_a_kinda_long_string_that_needs_upcasing"),
2117            None
2118        );
2119
2120        // Non ascii
2121        assert_eq!(grpc_status_str_to_int_value("🤣"), None);
2122    }
2123}