saluki_core/observability/metrics/
histogram.rs1use 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
13static BYTES_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); HISTOGRAM_BUCKET_COUNT]> =
16 LazyLock::new(|| histogram_buckets::<HISTOGRAM_BUCKET_COUNT>(256.0, 2.0));
17
18#[derive(Clone, Debug)]
24pub struct AggregatedHistogram {
25 sum: f64,
26 count: u64,
27 buckets: Vec<(f64, &'static str, u64)>,
28}
29
30impl AggregatedHistogram {
31 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 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 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 pub fn sum(&self) -> f64 {
89 self.sum
90 }
91
92 pub fn count(&self) -> u64 {
94 self.count
95 }
96
97 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
106fn 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 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 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 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 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 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 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 assert_eq!(left.count(), 3);
234 assert_eq!(left.sum(), 10.0);
235
236 let buckets: Vec<(&str, u64)> = left.buckets().collect();
237 assert_eq!(buckets[2], ("2", 1));
239 assert_eq!(buckets[4], ("4", 3));
240 }
241}