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    /// Return a protobuf of the sketch
87    pub fn into_pb(self) -> pb::DdSketch {
88        let contiguous_bins: Vec<f64> = self.store.bins.into();
89        pb::DdSketch {
90            mapping: Some(pb::IndexMapping {
91                gamma: self.mapping.gamma,
92                index_offset: self.mapping.index_offset,
93                interpolation: pb::index_mapping::Interpolation::None.into(),
94            }),
95            positive_values: Some(pb::Store {
96                bin_counts: HashMap::new(),
97                contiguous_bin_counts: contiguous_bins,
98                contiguous_bin_index_offset: self.store.offset,
99            }),
100            zero_count: self.zero_count,
101            negative_values: Some(pb::Store {
102                bin_counts: HashMap::new(),
103                contiguous_bin_counts: Vec::new(),
104                contiguous_bin_index_offset: 0,
105            }),
106        }
107    }
108
109    /// Return a serialized protobuf of the sketch
110    pub fn encode_to_vec(self) -> Vec<u8> {
111        self.into_pb().encode_to_vec()
112    }
113
114    /// Reconstruct a sketch from its protobuf. `None` if mapping missing/invalid.
115    pub fn from_pb(sketch: pb::DdSketch) -> Option<DDSketch> {
116        let mapping_pb = sketch.mapping?;
117        let mapping = LogMapping::new(mapping_pb.gamma, mapping_pb.index_offset)?;
118        let store = match sketch.positive_values {
119            Some(s) => LowCollapsingDenseStore {
120                bins: s.contiguous_bin_counts.into(),
121                offset: s.contiguous_bin_index_offset,
122                max_size: LowCollapsingDenseStore::default().max_size,
123            },
124            None => LowCollapsingDenseStore::default(),
125        };
126        Some(DDSketch {
127            store,
128            zero_count: sketch.zero_count,
129            mapping,
130        })
131    }
132
133    /// Decode a sketch from serialized protobuf bytes; `None` on decode/mapping failure.
134    pub fn from_encoded(bytes: &[u8]) -> Option<DDSketch> {
135        Self::from_pb(pb::DdSketch::decode(bytes).ok()?)
136    }
137}
138
139/// A store mapping the bin indexes to their respective weights
140///
141/// Stores the weights as contiguousBinCounts, only the bins within `offset` and the highest
142/// non empty bin are stored.
143///
144/// Stores the weights of a contiguous range of bins containing all non-empty bins. The range start
145/// at index `offset` and end at index `offset + bins.len()`
146///
147/// The range of stored bins is updated when accessing the index of a bin out of the range
148/// with [`Self::bin_idx_to_bin_idx()`]. If the `max_size` is reached the lower bins are
149/// collapsed together to free space.
150#[derive(Debug, Clone)]
151struct LowCollapsingDenseStore {
152    bins: VecDeque<f64>,
153    offset: i32,
154    max_size: i32,
155}
156
157impl LowCollapsingDenseStore {
158    fn new(max_size: i32) -> Option<Self> {
159        if max_size < 0 {
160            return None;
161        }
162        Some(Self {
163            bins: VecDeque::new(),
164            offset: 0,
165            max_size,
166        })
167    }
168
169    /// Return an iterator over the bins
170    /// The iterator yields pairs `(bin_index, count)`
171    fn bins(&self) -> impl Iterator<Item = (i32, f64)> + '_ {
172        self.bins
173            .iter()
174            .enumerate()
175            .map(|(i, &v)| (i as i32 + self.offset, v))
176    }
177
178    /// Return a mutable reference to the bin at index `bin_index`
179    fn bin_mut(&mut self, bin_index: i32) -> &mut f64 {
180        let store_index = self.bin_idx_to_store_idx(bin_index);
181        &mut self.bins[store_index]
182    }
183
184    /// Return the `store_index` of the bin at index `bin_index`
185    fn bin_idx_to_store_idx(&mut self, bin_index: i32) -> usize {
186        if self.bins.is_empty() {
187            // If the bins are empty, start them at the index
188            self.offset = bin_index;
189            self.bins.push_back(0.0);
190            return 0;
191        }
192
193        // General case
194        // Bucket lower than the stored range
195        if bin_index < self.offset {
196            let additional_low_bins = self.offset - bin_index;
197            debug_assert!(additional_low_bins >= 0);
198
199            let additional_low_bins = std::cmp::min(
200                additional_low_bins as usize,
201                self.max_size as usize - self.bins.len(),
202            );
203
204            self.bins.reserve(additional_low_bins);
205            for _ in 0..additional_low_bins {
206                self.bins.push_front(0.0);
207            }
208
209            self.offset -= additional_low_bins as i32;
210            0
211        }
212        // Bucket higher than the stored range
213        else if self.offset + self.bins.len() as i32 <= bin_index {
214            let bin_range_size = bin_index - self.offset + 1; // Number of bucket to store
215
216            if bin_range_size > self.max_size {
217                self.collapse_low_bins(bin_range_size - self.max_size);
218            }
219            debug_assert!(self.bins.len() as i32 <= self.max_size);
220
221            let store_index = bin_index - self.offset;
222            for _ in 0..(store_index - self.bins.len() as i32 + 1) {
223                self.bins.push_back(0.0);
224            }
225            store_index as usize
226        }
227        // Bucket within the stored range
228        else {
229            (bin_index - self.offset) as usize
230        }
231    }
232
233    /// Collapse the `bin_number` lowest bins
234    fn collapse_low_bins(&mut self, bin_number: i32) {
235        let mut count = 0.0;
236        for _ in 0..bin_number {
237            count += self.bins.pop_front().unwrap_or(0.0);
238        }
239        if let Some(lowest_bin) = self.bins.front_mut() {
240            *lowest_bin += count;
241        } else {
242            self.bins.push_front(count);
243        }
244        self.offset += bin_number;
245    }
246}
247
248impl Default for LowCollapsingDenseStore {
249    fn default() -> Self {
250        #[allow(clippy::unwrap_used)]
251        Self::new(2048).unwrap()
252    }
253}
254
255/// Logarithmic mapping of bucket index to value
256#[derive(Debug, Clone, Copy)]
257struct LogMapping {
258    gamma: f64,
259    multiplier: f64,
260    min_indexable_value: f64,
261    index_offset: f64,
262}
263
264impl LogMapping {
265    fn new(gamma: f64, offset: f64) -> Option<Self> {
266        if gamma <= 1.0 {
267            return None;
268        }
269        let multiplier = Self::multiplier_from_gamma(gamma);
270        Some(Self {
271            gamma,
272            multiplier,
273            min_indexable_value: max(
274                // So that the value representing the lowest bucket is >= std::f64::MIN_POSITIVE
275                f64::MIN_POSITIVE * gamma,
276                // Minimum value so that index >= i32::MIN
277                ((i32::MIN as f64 - offset) / multiplier + 1.0).exp(),
278            )?,
279            index_offset: offset,
280        })
281    }
282
283    /// Returns the multiplier used to convert ln to base-gamma logarithm
284    fn multiplier_from_gamma(gamma: f64) -> f64 {
285        1.0 / gamma.ln()
286    }
287
288    /// Returns the relative accuracy guaranteed by the mapping
289    fn relative_accuracy(&self) -> f64 {
290        1.0 - 2.0 / (1.0 + self.gamma)
291    }
292
293    /// Returns the index of the bucket containing `value`
294    fn index(&self, value: f64) -> i32 {
295        (value.ln() * self.multiplier + self.index_offset).floor() as i32
296    }
297
298    /// Returns the value representing the bucket at `index`
299    fn value(&self, index: i32) -> f64 {
300        ((index as f64 - self.index_offset) / self.multiplier).exp()
301            * (1.0 + self.relative_accuracy())
302    }
303}
304
305impl Default for LogMapping {
306    fn default() -> Self {
307        const RELATIVE_ACCURACY: f64 = 0.007751937984496124;
308        const GAMMA: f64 = (1.0 + RELATIVE_ACCURACY) / (1.0 - RELATIVE_ACCURACY);
309
310        const BACKEND_SKETCH_MIN_VALUE: f64 = 1e-9;
311        // offset used in datadog's backend for sketches
312        let offset: f64 = (1.0 - (BACKEND_SKETCH_MIN_VALUE.ln() / GAMMA.ln()).floor()) + 0.5;
313
314        #[allow(clippy::unwrap_used)]
315        Self::new(GAMMA, offset).unwrap()
316    }
317}
318
319fn max(a: f64, b: f64) -> Option<f64> {
320    if a.is_nan() || b.is_nan() {
321        None
322    } else if a > b {
323        Some(a)
324    } else {
325        Some(b)
326    }
327}
328
329#[cfg(test)]
330mod test {
331    use prost::Message;
332
333    use super::*;
334
335    macro_rules! assert_within {
336        ($x:expr, $y:expr, $tolerance:expr) => {
337            let diff = $x - $y;
338            assert!(
339                -$tolerance < diff && diff < $tolerance,
340                "x: {} y: {}",
341                $x,
342                $y,
343            );
344        };
345    }
346
347    #[test]
348    fn test_exponential_mapping_within_tolerances() {
349        let mapping = LogMapping::default();
350
351        let values: &[f64] = &[1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
352        for &value in values {
353            let index = mapping.index(value);
354            let value_bucket = mapping.value(index);
355
356            assert_within!(value_bucket / value, 1.0, 0.01);
357        }
358    }
359
360    #[test]
361    fn test_exponential_mapping_relative_accuracy() {
362        let mapping = LogMapping::default();
363
364        assert_within!(
365            mapping.relative_accuracy(),
366            0.007751937984496138,
367            f64::EPSILON
368        );
369    }
370
371    #[test]
372    fn test_sketch_add() {
373        let mut sketch = DDSketch::default();
374        let points: &[f64] = &[0.0, 1e-5, 0.1, 2.0, 10.0, 25.0, 10000.0];
375        for (i, &point) in points.iter().enumerate() {
376            assert!(sketch.add_with_count(point, i as f64 + 1.0).is_ok());
377        }
378
379        dbg!(sketch.store.bins.len(), sketch.store.offset);
380
381        for (i, (value, count)) in sketch
382            .ordered_bins()
383            .into_iter()
384            .filter(|(_, p)| *p != 0.0)
385            .enumerate()
386        {
387            if points[i] == 0.0 {
388                assert_within!(value, 0.0, f64::EPSILON);
389                assert_within!(count, i as f64 + 1.0, f64::EPSILON);
390            } else {
391                assert_within!(value / points[i], 1.0, 0.01);
392                assert_within!(count, i as f64 + 1.0, f64::EPSILON);
393            }
394        }
395    }
396
397    #[test]
398    fn test_skecth_add_negative() {
399        let mut sketch = DDSketch::default();
400        assert!(sketch.add(-1.0).is_err());
401    }
402
403    #[test]
404    fn test_skecth_add_nan() {
405        let mut sketch = DDSketch::default();
406        assert!(sketch.add(f64::NAN).is_err());
407    }
408
409    #[test]
410    fn test_sketch_count_add_with_count() {
411        let mut sketch = DDSketch::default();
412        assert_within!(sketch.count(), 0.0, f64::EPSILON);
413
414        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
415        for (i, &point) in points.iter().enumerate() {
416            assert!(sketch.add_with_count(point, i as f64).is_ok());
417        }
418
419        assert_within!(sketch.count(), 21.0, f64::EPSILON);
420    }
421
422    #[test]
423    fn test_sketch_count_add() {
424        let mut sketch = DDSketch::default();
425        assert_within!(sketch.count(), 0.0, f64::EPSILON);
426
427        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
428        for &point in points.iter() {
429            assert!(sketch.add(point).is_ok());
430        }
431        assert_within!(sketch.count(), 7.0, f64::EPSILON);
432
433        assert!(sketch.add(1.0).is_ok());
434        assert_within!(sketch.count(), 8.0, f64::EPSILON);
435
436        for n in 0..100 {
437            assert!(sketch.add(n as f64).is_ok());
438        }
439        assert_within!(sketch.count(), 108.0, f64::EPSILON);
440    }
441
442    #[test]
443    fn test_sketch_pb_roundtrip() {
444        let mut sketch = DDSketch::default();
445        for &p in &[0.0_f64, 0.1, 2.0, 10.0, 25.0, 10000.0] {
446            assert!(sketch.add(p).is_ok());
447        }
448        let expected_count = sketch.count();
449        let expected_bins = sketch.ordered_bins().len();
450        let decoded = DDSketch::from_pb(sketch.into_pb()).expect("decodes");
451        assert_within!(decoded.count(), expected_count, f64::EPSILON);
452        assert_eq!(decoded.ordered_bins().len(), expected_bins);
453    }
454
455    #[test]
456    fn test_skecth_encode() {
457        let mut sketch = DDSketch::default();
458        let points: &[f64] = &[0.0, 1e-30, 0.1, 2.0, 10.0, 25.0, 10000.0];
459        for (i, &point) in points.iter().enumerate() {
460            assert!(sketch.add_with_count(point, i as f64).is_ok());
461        }
462
463        let pb_sketch = sketch.into_pb().encode_to_vec();
464        assert!(!pb_sketch.is_empty());
465    }
466
467    #[test]
468    fn test_low_collapsing_store() {
469        let mut store = LowCollapsingDenseStore::new(5).unwrap();
470
471        // Test initial push up to capacity
472        for i in 0..5 {
473            *store.bin_mut(i + 10) = 1.0;
474        }
475        for (i, b) in store.bins().enumerate() {
476            assert_eq!(b.0, i as i32 + 10);
477            assert_eq!(b.1, 1.0)
478        }
479
480        // Indexing existing bins
481        for i in 0..5 {
482            *store.bin_mut(i + 10) += 1.0;
483        }
484        for (i, b) in store.bins().enumerate() {
485            assert_eq!(b.0, i as i32 + 10);
486            assert_eq!(b.1, 2.0)
487        }
488    }
489
490    #[test]
491    fn test_low_collapsing_store_low_bins_are_collapsed() {
492        let mut store = LowCollapsingDenseStore::new(5).unwrap();
493
494        // Test initial push up to capacity to max
495        for i in 0..5 {
496            *store.bin_mut(i + 10) = 1.0;
497        }
498
499        // Indexing low bins at max capacity
500        for i in 0..3 {
501            *store.bin_mut(i) += 1.0;
502        }
503        for (i, b) in store.bins().enumerate() {
504            assert_eq!(b.0, i as i32 + 10);
505            if i == 0 {
506                assert_eq!(b.1, 4.0)
507            } else {
508                assert_eq!(b.1, 1.0)
509            }
510        }
511
512        // Indexing higer bins collapses lower bins
513        *store.bin_mut(15) = 1.0;
514        for (i, b) in store.bins().enumerate() {
515            assert_eq!(b.0, i as i32 + 11);
516            if i == 0 {
517                assert_eq!(b.1, 5.0)
518            } else {
519                assert_eq!(b.1, 1.0)
520            }
521        }
522    }
523
524    #[test]
525    fn test_low_collapsing_store_up_expansion() {
526        let mut store = LowCollapsingDenseStore::new(3).unwrap();
527
528        *store.bin_mut(1) = 1.0;
529        *store.bin_mut(3) = 1.0;
530        assert_eq!(
531            store.bins().collect::<Vec<_>>(),
532            &[(1, 1.0), (2, 0.0), (3, 1.0)]
533        )
534    }
535
536    #[test]
537    fn test_low_collapsing_store_down_expansion() {
538        let mut store = LowCollapsingDenseStore::new(3).unwrap();
539
540        *store.bin_mut(3) = 1.0;
541        *store.bin_mut(1) = 1.0;
542        assert_eq!(
543            store.bins().collect::<Vec<_>>(),
544            &[(1, 1.0), (2, 0.0), (3, 1.0)]
545        )
546    }
547}