Skip to main content

feldera_storage/
histogram.rs

1use std::{
2    collections::VecDeque,
3    ops::RangeInclusive,
4    sync::atomic::{AtomicU64, Ordering},
5    time::{Duration, Instant},
6};
7
8use itertools::Itertools;
9
10const N_BUCKETS: usize = 92;
11
12/// A histogram with exponential buckets.
13///
14/// This histogram maintains 92 buckets, one for each value or range below,
15/// listing ranges by their lower endpoints:
16///
17/// - 0
18/// - 1, 2, 3, ... 9
19/// - 10, 20, 30, ... 90
20/// - 100, 200, 300, ... 900
21/// - 1000, 2000, 3000, ... 9000
22/// - 10_000, 20_000, 30_000, ... 90_000
23/// - 100_000, 200_000, 300_000, ... 900_000
24/// - 1_000_000, 2_000_000, 3_000_000, ... 9_000_000
25/// - 10_000_000, 20_000_000, 30_000_000, ... 90_000_000
26/// - 100_000_000, 200_000_000, 300_000_000, ... 900_000_000
27/// - 1_000_000_000, 2_000_000_000, 3_000_000_000, ... 9_000_000_000
28/// - 10_000_000_000 through [u64::MAX].
29#[derive(Debug)]
30pub struct ExponentialHistogram {
31    buckets: [AtomicU64; N_BUCKETS],
32    sum: AtomicU64,
33}
34
35impl ExponentialHistogram {
36    /// Constructs a new exponential histogram.
37    pub const fn new() -> Self {
38        Self {
39            buckets: [const { AtomicU64::new(0) }; N_BUCKETS],
40            sum: AtomicU64::new(0),
41        }
42    }
43
44    /// Records `value` in the histogram.
45    pub fn record(&self, value: impl TryInto<u64>) {
46        if let Ok(value) = value.try_into() {
47            self.buckets[number_to_bucket(value)].fetch_add(1, Ordering::Relaxed);
48            self.sum.fetch_add(value, Ordering::Relaxed);
49        }
50    }
51
52    /// Records the time elapsed since `start` in the histogram, as a count of
53    /// microseconds.
54    pub fn record_elapsed(&self, start: Instant) {
55        self.record_duration(start.elapsed());
56    }
57
58    /// Records `duration` as a count of microseconds.
59    pub fn record_duration(&self, duration: Duration) {
60        self.record(duration.as_micros());
61    }
62
63    /// Returns a snapshot of the histogram.
64    pub fn snapshot(&self) -> ExponentialHistogramSnapshot {
65        ExponentialHistogramSnapshot {
66            buckets: self
67                .buckets
68                .iter()
69                .map(|bucket| bucket.load(Ordering::Relaxed))
70                .collect_array()
71                .unwrap(),
72            sum: self.sum.load(Ordering::Relaxed),
73        }
74    }
75
76    /// Returns the sum of the values in the histogram
77    pub fn sum(&self) -> u64 {
78        self.sum.load(Ordering::Relaxed)
79    }
80
81    /// Calls `f` and records the amount of time that it takes to run, in
82    /// microseconds, in the histogram.
83    pub fn record_callback<F, T>(&self, f: F) -> T
84    where
85        F: FnOnce() -> T,
86    {
87        let start = Instant::now();
88        let retval = f();
89        self.record_elapsed(start);
90        retval
91    }
92}
93
94impl Default for ExponentialHistogram {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100pub struct ExponentialHistogramSnapshot {
101    buckets: [u64; N_BUCKETS],
102    sum: u64,
103}
104
105impl ExponentialHistogramSnapshot {
106    pub fn iter_buckets(&self) -> impl Iterator<Item = Bucket> + use<'_> {
107        self.buckets
108            .iter()
109            .enumerate()
110            .map(|(index, count)| Bucket {
111                range: bucket_to_range(index),
112                count: *count,
113            })
114    }
115    pub fn sum(&self) -> u64 {
116        self.sum
117    }
118
119    /// Approximate `q`-quantile (`q` in `0.0..=1.0`), as the lower bound of the
120    /// containing bucket. `None` if empty.
121    pub fn quantile(&self, q: f64) -> Option<u64> {
122        let total: u64 = self.buckets.iter().sum();
123        if total == 0 {
124            return None;
125        }
126        let rank = ((q.clamp(0.0, 1.0) * total as f64).ceil() as u64).clamp(1, total);
127        let mut cumulative = 0u64;
128        for (index, count) in self.buckets.iter().enumerate() {
129            cumulative += *count;
130            if cumulative >= rank {
131                return Some(*bucket_to_range(index).start());
132            }
133        }
134        // Unreachable: `cumulative` reaches `total >= rank` in the loop.
135        Some(*bucket_to_range(N_BUCKETS - 1).start())
136    }
137}
138
139pub struct Bucket {
140    pub range: RangeInclusive<u64>,
141    pub count: u64,
142}
143
144fn number_to_bucket(number: u64) -> usize {
145    let bucket = match number {
146        // buckets 0..=9
147        0..10 => number,
148        // buckets 10..=18
149        10..100 => (number - 10) / 10 + 10,
150        // buckets 19..=27
151        100..1000 => (number - 100) / 100 + 19,
152        // buckets 28..=36
153        1000..10_000 => (number - 1000) / 1000 + 28,
154        // buckets 37..=45
155        10_000..100_000 => (number - 10_000) / 10_000 + 37,
156        // buckets 46..=54
157        100_000..1_000_000 => (number - 100_000) / 100_000 + 46,
158        // buckets 55..=63
159        1_000_000..10_000_000 => (number - 1_000_000) / 1_000_000 + 55,
160        // buckets 64..=72
161        10_000_000..100_000_000 => (number - 10_000_000) / 10_000_000 + 64,
162        // buckets 73..=81
163        100_000_000..1_000_000_000 => (number - 100_000_000) / 100_000_000 + 73,
164        // buckets 82..=90
165        1_000_000_000..10_000_000_000 => (number - 1_000_000_000) / 1_000_000_000 + 82,
166        // bucket 91
167        _ => 91,
168    };
169    bucket as usize
170}
171
172fn bucket_to_range(bucket: usize) -> RangeInclusive<u64> {
173    let bucket = bucket as u64;
174    fn bucket_range(index: u64, width: u64) -> RangeInclusive<u64> {
175        let start = (index + 1) * width;
176        let end = start + (width - 1);
177        start..=end
178    }
179    match bucket {
180        0..=9 => bucket..=bucket,
181        10..=18 => bucket_range(bucket - 10, 10),
182        19..=27 => bucket_range(bucket - 19, 100),
183        28..=36 => bucket_range(bucket - 28, 1000),
184        37..=45 => bucket_range(bucket - 37, 10_000),
185        46..=54 => bucket_range(bucket - 46, 100_000),
186        55..=63 => bucket_range(bucket - 55, 1_000_000),
187        64..=72 => bucket_range(bucket - 64, 10_000_000),
188        73..=81 => bucket_range(bucket - 73, 100_000_000),
189        82..=90 => bucket_range(bucket - 82, 1_000_000_000),
190        91 => 1_000_000_001..=u64::MAX,
191        _ => unreachable!(),
192    }
193}
194
195/// A sliding histogram with exponential buckets.
196///
197/// This histogram records up to a specified number of samples across a
198/// specified maximum amount of time.  Within that range, it maintains an
199/// exponential histogram with the same form as [ExponentialHistogram].
200#[derive(Debug)]
201pub struct SlidingHistogram {
202    buckets: [u64; N_BUCKETS],
203    samples: VecDeque<Sample>,
204    sum: u64,
205    max_samples: usize,
206    max_elapsed: Duration,
207}
208
209#[derive(Debug)]
210struct Sample {
211    time: Instant,
212    value: u64,
213}
214
215impl SlidingHistogram {
216    /// Constructs a new sliding histogram.  The histogram will keep at most the
217    /// most recent `max_samples` samples that have been recorded over at most
218    /// the most recent `max_elapsed` amount of time.
219    pub const fn new(max_samples: usize, max_elapsed: Duration) -> Self {
220        Self {
221            buckets: [0; N_BUCKETS],
222            samples: VecDeque::new(),
223            sum: 0,
224            max_samples,
225            max_elapsed,
226        }
227    }
228
229    /// Records `value` in the histogram.
230    pub fn record(&mut self, value: impl TryInto<u64>) {
231        if let Ok(value) = value.try_into() {
232            if self.samples.len() >= self.max_samples {
233                self.drop_sample();
234            }
235            self.samples.push_back(Sample {
236                time: Instant::now(),
237                value,
238            });
239            self.buckets[number_to_bucket(value)] += 1;
240            self.sum += value;
241        }
242    }
243
244    /// Records the time elapsed since `start` in the histogram, as a count of
245    /// microseconds.
246    pub fn record_elapsed(&mut self, start: Instant) {
247        self.record(start.elapsed().as_micros());
248    }
249
250    /// Returns a snapshot of the histogram.
251    pub fn snapshot(&mut self) -> ExponentialHistogramSnapshot {
252        // Drop samples that are more than `max_elapsed` older than the most
253        // recent sample.
254        //
255        // (We use the most recent sample instead of the current time to avoid
256        // dropping all the samples if nothing has been recorded recently.)
257        if let Some(most_recent) = self.samples.back() {
258            let cutoff = most_recent.time - self.max_elapsed;
259            while self
260                .samples
261                .front()
262                .is_some_and(|sample| sample.time < cutoff)
263            {
264                self.drop_sample();
265            }
266        }
267
268        ExponentialHistogramSnapshot {
269            buckets: self.buckets,
270            sum: self.sum,
271        }
272    }
273
274    /// Returns the sum of the values in the histogram
275    pub fn sum(&self) -> u64 {
276        self.sum
277    }
278
279    /// Calls `f` and records the amount of time that it takes to run, in
280    /// microseconds, in the histogram.
281    pub fn record_callback<F, T>(&mut self, f: F) -> T
282    where
283        F: FnOnce() -> T,
284    {
285        let start = Instant::now();
286        let retval = f();
287        self.record_elapsed(start);
288        retval
289    }
290
291    fn drop_sample(&mut self) {
292        let sample = self.samples.pop_front().unwrap();
293        self.buckets[number_to_bucket(sample.value)] -= 1;
294        self.sum -= sample.value;
295    }
296}
297
298#[cfg(test)]
299mod test {
300    use crate::histogram::{ExponentialHistogram, N_BUCKETS, bucket_to_range, number_to_bucket};
301
302    #[test]
303    fn quantile_empty() {
304        let hist = ExponentialHistogram::new();
305        assert_eq!(hist.snapshot().quantile(0.5), None);
306        assert_eq!(hist.snapshot().quantile(0.99), None);
307    }
308
309    #[test]
310    fn quantile_single_sample() {
311        let hist = ExponentialHistogram::new();
312        hist.record(42u64);
313        // 42 lands in the bucket for [40, 49]; the lower bound is 40.
314        assert_eq!(hist.snapshot().quantile(0.0), Some(40));
315        assert_eq!(hist.snapshot().quantile(0.5), Some(40));
316        assert_eq!(hist.snapshot().quantile(1.0), Some(40));
317    }
318
319    #[test]
320    fn quantile_all_same_bucket() {
321        let hist = ExponentialHistogram::new();
322        for _ in 0..100 {
323            hist.record(5u64);
324        }
325        // Values 0..=9 each occupy their own bucket, so 5 is exact.
326        assert_eq!(hist.snapshot().quantile(0.5), Some(5));
327        assert_eq!(hist.snapshot().quantile(0.99), Some(5));
328    }
329
330    #[test]
331    fn quantile_known_distribution() {
332        let hist = ExponentialHistogram::new();
333        // 99 fast samples (bucket [0,0]) and 1 slow sample (bucket [900,999]).
334        for _ in 0..99 {
335            hist.record(0u64);
336        }
337        hist.record(950u64);
338        let snap = hist.snapshot();
339        // p50 stays with the fast majority.
340        assert_eq!(snap.quantile(0.5), Some(0));
341        // p99 (ceil(0.99*100)=99th value) is still the last fast sample.
342        assert_eq!(snap.quantile(0.99), Some(0));
343        // p100 reaches the lone slow sample: bucket [900, 999], lower bound 900.
344        assert_eq!(snap.quantile(1.0), Some(900));
345    }
346
347    #[test]
348    fn buckets() {
349        let mut base = 1;
350        while base <= u64::MAX / 10 {
351            for multiple in 1..10 {
352                let number = base * multiple;
353                for number in [number - 1, number, number + 1] {
354                    let bucket = number_to_bucket(number);
355                    assert!((0..N_BUCKETS).contains(&bucket));
356                    let bucket_range = bucket_to_range(bucket);
357                    assert!(bucket_range.contains(&number));
358                }
359            }
360            base *= 10;
361        }
362    }
363}