libdd-sampling 2.0.0

Core sampling logic for Datadog tracing
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
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

use crate::dd_constants::{
    RL_EFFECTIVE_RATE, SAMPLING_AGENT_RATE_TAG_KEY, SAMPLING_DECISION_MAKER_TAG_KEY,
    SAMPLING_KNUTH_RATE_TAG_KEY, SAMPLING_PRIORITY_TAG_KEY, SAMPLING_RULE_RATE_TAG_KEY,
};
use crate::dd_sampling::{mechanism, priority, SamplingMechanism, SamplingPriority};
use crate::sampling_rule_config::SamplingRuleConfig;

/// Type alias for sampling rules update callback
/// Consolidated callback type used across crates for remote config sampling updates
pub type SamplingRulesCallback = Box<dyn for<'a> Fn(&'a [SamplingRuleConfig]) + Send + Sync>;

use crate::types::{SamplingData, SpanProperties};

use super::agent_service_sampler::{AgentRates, ServicesSampler};
use super::rate_limiter::RateLimiter;
use super::rules_sampler::RulesSampler;
use super::sampling_rule::SamplingRule;

/// A composite sampler that applies rules in order of precedence
#[derive(Clone, Debug)]
pub struct DatadogSampler {
    /// Sampling rules to apply, in order of precedence
    rules: RulesSampler,

    /// Service-based samplers provided by the Agent
    service_samplers: ServicesSampler,

    /// Rate limiter for limiting the number of spans per second
    rate_limiter: RateLimiter,
}

impl DatadogSampler {
    /// Creates a new DatadogSampler with the given rules
    pub fn new(rules: Vec<SamplingRule>, rate_limit: i32) -> Self {
        // Create rate limiter with default value of 100 if not provided
        let limiter = RateLimiter::new(rate_limit, None);

        DatadogSampler {
            rules: RulesSampler::new(rules),
            service_samplers: ServicesSampler::default(),
            rate_limiter: limiter,
        }
    }

    // Test-only helper that bypasses the agent-response parsing path.
    #[cfg(test)]
    pub(crate) fn update_service_rates(&self, rates: impl IntoIterator<Item = (String, f64)>) {
        self.service_samplers.update_rates(rates);
    }

    pub fn on_agent_response(&self) -> Box<dyn for<'a> Fn(&'a str) + Send + Sync> {
        let service_samplers = self.service_samplers.clone();
        Box::new(move |s: &str| {
            let Ok(new_rates) = serde_json::de::from_str::<AgentRates>(s) else {
                return;
            };
            let Some(new_rates) = new_rates.rate_by_service else {
                return;
            };
            service_samplers.update_rates(new_rates.into_iter().map(|(k, v)| (k.to_string(), v)));
        })
    }

    /// Creates a callback for updating sampling rules from remote configuration.
    ///
    /// # Returns
    ///
    /// A boxed function that takes a slice of `SamplingRuleConfig` and updates the sampling rules.
    pub fn on_rules_update(&self) -> SamplingRulesCallback {
        let rules_sampler = self.rules.clone();
        Box::new(move |rule_configs: &[SamplingRuleConfig]| {
            let new_rules = SamplingRule::from_configs(rule_configs.to_vec());

            rules_sampler.update_rules(new_rules);
        })
    }

    /// Computes a key for service-based sampling
    fn service_key(&self, span: &impl SpanProperties) -> String {
        // `Cow<str>` implements `Display`, so no `into_owned()` allocation is needed here;
        // `format!` will borrow directly from the span.
        format!("service:{},env:{}", span.service(), span.env())
    }

    /// Finds the highest precedence rule that matches the span
    fn find_matching_rule(&self, span: &impl SpanProperties) -> Option<SamplingRule> {
        self.rules.find_matching_rule(|rule| rule.matches(span))
    }

    /// Returns the sampling mechanism used for the decision
    fn get_sampling_mechanism(
        &self,
        rule: Option<&SamplingRule>,
        used_agent_sampler: bool,
    ) -> SamplingMechanism {
        if let Some(rule) = rule {
            // Provenance is set when rules come from remote configuration
            // (see `on_rules_update`); locally configured rules use the default value.
            match rule.provenance.as_str() {
                "customer" => mechanism::REMOTE_USER_TRACE_SAMPLING_RULE,
                "dynamic" => mechanism::REMOTE_DYNAMIC_TRACE_SAMPLING_RULE,
                _ => mechanism::LOCAL_USER_TRACE_SAMPLING_RULE,
            }
        } else if used_agent_sampler {
            mechanism::AGENT_RATE_BY_SERVICE
        } else {
            // Should not happen in practice: agent rates default to covering all services.
            mechanism::DEFAULT
        }
    }

    /// Sample an incoming span based on the parent context and attributes.
    ///
    /// If a parent sampling decision is present it is inherited; otherwise the root-span
    /// sampling pipeline is run via [`Self::sample_root`].
    pub fn sample(&self, data: &impl SamplingData) -> DdSamplingResult {
        if let Some(is_parent_sampled) = data.is_parent_sampled() {
            let priority = match is_parent_sampled {
                false => priority::AUTO_REJECT,
                true => priority::AUTO_KEEP,
            };
            return DdSamplingResult {
                priority,
                trace_root_info: None,
            };
        }

        data.with_span_properties(self, |sampler, span| sampler.sample_root(data, span))
    }

    /// Sample the root span of a trace.
    ///
    /// Order of precedence:
    /// 1. A matching local/remote sampling rule (with rate limiting on keep).
    /// 2. Agent-provided per-service sampling rate.
    /// 3. Default 100% keep.
    fn sample_root(
        &self,
        data: &impl SamplingData,
        span: &impl SpanProperties,
    ) -> DdSamplingResult {
        let mut is_keep = true;
        let mut used_agent_sampler = false;
        let sample_rate;
        let mut rl_effective_rate: Option<f64> = None;
        let trace_id = data.trace_id();

        let matching_rule = self.find_matching_rule(span);

        if let Some(rule) = &matching_rule {
            sample_rate = rule.sample_rate;

            if !rule.sample(trace_id) {
                is_keep = false;
            } else if !self.rate_limiter.is_allowed() {
                // Rule kept the span, but the rate limiter dropped it.
                is_keep = false;
                rl_effective_rate = Some(self.rate_limiter.effective_rate());
            }
        } else {
            let service_key = self.service_key(span);
            if let Some(sampler) = self.service_samplers.get(&service_key) {
                used_agent_sampler = true;
                sample_rate = sampler.sample_rate();
                if !sampler.sample(trace_id) {
                    is_keep = false;
                }
            } else {
                // No agent rate for this service yet; keep with rate 1.0 until rates arrive.
                sample_rate = 1.0;
            }
        }

        let mechanism = self.get_sampling_mechanism(matching_rule.as_ref(), used_agent_sampler);

        DdSamplingResult {
            priority: mechanism.to_priority(is_keep),
            trace_root_info: Some(TraceRootSamplingInfo {
                mechanism,
                rate: sample_rate,
                rl_effective_rate,
            }),
        }
    }
}

/// Formats a sampling rate with up to 6 significant digits, stripping trailing zeros.
///
/// This matches the Go behavior of `strconv.FormatFloat(rate, 'g', 6, 64)`.
///
/// # Examples
/// - `1.0` → `Some("1")`
/// - `0.5` → `Some("0.5")`
/// - `0.7654321` → `Some("0.765432")`
/// - `0.100000` → `Some("0.1")`
/// - `-0.1` → `None`
/// - `1.1` → `None`
fn format_sampling_rate(rate: f64) -> Option<String> {
    if rate.is_nan() || !(0.0..=1.0).contains(&rate) {
        return None;
    }

    if rate == 0.0 {
        return Some("0".to_string());
    }

    let digits = 6_i32;
    let magnitude = rate.abs().log10().floor() as i32;
    let scale = 10f64.powi(digits - 1 - magnitude);
    let rounded = (rate * scale).round() / scale;

    // Determine decimal places needed for 6 significant digits
    let decimal_places = if magnitude >= digits - 1 {
        0
    } else {
        (digits - 1 - magnitude) as usize
    };

    let s = format!("{:.prec$}", rounded, prec = decimal_places);
    // Strip trailing zeros after decimal point
    Some(if s.contains('.') {
        s.trim_end_matches('0').trim_end_matches('.').to_string()
    } else {
        s
    })
}

pub struct TraceRootSamplingInfo {
    mechanism: SamplingMechanism,
    rate: f64,
    rl_effective_rate: Option<f64>,
}

impl TraceRootSamplingInfo {
    /// Returns the sampling mechanism used for this trace root
    pub fn mechanism(&self) -> SamplingMechanism {
        self.mechanism
    }

    /// Returns the sample rate used for this trace root
    pub fn rate(&self) -> f64 {
        self.rate
    }

    /// Returns the effective rate limit if rate limiting was applied
    pub fn rl_effective_rate(&self) -> Option<f64> {
        self.rl_effective_rate
    }
}

pub struct DdSamplingResult {
    priority: SamplingPriority,
    trace_root_info: Option<TraceRootSamplingInfo>,
}

impl DdSamplingResult {
    #[inline(always)]
    pub fn get_priority(&self) -> SamplingPriority {
        self.priority
    }

    pub fn get_trace_root_sampling_info(&self) -> &Option<TraceRootSamplingInfo> {
        &self.trace_root_info
    }

    /// Returns Datadog-specific sampling tags to be added as attributes
    ///
    /// # Parameters
    /// * `factory` - The attribute factory to use for creating attributes
    ///
    /// # Returns
    /// An optional vector of attributes to add to the sampling result
    pub fn to_dd_sampling_tags<F>(&self, factory: &F) -> Option<Vec<F::Attribute>>
    where
        F: crate::types::AttributeFactory,
    {
        let Some(root_info) = &self.trace_root_info else {
            return None; // No root info, return empty attributes
        };

        let mut result: Vec<F::Attribute>;
        // Add rate limiting tag if applicable
        if let Some(limit) = root_info.rl_effective_rate() {
            result = Vec::with_capacity(4);
            result.push(factory.create_f64(RL_EFFECTIVE_RATE, limit));
        } else {
            result = Vec::with_capacity(3);
        }

        // Add the sampling decision trace tag with the mechanism
        let mechanism = root_info.mechanism();
        result.push(factory.create_string(SAMPLING_DECISION_MAKER_TAG_KEY, mechanism.to_cow()));

        // Add the sample rate tag with the correct key based on the mechanism
        match mechanism {
            mechanism::AGENT_RATE_BY_SERVICE => {
                result.push(factory.create_f64(SAMPLING_AGENT_RATE_TAG_KEY, root_info.rate()));
                if let Some(rate_str) = format_sampling_rate(root_info.rate()) {
                    result.push(factory.create_string(
                        SAMPLING_KNUTH_RATE_TAG_KEY,
                        std::borrow::Cow::Owned(rate_str),
                    ));
                }
            }
            mechanism::REMOTE_USER_TRACE_SAMPLING_RULE
            | mechanism::REMOTE_DYNAMIC_TRACE_SAMPLING_RULE
            | mechanism::LOCAL_USER_TRACE_SAMPLING_RULE => {
                result.push(factory.create_f64(SAMPLING_RULE_RATE_TAG_KEY, root_info.rate()));
                if let Some(rate_str) = format_sampling_rate(root_info.rate()) {
                    result.push(factory.create_string(
                        SAMPLING_KNUTH_RATE_TAG_KEY,
                        std::borrow::Cow::Owned(rate_str),
                    ));
                }
            }
            _ => {}
        }

        let priority = self.priority;
        result.push(factory.create_i64(SAMPLING_PRIORITY_TAG_KEY, priority.into_i8() as i64));

        Some(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants::{
        attr::{ENV_TAG, RESOURCE_TAG},
        pattern,
    };
    use crate::types::{AttributeLike, TraceIdLike, ValueLike};
    use std::borrow::Cow;
    use std::collections::HashMap;

    // Test-only semantic convention constants
    const HTTP_REQUEST_METHOD: &str = "http.request.method";
    const SERVICE_NAME: &str = "service.name";

    // HTTP status code attribute constants (for tests)
    const HTTP_RESPONSE_STATUS_CODE: &str = "http.response.status_code";
    const HTTP_STATUS_CODE: &str = "http.status_code";

    // ============================================================================
    // Test-only data structures
    // ============================================================================

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct TestTraceId {
        bytes: [u8; 16],
    }

    impl TestTraceId {
        fn from_bytes(bytes: [u8; 16]) -> Self {
            Self { bytes }
        }
    }

    impl TraceIdLike for TestTraceId {
        fn to_u128(&self) -> u128 {
            u128::from_be_bytes(self.bytes)
        }
    }

    #[derive(Clone, Debug, PartialEq)]
    enum TestValue {
        String(String),
        I64(i64),
        F64(f64),
    }

    impl ValueLike for TestValue {
        fn as_float(&self) -> Option<f64> {
            match self {
                TestValue::I64(i) => Some(*i as f64),
                TestValue::F64(f) => Some(*f),
                _ => None,
            }
        }

        fn as_str(&self) -> Option<Cow<'_, str>> {
            match self {
                TestValue::String(s) => Some(Cow::Borrowed(s.as_str())),
                TestValue::I64(i) => Some(Cow::Owned(i.to_string())),
                TestValue::F64(f) => Some(Cow::Owned(f.to_string())),
            }
        }
    }

    #[derive(Clone, Debug)]
    struct TestAttribute {
        key: String,
        value: TestValue,
    }

    impl TestAttribute {
        fn new(key: impl Into<String>, value: impl Into<TestValue>) -> Self {
            Self {
                key: key.into(),
                value: value.into(),
            }
        }
    }

    impl AttributeLike for TestAttribute {
        type Value = TestValue;

        fn key(&self) -> &str {
            &self.key
        }

        fn value(&self) -> &Self::Value {
            &self.value
        }
    }

    impl From<&str> for TestValue {
        fn from(s: &str) -> Self {
            TestValue::String(s.to_string())
        }
    }

    impl From<String> for TestValue {
        fn from(s: String) -> Self {
            TestValue::String(s)
        }
    }

    struct TestSpan<'a> {
        name: &'a str,
        attributes: &'a [TestAttribute],
    }

    impl<'a> TestSpan<'a> {
        fn new(name: &'a str, attributes: &'a [TestAttribute]) -> Self {
            Self { name, attributes }
        }

        fn get_operation_name(&self) -> Cow<'_, str> {
            // Check for HTTP spans - label them all as client spans
            if self
                .attributes
                .iter()
                .any(|attr| attr.key() == HTTP_REQUEST_METHOD)
            {
                return Cow::Borrowed("http.client.request");
            }

            // Default fallback
            Cow::Borrowed("internal")
        }
    }

    impl SpanProperties for TestSpan<'_> {
        type Attribute<'b>
            = &'b TestAttribute
        where
            Self: 'b;

        fn operation_name(&self) -> Cow<'_, str> {
            self.get_operation_name()
        }

        fn service(&self) -> Cow<'_, str> {
            self.attributes
                .iter()
                .find(|attr| attr.key() == SERVICE_NAME)
                .and_then(|attr| attr.value().as_str())
                .unwrap_or(Cow::Borrowed(""))
        }

        fn env(&self) -> Cow<'_, str> {
            self.attributes
                .iter()
                .find(|attr| attr.key() == "datadog.env" || attr.key() == ENV_TAG)
                .and_then(|attr| attr.value().as_str())
                .unwrap_or(Cow::Borrowed(""))
        }

        fn resource(&self) -> Cow<'_, str> {
            self.attributes
                .iter()
                .find(|attr| attr.key() == RESOURCE_TAG)
                .and_then(|attr| attr.value().as_str())
                .unwrap_or(Cow::Borrowed(self.name))
        }

        fn status_code(&self) -> Option<u32> {
            self.attributes
                .iter()
                .find(|attr| {
                    attr.key() == HTTP_RESPONSE_STATUS_CODE || attr.key() == HTTP_STATUS_CODE
                })
                .and_then(|attr| match attr.value() {
                    TestValue::I64(i) => Some(*i as u32),
                    _ => None,
                })
        }

        fn attributes(&self) -> impl Iterator<Item = &TestAttribute> + '_ {
            self.attributes.iter()
        }

        fn get_alternate_key<'b>(&self, key: &'b str) -> Option<Cow<'b, str>> {
            match key {
                HTTP_RESPONSE_STATUS_CODE => Some(Cow::Borrowed(HTTP_STATUS_CODE)),
                HTTP_REQUEST_METHOD => Some(Cow::Borrowed("http.method")),
                _ => None,
            }
        }
    }

    struct TestSamplingData<'a> {
        is_parent_sampled: Option<bool>,
        trace_id: &'a TestTraceId,
        name: &'a str,
        attributes: &'a [TestAttribute],
    }

    impl<'a> TestSamplingData<'a> {
        fn new(
            is_parent_sampled: Option<bool>,
            trace_id: &'a TestTraceId,
            name: &'a str,
            attributes: &'a [TestAttribute],
        ) -> Self {
            Self {
                is_parent_sampled,
                trace_id,
                name,
                attributes,
            }
        }
    }

    impl SamplingData for TestSamplingData<'_> {
        type TraceId = TestTraceId;
        type Properties<'b>
            = TestSpan<'b>
        where
            Self: 'b;

        fn is_parent_sampled(&self) -> Option<bool> {
            self.is_parent_sampled
        }

        fn trace_id(&self) -> &Self::TraceId {
            self.trace_id
        }

        fn with_span_properties<S, T, F>(&self, s: &S, f: F) -> T
        where
            F: for<'b> Fn(&S, &TestSpan<'b>) -> T,
        {
            let span = TestSpan::new(self.name, self.attributes);
            f(s, &span)
        }
    }

    struct TestAttributeFactory;

    impl crate::types::AttributeFactory for TestAttributeFactory {
        type Attribute = TestAttribute;

        fn create_i64(&self, key: &'static str, value: i64) -> Self::Attribute {
            TestAttribute::new(key, TestValue::I64(value))
        }

        fn create_f64(&self, key: &'static str, value: f64) -> Self::Attribute {
            TestAttribute::new(key, TestValue::F64(value))
        }

        fn create_string(&self, key: &'static str, value: Cow<'static, str>) -> Self::Attribute {
            TestAttribute::new(key, TestValue::String(value.into_owned()))
        }
    }

    // ============================================================================
    // Test helper functions
    // ============================================================================

    // Helper function to create a trace ID
    fn create_trace_id() -> TestTraceId {
        let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
        TestTraceId::from_bytes(bytes)
    }

    // Helper function to create attributes for testing (with resource and env)
    fn create_attributes(resource: &'static str, env: &'static str) -> Vec<TestAttribute> {
        vec![
            TestAttribute::new(RESOURCE_TAG, resource),
            TestAttribute::new("datadog.env", env),
        ]
    }

    // Helper function to create attributes with service
    fn create_attributes_with_service(
        service: String,
        resource: &'static str,
        env: &'static str,
    ) -> Vec<TestAttribute> {
        vec![
            TestAttribute::new(SERVICE_NAME, service),
            TestAttribute::new(RESOURCE_TAG, resource),
            TestAttribute::new("datadog.env", env),
        ]
    }

    // Helper function to create attributes with service plus arbitrary extra string tags.
    fn create_attributes_with_extra(
        service: &'static str,
        resource: &'static str,
        env: &'static str,
        extra: &[(&'static str, &'static str)],
    ) -> Vec<TestAttribute> {
        let mut attrs = create_attributes_with_service(service.to_string(), resource, env);
        for (k, v) in extra {
            attrs.push(TestAttribute::new(*k, *v));
        }
        attrs
    }

    // Helper function to create SamplingData for testing
    fn create_sampling_data<'a>(
        is_parent_sampled: Option<bool>,
        trace_id: &'a TestTraceId,
        name: &'a str,
        attributes: &'a [TestAttribute],
    ) -> TestSamplingData<'a> {
        TestSamplingData::new(is_parent_sampled, trace_id, name, attributes)
    }

    #[test]
    fn test_sampling_rule_creation() {
        let rule = SamplingRule::new(
            0.5,
            Some("test-service".to_string()),
            Some("test-name".to_string()),
            Some("test-resource".to_string()),
            Some(HashMap::from([(
                "custom-tag".to_string(),
                "tag-value".to_string(),
            )])),
            Some("customer".to_string()),
        );

        assert_eq!(rule.sample_rate, 0.5);
        assert_eq!(rule.service_matcher.unwrap().pattern(), "test-service");
        assert_eq!(rule.name_matcher.unwrap().pattern(), "test-name");
        assert_eq!(
            rule.resource_matcher.unwrap().pattern(),
            "test-resource".to_string()
        );
        assert_eq!(
            rule.tag_matchers.get("custom-tag").unwrap().pattern(),
            "tag-value"
        );
        assert_eq!(rule.provenance, "customer");
    }

    #[test]
    fn test_sampling_rule_with_no_rule() {
        // Create a rule without specifying any criteria
        let rule = SamplingRule::new(
            0.5, None, // No service
            None, // No name
            None, // No resource
            None, // No tags
            None, // Default provenance
        );

        // Verify fields are set to None or empty
        assert_eq!(rule.sample_rate, 0.5);
        assert!(rule.service_matcher.is_none());
        assert!(rule.name_matcher.is_none());
        assert!(rule.resource_matcher.is_none());
        assert!(rule.tag_matchers.is_empty());
        assert_eq!(rule.provenance, "default");

        // Verify no matchers were created
        assert!(rule.service_matcher.is_none());
        assert!(rule.name_matcher.is_none());
        assert!(rule.resource_matcher.is_none());
        assert!(rule.tag_matchers.is_empty());

        // Test that a rule with NO_RULE constants behaves the same as None
        let rule_with_empty_strings = SamplingRule::new(
            0.5,
            Some(pattern::NO_RULE.to_string()), // Empty service string
            Some(pattern::NO_RULE.to_string()), // Empty name string
            Some(pattern::NO_RULE.to_string()), // Empty resource string
            Some(HashMap::from([(
                pattern::NO_RULE.to_string(),
                pattern::NO_RULE.to_string(),
            )])), // Empty tag
            None,
        );

        // Verify that matchers aren't created for NO_RULE values
        assert!(rule_with_empty_strings.service_matcher.is_none());
        assert!(rule_with_empty_strings.name_matcher.is_none());
        assert!(rule_with_empty_strings.resource_matcher.is_none());
        assert!(rule_with_empty_strings.tag_matchers.is_empty());

        // Create a span with some attributes
        let attributes = create_attributes("some-resource", "some-env");

        // Both rules should match any span since they have no criteria
        let span = TestSpan::new("", &attributes);
        assert!(rule.matches(&span));
        assert!(rule_with_empty_strings.matches(&span));
    }

    #[test]
    fn test_sampling_rule_matches() {
        // Rule constrained on service, operation name, and a required tag value.
        // `TestSpan::operation_name()` returns "http.client.request" when the span
        // carries an `http.request.method` attribute (see `get_operation_name`).
        let rule = SamplingRule::new(
            0.5,
            Some("web-*".to_string()),
            Some("http.client.*".to_string()),
            None,
            Some(HashMap::from([(
                "custom_key".to_string(),
                "custom_value".to_string(),
            )])),
            None,
        );

        // Matching span.
        let attrs = create_attributes_with_extra(
            "web-foo",
            "resource",
            "production",
            &[(HTTP_REQUEST_METHOD, "GET"), ("custom_key", "custom_value")],
        );
        let span = TestSpan::new("span-name", attrs.as_slice());
        assert!(rule.matches(&span), "rule should match qualifying span");

        // Non-matching service.
        let attrs_bad_service = create_attributes_with_extra(
            "api-foo",
            "resource",
            "production",
            &[(HTTP_REQUEST_METHOD, "GET"), ("custom_key", "custom_value")],
        );
        let span_bad_service = TestSpan::new("span-name", attrs_bad_service.as_slice());
        assert!(
            !rule.matches(&span_bad_service),
            "rule should not match different service"
        );

        // Missing required tag.
        let attrs_no_tag = create_attributes_with_extra(
            "web-foo",
            "resource",
            "production",
            &[(HTTP_REQUEST_METHOD, "GET")],
        );
        let span_no_tag = TestSpan::new("span-name", attrs_no_tag.as_slice());
        assert!(
            !rule.matches(&span_no_tag),
            "rule should not match without required tag"
        );
    }

    #[test]
    fn test_sample_method() {
        // Create two rules with different rates
        let rule_always = SamplingRule::new(1.0, None, None, None, None, None);
        let rule_never = SamplingRule::new(0.0, None, None, None, None, None);

        let trace_id = create_trace_id();

        // Rule with rate 1.0 should always sample
        assert!(rule_always.sample(&trace_id));

        // Rule with rate 0.0 should never sample
        assert!(!rule_never.sample(&trace_id));
    }

    #[test]
    fn test_datadog_sampler_creation() {
        // Create a sampler with default config
        let sampler = DatadogSampler::new(vec![], 100);
        assert!(sampler.rules.is_empty());
        assert!(sampler.service_samplers.is_empty());

        // Create a sampler with rules
        let rule = SamplingRule::new(0.5, None, None, None, None, None);
        let sampler_with_rules = DatadogSampler::new(vec![rule], 200);
        assert_eq!(sampler_with_rules.rules.len(), 1);
    }

    #[test]
    fn test_service_key_generation() {
        let test_service_name = "test-service".to_string();
        let sampler = DatadogSampler::new(vec![], 100);

        // Test with service and env
        let attrs =
            create_attributes_with_service(test_service_name.clone(), "resource", "production");
        let span = TestSpan::new("test-span", attrs.as_slice());
        assert_eq!(
            sampler.service_key(&span),
            format!("service:{test_service_name},env:production")
        );

        // Test with missing env
        let attrs_no_env = vec![
            TestAttribute::new(SERVICE_NAME, test_service_name.clone()),
            TestAttribute::new(RESOURCE_TAG, "resource"),
        ];
        let span = TestSpan::new("test-span", attrs_no_env.as_slice());
        assert_eq!(
            sampler.service_key(&span),
            format!("service:{test_service_name},env:")
        );
    }

    #[test]
    fn test_update_service_rates() {
        let sampler = DatadogSampler::new(vec![], 100);

        // Update with service rates
        let mut rates = HashMap::new();
        rates.insert("service:web,env:prod".to_string(), 0.5);
        rates.insert("service:api,env:prod".to_string(), 0.75);

        sampler.service_samplers.update_rates(rates);

        // Check number of samplers
        assert_eq!(sampler.service_samplers.len(), 2);

        // Verify keys exist
        assert!(sampler
            .service_samplers
            .contains_key("service:web,env:prod"));
        assert!(sampler
            .service_samplers
            .contains_key("service:api,env:prod"));

        // Verify the sampling rates are correctly set
        if let Some(web_sampler) = sampler.service_samplers.get("service:web,env:prod") {
            assert_eq!(web_sampler.sample_rate(), 0.5);
        } else {
            panic!("Web service sampler not found");
        }

        if let Some(api_sampler) = sampler.service_samplers.get("service:api,env:prod") {
            assert_eq!(api_sampler.sample_rate(), 0.75);
        } else {
            panic!("API service sampler not found");
        }
    }

    #[test]
    fn test_find_matching_rule() {
        // Create rules with different priorities and service matchers
        let rule1 = SamplingRule::new(
            0.1,
            Some("service1".to_string()),
            None,
            None,
            None,
            Some("customer".to_string()), // Highest priority
        );

        let rule2 = SamplingRule::new(
            0.2,
            Some("service2".to_string()),
            None,
            None,
            None,
            Some("dynamic".to_string()), // Middle priority
        );

        let rule3 = SamplingRule::new(
            0.3,
            Some("service*".to_string()), // Wildcard service
            None,
            None,
            None,
            Some("default".to_string()), // Lowest priority
        );

        let sampler = DatadogSampler::new(vec![rule1.clone(), rule2.clone(), rule3.clone()], 100);

        // Test with a specific service that should match the first rule (rule1)
        {
            let attrs1 = create_attributes_with_service(
                "service1".to_string(),
                "resource_val_for_attr1",
                "prod",
            );
            let span = TestSpan::new("test-span", attrs1.as_slice());
            let matching_rule_for_attrs1 = sampler.find_matching_rule(&span);
            assert!(
                matching_rule_for_attrs1.is_some(),
                "Expected rule1 to match for service1"
            );
            let rule = matching_rule_for_attrs1.unwrap();
            assert_eq!(rule.sample_rate, 0.1, "Expected rule1 sample rate");
            assert_eq!(rule.provenance, "customer", "Expected rule1 provenance");
        }

        // Test with a specific service that should match the second rule (rule2)
        {
            let attrs2 = create_attributes_with_service(
                "service2".to_string(),
                "resource_val_for_attr2",
                "prod",
            );
            let span = TestSpan::new("test-span", attrs2.as_slice());
            let matching_rule_for_attrs2 = sampler.find_matching_rule(&span);
            assert!(
                matching_rule_for_attrs2.is_some(),
                "Expected rule2 to match for service2"
            );
            let rule = matching_rule_for_attrs2.unwrap();
            assert_eq!(rule.sample_rate, 0.2, "Expected rule2 sample rate");
            assert_eq!(rule.provenance, "dynamic", "Expected rule2 provenance");
        }

        // Test with a service that matches the wildcard rule (rule3)
        {
            let attrs3 = create_attributes_with_service(
                "service3".to_string(),
                "resource_val_for_attr3",
                "prod",
            );
            let span = TestSpan::new("test-span", attrs3.as_slice());
            let matching_rule_for_attrs3 = sampler.find_matching_rule(&span);
            assert!(
                matching_rule_for_attrs3.is_some(),
                "Expected rule3 to match for service3"
            );
            let rule = matching_rule_for_attrs3.unwrap();
            assert_eq!(rule.sample_rate, 0.3, "Expected rule3 sample rate");
            assert_eq!(rule.provenance, "default", "Expected rule3 provenance");
        }

        // Test with a service that doesn't match any rule's service pattern
        {
            let attrs4 = create_attributes_with_service(
                "other_sampler_service".to_string(),
                "resource_val_for_attr4",
                "prod",
            );
            let span = TestSpan::new("test-span", attrs4.as_slice());
            let matching_rule_for_attrs4 = sampler.find_matching_rule(&span);
            assert!(
                matching_rule_for_attrs4.is_none(),
                "Expected no rule to match for service 'other_sampler_service'"
            );
        }
    }

    #[test]
    fn test_get_sampling_mechanism() {
        let sampler = DatadogSampler::new(vec![], 100);

        // Create rules with different provenances
        let rule_customer =
            SamplingRule::new(0.1, None, None, None, None, Some("customer".to_string()));
        let rule_dynamic =
            SamplingRule::new(0.2, None, None, None, None, Some("dynamic".to_string()));
        let rule_default =
            SamplingRule::new(0.3, None, None, None, None, Some("default".to_string()));

        // Test with customer rule
        let mechanism1 = sampler.get_sampling_mechanism(Some(&rule_customer), false);
        assert_eq!(mechanism1, mechanism::REMOTE_USER_TRACE_SAMPLING_RULE);

        // Test with dynamic rule
        let mechanism2 = sampler.get_sampling_mechanism(Some(&rule_dynamic), false);
        assert_eq!(mechanism2, mechanism::REMOTE_DYNAMIC_TRACE_SAMPLING_RULE);

        // Test with default rule
        let mechanism3 = sampler.get_sampling_mechanism(Some(&rule_default), false);
        assert_eq!(mechanism3, mechanism::LOCAL_USER_TRACE_SAMPLING_RULE);

        // Test with agent sampler
        let mechanism4 = sampler.get_sampling_mechanism(None, true);
        assert_eq!(mechanism4, mechanism::AGENT_RATE_BY_SERVICE);

        // Test fallback case
        let mechanism5 = sampler.get_sampling_mechanism(None, false);
        assert_eq!(mechanism5, mechanism::DEFAULT);
    }

    #[test]
    fn test_add_dd_sampling_tags() {
        // Test with RecordAndSample decision and LocalUserTraceSamplingRule mechanism
        let sample_rate = 0.5;
        let is_sampled = true;
        let mechanism = mechanism::LOCAL_USER_TRACE_SAMPLING_RULE;
        let sampling_result = DdSamplingResult {
            priority: mechanism.to_priority(is_sampled),
            trace_root_info: Some(TraceRootSamplingInfo {
                mechanism,
                rate: 0.5,
                rl_effective_rate: None,
            }),
        };

        let attrs = sampling_result
            .to_dd_sampling_tags(&TestAttributeFactory)
            .unwrap_or_default();

        // Verify the number of attributes (decision_maker + priority + rule_rate + ksr)
        assert_eq!(attrs.len(), 4);

        // Check individual attributes
        let mut found_decision_maker = false;
        let mut found_priority = false;
        let mut found_rule_rate = false;
        let mut found_ksr = false;

        for attr in &attrs {
            match attr.key() {
                SAMPLING_DECISION_MAKER_TAG_KEY => {
                    let value_str = match attr.value() {
                        TestValue::String(s) => s.to_string(),
                        _ => panic!("Expected string value for decision maker tag"),
                    };
                    assert_eq!(value_str, mechanism.to_cow());
                    found_decision_maker = true;
                }
                SAMPLING_PRIORITY_TAG_KEY => {
                    // For LocalUserTraceSamplingRule with KEEP, it should be USER_KEEP
                    let expected_priority = mechanism.to_priority(true).into_i8() as i64;

                    let value_int = match attr.value() {
                        TestValue::I64(i) => *i,
                        _ => panic!("Expected integer value for priority tag"),
                    };
                    assert_eq!(value_int, expected_priority);
                    found_priority = true;
                }
                SAMPLING_RULE_RATE_TAG_KEY => {
                    let value_float = match attr.value() {
                        TestValue::F64(f) => *f,
                        _ => panic!("Expected float value for rule rate tag"),
                    };
                    assert_eq!(value_float, sample_rate);
                    found_rule_rate = true;
                }
                SAMPLING_KNUTH_RATE_TAG_KEY => {
                    let value_str = match attr.value() {
                        TestValue::String(s) => s.to_string(),
                        _ => panic!("Expected string value for ksr tag"),
                    };
                    assert_eq!(value_str, "0.5");
                    found_ksr = true;
                }
                _ => {}
            }
        }

        assert!(found_decision_maker, "Missing decision maker tag");
        assert!(found_priority, "Missing priority tag");
        assert!(found_rule_rate, "Missing rule rate tag");
        assert!(found_ksr, "Missing knuth sampling rate tag");

        // Test with rate limiting
        let rate_limit = 0.5;
        let is_sampled = false;
        let mechanism = mechanism::LOCAL_USER_TRACE_SAMPLING_RULE;
        let sampling_result = DdSamplingResult {
            priority: mechanism.to_priority(is_sampled),
            trace_root_info: Some(TraceRootSamplingInfo {
                mechanism,
                rate: 0.5,
                rl_effective_rate: Some(rate_limit),
            }),
        };
        let attrs_with_limit = sampling_result
            .to_dd_sampling_tags(&TestAttributeFactory)
            .unwrap_or_default();

        // With rate limiting, there should be one more attribute
        assert_eq!(attrs_with_limit.len(), 5);

        // Check for rate limit attribute
        let mut found_limit = false;
        for attr in &attrs_with_limit {
            if attr.key() == RL_EFFECTIVE_RATE {
                let value_float = match attr.value() {
                    TestValue::F64(f) => *f,
                    _ => panic!("Expected float value for rate limit tag"),
                };
                assert_eq!(value_float, rate_limit);
                found_limit = true;
                break;
            }
        }

        assert!(found_limit, "Missing rate limit tag");

        // Test with AgentRateByService mechanism to check for SAMPLING_AGENT_RATE_TAG_KEY

        let agent_rate = 0.75;
        let is_sampled = false;
        let mechanism = mechanism::AGENT_RATE_BY_SERVICE;
        let sampling_result = DdSamplingResult {
            priority: mechanism.to_priority(is_sampled),
            trace_root_info: Some(TraceRootSamplingInfo {
                mechanism,
                rate: agent_rate,
                rl_effective_rate: None,
            }),
        };

        let agent_attrs = sampling_result
            .to_dd_sampling_tags(&TestAttributeFactory)
            .unwrap_or_default();

        // Verify the number of attributes (should be 4: decision_maker + priority +
        // agent_rate + ksr)
        assert_eq!(agent_attrs.len(), 4);

        // Check for agent rate tag and ksr tag
        let mut found_agent_rate = false;
        let mut found_ksr = false;
        for attr in &agent_attrs {
            match attr.key() {
                SAMPLING_AGENT_RATE_TAG_KEY => {
                    let value_float = match attr.value() {
                        TestValue::F64(f) => *f,
                        _ => panic!("Expected float value for agent rate tag"),
                    };
                    assert_eq!(value_float, agent_rate);
                    found_agent_rate = true;
                }
                SAMPLING_KNUTH_RATE_TAG_KEY => {
                    let value_str = match attr.value() {
                        TestValue::String(s) => s.to_string(),
                        _ => panic!("Expected string value for ksr tag"),
                    };
                    assert_eq!(value_str, "0.75");
                    found_ksr = true;
                }
                _ => {}
            }
        }

        assert!(found_agent_rate, "Missing agent rate tag");
        assert!(
            found_ksr,
            "Missing knuth sampling rate tag for agent mechanism"
        );

        // Also check that the SAMPLING_RULE_RATE_TAG_KEY is NOT present for agent mechanism
        for attr in &agent_attrs {
            assert_ne!(
                attr.key(),
                SAMPLING_RULE_RATE_TAG_KEY,
                "Rule rate tag should not be present for agent mechanism"
            );
        }
    }

    #[test]
    fn test_format_sampling_rate() {
        // Exact values
        assert_eq!(format_sampling_rate(1.0), Some("1".to_string()));
        assert_eq!(format_sampling_rate(0.5), Some("0.5".to_string()));
        assert_eq!(format_sampling_rate(0.1), Some("0.1".to_string()));
        assert_eq!(format_sampling_rate(0.0), Some("0".to_string()));

        // Trailing zeros should be stripped
        assert_eq!(format_sampling_rate(0.100000), Some("0.1".to_string()));
        assert_eq!(format_sampling_rate(0.500000), Some("0.5".to_string()));

        // Truncation to 6 significant digits
        assert_eq!(
            format_sampling_rate(0.7654321),
            Some("0.765432".to_string())
        );
        assert_eq!(
            format_sampling_rate(0.123456789),
            Some("0.123457".to_string())
        );

        // Small values
        assert_eq!(format_sampling_rate(0.001), Some("0.001".to_string()));

        // Boundary values
        assert_eq!(format_sampling_rate(0.75), Some("0.75".to_string()));
        assert_eq!(format_sampling_rate(0.999999), Some("0.999999".to_string()));

        // Invalid rates
        assert_eq!(format_sampling_rate(-0.1), None);
        assert_eq!(format_sampling_rate(1.1), None);
        assert_eq!(format_sampling_rate(f64::NAN), None);
        assert_eq!(format_sampling_rate(f64::INFINITY), None);
        assert_eq!(format_sampling_rate(f64::NEG_INFINITY), None);
    }

    #[test]
    fn test_should_sample_parent_context() {
        let sampler = DatadogSampler::new(vec![], 100);

        // Create empty slices for attributes and links
        let empty_attrs: &[TestAttribute] = &[];
        let trace_id = create_trace_id();

        // Test with sampled parent context
        let data_sampled = create_sampling_data(Some(true), &trace_id, "span", empty_attrs);
        let result_sampled = sampler.sample(&data_sampled);

        // Should inherit the sampling decision from parent
        assert!(result_sampled.get_priority().is_keep());
        assert!(result_sampled
            .to_dd_sampling_tags(&TestAttributeFactory)
            .is_none());

        // Test with non-sampled parent context
        let data_not_sampled = create_sampling_data(Some(false), &trace_id, "span", empty_attrs);
        let result_not_sampled = sampler.sample(&data_not_sampled);

        // Should inherit the sampling decision from parent
        assert!(!result_not_sampled.get_priority().is_keep());
        assert!(result_not_sampled
            .to_dd_sampling_tags(&TestAttributeFactory)
            .is_none());
    }

    #[test]
    fn test_should_sample_with_rule() {
        // Create a rule that always samples
        let rule = SamplingRule::new(
            1.0,
            Some("test-service".to_string()),
            None,
            None,
            None,
            None,
        );

        let sampler = DatadogSampler::new(vec![rule], 100);

        let trace_id = create_trace_id();

        // Test with matching attributes
        let attrs = create_attributes("resource", "prod");
        let data = create_sampling_data(None, &trace_id, "span", attrs.as_slice());
        let result = sampler.sample(&data);

        // Should sample and add attributes
        assert!(result.get_priority().is_keep());
        assert!(result.to_dd_sampling_tags(&TestAttributeFactory).is_some());

        // Test with non-matching attributes
        let attrs_no_match = create_attributes("other-resource", "prod");
        let data_no_match =
            create_sampling_data(None, &trace_id, "span", attrs_no_match.as_slice());
        let result_no_match = sampler.sample(&data_no_match);

        // Should still sample (default behavior when no rules match) and add attributes
        assert!(result_no_match.get_priority().is_keep());
        assert!(result_no_match
            .to_dd_sampling_tags(&TestAttributeFactory)
            .is_some());
    }

    #[test]
    fn test_should_sample_with_service_rates() {
        // Initialize sampler
        let sampler = DatadogSampler::new(vec![], 100);

        // Add service rates for different service+env combinations
        let mut rates = HashMap::new();
        rates.insert("service:test-service,env:prod".to_string(), 1.0); // Always sample for test-service in prod
        rates.insert("service:other-service,env:prod".to_string(), 0.0); // Never sample for other-service in prod

        sampler.update_service_rates(rates);

        let trace_id = create_trace_id();

        // Test with attributes that should lead to "service:test-service,env:prod" key
        let attrs_sample = create_attributes_with_service(
            "test-service".to_string(),
            "any_resource_name_matching_env",
            "prod",
        );
        let data_sample = create_sampling_data(
            None,
            &trace_id,
            "span_for_test_service",
            attrs_sample.as_slice(),
        );
        let result_sample = sampler.sample(&data_sample);
        // Expect RecordAndSample because service_key will be "service:test-service,env:prod" ->
        // rate 1.0
        assert!(
            result_sample.get_priority().is_keep(),
            "Span for test-service/prod should be sampled"
        );

        // Test with attributes that should lead to "service:other-service,env:prod" key
        let attrs_no_sample = create_attributes_with_service(
            "other-service".to_string(),
            "any_resource_name_matching_env",
            "prod",
        );
        let data_no_sample = create_sampling_data(
            None,
            &trace_id,
            "span_for_other_service",
            attrs_no_sample.as_slice(),
        );
        let result_no_sample = sampler.sample(&data_no_sample);
        // Expect Drop because service_key will be "service:other-service,env:prod" -> rate 0.0
        assert!(
            !result_no_sample.get_priority().is_keep(),
            "Span for other-service/prod should be dropped"
        );
    }

    #[test]
    fn test_sampling_rule_matches_float_attributes() {
        // Helper to create attributes with a float value
        fn create_attributes_with_float(
            tag_key: &'static str,
            float_value: f64,
        ) -> Vec<TestAttribute> {
            vec![
                TestAttribute::new(RESOURCE_TAG, "resource"),
                TestAttribute::new(ENV_TAG, "prod"),
                TestAttribute::new(tag_key, TestValue::F64(float_value)),
            ]
        }

        // Test case 1: Rule with exact value matching integer float
        let rule_integer = SamplingRule::new(
            0.5,
            None,
            None,
            None,
            Some(HashMap::from([("float_tag".to_string(), "42".to_string())])),
            None,
        );

        // Should match integer float
        let integer_float_attrs = create_attributes_with_float("float_tag", 42.0);
        let span = TestSpan::new("test-span", integer_float_attrs.as_slice());
        assert!(rule_integer.matches(&span));

        // Test case 2: Rule with wildcard pattern and non-integer float
        let rule_wildcard = SamplingRule::new(
            0.5,
            None,
            None,
            None,
            Some(HashMap::from([("float_tag".to_string(), "*".to_string())])),
            None,
        );

        // Should match non-integer float with wildcard pattern
        let decimal_float_attrs = create_attributes_with_float("float_tag", 42.5);
        let span = TestSpan::new("test-span", decimal_float_attrs.as_slice());
        assert!(rule_wildcard.matches(&span));

        // Test case 3: Rule with specific pattern and non-integer float
        // With our simplified logic, non-integer floats will never match non-wildcard patterns
        let rule_specific = SamplingRule::new(
            0.5,
            None,
            None,
            None,
            Some(HashMap::from([(
                "float_tag".to_string(),
                "42.5".to_string(),
            )])),
            None,
        );

        // Should NOT match the exact decimal value because non-integer floats only match wildcards
        let decimal_float_attrs = create_attributes_with_float("float_tag", 42.5);
        let span = TestSpan::new("test-span", decimal_float_attrs.as_slice());
        assert!(!rule_specific.matches(&span));
        // Test case 4: Pattern with partial wildcard '*' for suffix
        let rule_prefix = SamplingRule::new(
            0.5,
            None,
            None,
            None,
            Some(HashMap::from([(
                "float_tag".to_string(),
                "42.*".to_string(),
            )])),
            None,
        );

        // Should NOT match decimal values as we don't do partial pattern matching for non-integer
        // floats
        let span = TestSpan::new("test-span", decimal_float_attrs.as_slice());
        assert!(!rule_prefix.matches(&span));
    }

    #[test]
    fn test_operation_name() {
        // Test that the sampler correctly matches rules based on operation names
        // Operation name generation itself is tested in otel_mappings unit tests

        let http_rule = SamplingRule::new(
            1.0,
            None,
            Some("http.*.request".to_string()),
            None,
            None,
            Some("default".to_string()),
        );

        let sampler = DatadogSampler::new(vec![http_rule], 100);

        let trace_id = create_trace_id();

        // HTTP client request should match http_rule (operation name: http.client.request)
        let http_client_attrs = vec![TestAttribute::new(HTTP_REQUEST_METHOD, "GET")];
        let data = create_sampling_data(None, &trace_id, "test-span", &http_client_attrs);
        assert!(sampler.sample(&data).get_priority().is_keep());

        // Span that doesn't match the rule should still be sampled (default behavior)
        let internal_attrs = vec![TestAttribute::new("custom.tag", "value")];
        let data = create_sampling_data(None, &trace_id, "test-span", &internal_attrs);
        assert!(sampler.sample(&data).get_priority().is_keep());
    }

    #[test]
    fn test_on_rules_update_callback() {
        // Create a sampler with initial rules
        let initial_rule = SamplingRule::new(
            0.1,
            Some("initial-service".to_string()),
            None,
            None,
            None,
            Some("default".to_string()),
        );

        let sampler = DatadogSampler::new(vec![initial_rule], 100);

        // Verify initial state
        assert_eq!(sampler.rules.len(), 1);

        // Get the callback
        let callback = sampler.on_rules_update();

        // Create new rules directly as SamplingRuleConfig objects
        let new_rules = vec![
            SamplingRuleConfig {
                sample_rate: 0.5,
                service: Some("web-*".to_string()),
                name: Some("http.*".to_string()),
                resource: None,
                tags: std::collections::HashMap::new(),
                provenance: "customer".to_string(),
            },
            SamplingRuleConfig {
                sample_rate: 0.2,
                service: Some("api-*".to_string()),
                name: None,
                resource: Some("/api/*".to_string()),
                tags: [("env".to_string(), "prod".to_string())].into(),
                provenance: "dynamic".to_string(),
            },
        ];

        // Apply the update
        callback(&new_rules);

        // Verify the rules were updated
        assert_eq!(sampler.rules.len(), 2);

        // Test that the new rules work by finding a matching rule
        // Create attributes that will generate an operation name matching "http.*"
        // and service matching "web-*"
        let attrs = vec![
            TestAttribute::new(SERVICE_NAME, "web-frontend"),
            TestAttribute::new(HTTP_REQUEST_METHOD, "GET"), /* This will make operation name
                                                             * "http.client.request" */
        ];
        let span = TestSpan::new("test-span", attrs.as_slice());

        let matching_rule = sampler.find_matching_rule(&span);
        assert!(matching_rule.is_some(), "Expected to find a matching rule for service 'web-frontend' and name 'http.client.request'");
        let rule = matching_rule.unwrap();
        assert_eq!(rule.sample_rate, 0.5);
        assert_eq!(rule.provenance, "customer");

        // Test with empty rules array
        callback(&[]);
        assert_eq!(sampler.rules.len(), 0); // Should now have no rules
    }

    #[test]
    fn test_on_agent_response_updates_service_rates() {
        let sampler = DatadogSampler::new(vec![], 100);
        let callback = sampler.on_agent_response();

        // Valid JSON with rate_by_service
        let json = r#"{"rate_by_service":{"service:web,env:prod":0.5}}"#;
        callback(json);
        assert!(sampler
            .service_samplers
            .contains_key("service:web,env:prod"));

        // Invalid JSON — should not panic
        callback("not json");

        // Missing rate_by_service — should not panic
        callback(r#"{"other_field":1}"#);
    }

    #[test]
    fn test_rate_limiter_drop_branch() {
        // Rule with sample_rate=1.0 keeps everything, but rate_limit=0 then drops
        // every kept span via the rate limiter, exercising the drop branch.
        let always_keep = SamplingRule::new(1.0, None, None, None, None, None);
        let sampler = DatadogSampler::new(vec![always_keep], 0);
        let trace_id = TestTraceId::from_bytes([0u8; 16]);
        let attributes = create_attributes("res", "prod");
        let data = create_sampling_data(None, &trace_id, "op", &attributes);
        let decision = sampler.sample(&data);
        assert_eq!(
            decision.priority,
            priority::USER_REJECT,
            "rule kept span, rate_limit=0 should then drop it"
        );
    }

    #[test]
    fn test_get_trace_root_sampling_info() {
        let sampler = DatadogSampler::new(vec![], 100);
        let trace_id = TestTraceId::from_bytes([0u8; 16]);
        let attributes = create_attributes("res", "prod");
        let data = create_sampling_data(None, &trace_id, "op", &attributes);
        let decision = sampler.sample(&data);
        let _info = decision.get_trace_root_sampling_info();
    }
}