Skip to main content

libdd_ddsketch/
lib.rs

1// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4//! This crate defines a minimal implementation of DDSketch.
5//!
6//! DDSketch is a data sketch used to generate percentiles over streaming data using constant
7//! memory. A DDSketch is essentially a histogram that partitions the range of positive values into
8//! an infinite number of indexed bins whose size grows exponentially. It keeps track of the number
9//! of values (or possibly floating-point weights) added to each bin. Negative values are
10//! partitioned like positive values, symmetrically to zero. The value zero as well as its close
11//! neighborhood that would be mapped to extreme bin indexes is mapped to a specific counter.
12
13#![cfg_attr(not(test), deny(clippy::panic))]
14#![cfg_attr(not(test), deny(clippy::unwrap_used))]
15#![cfg_attr(not(test), deny(clippy::expect_used))]
16#![cfg_attr(not(test), deny(clippy::todo))]
17#![cfg_attr(not(test), deny(clippy::unimplemented))]
18
19use std::collections::{HashMap, VecDeque};
20
21use prost::Message;
22
23/// Protobuf representation of DDSketch - generated by build.rs
24#[rustfmt::skip]
25pub mod pb;
26
27/// This is a minimal DDSketch implementation
28///
29/// This implementation only supports a part of the standard (which is also only the parts dd
30/// backend supports :shrug:)
31/// - max length contiguous bin store, with lower bin collapse behavior.
32/// - Positive or zero values
33///
34/// The default sketch has a 1% relative accuracy, and only accepts positive points
35///
36/// See <https://github.com/DataDog/sketches-go> for the reference implementation
37#[derive(Debug, Default, Clone)]
38pub struct DDSketch {
39    store: LowCollapsingDenseStore, // Store the weight of each bin
40    zero_count: f64,                // Store the weight of the bin of value 0
41    mapping: LogMapping,            // Bin-Value mapping
42}
43
44impl DDSketch {
45    /// Return an iterator over `(value, weight)` pair for each bin
46    pub fn ordered_bins(&self) -> Vec<(f64, f64)> {
47        let mut bins: Vec<_> = std::iter::once((0.0, self.zero_count))
48            .chain(self.store.bins().map(|(b, v)| (self.mapping.value(b), v)))
49            .collect();
50        bins.sort_by(|a, b| a.0.total_cmp(&b.0));
51        bins
52    }
53
54    // Return the number of points in the sketch
55    pub fn count(&self) -> f64 {
56        self.zero_count + self.store.bins.iter().sum::<f64>()
57    }
58
59    /// Add a point with value `point` to the sketch
60    /// `point` must be positive
61    pub fn add(&mut self, point: f64) -> Result<(), Box<dyn std::error::Error>> {
62        self.add_with_count(point, 1.0)
63    }
64
65    /// Add `count` point with value `point` to the sketch
66    /// `count` and `point` must be positive
67    pub fn add_with_count(
68        &mut self,
69        point: f64,
70        count: f64,
71    ) -> Result<(), Box<dyn std::error::Error>> {
72        if count.is_nan() || count.is_infinite() {
73            return Err("count is invalid".into());
74        }
75        if point < 0.0 || point.is_nan() || point.is_infinite() {
76            return Err("point is invalid".into());
77        } else if point < self.mapping.min_indexable_value {
78            self.zero_count += count;
79        } else {
80            let index = self.mapping.index(point);
81            *self.store.bin_mut(index) += count;
82        }
83        Ok(())
84    }
85
86    /// A sketch whose logarithmic mapping has the given `gamma` and `index_offset` rather than
87    /// the default ones, or `None` if they do not describe a mapping.
88    ///
89    /// Bins only line up between sketches whose mappings agree on both, so a producer whose
90    /// consumer expects a particular mapping has to build its sketches with that mapping.
91    pub fn with_log_mapping(gamma: f64, index_offset: f64) -> Option<Self> {
92        Some(Self {
93            mapping: LogMapping::new(gamma, index_offset)?,
94            ..Default::default()
95        })
96    }
97
98    /// Index of the bin `point` falls into, or `None` for a point the sketch would count as
99    /// zero or does not accept.
100    pub fn bin_index(&self, point: f64) -> Option<i32> {
101        if point < self.mapping.min_indexable_value || point.is_nan() || point.is_infinite() {
102            return None;
103        }
104        Some(self.mapping.index(point))
105    }
106
107    /// Add `count` points to the bin at `index`, as [`Self::bin_index`] numbers them.
108    ///
109    /// For producers that bin values themselves and only hand the sketch their counts.
110    /// `count` must be positive, and `index` one that [`Self::bin_index`] can return.
111    pub fn add_to_bin(&mut self, index: i32, count: f64) -> Result<(), Box<dyn std::error::Error>> {
112        if !count.is_finite() || count <= 0.0 {
113            return Err("count must be positive and finite".into());
114        }
115        // An index the mapping could never produce could make the store span past `i32`.
116        let lowest = self.bin_index(self.mapping.min_indexable_value);
117        let highest = self.bin_index(f64::MAX);
118        if !lowest
119            .zip(highest)
120            .is_some_and(|(lo, hi)| (lo..=hi).contains(&index))
121        {
122            return Err("index is outside the sketch's mapping".into());
123        }
124        *self.store.bin_mut(index) += count;
125        Ok(())
126    }
127
128    /// Return a protobuf of the sketch
129    pub fn into_pb(self) -> pb::DdSketch {
130        let contiguous_bins: Vec<f64> = self.store.bins.into();
131        pb::DdSketch {
132            mapping: Some(pb::IndexMapping {
133                gamma: self.mapping.gamma,
134                index_offset: self.mapping.index_offset,
135                interpolation: pb::index_mapping::Interpolation::None.into(),
136            }),
137            positive_values: Some(pb::Store {
138                bin_counts: HashMap::new(),
139                contiguous_bin_counts: contiguous_bins,
140                contiguous_bin_index_offset: self.store.offset,
141            }),
142            zero_count: self.zero_count,
143            negative_values: Some(pb::Store {
144                bin_counts: HashMap::new(),
145                contiguous_bin_counts: Vec::new(),
146                contiguous_bin_index_offset: 0,
147            }),
148        }
149    }
150
151    /// Return a serialized protobuf of the sketch
152    pub fn encode_to_vec(self) -> Vec<u8> {
153        self.into_pb().encode_to_vec()
154    }
155
156    /// Reconstruct a sketch from its protobuf. `None` if mapping missing/invalid.
157    pub fn from_pb(sketch: pb::DdSketch) -> Option<DDSketch> {
158        let mapping_pb = sketch.mapping?;
159        let mapping = LogMapping::new(mapping_pb.gamma, mapping_pb.index_offset)?;
160        let store = match sketch.positive_values {
161            Some(s) => LowCollapsingDenseStore {
162                bins: s.contiguous_bin_counts.into(),
163                offset: s.contiguous_bin_index_offset,
164                max_size: LowCollapsingDenseStore::default().max_size,
165            },
166            None => LowCollapsingDenseStore::default(),
167        };
168        Some(DDSketch {
169            store,
170            zero_count: sketch.zero_count,
171            mapping,
172        })
173    }
174
175    /// Decode a sketch from serialized protobuf bytes; `None` on decode/mapping failure.
176    pub fn from_encoded(bytes: &[u8]) -> Option<DDSketch> {
177        Self::from_pb(pb::DdSketch::decode(bytes).ok()?)
178    }
179}
180
181/// A store mapping the bin indexes to their respective weights
182///
183/// Stores the weights as contiguousBinCounts, only the bins within `offset` and the highest
184/// non empty bin are stored.
185///
186/// Stores the weights of a contiguous range of bins containing all non-empty bins. The range start
187/// at index `offset` and end at index `offset + bins.len()`
188///
189/// The range of stored bins is updated when accessing the index of a bin out of the range
190/// with [`Self::bin_idx_to_store_idx()`]. If the `max_size` is reached the lower bins are
191/// collapsed together to free space.
192#[derive(Debug, Clone)]
193struct LowCollapsingDenseStore {
194    bins: VecDeque<f64>,
195    offset: i32,
196    max_size: i32,
197}
198
199impl LowCollapsingDenseStore {
200    fn new(max_size: i32) -> Option<Self> {
201        if max_size < 0 {
202            return None;
203        }
204        Some(Self {
205            bins: VecDeque::new(),
206            offset: 0,
207            max_size,
208        })
209    }
210
211    /// Return an iterator over the bins
212    /// The iterator yields pairs `(bin_index, count)`
213    fn bins(&self) -> impl Iterator<Item = (i32, f64)> + '_ {
214        self.bins
215            .iter()
216            .enumerate()
217            .map(|(i, &v)| (i as i32 + self.offset, v))
218    }
219
220    /// Return a mutable reference to the bin at index `bin_index`
221    fn bin_mut(&mut self, bin_index: i32) -> &mut f64 {
222        let store_index = self.bin_idx_to_store_idx(bin_index);
223        &mut self.bins[store_index]
224    }
225
226    /// Return the `store_index` of the bin at index `bin_index`
227    fn bin_idx_to_store_idx(&mut self, bin_index: i32) -> usize {
228        if self.bins.is_empty() {
229            // If the bins are empty, start them at the index
230            self.offset = bin_index;
231            self.bins.push_back(0.0);
232            return 0;
233        }
234
235        // General case
236        // Bucket lower than the stored range
237        if bin_index < self.offset {
238            let additional_low_bins = self.offset - bin_index;
239            debug_assert!(additional_low_bins >= 0);
240
241            let additional_low_bins = std::cmp::min(
242                additional_low_bins as usize,
243                self.max_size as usize - self.bins.len(),
244            );
245
246            self.bins.reserve(additional_low_bins);
247            for _ in 0..additional_low_bins {
248                self.bins.push_front(0.0);
249            }
250
251            self.offset -= additional_low_bins as i32;
252            0
253        }
254        // Bucket higher than the stored range
255        else if self.offset + self.bins.len() as i32 <= bin_index {
256            let bin_range_size = bin_index - self.offset + 1; // Number of bucket to store
257
258            if bin_range_size > self.max_size {
259                self.collapse_low_bins(bin_range_size - self.max_size);
260            }
261            debug_assert!(self.bins.len() as i32 <= self.max_size);
262
263            let store_index = bin_index - self.offset;
264            for _ in 0..(store_index - self.bins.len() as i32 + 1) {
265                self.bins.push_back(0.0);
266            }
267            store_index as usize
268        }
269        // Bucket within the stored range
270        else {
271            (bin_index - self.offset) as usize
272        }
273    }
274
275    /// Collapse the `bin_number` lowest bins
276    fn collapse_low_bins(&mut self, bin_number: i32) {
277        let mut count = 0.0;
278        for _ in 0..bin_number {
279            count += self.bins.pop_front().unwrap_or(0.0);
280        }
281        if let Some(lowest_bin) = self.bins.front_mut() {
282            *lowest_bin += count;
283        } else {
284            self.bins.push_front(count);
285        }
286        self.offset += bin_number;
287    }
288}
289
290impl Default for LowCollapsingDenseStore {
291    fn default() -> Self {
292        #[allow(clippy::unwrap_used)]
293        Self::new(2048).unwrap()
294    }
295}
296
297/// Logarithmic mapping of bucket index to value
298#[derive(Debug, Clone, Copy)]
299struct LogMapping {
300    gamma: f64,
301    multiplier: f64,
302    min_indexable_value: f64,
303    index_offset: f64,
304}
305
306impl LogMapping {
307    fn new(gamma: f64, offset: f64) -> Option<Self> {
308        if gamma <= 1.0 {
309            return None;
310        }
311        let multiplier = Self::multiplier_from_gamma(gamma);
312        Some(Self {
313            gamma,
314            multiplier,
315            min_indexable_value: max(
316                // So that the value representing the lowest bucket is >= std::f64::MIN_POSITIVE
317                f64::MIN_POSITIVE * gamma,
318                // Minimum value so that index >= i32::MIN
319                ((i32::MIN as f64 - offset) / multiplier + 1.0).exp(),
320            )?,
321            index_offset: offset,
322        })
323    }
324
325    /// Returns the multiplier used to convert ln to base-gamma logarithm
326    fn multiplier_from_gamma(gamma: f64) -> f64 {
327        1.0 / gamma.ln()
328    }
329
330    /// Returns the relative accuracy guaranteed by the mapping
331    fn relative_accuracy(&self) -> f64 {
332        1.0 - 2.0 / (1.0 + self.gamma)
333    }
334
335    /// Returns the index of the bucket containing `value`
336    fn index(&self, value: f64) -> i32 {
337        (value.ln() * self.multiplier + self.index_offset).floor() as i32
338    }
339
340    /// Returns the value representing the bucket at `index`
341    fn value(&self, index: i32) -> f64 {
342        ((index as f64 - self.index_offset) / self.multiplier).exp()
343            * (1.0 + self.relative_accuracy())
344    }
345}
346
347impl Default for LogMapping {
348    fn default() -> Self {
349        const RELATIVE_ACCURACY: f64 = 0.007751937984496124;
350        const GAMMA: f64 = (1.0 + RELATIVE_ACCURACY) / (1.0 - RELATIVE_ACCURACY);
351
352        const BACKEND_SKETCH_MIN_VALUE: f64 = 1e-9;
353        // offset used in datadog's backend for sketches
354        let offset: f64 = (1.0 - (BACKEND_SKETCH_MIN_VALUE.ln() / GAMMA.ln()).floor()) + 0.5;
355
356        #[allow(clippy::unwrap_used)]
357        Self::new(GAMMA, offset).unwrap()
358    }
359}
360
361fn max(a: f64, b: f64) -> Option<f64> {
362    if a.is_nan() || b.is_nan() {
363        None
364    } else if a > b {
365        Some(a)
366    } else {
367        Some(b)
368    }
369}
370
371#[cfg(test)]
372mod test {
373    use prost::Message;
374
375    use super::*;
376
377    macro_rules! assert_within {
378        ($x:expr, $y:expr, $tolerance:expr) => {
379            let diff = $x - $y;
380            assert!(
381                -$tolerance < diff && diff < $tolerance,
382                "x: {} y: {}",
383                $x,
384                $y,
385            );
386        };
387    }
388
389    #[test]
390    fn test_exponential_mapping_within_tolerances() {
391        let mapping = LogMapping::default();
392
393        let values: &[f64] = &[1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
394        for &value in values {
395            let index = mapping.index(value);
396            let value_bucket = mapping.value(index);
397
398            assert_within!(value_bucket / value, 1.0, 0.01);
399        }
400    }
401
402    #[test]
403    fn test_exponential_mapping_relative_accuracy() {
404        let mapping = LogMapping::default();
405
406        assert_within!(
407            mapping.relative_accuracy(),
408            0.007751937984496138,
409            f64::EPSILON
410        );
411    }
412
413    #[test]
414    fn test_sketch_add() {
415        let mut sketch = DDSketch::default();
416        let points: &[f64] = &[0.0, 1e-5, 0.1, 2.0, 10.0, 25.0, 10000.0];
417        for (i, &point) in points.iter().enumerate() {
418            assert!(sketch.add_with_count(point, i as f64 + 1.0).is_ok());
419        }
420
421        dbg!(sketch.store.bins.len(), sketch.store.offset);
422
423        for (i, (value, count)) in sketch
424            .ordered_bins()
425            .into_iter()
426            .filter(|(_, p)| *p != 0.0)
427            .enumerate()
428        {
429            if points[i] == 0.0 {
430                assert_within!(value, 0.0, f64::EPSILON);
431                assert_within!(count, i as f64 + 1.0, f64::EPSILON);
432            } else {
433                assert_within!(value / points[i], 1.0, 0.01);
434                assert_within!(count, i as f64 + 1.0, f64::EPSILON);
435            }
436        }
437    }
438
439    #[test]
440    fn test_skecth_add_negative() {
441        let mut sketch = DDSketch::default();
442        assert!(sketch.add(-1.0).is_err());
443    }
444
445    #[test]
446    fn test_skecth_add_nan() {
447        let mut sketch = DDSketch::default();
448        assert!(sketch.add(f64::NAN).is_err());
449    }
450
451    #[test]
452    fn test_sketch_count_add_with_count() {
453        let mut sketch = DDSketch::default();
454        assert_within!(sketch.count(), 0.0, f64::EPSILON);
455
456        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
457        for (i, &point) in points.iter().enumerate() {
458            assert!(sketch.add_with_count(point, i as f64).is_ok());
459        }
460
461        assert_within!(sketch.count(), 21.0, f64::EPSILON);
462    }
463
464    #[test]
465    fn a_custom_mapping_is_what_the_protobuf_reports() {
466        let mut sketch = DDSketch::with_log_mapping(1.015625, 1.8761281912861705).unwrap();
467        assert!(sketch.add(1.0).is_ok());
468        let mapping = sketch.into_pb().mapping.unwrap();
469        assert_eq!(mapping.gamma, 1.015625);
470        assert_eq!(mapping.index_offset, 1.8761281912861705);
471
472        assert!(DDSketch::with_log_mapping(1.0, 0.0).is_none());
473        assert!(DDSketch::with_log_mapping(0.5, 0.0).is_none());
474    }
475
476    /// Counting a point into the bin `bin_index` names has to leave the sketch exactly as
477    /// adding the point itself would.
478    #[test]
479    fn adding_to_a_bin_matches_adding_its_points() {
480        let points: &[f64] = &[1e-6, 0.003, 0.1, 2.0, 10.0, 25.0, 10000.0];
481        let mut by_point = DDSketch::with_log_mapping(1.015625, 1.8761281912861705).unwrap();
482        let mut by_bin = by_point.clone();
483        for (i, &point) in points.iter().enumerate() {
484            let count = (i + 1) as f64;
485            assert!(by_point.add_with_count(point, count).is_ok());
486            let index = by_bin.bin_index(point).unwrap();
487            assert!(by_bin.add_to_bin(index, count).is_ok());
488        }
489        assert_eq!(by_point.into_pb(), by_bin.into_pb());
490    }
491
492    #[test]
493    fn points_counted_as_zero_have_no_bin() {
494        let sketch = DDSketch::default();
495        assert_eq!(sketch.bin_index(0.0), None);
496        assert_eq!(sketch.bin_index(-1.0), None);
497        assert_eq!(sketch.bin_index(f64::NAN), None);
498        assert_eq!(sketch.bin_index(f64::INFINITY), None);
499        assert!(sketch.bin_index(1.0).is_some());
500    }
501
502    #[test]
503    fn bins_only_take_positive_finite_counts() {
504        let mut sketch = DDSketch::default();
505        for count in [f64::NAN, f64::INFINITY, -1.0, 0.0] {
506            assert!(sketch.add_to_bin(0, count).is_err(), "{count}");
507        }
508        assert_eq!(sketch.count(), 0.0);
509        assert!(sketch.add_to_bin(0, 1.0).is_ok());
510        assert_eq!(sketch.count(), 1.0);
511    }
512
513    #[test]
514    fn bins_only_take_indices_the_mapping_produces() {
515        let mut sketch = DDSketch::default();
516        let lowest = sketch
517            .bin_index(sketch.mapping.min_indexable_value)
518            .unwrap();
519        let highest = sketch.bin_index(f64::MAX).unwrap();
520        assert!(sketch.add_to_bin(lowest, 1.0).is_ok());
521        assert!(sketch.add_to_bin(highest, 1.0).is_ok());
522        assert!(sketch.add_to_bin(lowest - 1, 1.0).is_err());
523        assert!(sketch.add_to_bin(highest + 1, 1.0).is_err());
524        // Far enough apart that the store's offsets would overflow `i32`.
525        assert!(sketch.add_to_bin(i32::MIN, 1.0).is_err());
526        assert!(sketch.add_to_bin(i32::MAX, 1.0).is_err());
527        assert_eq!(sketch.count(), 2.0);
528    }
529
530    #[test]
531    fn test_sketch_count_add() {
532        let mut sketch = DDSketch::default();
533        assert_within!(sketch.count(), 0.0, f64::EPSILON);
534
535        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
536        for &point in points.iter() {
537            assert!(sketch.add(point).is_ok());
538        }
539        assert_within!(sketch.count(), 7.0, f64::EPSILON);
540
541        assert!(sketch.add(1.0).is_ok());
542        assert_within!(sketch.count(), 8.0, f64::EPSILON);
543
544        for n in 0..100 {
545            assert!(sketch.add(n as f64).is_ok());
546        }
547        assert_within!(sketch.count(), 108.0, f64::EPSILON);
548    }
549
550    #[test]
551    fn test_sketch_pb_roundtrip() {
552        let mut sketch = DDSketch::default();
553        for &p in &[0.0_f64, 0.1, 2.0, 10.0, 25.0, 10000.0] {
554            assert!(sketch.add(p).is_ok());
555        }
556        let expected_count = sketch.count();
557        let expected_bins = sketch.ordered_bins().len();
558        let decoded = DDSketch::from_pb(sketch.into_pb()).expect("decodes");
559        assert_within!(decoded.count(), expected_count, f64::EPSILON);
560        assert_eq!(decoded.ordered_bins().len(), expected_bins);
561    }
562
563    #[test]
564    fn test_skecth_encode() {
565        let mut sketch = DDSketch::default();
566        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
567        for (i, &point) in points.iter().enumerate() {
568            assert!(sketch.add_with_count(point, i as f64).is_ok());
569        }
570
571        let pb_sketch = sketch.into_pb().encode_to_vec();
572        assert!(!pb_sketch.is_empty());
573    }
574
575    #[test]
576    fn test_low_collapsing_store() {
577        let mut store = LowCollapsingDenseStore::new(5).unwrap();
578
579        // Test initial push up to capacity
580        for i in 0..5 {
581            *store.bin_mut(i + 10) = 1.0;
582        }
583        for (i, b) in store.bins().enumerate() {
584            assert_eq!(b.0, i as i32 + 10);
585            assert_eq!(b.1, 1.0)
586        }
587
588        // Indexing existing bins
589        for i in 0..5 {
590            *store.bin_mut(i + 10) += 1.0;
591        }
592        for (i, b) in store.bins().enumerate() {
593            assert_eq!(b.0, i as i32 + 10);
594            assert_eq!(b.1, 2.0)
595        }
596    }
597
598    #[test]
599    fn test_low_collapsing_store_low_bins_are_collapsed() {
600        let mut store = LowCollapsingDenseStore::new(5).unwrap();
601
602        // Test initial push up to capacity to max
603        for i in 0..5 {
604            *store.bin_mut(i + 10) = 1.0;
605        }
606
607        // Indexing low bins at max capacity
608        for i in 0..3 {
609            *store.bin_mut(i) += 1.0;
610        }
611        for (i, b) in store.bins().enumerate() {
612            assert_eq!(b.0, i as i32 + 10);
613            if i == 0 {
614                assert_eq!(b.1, 4.0)
615            } else {
616                assert_eq!(b.1, 1.0)
617            }
618        }
619
620        // Indexing higer bins collapses lower bins
621        *store.bin_mut(15) = 1.0;
622        for (i, b) in store.bins().enumerate() {
623            assert_eq!(b.0, i as i32 + 11);
624            if i == 0 {
625                assert_eq!(b.1, 5.0)
626            } else {
627                assert_eq!(b.1, 1.0)
628            }
629        }
630    }
631
632    #[test]
633    fn test_low_collapsing_store_up_expansion() {
634        let mut store = LowCollapsingDenseStore::new(3).unwrap();
635
636        *store.bin_mut(1) = 1.0;
637        *store.bin_mut(3) = 1.0;
638        assert_eq!(
639            store.bins().collect::<Vec<_>>(),
640            &[(1, 1.0), (2, 0.0), (3, 1.0)]
641        )
642    }
643
644    #[test]
645    fn test_low_collapsing_store_down_expansion() {
646        let mut store = LowCollapsingDenseStore::new(3).unwrap();
647
648        *store.bin_mut(3) = 1.0;
649        *store.bin_mut(1) = 1.0;
650        assert_eq!(
651            store.bins().collect::<Vec<_>>(),
652            &[(1, 1.0), (2, 0.0), (3, 1.0)]
653        )
654    }
655}