Skip to main content

saluki_core/observability/metrics/
histogram.rs

1//! Fixed-bucket histogram aggregation for Prometheus exposition.
2
3use std::sync::LazyLock;
4
5use crate::data_model::event::metric::Histogram;
6
7const HISTOGRAM_BUCKET_COUNT: usize = 30;
8static TIME_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); HISTOGRAM_BUCKET_COUNT]> =
9    LazyLock::new(|| histogram_buckets::<HISTOGRAM_BUCKET_COUNT>(0.000000128, 4.0));
10static NON_TIME_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); HISTOGRAM_BUCKET_COUNT]> =
11    LazyLock::new(|| histogram_buckets::<HISTOGRAM_BUCKET_COUNT>(1.0, 2.0));
12
13// Sizes in bytes span far more than the generic schedule's last bucket of 24,576: request payloads reach several
14// megabytes. This schedule starts at 256 bytes and ends past 6 MiB.
15static BYTES_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); HISTOGRAM_BUCKET_COUNT]> =
16    LazyLock::new(|| histogram_buckets::<HISTOGRAM_BUCKET_COUNT>(256.0, 2.0));
17
18/// An aggregated histogram with fixed buckets, suitable for Prometheus exposition.
19///
20/// Bucket layout follows a log-linear schedule. A metric name ending in `_seconds` selects the
21/// time-oriented bucket schedule, one ending in `_bytes` selects the size-oriented schedule, and everything else uses
22/// the generic non-time schedule.
23#[derive(Clone, Debug)]
24pub struct AggregatedHistogram {
25    sum: f64,
26    count: u64,
27    buckets: Vec<(f64, &'static str, u64)>,
28}
29
30impl AggregatedHistogram {
31    /// Creates a new `AggregatedHistogram` for the given metric name.
32    ///
33    /// The metric name determines the bucket schedule: names ending in `_seconds` use a
34    /// time-oriented schedule, names ending in `_bytes` use a size-oriented schedule, and everything else uses a
35    /// generic non-time schedule.
36    pub fn new(metric_name: &str) -> Self {
37        let base_buckets = if metric_name.ends_with("_seconds") {
38            &TIME_HISTOGRAM_BUCKETS[..]
39        } else if metric_name.ends_with("_bytes") {
40            &BYTES_HISTOGRAM_BUCKETS[..]
41        } else {
42            &NON_TIME_HISTOGRAM_BUCKETS[..]
43        };
44
45        let buckets = base_buckets
46            .iter()
47            .map(|(upper_bound, upper_bound_str)| (*upper_bound, *upper_bound_str, 0))
48            .collect();
49
50        Self {
51            sum: 0.0,
52            count: 0,
53            buckets,
54        }
55    }
56
57    /// Merges another aggregated histogram into this one.
58    ///
59    /// The two histograms must have been constructed with the same bucket schedule (in practice,
60    /// this means they were constructed for the same metric name).
61    pub fn merge(&mut self, other: &AggregatedHistogram) {
62        self.sum += other.sum;
63        self.count += other.count;
64        for (dst, src) in self.buckets.iter_mut().zip(other.buckets.iter()) {
65            dst.2 += src.2;
66        }
67    }
68
69    /// Folds the samples from `histogram` into this aggregated histogram.
70    pub fn merge_histogram(&mut self, histogram: &Histogram) {
71        for sample in histogram.samples() {
72            self.add_sample(sample.value.into_inner(), sample.weight.0 as u64);
73        }
74    }
75
76    fn add_sample(&mut self, value: f64, weight: u64) {
77        self.sum += value * weight as f64;
78        self.count += weight;
79
80        for (upper_bound, _, count) in &mut self.buckets {
81            if value <= *upper_bound {
82                *count += weight;
83            }
84        }
85    }
86
87    /// Returns the running sum of all observed samples.
88    pub fn sum(&self) -> f64 {
89        self.sum
90    }
91
92    /// Returns the running count of all observed samples.
93    pub fn count(&self) -> u64 {
94        self.count
95    }
96
97    /// Returns an iterator over the buckets as `(upper_bound_str, cumulative_count)` pairs, in
98    /// ascending order by upper bound.
99    pub fn buckets(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
100        self.buckets
101            .iter()
102            .map(|(_, upper_bound_str, count)| (*upper_bound_str, *count))
103    }
104}
105
106/// Generates a set of `N` log-linear histogram buckets.
107///
108/// The n-th pair of buckets is `(i, j)`, where `i = base * scale^n` and `j` is the midpoint between
109/// `i` and `base * scale^(n+1)`. For example, with `base=2` and `scale=4`, the sequence is `2, 5, 8,
110/// 20, 32, 80, 128, 320, 512, ...`.
111fn histogram_buckets<const N: usize>(base: f64, scale: f64) -> [(f64, &'static str); N] {
112    let mut buckets = [(0.0, ""); N];
113
114    let log_linear_buckets = std::iter::repeat(base).enumerate().flat_map(|(i, base)| {
115        let pow = scale.powf(i as f64);
116        let value = base * pow;
117
118        let next_pow = scale.powf((i + 1) as f64);
119        let next_value = base * next_pow;
120        let midpoint = (value + next_value) / 2.0;
121
122        [value, midpoint]
123    });
124
125    for (i, current_le) in log_linear_buckets.enumerate().take(N) {
126        let (bucket_le, bucket_le_str) = &mut buckets[i];
127        let current_le_str = format!("{}", current_le);
128
129        *bucket_le = current_le;
130        *bucket_le_str = current_le_str.leak();
131    }
132
133    buckets
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn generates_log_linear_bucket_schedule() {
142        // Ported directly from the worked example in `histogram_buckets`'s own doc comment: with
143        // base=2 and scale=4, the n-th pair is `(base*scale^n, midpoint(base*scale^n, base*scale^(n+1)))`,
144        // producing the flattened sequence 2, 5, 8, 20, 32, 80, 128, 320, 512.
145        let buckets = histogram_buckets::<9>(2.0, 4.0);
146        let bounds: Vec<f64> = buckets.iter().map(|(bound, _)| *bound).collect();
147        assert_eq!(bounds, vec![2.0, 5.0, 8.0, 20.0, 32.0, 80.0, 128.0, 320.0, 512.0]);
148
149        // The string labels are the plain `Display` form of each upper bound.
150        let labels: Vec<&str> = buckets.iter().map(|(_, label)| *label).collect();
151        assert_eq!(labels, vec!["2", "5", "8", "20", "32", "80", "128", "320", "512"]);
152
153        // The generic (non-time) schedule uses base=1, scale=2.
154        let non_time = histogram_buckets::<6>(1.0, 2.0);
155        let non_time_bounds: Vec<f64> = non_time.iter().map(|(bound, _)| *bound).collect();
156        assert_eq!(non_time_bounds, vec![1.0, 1.5, 2.0, 3.0, 4.0, 6.0]);
157    }
158
159    #[test]
160    fn metric_name_suffix_selects_the_bucket_schedule() {
161        // A `_seconds` suffix selects the time-oriented schedule; everything else uses the generic
162        // non-time schedule, which starts at an upper bound of 1.0.
163        let time = AggregatedHistogram::new("request_latency_seconds");
164        let non_time = AggregatedHistogram::new("request_count");
165
166        let time_first = time.buckets().next().expect("time schedule has buckets").0;
167        let non_time_first = non_time.buckets().next().expect("non-time schedule has buckets").0;
168
169        assert_eq!(
170            non_time_first, "1",
171            "the non-time schedule starts at an upper bound of 1.0"
172        );
173        assert_ne!(
174            time_first, non_time_first,
175            "the `_seconds` suffix must select a different, time-oriented bucket schedule"
176        );
177    }
178
179    #[test]
180    fn byte_sizes_up_to_the_intake_limit_get_a_finite_bucket() {
181        // Payloads reach 3.2 MB. The generic schedule's last finite bucket is 24,576, so every large payload would
182        // fall into the `+Inf` bucket and sizes of 100 KB and 3 MB would look the same.
183        let last_finite = |name: &str| {
184            let histogram = AggregatedHistogram::new(name);
185            histogram.buckets.last().expect("schedule has buckets").0
186        };
187        assert_eq!(last_finite("payload_size"), 24_576.0);
188        assert!(last_finite("payload_size_bytes") >= 3_200_000.0);
189
190        let mut histogram = AggregatedHistogram::new("payload_size_bytes");
191        histogram.add_sample(100_000.0, 1);
192        histogram.add_sample(3_000_000.0, 1);
193        let finite = |upper_bound: &str| {
194            histogram
195                .buckets()
196                .find(|(label, _)| *label == upper_bound)
197                .map(|(_, count)| count)
198                .expect("bucket exists")
199        };
200        assert_eq!(finite("131072"), 1);
201        assert_eq!(finite("3145728"), 2);
202    }
203
204    #[test]
205    fn adds_weighted_samples_into_cumulative_buckets() {
206        // Using the non-time schedule (1, 1.5, 2, 3, 4, ...), a single value of 2.0 with weight 3 adds
207        // to the sum/count by its weight and increments every cumulative "le" bucket whose upper bound
208        // is >= 2.0.
209        let mut histogram = AggregatedHistogram::new("queue_depth");
210        histogram.add_sample(2.0, 3);
211
212        assert_eq!(histogram.count(), 3);
213        assert_eq!(histogram.sum(), 6.0);
214
215        let buckets: Vec<(&str, u64)> = histogram.buckets().collect();
216        assert_eq!(buckets[0], ("1", 0));
217        assert_eq!(buckets[1], ("1.5", 0));
218        assert_eq!(buckets[2], ("2", 3));
219        assert_eq!(buckets[3], ("3", 3));
220    }
221
222    #[test]
223    fn merge_sums_counts_sum_and_per_bucket_counts() {
224        let mut left = AggregatedHistogram::new("queue_depth");
225        left.add_sample(2.0, 1);
226
227        let mut right = AggregatedHistogram::new("queue_depth");
228        right.add_sample(4.0, 2);
229
230        left.merge(&right);
231
232        // Sum is weighted (2.0*1 + 4.0*2), count is total weight (1 + 2).
233        assert_eq!(left.count(), 3);
234        assert_eq!(left.sum(), 10.0);
235
236        let buckets: Vec<(&str, u64)> = left.buckets().collect();
237        // The `2` bucket only counts the value 2.0 (weight 1); the `4` bucket counts both samples.
238        assert_eq!(buckets[2], ("2", 1));
239        assert_eq!(buckets[4], ("4", 3));
240    }
241}