1#![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#[rustfmt::skip]
25pub mod pb;
26
27#[derive(Debug, Default, Clone)]
38pub struct DDSketch {
39 store: LowCollapsingDenseStore, zero_count: f64, mapping: LogMapping, }
43
44impl DDSketch {
45 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 pub fn count(&self) -> f64 {
56 self.zero_count + self.store.bins.iter().sum::<f64>()
57 }
58
59 pub fn add(&mut self, point: f64) -> Result<(), Box<dyn std::error::Error>> {
62 self.add_with_count(point, 1.0)
63 }
64
65 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 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 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 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 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 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 pub fn encode_to_vec(self) -> Vec<u8> {
153 self.into_pb().encode_to_vec()
154 }
155
156 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 pub fn from_encoded(bytes: &[u8]) -> Option<DDSketch> {
177 Self::from_pb(pb::DdSketch::decode(bytes).ok()?)
178 }
179}
180
181#[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 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 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 fn bin_idx_to_store_idx(&mut self, bin_index: i32) -> usize {
228 if self.bins.is_empty() {
229 self.offset = bin_index;
231 self.bins.push_back(0.0);
232 return 0;
233 }
234
235 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 else if self.offset + self.bins.len() as i32 <= bin_index {
256 let bin_range_size = bin_index - self.offset + 1; 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 else {
271 (bin_index - self.offset) as usize
272 }
273 }
274
275 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#[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 f64::MIN_POSITIVE * gamma,
318 ((i32::MIN as f64 - offset) / multiplier + 1.0).exp(),
320 )?,
321 index_offset: offset,
322 })
323 }
324
325 fn multiplier_from_gamma(gamma: f64) -> f64 {
327 1.0 / gamma.ln()
328 }
329
330 fn relative_accuracy(&self) -> f64 {
332 1.0 - 2.0 / (1.0 + self.gamma)
333 }
334
335 fn index(&self, value: f64) -> i32 {
337 (value.ln() * self.multiplier + self.index_offset).floor() as i32
338 }
339
340 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 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 #[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 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 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 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 for i in 0..5 {
604 *store.bin_mut(i + 10) = 1.0;
605 }
606
607 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 *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}