libdd-trace-stats 8.0.0

This crate provides utilities to compute stats from Datadog traces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

//! This module implement the logic for stats aggregation into time buckets and stats group.
//! This includes the aggregation key to group spans together and the computation of stats from a
//! span.

use hashbrown::{HashMap, HashSet};
use libdd_trace_obfuscation::ip_address::quantize_peer_ip_addresses;
use libdd_trace_protobuf::pb;
use libdd_trace_utils::span::SpanText;
use std::{
    borrow::{Borrow, Cow},
    hash::{DefaultHasher, Hash, Hasher as _},
};
use tracing::warn;

use crate::span_concentrator::{cardinality_limit_telemetry::CollapsedFieldSet, StatSpan};

use super::{
    cardinality_limit_telemetry::{self, CollapsedFieldsMetrics},
    CardinalityLimitConfig,
};

/// Sentinel value used for cardinality limiting.
pub const TRACER_BLOCKED_VALUE: &str = "tracer_blocked_value";

const TAG_STATUS_CODE: &str = "http.status_code";
const ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN: usize = 200;
const TAG_SYNTHETICS: &str = "synthetics";
const TAG_SPANKIND: &str = "span.kind";
const TAG_ORIGIN: &str = "_dd.origin";
const TAG_SVC_SRC: &str = "_dd.svc_src";
const GRPC_STATUS_CODE_FIELD: &[&str] = &[
    "rpc.grpc.status_code",
    "grpc.code",
    "rpc.grpc.status.code",
    "grpc.status.code",
];

/// Aggregation key fields shared across all concentrator implementations — everything
/// **except** peer tags.
///
/// `T` is the string representation:
/// * `&'a str`   — borrowed references used in [`BorrowedAggregationKey`]
/// * `String`    — owned values used in `OwnedAggregationKey`
/// * `StringRef` — offset+len into a SHM string pool, used in `ShmKeyHeader`
#[derive(
    Clone, Default, Hash, Eq, PartialEq, Debug, PartialOrd, serde::Serialize, serde::Deserialize,
)]
pub struct FixedAggregationKey<T> {
    pub resource_name: T,
    pub service_name: T,
    pub operation_name: T,
    pub span_type: T,
    pub span_kind: T,
    pub http_method: T,
    pub http_endpoint: T,
    pub service_source: T,
    pub http_status_code: u32,
    pub grpc_status_code: Option<u8>,
    pub is_synthetics_request: bool,
    pub is_trace_root: pb::Trilean,
}

impl<T> FixedAggregationKey<T> {
    /// Map all string fields through `f`, preserving scalar fields.
    pub fn convert<'a, V: 'a, I: ?Sized + 'a, F: Fn(&'a I) -> V>(
        &'a self,
        f: F,
    ) -> FixedAggregationKey<V>
    where
        T: Borrow<I>,
    {
        FixedAggregationKey {
            resource_name: f(self.resource_name.borrow()),
            service_name: f(self.service_name.borrow()),
            operation_name: f(self.operation_name.borrow()),
            span_type: f(self.span_type.borrow()),
            span_kind: f(self.span_kind.borrow()),
            http_method: f(self.http_method.borrow()),
            http_endpoint: f(self.http_endpoint.borrow()),
            service_source: f(self.service_source.borrow()),
            http_status_code: self.http_status_code,
            grpc_status_code: self.grpc_status_code,
            is_synthetics_request: self.is_synthetics_request,
            is_trace_root: self.is_trace_root,
        }
    }
}

#[derive(Clone, Hash, PartialEq, Eq)]
/// Represent a stats aggregation key borrowed from span data
pub(super) struct BorrowedAggregationKey<'a> {
    fixed: FixedAggregationKey<&'a str>,
    peer_tags: Vec<(&'a str, Cow<'a, str>)>,
    additional_metric_tags: Vec<(&'a str, &'a str)>,
}

impl hashbrown::Equivalent<OwnedAggregationKey> for BorrowedAggregationKey<'_> {
    #[inline]
    fn equivalent(&self, other: &OwnedAggregationKey) -> bool {
        self.fixed == other.fixed.convert(|s| s)
            && self.peer_tags.len() == other.peer_tags.len()
            && self
                .peer_tags
                .iter()
                .zip(other.peer_tags.iter())
                .all(|((k1, v1), (k2, v2))| k1 == k2 && v1 == v2)
            && self.additional_metric_tags.len() == other.additional_metric_tags.len()
            && self
                .additional_metric_tags
                .iter()
                .zip(other.additional_metric_tags.iter())
                .all(|((k1, v1), (k2, v2))| k1 == k2 && v1 == v2)
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Default)]
/// Represents a span aggregation key with owned data
///
/// To be able to use BorrowedAggregationKey to index into a stats bucket hashmap two
/// conditions must stay true:
/// * Hashing an owned key derived from a borrowed key should produce the same hash as hashing the
///   borrowed key
/// * Running the Equivalent trait on an owned key derived from a borrowed key should produce true
pub(super) struct OwnedAggregationKey {
    fixed: FixedAggregationKey<String>,
    peer_tags: Vec<(String, String)>,
    additional_metric_tags: Vec<(String, String)>,
}

impl From<&BorrowedAggregationKey<'_>> for OwnedAggregationKey {
    fn from(value: &BorrowedAggregationKey<'_>) -> Self {
        OwnedAggregationKey {
            fixed: value.fixed.convert(str::to_owned),
            peer_tags: value
                .peer_tags
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            additional_metric_tags: value
                .additional_metric_tags
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        }
    }
}

fn float_to_int(f: f64) -> Option<u8> {
    if f.floor() != f {
        return None;
    }
    if f < 0.0 || (u8::MAX as f64) < f {
        return None;
    }
    Some(f as u8)
}

fn get_grpc_status_code<'a>(span: &'a impl StatSpan<'a>) -> Option<u8> {
    for key in GRPC_STATUS_CODE_FIELD {
        if let Some(val) = span.get_meta(key) {
            if let Some(code) = grpc_status_str_to_int_value(val) {
                return Some(code);
            }
        }
    }

    for key in GRPC_STATUS_CODE_FIELD {
        if let Some(val) = span.get_metrics(key) {
            if let Some(code) = float_to_int(val) {
                return Some(code);
            }
        }
    }

    None
}

fn grpc_status_str_to_int_value(v: &str) -> Option<u8> {
    if let Ok(status) = v.parse() {
        return Some(status);
    }
    let mut status_uppercase = [0u8; 32];
    let mut status = v.trim_start_matches("StatusCode.");

    let mut needs_upcasing = false;
    for b in status.as_bytes() {
        if !b.is_ascii() {
            return None;
        }
        needs_upcasing |= b.is_ascii_lowercase()
    }
    if needs_upcasing {
        for (c, d) in status.as_bytes().iter().zip(&mut status_uppercase) {
            *d = c.to_ascii_uppercase();
        }
        status = std::str::from_utf8(&status_uppercase[0..status.len().min(status_uppercase.len())])
            .ok()?
    }

    match status {
        "OK" => return Some(0),
        "CANCELLED" | "CANCELED" => return Some(1),
        "UNKNOWN" => return Some(2),
        "INVALID_ARGUMENT" | "INVALIDARGUMENT" => return Some(3),
        "DEADLINE_EXCEEDED" | "DEADLINEEXCEEDED" => return Some(4),
        "NOT_FOUND" | "NOTFOUND" => return Some(5),
        "ALREADY_EXISTS" | "ALREADYEXISTS" => return Some(6),
        "PERMISSION_DENIED" | "PERMISSIONDENIED" => return Some(7),
        "UNAUTHENTICATED" => return Some(16),
        "RESOURCE_EXHAUSTED" | "RESOURCEEXHAUSTED" => return Some(8),
        "FAILED_PRECONDITION" | "FAILEDPRECONDITION" => return Some(9),
        "ABORTED" => return Some(10),
        "OUT_OF_RANGE" | "OUTOFRANGE" => return Some(11),
        "UNIMPLEMENTED" => return Some(12),
        "INTERNAL" => return Some(13),
        "UNAVAILABLE" => return Some(14),
        "DATA_LOSS" | "DATALOSS" => return Some(15),
        _ => {}
    }
    None
}

impl<'a> BorrowedAggregationKey<'a> {
    /// Return an AggregationKey matching the given span.
    ///
    /// If `peer_tag_keys` is not empty then the peer tags of the span will be included in the
    /// key.
    /// If `additional_metric_tags` is not empty then matching span tags keys are included in the
    /// key.
    pub(super) fn from_span<T: StatSpan<'a>>(
        span: &'a T,
        peer_tag_keys: &'a [String],
        additional_metric_tag_keys: &'a [String],
    ) -> Self {
        Self::from_obfuscated_span(
            span.resource(),
            span,
            peer_tag_keys,
            additional_metric_tag_keys,
        )
    }

    pub(crate) fn from_obfuscated_span<'b, T>(
        resource_name: &'a str,
        span: &'b T,
        peer_tag_keys: &'b [String],
        additional_metric_tag_keys: &'b [String],
    ) -> BorrowedAggregationKey<'a>
    where
        T: StatSpan<'b>,
        // resource_name is a temporary string on the stack the span will outlive it
        'b: 'a,
    {
        let span_kind = span.get_meta(TAG_SPANKIND).unwrap_or_default();
        let peer_tags = if should_track_peer_tags(span_kind) {
            // Parse the meta tags of the span and return a list of the peer tags based on the list
            // of `peer_tag_keys`. IP address values are quantized to reduce cardinality.
            peer_tag_keys
                .iter()
                .filter_map(|key| {
                    let value = span.get_meta(key.as_str())?;
                    Some((key.as_str(), quantize_peer_ip_addresses(value)))
                })
                .collect()
        } else if let Some(base_service) = span.get_meta("_dd.base_service") {
            // Internal spans with a base service override use only _dd.base_service as peer tag
            vec![("_dd.base_service", Cow::Borrowed(base_service))]
        } else {
            vec![]
        };

        let http_method = span.get_meta("http.method").unwrap_or_default();

        let http_endpoint = span
            .get_meta("http.endpoint")
            .or_else(|| span.get_meta("http.route"))
            .unwrap_or_default();

        let status_code = if let Some(status_code) = span.get_metrics(TAG_STATUS_CODE) {
            status_code as u32
        } else if let Some(status_code) = span.get_meta(TAG_STATUS_CODE) {
            status_code.parse().unwrap_or_default()
        } else {
            0
        };

        let grpc_status_code = get_grpc_status_code(span);
        let service_source = span.get_meta(TAG_SVC_SRC).unwrap_or_default();

        let additional_metric_tags: Vec<(&'a str, &'a str)> = additional_metric_tag_keys
            .iter()
            .filter_map(|key| match span.get_meta(key.as_str()) {
                Some(v) if !v.is_empty() => {
                    // Byte length >= char count, so skip the char walk when byte length alone
                    // is within the max character length, otherwise stop as soon as we pass the max character length.
                    if v.len() > ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN
                        && v.chars().nth(ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN).is_some()
                    {
                        warn!(
                            "additional_metric_tags: value for key '{}' exceeds {} characters; substituting tracer_blocked_value",
                            key, ADDITIONAL_METRIC_TAG_VALUE_MAX_LEN,
                        );
                        Some((key.as_str(), TRACER_BLOCKED_VALUE))
                    } else {
                        Some((key.as_str(), v))
                    }
                }
                _ => None,
            })
            .collect();

        Self {
            fixed: FixedAggregationKey {
                resource_name,
                service_name: span.service(),
                operation_name: span.name(),
                span_type: span.r#type(),
                span_kind,
                http_method,
                http_endpoint,
                service_source,
                http_status_code: status_code,
                grpc_status_code,
                is_synthetics_request: span
                    .get_meta(TAG_ORIGIN)
                    .is_some_and(|origin| origin.starts_with(TAG_SYNTHETICS)),
                is_trace_root: if span.is_trace_root() {
                    pb::Trilean::True
                } else {
                    pb::Trilean::False
                },
            },
            peer_tags,
            additional_metric_tags,
        }
    }

    /// Truncates string fields in accordance with the cardinality limit RFC
    ///
    /// This should be called only after obfuscation
    #[cfg_attr(not(feature = "stats-obfuscation"), allow(unused))]
    pub(crate) fn truncate(&mut self, big_resource: bool) {
        let resource_length_limit = if big_resource { 15_000 } else { 5000 };
        self.fixed.resource_name = slice_up_to(self.fixed.resource_name, resource_length_limit);
        self.fixed.service_name = slice_up_to(self.fixed.service_name, 100);
        self.fixed.operation_name = slice_up_to(self.fixed.operation_name, 100);
        self.fixed.span_type = slice_up_to(self.fixed.span_type, 100);
    }
}

/// Truncate `s` to at most `max_len` bytes
fn slice_up_to(s: &str, max_len: usize) -> &str {
    if max_len >= s.len() {
        return s;
    }
    // TODO: use `floor_char_boundary` once our MSRV is 1.91 or higher
    // (https://doc.rust-lang.org/std/primitive.str.html#method.floor_char_boundary)
    let mut idx = max_len;
    while !s.is_char_boundary(idx) {
        idx -= 1;
    }
    &s[..idx]
}

impl OwnedAggregationKey {
    /// Return the overflow sentinel key.
    pub(super) fn overflow_key() -> Self {
        OwnedAggregationKey {
            fixed: FixedAggregationKey {
                resource_name: TRACER_BLOCKED_VALUE.to_owned(),
                service_name: TRACER_BLOCKED_VALUE.to_owned(),
                operation_name: TRACER_BLOCKED_VALUE.to_owned(),
                span_type: TRACER_BLOCKED_VALUE.to_owned(),
                span_kind: TRACER_BLOCKED_VALUE.to_owned(),
                http_method: TRACER_BLOCKED_VALUE.to_owned(),
                http_endpoint: TRACER_BLOCKED_VALUE.to_owned(),
                service_source: TRACER_BLOCKED_VALUE.to_owned(),
                http_status_code: 0,
                grpc_status_code: None,
                is_synthetics_request: false,
                is_trace_root: pb::Trilean::NotSet,
            },
            peer_tags: vec![(TRACER_BLOCKED_VALUE.to_owned(), "".to_owned())],
            additional_metric_tags: vec![(TRACER_BLOCKED_VALUE.to_owned(), "".to_owned())],
        }
    }
}

impl From<pb::ClientGroupedStats> for OwnedAggregationKey {
    fn from(value: pb::ClientGroupedStats) -> Self {
        Self {
            fixed: FixedAggregationKey {
                resource_name: value.resource,
                service_name: value.service,
                operation_name: value.name,
                span_type: value.r#type,
                span_kind: value.span_kind,
                http_method: value.http_method,
                http_endpoint: value.http_endpoint,
                service_source: value.service_source,
                http_status_code: value.http_status_code,
                grpc_status_code: value.grpc_status_code.parse().ok(),
                is_synthetics_request: value.synthetics,
                is_trace_root: pb::Trilean::try_from(value.is_trace_root)
                    .unwrap_or(pb::Trilean::NotSet),
            },
            peer_tags: value
                .peer_tags
                .into_iter()
                .filter_map(|t| {
                    let (key, value) = t.split_once(':')?;
                    Some((key.to_string(), value.to_string()))
                })
                .collect(),
            additional_metric_tags: value
                .additional_metric_tags
                .into_iter()
                .filter_map(|t| {
                    let (key, value) = t.split_once(':')?;
                    Some((key.to_string(), value.to_string()))
                })
                .collect(),
        }
    }
}

/// Return true if we care about peer tags on the span
fn should_track_peer_tags<T>(span_kind: T) -> bool
where
    T: SpanText,
{
    matches!(
        span_kind.borrow().to_lowercase().as_str(),
        "client" | "producer" | "consumer"
    )
}

/// The stats computed from a group of span with the same AggregationKey
#[derive(Debug, Default, Clone)]
pub(super) struct GroupedStats {
    hits: u64,
    errors: u64,
    duration: u64,
    top_level_hits: u64,
    ok_summary: libdd_ddsketch::DDSketch,
    error_summary: libdd_ddsketch::DDSketch,
    // Exact per-cell (ok/error) scalars used by the OTLP trace-metrics path. These are tracked
    // separately from `duration` so the /v0.6/stats agent payload is byte-for-byte unchanged.
    ok_duration: u64,
    ok_min: u64,
    ok_max: u64,
    error_duration: u64,
    error_min: u64,
    error_max: u64,
}

impl GroupedStats {
    /// Update the stats of a GroupedStats by inserting a span.
    fn insert(&mut self, duration: i64, is_error: bool, is_top_level: bool) {
        self.hits += 1;
        self.duration += duration as u64;
        let d = duration as u64;
        if is_error {
            self.errors += 1;
            let _ = self.error_summary.add(duration as f64);
            self.error_duration += d;
            self.error_min = if self.errors == 1 {
                d
            } else {
                self.error_min.min(d)
            };
            self.error_max = self.error_max.max(d);
        } else {
            let _ = self.ok_summary.add(duration as f64);
            self.ok_duration += d;
            let ok_count = self.hits - self.errors;
            self.ok_min = if ok_count == 1 { d } else { self.ok_min.min(d) };
            self.ok_max = self.ok_max.max(d);
        }
        if is_top_level {
            self.top_level_hits += 1;
        }
    }
}

/// Exact per-cell (ok or error) scalars for one aggregation group, surfaced to the OTLP
/// trace-metrics path. `count` is exact; `duration_ns`/`min_ns`/`max_ns` are exact when
/// `count > 0` and meaningless otherwise (the OTLP mapper suppresses empty cells).
#[derive(Debug, Clone, Copy, Default)]
pub struct OtlpExactCell {
    pub count: u64,
    pub duration_ns: u64,
    pub min_ns: u64,
    pub max_ns: u64,
}

/// Exact OK/ERROR cells for one aggregation group, in the same order as the `stats` vector
/// of the accompanying [`pb::ClientStatsBucket`].
#[derive(Debug, Clone, Default)]
pub struct OtlpExactGroup {
    pub ok: OtlpExactCell,
    pub error: OtlpExactCell,
}

/// A bucket flushed for the OTLP trace-metrics path. `exact[i]` is the exact-scalar sidecar
/// for `bucket.stats[i]`; the protobuf bucket itself is identical to what the agent path uses.
#[derive(Debug, Clone)]
pub struct OtlpStatsBucket {
    pub bucket: pb::ClientStatsBucket,
    pub exact: Vec<OtlpExactGroup>,
}

/// A time bucket used for stats aggregation. It stores a map of GroupedStats storing the stats of
/// spans aggregated on their AggregationKey.
#[derive(Debug, Clone)]
pub(super) struct StatsBucket {
    data: HashMap<OwnedAggregationKey, GroupedStats>,
    start: u64,
    /// Maximum number of distinct aggregation keys this bucket will hold before collapsing new
    /// ones into the overflow sentinel key.
    cardinality_limits: CardinalityLimitConfig,
    // HashSet of hashes of field values so we save memory
    // This is not 100% accurate but the probability of getting collision is close to 0
    // In the very rare case we get a collision, we would get one extra bucket which is totally
    // fine
    distinct_resources: HashSet<u64>,
    distinct_http_endpoints: HashSet<u64>,
    distinct_peer_tags: HashSet<u64>,
    distinct_additional_tags: HashSet<u64>,
    /// Number of spans collapsed into the overflow bucket due to whole-key cardinality limiting.
    collapsed_count: u64,
    collapsed_fields_metrics: CollapsedFieldsMetrics,
    /// Indicates if stats obfuscated in this bucket. This is set once at creation and stays
    /// constant per bucket
    #[cfg(feature = "stats-obfuscation")]
    pub(super) obfuscated: bool,
}

impl StatsBucket {
    /// Return a new StatsBucket starting at `start_timestamp`.
    ///
    /// `cardinality_limits` are the values for whole-key and per-field cardinality limits
    pub(super) fn new(
        start_timestamp: u64,
        cardinality_limits: CardinalityLimitConfig,
        #[cfg(feature = "stats-obfuscation")] obfuscation_enabled: bool,
    ) -> Self {
        Self {
            data: HashMap::new(),
            start: start_timestamp,
            cardinality_limits,
            collapsed_count: 0,
            #[cfg(feature = "stats-obfuscation")]
            obfuscated: obfuscation_enabled,
            distinct_resources: HashSet::new(),
            distinct_http_endpoints: HashSet::new(),
            distinct_peer_tags: HashSet::new(),
            distinct_additional_tags: HashSet::new(),
            collapsed_fields_metrics: cardinality_limit_telemetry::CollapsedFieldsMetrics::zero(),
        }
    }

    /// Returns metrics on spans field collapse with reasons.
    pub fn collapsed_fields_metrics(&self) -> cardinality_limit_telemetry::CollapsedFieldsMetrics {
        self.collapsed_fields_metrics
    }

    /// Return the number of spans collapsed into the overflow bucket.
    pub(super) fn collapsed_count(&self) -> u64 {
        self.collapsed_count
    }

    /// Insert a value as stats in the group corresponding to the aggregation key, if it does not
    /// exist it creates it.
    ///
    /// Keys that already exist in this bucket always merge normally. A new key is subject to the
    /// `max_entries` limit, which collapses it into the overflow sentinel key.
    pub(super) fn insert(
        &mut self,
        mut key: BorrowedAggregationKey<'_>,
        duration: i64,
        is_error: bool,
        is_top_level: bool,
    ) {
        // Per field cardinality limiting
        self.collapse_key_fields_cardinality(&mut key);

        // The map can't change size before the entry below is resolved, so this single read
        // covers the `max_entries` check in the vacant branch without a further lookup.
        let len_before_insert = self.data.len();

        match self.data.entry_ref(&key) {
            // Existing key, merge
            hashbrown::hash_map::EntryRef::Occupied(mut e) => {
                e.get_mut().insert(duration, is_error, is_top_level);
            }
            hashbrown::hash_map::EntryRef::Vacant(e) => {
                // New key over the max entry limit, collapse into the overflow
                // sentinel.
                if len_before_insert >= self.cardinality_limits.whole_key_limit {
                    self.collapsed_count += 1;
                    self.data
                        .entry(OwnedAggregationKey::overflow_key())
                        .or_default()
                        .insert(duration, is_error, is_top_level);
                    return;
                }
                // Within the max entry limit, admit key as a new distinct entry.
                e.insert(GroupedStats::default())
                    .insert(duration, is_error, is_top_level);
            }
        }
    }

    /// Collapse an aggregation key fields following the bucket's `CardinalityLimitConfig`
    fn collapse_key_fields_cardinality(&mut self, key: &mut BorrowedAggregationKey<'_>) {
        use hashbrown::hash_set::Entry;
        fn hash(input: &impl Hash) -> u64 {
            let mut hasher = DefaultHasher::new();
            input.hash(&mut hasher);
            hasher.finish()
        }

        let mut collapsed_fields = CollapsedFieldSet::empty();

        let resource_hash = hash(&key.fixed.resource_name);
        let resources_count = self.distinct_resources.len();
        if let Entry::Vacant(slot) = self.distinct_resources.entry(resource_hash) {
            if resources_count >= self.cardinality_limits.resource_limit {
                key.fixed.resource_name = TRACER_BLOCKED_VALUE;
                collapsed_fields.add(CollapsedFieldSet::RESOURCE_NAME);
            } else {
                slot.insert();
            }
        }

        let http_endpoint_hash = hash(&key.fixed.http_endpoint);
        let http_endpoints_count = self.distinct_http_endpoints.len();
        if let Entry::Vacant(slot) = self.distinct_http_endpoints.entry(http_endpoint_hash) {
            if http_endpoints_count >= self.cardinality_limits.http_endpoint_limit {
                key.fixed.http_endpoint = TRACER_BLOCKED_VALUE;
                collapsed_fields.add(CollapsedFieldSet::HTTP_ENDPOINT);
            } else {
                slot.insert();
            }
        }

        let peer_tags_hash = hash(&key.peer_tags);
        let peer_tags_count = self.distinct_peer_tags.len();
        if let Entry::Vacant(slot) = self.distinct_peer_tags.entry(peer_tags_hash) {
            if peer_tags_count >= self.cardinality_limits.peer_tags_limit {
                key.peer_tags = vec![(TRACER_BLOCKED_VALUE, Cow::Borrowed(""))];
                collapsed_fields.add(CollapsedFieldSet::PEER_TAGS);
            } else {
                slot.insert();
            }
        }

        let additional_tags_hash = hash(&key.additional_metric_tags);
        let additional_tags_count = self.distinct_additional_tags.len();
        if let Entry::Vacant(slot) = self.distinct_additional_tags.entry(additional_tags_hash) {
            if additional_tags_count >= self.cardinality_limits.additional_tags_limit {
                key.additional_metric_tags = vec![(TRACER_BLOCKED_VALUE, "")];
                collapsed_fields.add(CollapsedFieldSet::ADDITIONAL_TAGS);
            } else {
                slot.insert();
            }
        }
        self.collapsed_fields_metrics.increment(collapsed_fields);
    }

    /// Consume the bucket and return a ClientStatsBucket containing the bucket stats.
    /// `bucket_duration` is the size of buckets for the concentrator containing the bucket.
    pub(super) fn flush(self, bucket_duration: u64) -> pb::ClientStatsBucket {
        self.flush_with_otlp_exact(bucket_duration).bucket
    }

    /// Like [`Self::flush`], but additionally produces exact per-cell scalars for the OTLP
    /// trace-metrics path. The `bucket` field is identical to what [`Self::flush`] returns.
    pub(super) fn flush_with_otlp_exact(self, bucket_duration: u64) -> OtlpStatsBucket {
        let mut stats = Vec::with_capacity(self.data.len());
        let mut exact = Vec::with_capacity(self.data.len());
        for (k, g) in self.data {
            exact.push(OtlpExactGroup {
                ok: OtlpExactCell {
                    count: g.hits.saturating_sub(g.errors),
                    duration_ns: g.ok_duration,
                    min_ns: g.ok_min,
                    max_ns: g.ok_max,
                },
                error: OtlpExactCell {
                    count: g.errors,
                    duration_ns: g.error_duration,
                    min_ns: g.error_min,
                    max_ns: g.error_max,
                },
            });
            stats.push(encode_grouped_stats(k, g));
        }
        OtlpStatsBucket {
            bucket: pb::ClientStatsBucket {
                start: self.start,
                duration: bucket_duration,
                stats,
                agent_time_shift: 0,
            },
            exact,
        }
    }
}

/// Create a ClientGroupedStats struct based on the given AggregationKey and GroupedStats
fn encode_grouped_stats(key: OwnedAggregationKey, group: GroupedStats) -> pb::ClientGroupedStats {
    let f = key.fixed;
    pb::ClientGroupedStats {
        service: f.service_name,
        name: f.operation_name,
        resource: f.resource_name,
        http_status_code: f.http_status_code,
        r#type: f.span_type,
        db_type: String::new(), // db_type is not used yet (see proto definition)

        hits: group.hits,
        errors: group.errors,
        duration: group.duration,

        ok_summary: group.ok_summary.encode_to_vec(),
        error_summary: group.error_summary.encode_to_vec(),
        synthetics: f.is_synthetics_request,
        top_level_hits: group.top_level_hits,
        span_kind: f.span_kind,

        peer_tags: key
            .peer_tags
            .into_iter()
            .map(|(k, v)| {
                if v.is_empty() {
                    k.to_string()
                } else {
                    format!("{k}:{v}")
                }
            })
            .collect(),
        is_trace_root: f.is_trace_root.into(),
        http_method: f.http_method,
        http_endpoint: f.http_endpoint,
        grpc_status_code: f
            .grpc_status_code
            .map(|c| c.to_string())
            .unwrap_or_default(),
        service_source: f.service_source,
        span_derived_primary_tags: vec![],
        additional_metric_tags: key
            .additional_metric_tags
            .into_iter()
            .map(|(k, v)| format!("{k}:{v}"))
            .collect(),
    }
}

#[cfg(test)]
mod tests {
    use libdd_trace_utils::span::v04::{SpanBytes, SpanSlice};

    use super::*;
    use libdd_trace_protobuf::pb;
    use std::hash::Hash;

    fn get_hash(v: &impl Hash) -> u64 {
        use std::hash::Hasher;
        let mut hasher = std::hash::DefaultHasher::new();
        v.hash(&mut hasher);
        hasher.finish()
    }

    impl FixedAggregationKey<String> {
        fn into_key(self) -> OwnedAggregationKey {
            OwnedAggregationKey {
                fixed: self,
                peer_tags: vec![],
                additional_metric_tags: vec![],
            }
        }
        fn into_key_with_peers(self, peer_tags: Vec<(String, String)>) -> OwnedAggregationKey {
            OwnedAggregationKey {
                fixed: self,
                peer_tags,
                additional_metric_tags: vec![],
            }
        }
    }

    #[test]
    fn test_aggregation_key_from_span() {
        let test_cases: Vec<(SpanBytes, OwnedAggregationKey)> = vec![
            // Root span
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with span kind
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("span.kind".into(), "client".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "client".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with peer tags but peertags aggregation disabled
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("span.kind".into(), "client".into()),
                        ("aws.s3.bucket".into(), "bucket-a".into()),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "client".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with multiple peer tags but peertags aggregation disabled
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("span.kind".into(), "producer".into()),
                        ("aws.s3.bucket".into(), "bucket-a".into()),
                        ("db.instance".into(), "dynamo.test.us1".into()),
                        ("db.system".into(), "dynamodb".into()),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "producer".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with multiple peer tags but peertags aggregation disabled and span kind is
            // server
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("span.kind".into(), "server".into()),
                        ("aws.s3.bucket".into(), "bucket-a".into()),
                        ("db.instance".into(), "dynamo.test.us1".into()),
                        ("db.system".into(), "dynamodb".into()),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "server".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span from synthetics
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("_dd.origin".into(), "synthetics-browser".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_synthetics_request: true,
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with status code in meta
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("http.status_code".into(), "418".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_synthetics_request: false,
                    is_trace_root: pb::Trilean::True,
                    http_status_code: 418,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with invalid status code in meta
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("http.status_code".into(), "x".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_synthetics_request: false,
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with status code in metrics
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    metrics: vec![("http.status_code".into(), 418.0)].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_synthetics_request: false,
                    is_trace_root: pb::Trilean::True,
                    http_status_code: 418,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with http.method and http.route
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "GET /api/v1/users".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("http.method".into(), "GET".into()),
                        ("http.route".into(), "/api/v1/users".into()),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "GET /api/v1/users".into(),
                    http_method: "GET".into(),
                    http_endpoint: "/api/v1/users".into(),
                    is_synthetics_request: false,
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with http.method and http.endpoint (http.endpoint takes precedence)
            (
                SpanBytes {
                    service: "service".into(),
                    name: "op".into(),
                    resource: "POST /users/create".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("http.method".into(), "POST".into()),
                        ("http.route".into(), "/users/create".into()),
                        ("http.endpoint".into(), "/users/create2".into()),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "POST /users/create".into(),
                    http_method: "POST".into(),
                    http_endpoint: "/users/create2".into(),
                    is_synthetics_request: false,
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with grpc status from meta as named string
            (
                SpanBytes {
                    meta: vec![("rpc.grpc.status_code".into(), "OK".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    grpc_status_code: Some(0),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // grpc.method.name is carried in GroupedStats (for OTLP), not in the aggregation key.
            (
                SpanBytes {
                    meta: vec![("grpc.method.name".into(), "/pkg.Svc/Method".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with grpc status from meta as numeric string
            (
                SpanBytes {
                    meta: vec![("rpc.grpc.status_code".into(), "14".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    grpc_status_code: Some(14),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with grpc status from meta with StatusCode. prefix
            (
                SpanBytes {
                    meta: vec![("grpc.code".into(), "StatusCode.UNAVAILABLE".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    grpc_status_code: Some(14),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with grpc status from metrics takes precedence over meta
            (
                SpanBytes {
                    meta: vec![("rpc.grpc.status_code".into(), "PERMISSION_DENIED".into())].into(),
                    metrics: vec![("rpc.grpc.status_code".into(), 2.0)].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    grpc_status_code: Some(7),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with grpc status from metrics via secondary key
            (
                SpanBytes {
                    metrics: vec![("grpc.code".into(), 3.0)].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    grpc_status_code: Some(3),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with invalid grpc status string
            (
                SpanBytes {
                    meta: vec![("rpc.grpc.status_code".into(), "NOPE".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with service source set by integration
            (
                SpanBytes {
                    service: "my-service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("_dd.svc_src".into(), "redis".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "my-service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_trace_root: pb::Trilean::True,
                    service_source: "redis".into(),
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span with service source set by configuration option
            (
                SpanBytes {
                    service: "my-service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("_dd.svc_src".into(), "opt.split_by_tag".into())].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "my-service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_trace_root: pb::Trilean::True,
                    service_source: "opt.split_by_tag".into(),
                    ..Default::default()
                }
                .into_key(),
            ),
            // Span without service source (default service name)
            (
                SpanBytes {
                    service: "my-service".into(),
                    name: "op".into(),
                    resource: "res".into(),
                    span_id: 1,
                    parent_id: 0,
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "my-service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    is_trace_root: pb::Trilean::True,
                    service_source: "".into(),
                    ..Default::default()
                }
                .into_key(),
            ),
        ];

        let test_peer_tags = vec![
            "aws.s3.bucket".to_string(),
            "db.instance".to_string(),
            "db.system".to_string(),
        ];

        let test_cases_with_peer_tags: Vec<(SpanSlice, OwnedAggregationKey)> = vec![
            // Span with peer tags with peertags aggregation enabled
            (
                SpanSlice {
                    service: "service",
                    name: "op",
                    resource: "res",
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![("span.kind", "client"), ("aws.s3.bucket", "bucket-a")].into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "client".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key_with_peers(vec![("aws.s3.bucket".into(), "bucket-a".into())]),
            ),
            // Span with multiple peer tags with peertags aggregation enabled
            (
                SpanSlice {
                    service: "service",
                    name: "op",
                    resource: "res",
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("span.kind", "producer"),
                        ("aws.s3.bucket", "bucket-a"),
                        ("db.instance", "dynamo.test.us1"),
                        ("db.system", "dynamodb"),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "producer".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key_with_peers(vec![
                    ("aws.s3.bucket".into(), "bucket-a".into()),
                    ("db.instance".into(), "dynamo.test.us1".into()),
                    ("db.system".into(), "dynamodb".into()),
                ]),
            ),
            // Span with multiple peer tags with peertags aggregation enabled and span kind is
            // server
            (
                SpanSlice {
                    service: "service",
                    name: "op",
                    resource: "res",
                    span_id: 1,
                    parent_id: 0,
                    meta: vec![
                        ("span.kind", "server"),
                        ("aws.s3.bucket", "bucket-a"),
                        ("db.instance", "dynamo.test.us1"),
                        ("db.system", "dynamodb"),
                    ]
                    .into(),
                    ..Default::default()
                },
                FixedAggregationKey {
                    service_name: "service".into(),
                    operation_name: "op".into(),
                    resource_name: "res".into(),
                    span_kind: "server".into(),
                    is_trace_root: pb::Trilean::True,
                    ..Default::default()
                }
                .into_key(),
            ),
        ];

        for (span, expected_key) in test_cases {
            let borrowed_key = BorrowedAggregationKey::from_span(&span, &[], &[]);
            assert_eq!(
                OwnedAggregationKey::from(&borrowed_key),
                expected_key,
                "for span {span:?}"
            );
            assert_eq!(
                get_hash(&borrowed_key),
                get_hash(&OwnedAggregationKey::from(&borrowed_key))
            );
        }

        for (span, expected_key) in test_cases_with_peer_tags {
            let borrowed_key =
                BorrowedAggregationKey::from_span(&span, test_peer_tags.as_slice(), &[]);
            assert_eq!(OwnedAggregationKey::from(&borrowed_key), expected_key);
            assert_eq!(
                get_hash(&borrowed_key),
                get_hash(&OwnedAggregationKey::from(&borrowed_key))
            );
        }
    }

    #[test]
    fn test_peer_tag_ip_quantization_in_aggregation_key() {
        let peer_tag_keys = vec!["peer.hostname".to_string(), "db.instance".to_string()];

        // IPv4 address peer tag gets replaced with blocked-ip-address
        let span_ipv4 = SpanSlice {
            service: "service",
            name: "op",
            resource: "res",
            span_id: 1,
            parent_id: 0,
            meta: vec![
                ("span.kind", "client"),
                ("peer.hostname", "10.1.2.3"),
                ("db.instance", "my-db"),
            ]
            .into(),
            ..Default::default()
        };
        let key = BorrowedAggregationKey::from_span(&span_ipv4, &peer_tag_keys, &[]);
        let owned = OwnedAggregationKey::from(&key);
        assert_eq!(
            owned.peer_tags,
            vec![
                (
                    "peer.hostname".to_string(),
                    "blocked-ip-address".to_string()
                ),
                ("db.instance".to_string(), "my-db".to_string()),
            ]
        );

        // IPv6 address peer tag gets replaced with blocked-ip-address
        let span_ipv6 = SpanSlice {
            service: "service",
            name: "op",
            resource: "res",
            span_id: 1,
            parent_id: 0,
            meta: vec![
                ("span.kind", "client"),
                ("peer.hostname", "2001:db8:3333:4444:CCCC:DDDD:EEEE:FFFF"),
            ]
            .into(),
            ..Default::default()
        };
        let ipv6_keys = vec!["peer.hostname".to_string()];
        let key = BorrowedAggregationKey::from_span(&span_ipv6, &ipv6_keys, &[]);
        let owned = OwnedAggregationKey::from(&key);
        assert_eq!(
            owned.peer_tags,
            vec![(
                "peer.hostname".to_string(),
                "blocked-ip-address".to_string()
            )]
        );

        // Non-IP peer tags pass through unchanged
        let span_non_ip = SpanSlice {
            service: "service",
            name: "op",
            resource: "res",
            span_id: 1,
            parent_id: 0,
            meta: vec![("span.kind", "client"), ("db.instance", "dynamo.test.us1")].into(),
            ..Default::default()
        };
        let non_ip_keys = vec!["db.instance".to_string()];
        let key = BorrowedAggregationKey::from_span(&span_non_ip, &non_ip_keys, &[]);
        let owned = OwnedAggregationKey::from(&key);
        assert_eq!(
            owned.peer_tags,
            vec![("db.instance".to_string(), "dynamo.test.us1".to_string())]
        );
    }

    #[test]
    fn test_grpc_status_str_to_int_value() {
        // Numeric strings parse directly
        assert_eq!(grpc_status_str_to_int_value("0"), Some(0));
        assert_eq!(grpc_status_str_to_int_value("14"), Some(14));
        assert_eq!(grpc_status_str_to_int_value("255"), Some(255));
        assert_eq!(grpc_status_str_to_int_value("256"), None);
        assert_eq!(grpc_status_str_to_int_value("-1"), None);

        // Named status codes (uppercase)
        assert_eq!(grpc_status_str_to_int_value("OK"), Some(0));
        assert_eq!(grpc_status_str_to_int_value("CANCELLED"), Some(1));
        assert_eq!(grpc_status_str_to_int_value("UNKNOWN"), Some(2));
        assert_eq!(grpc_status_str_to_int_value("INVALID_ARGUMENT"), Some(3));
        assert_eq!(grpc_status_str_to_int_value("DEADLINE_EXCEEDED"), Some(4));
        assert_eq!(grpc_status_str_to_int_value("NOT_FOUND"), Some(5));
        assert_eq!(grpc_status_str_to_int_value("ALREADY_EXISTS"), Some(6));
        assert_eq!(grpc_status_str_to_int_value("PERMISSION_DENIED"), Some(7));
        assert_eq!(grpc_status_str_to_int_value("UNAUTHENTICATED"), Some(16));
        assert_eq!(grpc_status_str_to_int_value("RESOURCE_EXHAUSTED"), Some(8));
        assert_eq!(grpc_status_str_to_int_value("FAILED_PRECONDITION"), Some(9));
        assert_eq!(grpc_status_str_to_int_value("ABORTED"), Some(10));
        assert_eq!(grpc_status_str_to_int_value("OUT_OF_RANGE"), Some(11));
        assert_eq!(grpc_status_str_to_int_value("UNIMPLEMENTED"), Some(12));
        assert_eq!(grpc_status_str_to_int_value("INTERNAL"), Some(13));
        assert_eq!(grpc_status_str_to_int_value("UNAVAILABLE"), Some(14));
        assert_eq!(grpc_status_str_to_int_value("DATA_LOSS"), Some(15));

        // Case-insensitive matching
        assert_eq!(grpc_status_str_to_int_value("ok"), Some(0));
        assert_eq!(grpc_status_str_to_int_value("Cancelled"), Some(1));
        assert_eq!(grpc_status_str_to_int_value("not_found"), Some(5));

        // StatusCode. prefix is stripped
        assert_eq!(grpc_status_str_to_int_value("StatusCode.OK"), Some(0));
        assert_eq!(
            grpc_status_str_to_int_value("StatusCode.UNAVAILABLE"),
            Some(14)
        );
        assert_eq!(
            grpc_status_str_to_int_value("StatusCode.not_found"),
            Some(5)
        );

        // Alternate spellings
        assert_eq!(grpc_status_str_to_int_value("CANCELED"), Some(1));

        // Unknown / empty strings
        assert_eq!(grpc_status_str_to_int_value("NOPE"), None);
        assert_eq!(grpc_status_str_to_int_value(""), None);
        assert_eq!(
            grpc_status_str_to_int_value("this_is_a_kinda_long_string_that_needs_upcasing"),
            None
        );

        // Non ascii
        assert_eq!(grpc_status_str_to_int_value("🤣"), None);
    }
}