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(start.elapsed().as_micros());
56    }
57
58    /// Returns a snapshot of the histogram.
59    pub fn snapshot(&self) -> ExponentialHistogramSnapshot {
60        ExponentialHistogramSnapshot {
61            buckets: self
62                .buckets
63                .iter()
64                .map(|bucket| bucket.load(Ordering::Relaxed))
65                .collect_array()
66                .unwrap(),
67            sum: self.sum.load(Ordering::Relaxed),
68        }
69    }
70
71    /// Returns the sum of the values in the histogram
72    pub fn sum(&self) -> u64 {
73        self.sum.load(Ordering::Relaxed)
74    }
75
76    /// Calls `f` and records the amount of time that it takes to run, in
77    /// microseconds, in the histogram.
78    pub fn record_callback<F, T>(&self, f: F) -> T
79    where
80        F: FnOnce() -> T,
81    {
82        let start = Instant::now();
83        let retval = f();
84        self.record_elapsed(start);
85        retval
86    }
87}
88
89impl Default for ExponentialHistogram {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95pub struct ExponentialHistogramSnapshot {
96    buckets: [u64; N_BUCKETS],
97    sum: u64,
98}
99
100impl ExponentialHistogramSnapshot {
101    pub fn iter_buckets(&self) -> impl Iterator<Item = Bucket> + use<'_> {
102        self.buckets
103            .iter()
104            .enumerate()
105            .map(|(index, count)| Bucket {
106                range: bucket_to_range(index),
107                count: *count,
108            })
109    }
110    pub fn sum(&self) -> u64 {
111        self.sum
112    }
113}
114
115pub struct Bucket {
116    pub range: RangeInclusive<u64>,
117    pub count: u64,
118}
119
120fn number_to_bucket(number: u64) -> usize {
121    let bucket = match number {
122        // buckets 0..=9
123        0..10 => number,
124        // buckets 10..=18
125        10..100 => (number - 10) / 10 + 10,
126        // buckets 19..=27
127        100..1000 => (number - 100) / 100 + 19,
128        // buckets 28..=36
129        1000..10_000 => (number - 1000) / 1000 + 28,
130        // buckets 37..=45
131        10_000..100_000 => (number - 10_000) / 10_000 + 37,
132        // buckets 46..=54
133        100_000..1_000_000 => (number - 100_000) / 100_000 + 46,
134        // buckets 55..=63
135        1_000_000..10_000_000 => (number - 1_000_000) / 1_000_000 + 55,
136        // buckets 64..=72
137        10_000_000..100_000_000 => (number - 10_000_000) / 10_000_000 + 64,
138        // buckets 73..=81
139        100_000_000..1_000_000_000 => (number - 100_000_000) / 100_000_000 + 73,
140        // buckets 82..=90
141        1_000_000_000..10_000_000_000 => (number - 1_000_000_000) / 1_000_000_000 + 82,
142        // bucket 91
143        _ => 91,
144    };
145    bucket as usize
146}
147
148fn bucket_to_range(bucket: usize) -> RangeInclusive<u64> {
149    let bucket = bucket as u64;
150    fn bucket_range(index: u64, width: u64) -> RangeInclusive<u64> {
151        let start = (index + 1) * width;
152        let end = start + (width - 1);
153        start..=end
154    }
155    match bucket {
156        0..=9 => bucket..=bucket,
157        10..=18 => bucket_range(bucket - 10, 10),
158        19..=27 => bucket_range(bucket - 19, 100),
159        28..=36 => bucket_range(bucket - 28, 1000),
160        37..=45 => bucket_range(bucket - 37, 10_000),
161        46..=54 => bucket_range(bucket - 46, 100_000),
162        55..=63 => bucket_range(bucket - 55, 1_000_000),
163        64..=72 => bucket_range(bucket - 64, 10_000_000),
164        73..=81 => bucket_range(bucket - 73, 100_000_000),
165        82..=90 => bucket_range(bucket - 82, 1_000_000_000),
166        91 => 1_000_000_001..=u64::MAX,
167        _ => unreachable!(),
168    }
169}
170
171/// A sliding histogram with exponential buckets.
172///
173/// This histogram records up to a specified number of samples across a
174/// specified maximum amount of time.  Within that range, it maintains an
175/// exponential histogram with the same form as [ExponentialHistogram].
176#[derive(Debug)]
177pub struct SlidingHistogram {
178    buckets: [u64; N_BUCKETS],
179    samples: VecDeque<Sample>,
180    sum: u64,
181    max_samples: usize,
182    max_elapsed: Duration,
183}
184
185#[derive(Debug)]
186struct Sample {
187    time: Instant,
188    value: u64,
189}
190
191impl SlidingHistogram {
192    /// Constructs a new sliding histogram.  The histogram will keep at most the
193    /// most recent `max_samples` samples that have been recorded over at most
194    /// the most recent `max_elapsed` amount of time.
195    pub const fn new(max_samples: usize, max_elapsed: Duration) -> Self {
196        Self {
197            buckets: [0; N_BUCKETS],
198            samples: VecDeque::new(),
199            sum: 0,
200            max_samples,
201            max_elapsed,
202        }
203    }
204
205    /// Records `value` in the histogram.
206    pub fn record(&mut self, value: impl TryInto<u64>) {
207        if let Ok(value) = value.try_into() {
208            if self.samples.len() >= self.max_samples {
209                self.drop_sample();
210            }
211            self.samples.push_back(Sample {
212                time: Instant::now(),
213                value,
214            });
215            self.buckets[number_to_bucket(value)] += 1;
216            self.sum += value;
217        }
218    }
219
220    /// Records the time elapsed since `start` in the histogram, as a count of
221    /// microseconds.
222    pub fn record_elapsed(&mut self, start: Instant) {
223        self.record(start.elapsed().as_micros());
224    }
225
226    /// Returns a snapshot of the histogram.
227    pub fn snapshot(&mut self) -> ExponentialHistogramSnapshot {
228        // Drop samples that are more than `max_elapsed` older than the most
229        // recent sample.
230        //
231        // (We use the most recent sample instead of the current time to avoid
232        // dropping all the samples if nothing has been recorded recently.)
233        if let Some(most_recent) = self.samples.back() {
234            let cutoff = most_recent.time - self.max_elapsed;
235            while self
236                .samples
237                .front()
238                .is_some_and(|sample| sample.time < cutoff)
239            {
240                self.drop_sample();
241            }
242        }
243
244        ExponentialHistogramSnapshot {
245            buckets: self.buckets,
246            sum: self.sum,
247        }
248    }
249
250    /// Returns the sum of the values in the histogram
251    pub fn sum(&self) -> u64 {
252        self.sum
253    }
254
255    /// Calls `f` and records the amount of time that it takes to run, in
256    /// microseconds, in the histogram.
257    pub fn record_callback<F, T>(&mut self, f: F) -> T
258    where
259        F: FnOnce() -> T,
260    {
261        let start = Instant::now();
262        let retval = f();
263        self.record_elapsed(start);
264        retval
265    }
266
267    fn drop_sample(&mut self) {
268        let sample = self.samples.pop_front().unwrap();
269        self.buckets[number_to_bucket(sample.value)] -= 1;
270        self.sum -= sample.value;
271    }
272}
273
274#[cfg(test)]
275mod test {
276    use crate::histogram::{N_BUCKETS, bucket_to_range, number_to_bucket};
277
278    #[test]
279    fn buckets() {
280        let mut base = 1;
281        while base <= u64::MAX / 10 {
282            for multiple in 1..10 {
283                let number = base * multiple;
284                for number in [number - 1, number, number + 1] {
285                    let bucket = number_to_bucket(number);
286                    assert!((0..N_BUCKETS).contains(&bucket));
287                    let bucket_range = bucket_to_range(bucket);
288                    assert!(bucket_range.contains(&number));
289                }
290            }
291            base *= 10;
292        }
293    }
294}