Skip to main content

torvyn_observability/tracer/
sampling.rs

1//! Trace sampling strategies.
2//!
3//! Per HLI Doc 05 ยง2.3: three sampling strategies:
4//! - Head-based: configurable fraction of flows are fully traced.
5//! - Error-triggered: errored flows are promoted to full trace.
6//! - Tail-latency: flows exceeding a latency threshold are promoted.
7
8use crate::config::TracingConfig;
9
10/// Sampling decision for a flow.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum SamplingDecision {
13    /// Do not export spans for this flow.
14    Drop,
15    /// Export spans (flow was selected by head sampling or promoted).
16    Sample,
17}
18
19/// Sampler that makes per-flow sampling decisions.
20///
21/// # Thread-safety
22/// Immutable after creation. Safe to share across tasks.
23pub struct Sampler {
24    /// Head-based sample rate [0.0, 1.0].
25    sample_rate: f64,
26    /// Whether to promote errored flows.
27    error_promote: bool,
28    /// Latency threshold in nanoseconds for promotion.
29    latency_promote_threshold_ns: u64,
30}
31
32impl Sampler {
33    /// Create a new sampler from configuration.
34    ///
35    /// # COLD PATH
36    pub fn new(config: &TracingConfig) -> Self {
37        Self {
38            sample_rate: config.sample_rate,
39            error_promote: config.error_promote,
40            latency_promote_threshold_ns: config.latency_promote_threshold_ms * 1_000_000,
41        }
42    }
43
44    /// Make a head-based sampling decision for a new flow.
45    ///
46    /// Uses a deterministic hash of the trace ID so sampling is reproducible.
47    ///
48    /// # COLD PATH โ€” called once per flow.
49    pub fn should_sample_head(&self, trace_id_bytes: &[u8; 16]) -> SamplingDecision {
50        if self.sample_rate >= 1.0 {
51            return SamplingDecision::Sample;
52        }
53        if self.sample_rate <= 0.0 {
54            return SamplingDecision::Drop;
55        }
56
57        // Use the last 8 bytes of trace ID as a u64, then check if it falls
58        // within the sample rate range.
59        let hash = u64::from_le_bytes([
60            trace_id_bytes[8],
61            trace_id_bytes[9],
62            trace_id_bytes[10],
63            trace_id_bytes[11],
64            trace_id_bytes[12],
65            trace_id_bytes[13],
66            trace_id_bytes[14],
67            trace_id_bytes[15],
68        ]);
69
70        let threshold = (self.sample_rate * u64::MAX as f64) as u64;
71        if hash <= threshold {
72            SamplingDecision::Sample
73        } else {
74            SamplingDecision::Drop
75        }
76    }
77
78    /// Check if a flow should be promoted due to an error.
79    ///
80    /// # WARM PATH โ€” called when an error occurs.
81    #[inline]
82    pub fn should_promote_error(&self) -> bool {
83        self.error_promote
84    }
85
86    /// Check if a flow should be promoted due to high latency.
87    ///
88    /// # WARM PATH โ€” called at flow completion.
89    #[inline]
90    pub fn should_promote_latency(&self, latency_ns: u64) -> bool {
91        self.latency_promote_threshold_ns > 0 && latency_ns > self.latency_promote_threshold_ns
92    }
93}
94
95// ---------------------------------------------------------------------------
96// Tests
97// ---------------------------------------------------------------------------
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    fn default_config() -> TracingConfig {
104        TracingConfig::default()
105    }
106
107    #[test]
108    fn test_sampler_rate_zero_drops_all() {
109        let mut config = default_config();
110        config.sample_rate = 0.0;
111        let sampler = Sampler::new(&config);
112
113        for i in 0u8..100 {
114            let trace_id = [i; 16];
115            assert_eq!(
116                sampler.should_sample_head(&trace_id),
117                SamplingDecision::Drop
118            );
119        }
120    }
121
122    #[test]
123    fn test_sampler_rate_one_samples_all() {
124        let mut config = default_config();
125        config.sample_rate = 1.0;
126        let sampler = Sampler::new(&config);
127
128        for i in 0u8..100 {
129            let trace_id = [i; 16];
130            assert_eq!(
131                sampler.should_sample_head(&trace_id),
132                SamplingDecision::Sample
133            );
134        }
135    }
136
137    #[test]
138    fn test_sampler_partial_rate() {
139        let mut config = default_config();
140        config.sample_rate = 0.5;
141        let sampler = Sampler::new(&config);
142
143        let mut sampled = 0;
144        let total = 10000;
145        for i in 0u64..total {
146            // Spread values across the full u64 range using a multiplicative hash,
147            // otherwise small sequential i values all fall below the threshold.
148            let val = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
149            let trace_id = val.to_le_bytes();
150            let mut full = [0u8; 16];
151            full[8..].copy_from_slice(&trace_id);
152            if sampler.should_sample_head(&full) == SamplingDecision::Sample {
153                sampled += 1;
154            }
155        }
156
157        // With 50% rate, expect roughly 5000 +/- generous margin.
158        assert!(
159            sampled > 3000 && sampled < 7000,
160            "sampled {sampled} out of {total}"
161        );
162    }
163
164    #[test]
165    fn test_promote_error() {
166        let config = default_config(); // error_promote = true
167        let sampler = Sampler::new(&config);
168        assert!(sampler.should_promote_error());
169    }
170
171    #[test]
172    fn test_promote_error_disabled() {
173        let mut config = default_config();
174        config.error_promote = false;
175        let sampler = Sampler::new(&config);
176        assert!(!sampler.should_promote_error());
177    }
178
179    #[test]
180    fn test_promote_latency() {
181        let config = default_config(); // threshold = 10ms
182        let sampler = Sampler::new(&config);
183
184        assert!(!sampler.should_promote_latency(5_000_000)); // 5ms
185        assert!(sampler.should_promote_latency(15_000_000)); // 15ms
186    }
187
188    #[test]
189    fn test_promote_latency_zero_threshold() {
190        let mut config = default_config();
191        config.latency_promote_threshold_ms = 0;
192        let sampler = Sampler::new(&config);
193
194        assert!(!sampler.should_promote_latency(100_000_000));
195    }
196}