tisonkun commented on code in PR #400: URL: https://github.com/apache/datasketches-rust/pull/400#discussion_r4658951811
########## datasketches/src/ddsketch/sketch.rs: ########## @@ -0,0 +1,832 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::fmt; + +use super::DEFAULT_RELATIVE_ACCURACY; +use super::iter::DdSketchIter; +use super::mapping::IndexMapping; +use super::mapping::MappingKind; +use super::serialization::deserialize_compat_sketch; +use super::serialization::deserialize_sketch; +use super::serialization::serialize_compat_sketch; +use super::serialization::serialize_sketch; +use super::store::Store; +use super::store::StoreKind; +use super::store::validate_store_kind; +use crate::error::Error; + +/// Builder for configuring and constructing a [`DdSketch`]. +/// +/// Defaults to `relative_accuracy = 0.01`, [`MappingKind::Cubic`], and +/// [`StoreKind::CollapsingLowestDense`] with `2048` bins per sign. +/// +/// # Examples +/// +/// ``` +/// use datasketches::ddsketch::DdSketchBuilder; +/// use datasketches::ddsketch::MappingKind; +/// use datasketches::ddsketch::StoreKind; +/// +/// let mut sketch = DdSketchBuilder::new(0.005) +/// .mapping(MappingKind::Logarithmic) +/// .store(StoreKind::Sparse) +/// .build()?; +/// sketch.update(42.0); +/// assert_eq!(sketch.total_weight(), 1); +/// # Ok::<(), datasketches::error::Error>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct DdSketchBuilder { + relative_accuracy: f64, + mapping_kind: MappingKind, + store_kind: StoreKind, +} + +impl Default for DdSketchBuilder { + fn default() -> Self { + Self::new(DEFAULT_RELATIVE_ACCURACY) + } +} + +impl DdSketchBuilder { + /// Creates a builder with the given `relative_accuracy` and default mapping and store settings. + pub fn new(relative_accuracy: f64) -> Self { + Self { + relative_accuracy, + mapping_kind: MappingKind::default(), + store_kind: StoreKind::default(), + } + } + + /// Sets the index mapping curve used to assign positive magnitudes to bucket indices. + #[inline] + pub fn mapping(mut self, mapping_kind: MappingKind) -> Self { + self.mapping_kind = mapping_kind; + self + } + + /// Sets the bin storage strategy used for both positive and negative stores. + #[inline] + pub fn store(mut self, store_kind: StoreKind) -> Self { + self.store_kind = store_kind; + self + } + + /// Validates configuration parameters and creates an empty [`DdSketch`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`, or if `store` specifies a collapsing + /// dense store with `max_num_bins` outside `1..=67_108_864`. + pub fn build(self) -> Result<DdSketch, Error> { + validate_store_kind(self.store_kind)?; + let mapping = IndexMapping::from_accuracy(self.mapping_kind, self.relative_accuracy)?; + let negative = Store::new(self.store_kind)?; + let positive = Store::new(self.store_kind)?; + Ok(DdSketch::from_parts(mapping, negative, positive, 0, 0)) + } +} + +/// Mergeable quantile sketch over finite `f64` values with relative-value error guarantees. +/// +/// See the [module documentation](super) for accuracy, memory, and compatibility details. +#[derive(Clone)] +pub struct DdSketch { + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, +} + +impl fmt::Debug for DdSketch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DdSketch") + .field("relative_accuracy", &self.mapping.relative_accuracy()) + .field("mapping_kind", &self.mapping.kind()) + .field("store_kind", &self.positive.kind()) + .field("is_empty", &self.is_empty()) + .field("total_weight", &self.total_weight) + .field("zero_weight", &self.zero_weight) + .field("num_retained", &self.num_retained()) + .field("min_value", &self.min_value()) + .field("max_value", &self.max_value()) + .finish() + } +} + +impl Default for DdSketch { + fn default() -> Self { + DdSketchBuilder::default() + .build() + .expect("default DDSketch configuration is valid") + } +} + +impl DdSketch { + /// Creates an empty sketch with the given `relative_accuracy`, [`MappingKind::Cubic`], and + /// [`StoreKind::default()`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let sketch = DdSketch::new(0.01)?; + /// assert!(sketch.is_empty()); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn new(relative_accuracy: f64) -> Result<Self, Error> { + DdSketchBuilder::new(relative_accuracy).build() + } + + pub(super) fn from_parts( + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, + ) -> Self { + debug_assert_eq!( + negative.total_weight() + zero_weight + positive.total_weight(), + total_weight + ); + Self { + mapping, + negative, + positive, + zero_weight, + total_weight, + } + } + + #[inline] + pub(super) const fn mapping(&self) -> IndexMapping { + self.mapping + } + + #[inline] + pub(super) const fn positive_store(&self) -> &Store { + &self.positive + } + + #[inline] + pub(super) const fn negative_store(&self) -> &Store { + &self.negative + } + + /// Returns the relative value accuracy guaranteed for non-collapsed buckets. + #[inline] + pub fn relative_accuracy(&self) -> f64 { + self.mapping.relative_accuracy() + } + + /// Returns the index mapping curve used by this sketch. + #[inline] + pub fn mapping_kind(&self) -> MappingKind { + self.mapping.kind() + } + + /// Returns the bin storage strategy used by this sketch. + #[inline] + pub fn store_kind(&self) -> StoreKind { + self.positive.kind() + } + + /// Returns the magnitude threshold below or at which inputs map to the zero bucket. + /// + /// Any finite input `x` with `|x| <= self.zero_threshold()` increments + /// [`zero_weight`](Self::zero_weight) and is approximated by `0.0`. + #[inline] + pub fn zero_threshold(&self) -> f64 { + self.mapping.min_indexable_value() + } + + /// Returns `true` if this sketch has not recorded any finite observations. + #[inline] + pub fn is_empty(&self) -> bool { + self.total_weight == 0 + } + + /// Returns the accumulated stream weight across all buckets. + #[inline] + pub fn total_weight(&self) -> u64 { + self.total_weight + } + + /// Returns the accumulated stream weight in the zero bucket. + #[inline] + pub fn zero_weight(&self) -> u64 { + self.zero_weight + } + + /// Returns the number of non-empty buckets currently retained by this sketch, including the + /// zero bucket when [`zero_weight`](Self::zero_weight) is non-zero. + #[inline] + pub fn num_retained(&self) -> usize { + self.negative.num_occupied() + + usize::from(self.zero_weight != 0) + + self.positive.num_occupied() + } + + /// Returns an implementation-dependent estimate of heap memory usage in bytes. + pub fn estimated_size(&self) -> usize { + self.negative + .estimated_size() + .saturating_add(self.positive.estimated_size()) + } + + /// Updates this sketch with a single observation. + /// + /// [`f64::NAN`], [`f64::INFINITY`], and [`f64::NEG_INFINITY`] values are ignored. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(10.0); + /// assert_eq!(sketch.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update(&mut self, value: f64) { + self.update_with_weight(value, 1); + } + + /// Updates this sketch with `value` repeated `weight` times. + /// + /// [`f64::NAN`], [`f64::INFINITY`], [`f64::NEG_INFINITY`], and a `weight` of `0` are no-ops. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Cross-language compatibility + /// + /// In the reference DDSketch implementations, Go rejects `NaN`, infinite, and negative-count + /// inputs with an error, whereas Java rejects out-of-range finite/infinite and negative-count + /// inputs while counting `NaN` into the zero bucket; both accept fractional `f64` counts. This + /// method ignores non-finite values and accumulates exact `u64` integer weights; keep + /// per-bucket weights (and [`total_weight`](Self::total_weight) for Java quantile readers) at + /// or below `2^53 - 1` when serializing with [`serialize_compat`](Self::serialize_compat). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update_with_weight(25.0, 100); + /// assert_eq!(sketch.total_weight(), 100); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update_with_weight(&mut self, value: f64, weight: u64) { + if !value.is_finite() || weight == 0 { + return; + } + let next_total = self + .total_weight + .checked_add(weight) + .expect("total stream weight overflow"); + + let min_indexable = self.mapping.min_indexable_value(); + if value > min_indexable { + let idx = self.mapping.index(value); + self.positive.ensure_index_capacity(idx); + self.positive.add(idx, weight); + } else if value < -min_indexable { + let idx = self.mapping.index(-value); + self.negative.ensure_index_capacity(idx); + self.negative.add(idx, weight); + } else { + self.zero_weight += weight; + } + self.total_weight = next_total; + } + + /// Merges `other` into `self`, retaining `self`'s [`StoreKind`]. + /// + /// Sketches that share an equivalent index mapping can be merged even when they use different + /// [`StoreKind`] strategies. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) without modifying + /// `self` if `other` uses an incompatible index mapping (even when either sketch is empty), if + /// the combined [`total_weight`](Self::total_weight) would exceed [`u64::MAX`], or if merging + /// into [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut left = DdSketch::new(0.01)?; + /// let mut right = DdSketch::new(0.01)?; + /// left.update(1.0); + /// right.update(100.0); + /// left.merge(&right)?; + /// assert_eq!(left.total_weight(), 2); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { + if !self.mapping.is_compatible(&other.mapping) { + return Err(Error::invalid_argument(format!( + "cannot merge DDSketches with incompatible index mappings: expected ({:?}, gamma={}, offset={}), got ({:?}, gamma={}, offset={})", + self.mapping.kind(), + self.mapping.gamma(), + self.mapping.index_offset(), + other.mapping.kind(), + other.mapping.gamma(), + other.mapping.index_offset(), + ))); + } + + if other.is_empty() { + return Ok(()); + } + + let next_total = self + .total_weight + .checked_add(other.total_weight) + .ok_or_else(|| { + Error::invalid_argument(format!( + "combined stream weight exceeds {}: left {}, right {}", + u64::MAX, + self.total_weight, + other.total_weight + )) + })?; + + self.negative.validate_merge_capacity(&other.negative)?; + self.positive.validate_merge_capacity(&other.positive)?; + + self.negative.merge_from(&other.negative); + self.positive.merge_from(&other.positive); + self.zero_weight += other.zero_weight; + self.total_weight = next_total; + Ok(()) + } + + /// Resets this sketch to its empty state while retaining its configuration and allocated + /// dense-store capacity. + pub fn reset(&mut self) { + self.negative.reset(); + self.positive.reset(); + self.zero_weight = 0; + self.total_weight = 0; + } + + /// Returns the bucket-approximated minimum value, or `None` if this sketch is empty. + /// + /// Equivalent to `self.quantile(0.0)?.unwrap()` on a non-empty sketch: returns the + /// representative value of the lowest occupied numerical bucket rather than an exact retained + /// input sample. + pub fn min_value(&self) -> Option<f64> { + if let Some(max_neg_idx) = self.negative.max_index() { + Some(-self.mapping.value(max_neg_idx)) + } else if self.zero_weight > 0 { + Some(0.0) + } else { + self.positive + .min_index() + .map(|min_pos_idx| self.mapping.value(min_pos_idx)) + } + } + + /// Returns the bucket-approximated maximum value, or `None` if this sketch is empty. + /// + /// Equivalent to `self.quantile(1.0)?.unwrap()` on a non-empty sketch: returns the + /// representative value of the highest occupied numerical bucket rather than an exact retained + /// input sample. + pub fn max_value(&self) -> Option<f64> { + if let Some(max_pos_idx) = self.positive.max_index() { + Some(self.mapping.value(max_pos_idx)) + } else if self.zero_weight > 0 { + Some(0.0) + } else { + self.negative + .min_index() + .map(|min_neg_idx| -self.mapping.value(min_neg_idx)) + } + } + + /// Returns the bucket-approximated sum of recorded values (`0.0` when empty). + /// + /// When all recorded values have the same sign, exceed [`zero_threshold`](Self::zero_threshold) + /// in magnitude, fall into uncollapsed buckets, and produce a finite weighted bucket sum, the + /// returned value satisfies the configured [`relative_accuracy`](Self::relative_accuracy) bound + /// relative to the true stream sum. + pub fn sum(&self) -> f64 { + let mut total = 0.0_f64; + for (idx, weight) in self.negative.iter_asc() { + total -= self.mapping.value(idx) * (weight as f64); + } + for (idx, weight) in self.positive.iter_asc() { + total += self.mapping.value(idx) * (weight as f64); + } + total + } + + /// Returns the approximate lower discrete quantile for `rank` in `[0.0, 1.0]`, or `Ok(None)` + /// if this sketch is empty. + /// + /// Selects the bucket containing zero-based sorted item `floor(rank * (total_weight - 1))`, + /// evaluated with exact integer scaling for weights above `2^53`. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if `rank` is NaN or + /// outside `[0.0, 1.0]`, even if this sketch is empty. + /// + /// # Cross-language compatibility + /// + /// Rank scaling multiplies `total_weight - 1` by the exact binary value of `rank` without + /// intermediate `f64` rounding, whereas the Java reference implementation truncates the `f64` + /// product `rank * (total_weight - 1) as f64` and the Go reference implementation subtracts + /// that untruncated `f64` product from `negative_weight - 1` when indexing negative buckets + /// (either of which can shift boundary quantiles by one discrete index at binary-inexact + /// decimals such as `0.95`). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// for value in 1..=100 { + /// sketch.update(f64::from(value)); + /// } + /// let p95 = sketch.quantile(0.95)?.unwrap(); + /// assert!((p95 - 95.0).abs() <= 0.01 * 95.0); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn quantile(&self, rank: f64) -> Result<Option<f64>, Error> { + check_rank(rank)?; + if self.is_empty() { + return Ok(None); + } + Ok(Some(self.quantile_unchecked(rank))) + } + + /// Returns approximate quantiles for `ranks` in input order, or `Ok(None)` if this sketch is + /// empty. + /// + /// For a non-empty sketch, an empty `ranks` slice returns `Ok(Some(vec![]))`. Multiple ranks + /// are answered in a single pass over the retained buckets regardless of input order. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if any rank is NaN or + /// outside `[0.0, 1.0]`, even if this sketch is empty. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// for value in 1..=1000 { + /// sketch.update(f64::from(value)); + /// } + /// let qs = sketch.quantiles(&[0.5, 0.9, 0.99])?.unwrap(); + /// assert_eq!(qs.len(), 3); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn quantiles(&self, ranks: &[f64]) -> Result<Option<Vec<f64>>, Error> { + for &rank in ranks { + check_rank(rank)?; + } + if self.is_empty() { + return Ok(None); + } + if ranks.is_empty() { + return Ok(Some(Vec::new())); + } + if ranks.len() == 1 { + return Ok(Some(vec![self.quantile_unchecked(ranks[0])])); + } + + let last = self.total_weight - 1; + let is_non_decreasing = ranks.windows(2).all(|pair| pair[0] <= pair[1]); + let mut out = vec![0.0; ranks.len()]; + if is_non_decreasing { + self.resolve_non_decreasing_ranks(ranks, last, &mut out); + return Ok(Some(out)); + } + + let mut indexed: Vec<(u64, usize)> = ranks + .iter() + .enumerate() + .map(|(pos, &rank)| (quantile_target_index(rank, last), pos)) + .collect(); + indexed.sort_unstable_by_key(|&(target, _)| target); + self.resolve_sorted_targets(&indexed, &mut out); + Ok(Some(out)) + } + + /// Returns an iterator over non-empty `(value, weight)` buckets in ascending numerical order. + #[inline] + pub fn iter(&self) -> DdSketchIter<'_> { + DdSketchIter::new( + self.mapping, + self.negative.iter_asc(), + self.zero_weight, + self.positive.iter_asc(), + self.num_retained(), + ) + } + + /// Serializes this sketch in this crate's native `DDSKETCH` binary format, preserving + /// [`MappingKind`], [`StoreKind`], collapse state, and exact `u64` bucket weights. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(3.5); + /// let bytes = sketch.serialize(); + /// let decoded = DdSketch::deserialize(&bytes)?; + /// assert_eq!(decoded.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn serialize(&self) -> Vec<u8> { + serialize_sketch(self) + } + + /// Deserializes a sketch from this crate's native `DDSKETCH` binary format, restoring its + /// encoded [`StoreKind`]. + /// + /// Use [`deserialize_compat`](Self::deserialize_compat) to decode compact flag-block images + /// produced by the Java and Go reference DDSketch implementations. + /// + /// # Errors + /// + /// Returns [`InvalidData`](crate::error::ErrorKind::InvalidData) if the image is empty, + /// truncated, has an unsupported family, version, or flag, or violates index, store, or weight + /// bounds. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + deserialize_sketch(bytes) + } + + /// Serializes this sketch in the compact flag-block binary format of the [Java][java-ref] and + /// [Go][go-ref] reference DDSketch implementations (distinct from the Protobuf format used by + /// Python and JavaScript). + /// + /// [java-ref]: https://github.com/DataDog/sketches-java + /// [go-ref]: https://github.com/DataDog/sketches-go + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// [`zero_weight`](Self::zero_weight) or any retained bucket weight exceeds `2^53 - 1` + /// (`9_007_199_254_740_991`), the maximum integer representable without rounding in the + /// compatibility format's `v + 1.0` floating-point counter encoding. + /// + /// # Cross-language compatibility + /// + /// [`StoreKind`] and collapse state are in-memory properties in the reference format and are + /// not recorded in the output bytes; decode with + /// [`deserialize_compat`](Self::deserialize_compat) and an explicit [`StoreKind`]. For + /// downstream Java or Go readers, keep [`total_weight`](Self::total_weight) at or below + /// `2^53 - 1` (Java computes `total_weight - 1` in `f64`), per-sign bucket index spans at or + /// below `2^26` (Go's default `MaxDecodeIndexRange`), and input magnitudes within the target Review Comment: Updated the `serialize_compat` docs in e80fc28e24b31dda7d5fc38b170d3126e8382e5b to note that `MaxDecodeIndexRange` (`2^26`) is on `sketches-go` `main` and unreleased as of `v1.4.8`. ########## datasketches/src/ddsketch/sketch.rs: ########## @@ -0,0 +1,832 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::fmt; + +use super::DEFAULT_RELATIVE_ACCURACY; +use super::iter::DdSketchIter; +use super::mapping::IndexMapping; +use super::mapping::MappingKind; +use super::serialization::deserialize_compat_sketch; +use super::serialization::deserialize_sketch; +use super::serialization::serialize_compat_sketch; +use super::serialization::serialize_sketch; +use super::store::Store; +use super::store::StoreKind; +use super::store::validate_store_kind; +use crate::error::Error; + +/// Builder for configuring and constructing a [`DdSketch`]. +/// +/// Defaults to `relative_accuracy = 0.01`, [`MappingKind::Cubic`], and +/// [`StoreKind::CollapsingLowestDense`] with `2048` bins per sign. +/// +/// # Examples +/// +/// ``` +/// use datasketches::ddsketch::DdSketchBuilder; +/// use datasketches::ddsketch::MappingKind; +/// use datasketches::ddsketch::StoreKind; +/// +/// let mut sketch = DdSketchBuilder::new(0.005) +/// .mapping(MappingKind::Logarithmic) +/// .store(StoreKind::Sparse) +/// .build()?; +/// sketch.update(42.0); +/// assert_eq!(sketch.total_weight(), 1); +/// # Ok::<(), datasketches::error::Error>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct DdSketchBuilder { + relative_accuracy: f64, + mapping_kind: MappingKind, + store_kind: StoreKind, +} + +impl Default for DdSketchBuilder { + fn default() -> Self { + Self::new(DEFAULT_RELATIVE_ACCURACY) + } +} + +impl DdSketchBuilder { + /// Creates a builder with the given `relative_accuracy` and default mapping and store settings. + pub fn new(relative_accuracy: f64) -> Self { + Self { + relative_accuracy, + mapping_kind: MappingKind::default(), + store_kind: StoreKind::default(), + } + } + + /// Sets the index mapping curve used to assign positive magnitudes to bucket indices. + #[inline] + pub fn mapping(mut self, mapping_kind: MappingKind) -> Self { + self.mapping_kind = mapping_kind; + self + } + + /// Sets the bin storage strategy used for both positive and negative stores. + #[inline] + pub fn store(mut self, store_kind: StoreKind) -> Self { + self.store_kind = store_kind; + self + } + + /// Validates configuration parameters and creates an empty [`DdSketch`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`, or if `store` specifies a collapsing + /// dense store with `max_num_bins` outside `1..=67_108_864`. + pub fn build(self) -> Result<DdSketch, Error> { + validate_store_kind(self.store_kind)?; + let mapping = IndexMapping::from_accuracy(self.mapping_kind, self.relative_accuracy)?; + let negative = Store::new(self.store_kind)?; + let positive = Store::new(self.store_kind)?; + Ok(DdSketch::from_parts(mapping, negative, positive, 0, 0)) + } +} + +/// Mergeable quantile sketch over finite `f64` values with relative-value error guarantees. +/// +/// See the [module documentation](super) for accuracy, memory, and compatibility details. +#[derive(Clone)] +pub struct DdSketch { + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, +} + +impl fmt::Debug for DdSketch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DdSketch") + .field("relative_accuracy", &self.mapping.relative_accuracy()) + .field("mapping_kind", &self.mapping.kind()) + .field("store_kind", &self.positive.kind()) + .field("is_empty", &self.is_empty()) + .field("total_weight", &self.total_weight) + .field("zero_weight", &self.zero_weight) + .field("num_retained", &self.num_retained()) + .field("min_value", &self.min_value()) + .field("max_value", &self.max_value()) + .finish() + } +} + +impl Default for DdSketch { + fn default() -> Self { + DdSketchBuilder::default() + .build() + .expect("default DDSketch configuration is valid") + } +} + +impl DdSketch { + /// Creates an empty sketch with the given `relative_accuracy`, [`MappingKind::Cubic`], and + /// [`StoreKind::default()`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let sketch = DdSketch::new(0.01)?; + /// assert!(sketch.is_empty()); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn new(relative_accuracy: f64) -> Result<Self, Error> { + DdSketchBuilder::new(relative_accuracy).build() + } + + pub(super) fn from_parts( + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, + ) -> Self { + debug_assert_eq!( + negative.total_weight() + zero_weight + positive.total_weight(), + total_weight + ); + Self { + mapping, + negative, + positive, + zero_weight, + total_weight, + } + } + + #[inline] + pub(super) const fn mapping(&self) -> IndexMapping { + self.mapping + } + + #[inline] + pub(super) const fn positive_store(&self) -> &Store { + &self.positive + } + + #[inline] + pub(super) const fn negative_store(&self) -> &Store { + &self.negative + } + + /// Returns the relative value accuracy guaranteed for non-collapsed buckets. + #[inline] + pub fn relative_accuracy(&self) -> f64 { + self.mapping.relative_accuracy() + } + + /// Returns the index mapping curve used by this sketch. + #[inline] + pub fn mapping_kind(&self) -> MappingKind { + self.mapping.kind() + } + + /// Returns the bin storage strategy used by this sketch. + #[inline] + pub fn store_kind(&self) -> StoreKind { + self.positive.kind() + } + + /// Returns the magnitude threshold below or at which inputs map to the zero bucket. + /// + /// Any finite input `x` with `|x| <= self.zero_threshold()` increments + /// [`zero_weight`](Self::zero_weight) and is approximated by `0.0`. + #[inline] + pub fn zero_threshold(&self) -> f64 { + self.mapping.min_indexable_value() + } + + /// Returns `true` if this sketch has not recorded any finite observations. + #[inline] + pub fn is_empty(&self) -> bool { + self.total_weight == 0 + } + + /// Returns the accumulated stream weight across all buckets. + #[inline] + pub fn total_weight(&self) -> u64 { + self.total_weight + } + + /// Returns the accumulated stream weight in the zero bucket. + #[inline] + pub fn zero_weight(&self) -> u64 { + self.zero_weight + } + + /// Returns the number of non-empty buckets currently retained by this sketch, including the + /// zero bucket when [`zero_weight`](Self::zero_weight) is non-zero. + #[inline] + pub fn num_retained(&self) -> usize { + self.negative.num_occupied() + + usize::from(self.zero_weight != 0) + + self.positive.num_occupied() + } + + /// Returns an implementation-dependent estimate of heap memory usage in bytes. + pub fn estimated_size(&self) -> usize { + self.negative + .estimated_size() + .saturating_add(self.positive.estimated_size()) + } + + /// Updates this sketch with a single observation. + /// + /// [`f64::NAN`], [`f64::INFINITY`], and [`f64::NEG_INFINITY`] values are ignored. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(10.0); + /// assert_eq!(sketch.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update(&mut self, value: f64) { + self.update_with_weight(value, 1); + } + + /// Updates this sketch with `value` repeated `weight` times. + /// + /// [`f64::NAN`], [`f64::INFINITY`], [`f64::NEG_INFINITY`], and a `weight` of `0` are no-ops. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Cross-language compatibility + /// + /// In the reference DDSketch implementations, Go rejects `NaN`, infinite, and negative-count + /// inputs with an error, whereas Java rejects out-of-range finite/infinite and negative-count + /// inputs while counting `NaN` into the zero bucket; both accept fractional `f64` counts. This + /// method ignores non-finite values and accumulates exact `u64` integer weights; keep + /// per-bucket weights (and [`total_weight`](Self::total_weight) for Java quantile readers) at + /// or below `2^53 - 1` when serializing with [`serialize_compat`](Self::serialize_compat). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update_with_weight(25.0, 100); + /// assert_eq!(sketch.total_weight(), 100); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update_with_weight(&mut self, value: f64, weight: u64) { + if !value.is_finite() || weight == 0 { + return; + } + let next_total = self + .total_weight + .checked_add(weight) + .expect("total stream weight overflow"); + + let min_indexable = self.mapping.min_indexable_value(); + if value > min_indexable { + let idx = self.mapping.index(value); + self.positive.ensure_index_capacity(idx); + self.positive.add(idx, weight); + } else if value < -min_indexable { + let idx = self.mapping.index(-value); + self.negative.ensure_index_capacity(idx); + self.negative.add(idx, weight); + } else { + self.zero_weight += weight; + } + self.total_weight = next_total; + } + + /// Merges `other` into `self`, retaining `self`'s [`StoreKind`]. + /// + /// Sketches that share an equivalent index mapping can be merged even when they use different + /// [`StoreKind`] strategies. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) without modifying + /// `self` if `other` uses an incompatible index mapping (even when either sketch is empty), if + /// the combined [`total_weight`](Self::total_weight) would exceed [`u64::MAX`], or if merging + /// into [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut left = DdSketch::new(0.01)?; + /// let mut right = DdSketch::new(0.01)?; + /// left.update(1.0); + /// right.update(100.0); + /// left.merge(&right)?; + /// assert_eq!(left.total_weight(), 2); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { + if !self.mapping.is_compatible(&other.mapping) { + return Err(Error::invalid_argument(format!( + "cannot merge DDSketches with incompatible index mappings: expected ({:?}, gamma={}, offset={}), got ({:?}, gamma={}, offset={})", + self.mapping.kind(), + self.mapping.gamma(), + self.mapping.index_offset(), + other.mapping.kind(), + other.mapping.gamma(), + other.mapping.index_offset(), + ))); + } + + if other.is_empty() { + return Ok(()); + } + + let next_total = self + .total_weight + .checked_add(other.total_weight) + .ok_or_else(|| { + Error::invalid_argument(format!( + "combined stream weight exceeds {}: left {}, right {}", + u64::MAX, + self.total_weight, + other.total_weight + )) + })?; + + self.negative.validate_merge_capacity(&other.negative)?; + self.positive.validate_merge_capacity(&other.positive)?; + + self.negative.merge_from(&other.negative); + self.positive.merge_from(&other.positive); + self.zero_weight += other.zero_weight; + self.total_weight = next_total; + Ok(()) + } + + /// Resets this sketch to its empty state while retaining its configuration and allocated + /// dense-store capacity. + pub fn reset(&mut self) { + self.negative.reset(); + self.positive.reset(); + self.zero_weight = 0; + self.total_weight = 0; + } + + /// Returns the bucket-approximated minimum value, or `None` if this sketch is empty. + /// + /// Equivalent to `self.quantile(0.0)?.unwrap()` on a non-empty sketch: returns the + /// representative value of the lowest occupied numerical bucket rather than an exact retained + /// input sample. + pub fn min_value(&self) -> Option<f64> { + if let Some(max_neg_idx) = self.negative.max_index() { + Some(-self.mapping.value(max_neg_idx)) + } else if self.zero_weight > 0 { + Some(0.0) + } else { + self.positive + .min_index() + .map(|min_pos_idx| self.mapping.value(min_pos_idx)) + } + } + + /// Returns the bucket-approximated maximum value, or `None` if this sketch is empty. + /// + /// Equivalent to `self.quantile(1.0)?.unwrap()` on a non-empty sketch: returns the + /// representative value of the highest occupied numerical bucket rather than an exact retained + /// input sample. + pub fn max_value(&self) -> Option<f64> { + if let Some(max_pos_idx) = self.positive.max_index() { + Some(self.mapping.value(max_pos_idx)) + } else if self.zero_weight > 0 { + Some(0.0) + } else { + self.negative + .min_index() + .map(|min_neg_idx| -self.mapping.value(min_neg_idx)) + } + } + + /// Returns the bucket-approximated sum of recorded values (`0.0` when empty). + /// + /// When all recorded values have the same sign, exceed [`zero_threshold`](Self::zero_threshold) + /// in magnitude, fall into uncollapsed buckets, and produce a finite weighted bucket sum, the + /// returned value satisfies the configured [`relative_accuracy`](Self::relative_accuracy) bound + /// relative to the true stream sum. + pub fn sum(&self) -> f64 { + let mut total = 0.0_f64; + for (idx, weight) in self.negative.iter_asc() { + total -= self.mapping.value(idx) * (weight as f64); + } + for (idx, weight) in self.positive.iter_asc() { + total += self.mapping.value(idx) * (weight as f64); + } + total + } + + /// Returns the approximate lower discrete quantile for `rank` in `[0.0, 1.0]`, or `Ok(None)` + /// if this sketch is empty. + /// + /// Selects the bucket containing zero-based sorted item `floor(rank * (total_weight - 1))`, + /// evaluated with exact integer scaling for weights above `2^53`. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if `rank` is NaN or + /// outside `[0.0, 1.0]`, even if this sketch is empty. + /// + /// # Cross-language compatibility + /// + /// Rank scaling multiplies `total_weight - 1` by the exact binary value of `rank` without + /// intermediate `f64` rounding, whereas the Java reference implementation truncates the `f64` + /// product `rank * (total_weight - 1) as f64` and the Go reference implementation subtracts + /// that untruncated `f64` product from `negative_weight - 1` when indexing negative buckets + /// (either of which can shift boundary quantiles by one discrete index at binary-inexact + /// decimals such as `0.95`). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// for value in 1..=100 { + /// sketch.update(f64::from(value)); + /// } + /// let p95 = sketch.quantile(0.95)?.unwrap(); + /// assert!((p95 - 95.0).abs() <= 0.01 * 95.0); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn quantile(&self, rank: f64) -> Result<Option<f64>, Error> { + check_rank(rank)?; + if self.is_empty() { + return Ok(None); + } + Ok(Some(self.quantile_unchecked(rank))) + } + + /// Returns approximate quantiles for `ranks` in input order, or `Ok(None)` if this sketch is + /// empty. + /// + /// For a non-empty sketch, an empty `ranks` slice returns `Ok(Some(vec![]))`. Multiple ranks + /// are answered in a single pass over the retained buckets regardless of input order. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if any rank is NaN or + /// outside `[0.0, 1.0]`, even if this sketch is empty. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// for value in 1..=1000 { + /// sketch.update(f64::from(value)); + /// } + /// let qs = sketch.quantiles(&[0.5, 0.9, 0.99])?.unwrap(); + /// assert_eq!(qs.len(), 3); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn quantiles(&self, ranks: &[f64]) -> Result<Option<Vec<f64>>, Error> { + for &rank in ranks { + check_rank(rank)?; + } + if self.is_empty() { + return Ok(None); + } + if ranks.is_empty() { + return Ok(Some(Vec::new())); + } + if ranks.len() == 1 { + return Ok(Some(vec![self.quantile_unchecked(ranks[0])])); + } + + let last = self.total_weight - 1; + let is_non_decreasing = ranks.windows(2).all(|pair| pair[0] <= pair[1]); + let mut out = vec![0.0; ranks.len()]; + if is_non_decreasing { + self.resolve_non_decreasing_ranks(ranks, last, &mut out); + return Ok(Some(out)); + } + + let mut indexed: Vec<(u64, usize)> = ranks + .iter() + .enumerate() + .map(|(pos, &rank)| (quantile_target_index(rank, last), pos)) + .collect(); + indexed.sort_unstable_by_key(|&(target, _)| target); + self.resolve_sorted_targets(&indexed, &mut out); + Ok(Some(out)) + } + + /// Returns an iterator over non-empty `(value, weight)` buckets in ascending numerical order. + #[inline] + pub fn iter(&self) -> DdSketchIter<'_> { + DdSketchIter::new( + self.mapping, + self.negative.iter_asc(), + self.zero_weight, + self.positive.iter_asc(), + self.num_retained(), + ) + } + + /// Serializes this sketch in this crate's native `DDSKETCH` binary format, preserving + /// [`MappingKind`], [`StoreKind`], collapse state, and exact `u64` bucket weights. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(3.5); + /// let bytes = sketch.serialize(); + /// let decoded = DdSketch::deserialize(&bytes)?; + /// assert_eq!(decoded.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn serialize(&self) -> Vec<u8> { + serialize_sketch(self) + } + + /// Deserializes a sketch from this crate's native `DDSKETCH` binary format, restoring its + /// encoded [`StoreKind`]. + /// + /// Use [`deserialize_compat`](Self::deserialize_compat) to decode compact flag-block images + /// produced by the Java and Go reference DDSketch implementations. + /// + /// # Errors + /// + /// Returns [`InvalidData`](crate::error::ErrorKind::InvalidData) if the image is empty, + /// truncated, has an unsupported family, version, or flag, or violates index, store, or weight + /// bounds. + pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> { + deserialize_sketch(bytes) + } + + /// Serializes this sketch in the compact flag-block binary format of the [Java][java-ref] and + /// [Go][go-ref] reference DDSketch implementations (distinct from the Protobuf format used by + /// Python and JavaScript). + /// + /// [java-ref]: https://github.com/DataDog/sketches-java + /// [go-ref]: https://github.com/DataDog/sketches-go + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// [`zero_weight`](Self::zero_weight) or any retained bucket weight exceeds `2^53 - 1` + /// (`9_007_199_254_740_991`), the maximum integer representable without rounding in the + /// compatibility format's `v + 1.0` floating-point counter encoding. + /// + /// # Cross-language compatibility + /// + /// [`StoreKind`] and collapse state are in-memory properties in the reference format and are + /// not recorded in the output bytes; decode with + /// [`deserialize_compat`](Self::deserialize_compat) and an explicit [`StoreKind`]. For + /// downstream Java or Go readers, keep [`total_weight`](Self::total_weight) at or below + /// `2^53 - 1` (Java computes `total_weight - 1` in `f64`), per-sign bucket index spans at or + /// below `2^26` (Go's default `MaxDecodeIndexRange`), and input magnitudes within the target + /// reader's `maxIndexableValue` (reference readers do not clamp near-[`f64::MAX`] buckets). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// use datasketches::ddsketch::StoreKind; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(42.0); + /// let compat_bytes = sketch.serialize_compat()?; + /// let decoded = DdSketch::deserialize_compat(&compat_bytes, StoreKind::default())?; + /// assert_eq!(decoded.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn serialize_compat(&self) -> Result<Vec<u8>, Error> { + serialize_compat_sketch(self) + } + + /// Deserializes a sketch from the compact flag-block binary format of the [Java][java-ref] and + /// [Go][go-ref] reference DDSketch implementations into the specified `store` strategy. + /// + /// [java-ref]: https://github.com/DataDog/sketches-java + /// [go-ref]: https://github.com/DataDog/sketches-go + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if `store` has an + /// invalid `max_num_bins` bound, or [`InvalidData`](crate::error::ErrorKind::InvalidData) if + /// the image is empty, truncated, missing an index mapping, encodes a mapping that cannot index + /// up to [`f64::MAX`] within 32-bit bucket bounds, contains unsupported flags or + /// non-integer/negative counts, overflows index or `u64` weight bounds, or spans more than + /// `67_108_864` total bins across negative and positive stores when `store` is + /// [`StoreKind::UnboundedDense`]. + /// + /// # Cross-language compatibility + /// + /// Accepts images carrying optional exact summary-statistic blocks (`count`, `sum`, `min`, + /// `max`), skipping those auxiliary fields; encoded counts must be non-negative integers below + /// `2^64`. Because reference images do not record [`StoreKind`], choose [`StoreKind::Sparse`] + /// or a sufficiently wide dense bound when decoding a wide-span sketch without bin collapsing. + pub fn deserialize_compat(bytes: &[u8], store: StoreKind) -> Result<Self, Error> { + validate_store_kind(store)?; + deserialize_compat_sketch(bytes, store) + } + + fn quantile_unchecked(&self, rank: f64) -> f64 { + debug_assert!(!self.is_empty()); + let last = self.total_weight - 1; + let target = quantile_target_index(rank, last); + if target == 0 { + return self.min_value().expect("non-empty sketch has min_value"); + } + if target == last { + return self.max_value().expect("non-empty sketch has max_value"); + } + + let neg_weight = self.negative.total_weight(); + if target < neg_weight { + let mag_rank = neg_weight - 1 - target; Review Comment: Updated the `quantile` compatibility docs in e80fc28e24b31dda7d5fc38b170d3126e8382e5b to describe `sketches-go`'s mirrored negative-side rank rule (differing on any fractional negative-side rank, such as `p50` of `[-100.0, -1.0]`). Adding a configurable rank-rule option as a follow-up sounds good. ########## datasketches/src/ddsketch/mapping.rs: ########## @@ -0,0 +1,413 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::f64::consts::LN_2; + +use super::MIN_RELATIVE_ACCURACY; +use crate::error::Error; + +const SIGNIFICAND_MASK: u64 = 0x000f_ffff_ffff_ffff; +const EXPONENT_MASK: u64 = 0x7ff0_0000_0000_0000; +const EXPONENT_SHIFT: u32 = 52; +const EXPONENT_BIAS: i32 = 1023; +const ONE_BITS: u64 = 0x3ff0_0000_0000_0000; + +// Optimal cubic polynomial coefficients on s in [0, 1) minimizing worst-case bucket overhead +// while preserving monotonicity and C^0 continuity across powers of two: +// P(s) = (6/35) s^3 - (3/5) s^2 + (10/7) s, with inf_{s in [0, 1)} (1 + s) P'(s) = 10/7. +const CUBIC_A: f64 = 6.0 / 35.0; +const CUBIC_B: f64 = -3.0 / 5.0; +const CUBIC_C: f64 = 10.0 / 7.0; +const CUBIC_D0: f64 = CUBIC_B * CUBIC_B - 3.0 * CUBIC_A * CUBIC_C; + +/// Index mapping curve used by a [`DdSketch`](super::DdSketch) to map positive magnitudes to +/// integer bucket indices. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum MappingKind { + /// Exact logarithmic mapping (`floor(ln(x) / ln(gamma))`). + /// + /// Uses the fewest buckets for a target relative accuracy at the cost of evaluating a natural + /// logarithm on each update. + Logarithmic, + /// Base-2 exponent extraction with linear significand interpolation. + /// + /// Avoids transcendental math on updates and queries, using about 44% more buckets than + /// [`MappingKind::Logarithmic`] for the same relative accuracy. + Linear, + /// Base-2 exponent extraction with cubic significand interpolation (default). + /// + /// Evaluates a degree-3 polynomial on the IEEE 754 significand, using under 1% more buckets + /// than [`MappingKind::Logarithmic`] with fast, platform-independent updates. + #[default] + Cubic, +} + +#[derive(Debug, Clone, Copy)] +pub struct IndexMapping { + kind: MappingKind, + gamma: f64, + index_offset: f64, + multiplier: f64, + relative_accuracy: f64, + min_indexable_value: f64, + min_index: i32, + max_index: i32, +} + +impl IndexMapping { + pub fn from_accuracy(kind: MappingKind, relative_accuracy: f64) -> Result<Self, Error> { + if !(MIN_RELATIVE_ACCURACY..1.0).contains(&relative_accuracy) { + return Err(Error::invalid_argument(format!( + "relative_accuracy must be in [{MIN_RELATIVE_ACCURACY}, 1.0), got {relative_accuracy}" + ))); + } + + let exact_gamma = (1.0 + relative_accuracy) / (1.0 - relative_accuracy); + let (gamma, index_offset) = match kind { + MappingKind::Logarithmic => (exact_gamma, 0.0), + MappingKind::Linear => { + let gamma = exact_gamma.powf(LN_2); + // Matches the historical offset convention of Datadog's + // LinearlyInterpolatedMapping. + let index_offset = + 1.0 / (2.0 * relative_accuracy / (1.0 - relative_accuracy)).ln_1p(); + (gamma, index_offset) + } + MappingKind::Cubic => (exact_gamma.powf(10.0 * LN_2 / 7.0), 0.0), + }; + + Self::build(kind, gamma, index_offset).map_err(Error::invalid_argument) + } + + pub fn from_gamma_offset( + kind: MappingKind, + gamma: f64, + index_offset: f64, + ) -> Result<Self, Error> { + Self::build(kind, gamma, index_offset).map_err(Error::deserial) + } + + fn build(kind: MappingKind, gamma: f64, index_offset: f64) -> Result<Self, String> { + if !gamma.is_finite() || gamma <= 1.0 { + return Err(format!("gamma must be finite and > 1.0, got {gamma}")); + } + if !index_offset.is_finite() { + return Err(format!("index_offset must be finite, got {index_offset}")); + } + // Canonicalize `-0.0` so equivalent zero offsets serialize and compare identically. + let index_offset = if index_offset == 0.0 { + 0.0 + } else { + index_offset + }; + + let ln_gamma = (gamma - 1.0).ln_1p(); + if !ln_gamma.is_finite() || ln_gamma <= 0.0 { + return Err(format!("gamma is too close to 1.0: {gamma}")); + } + + let (multiplier, exact_gamma, max_log) = match kind { + MappingKind::Logarithmic => (1.0 / ln_gamma, gamma, f64::MAX.ln()), + MappingKind::Linear => (LN_2 / ln_gamma, gamma.powf(1.0 / LN_2), 1024.0), + MappingKind::Cubic => (LN_2 / ln_gamma, gamma.powf(7.0 / (10.0 * LN_2)), 1024.0), + }; + + if !multiplier.is_finite() || multiplier <= 0.0 || !exact_gamma.is_finite() { + return Err(format!( + "invalid mapping parameters: gamma={gamma}, index_offset={index_offset}" + )); + } + + let relative_accuracy = if exact_gamma <= 2.0 { + (exact_gamma - 1.0) / (exact_gamma + 1.0) + } else { + 1.0 - 2.0 / (1.0 + exact_gamma) + }; + if !relative_accuracy.is_finite() || relative_accuracy <= 0.0 || relative_accuracy >= 1.0 { + return Err(format!( + "mapping relative_accuracy must be in (0.0, 1.0), got {relative_accuracy}" + )); + } + + // Ensure every finite normal value up to f64::MAX maps within [i32::MIN, i32::MAX]. + let max_raw_index = max_log * multiplier + index_offset; + if !max_raw_index.is_finite() + || max_raw_index > f64::from(i32::MAX) + || max_raw_index <= f64::from(i32::MIN) + 1.0 + { + return Err(format!( + "mapping parameters overflow 32-bit bucket indices at f64::MAX: gamma={gamma}, index_offset={index_offset}" + )); + } + + let min_exp_arg = (f64::from(i32::MIN) - index_offset) / multiplier + 1.0; + let min_from_i32 = match kind { + MappingKind::Logarithmic => min_exp_arg.exp(), + MappingKind::Linear | MappingKind::Cubic => min_exp_arg.exp2(), + }; + let min_from_normal = f64::MIN_POSITIVE * exact_gamma; + let min_indexable_value = min_from_i32.max(min_from_normal); + if !min_indexable_value.is_finite() || min_indexable_value >= f64::MAX { + return Err(format!( + "mapping has empty indexable domain: min_indexable_value={min_indexable_value}" + )); + } + + let first_raw = + approx_log_of(kind, min_indexable_value.next_up()) * multiplier + index_offset; + let last_raw = approx_log_of(kind, f64::MAX) * multiplier + index_offset; + if !first_raw.is_finite() + || first_raw < f64::from(i32::MIN) + || !last_raw.is_finite() + || last_raw > f64::from(i32::MAX) + { + return Err(format!( + "mapping parameters overflow 32-bit bucket indices: gamma={gamma}, index_offset={index_offset}" + )); + } + // Allow the 1-bin shift when `first_raw` lands on an exact negative integer in reference + // Java/Go encoders (`(int) raw - 1`). + let min_index = if first_raw < 0.0 && first_raw.fract() == 0.0 { + (first_raw as i32).saturating_sub(1) + } else { + first_raw.floor() as i32 + }; + let max_index = last_raw.floor() as i32; + if min_index > max_index { + return Err(format!( + "mapping has inverted index bounds [{min_index}, {max_index}]" + )); + } + + Ok(Self { + kind, + gamma, + index_offset, + multiplier, + relative_accuracy, + min_indexable_value, + min_index, + max_index, + }) + } + + #[inline] + pub const fn kind(&self) -> MappingKind { + self.kind + } + + #[inline] + pub const fn gamma(&self) -> f64 { + self.gamma + } + + #[inline] + pub const fn index_offset(&self) -> f64 { + self.index_offset + } + + #[inline] + pub const fn relative_accuracy(&self) -> f64 { + self.relative_accuracy + } + + #[inline] + pub const fn min_indexable_value(&self) -> f64 { + self.min_indexable_value + } + + #[inline] + pub fn is_compatible(&self, other: &Self) -> bool { + self.kind == other.kind + && self.gamma == other.gamma + && self.index_offset == other.index_offset + } + + #[inline] + pub fn index(&self, value: f64) -> i32 { + debug_assert!(value > self.min_indexable_value && value.is_finite()); + let approx_log = approx_log_of(self.kind, value); + let raw = (approx_log * self.multiplier + self.index_offset).floor(); Review Comment: Documented this under `# Cross-language compatibility` in e80fc28e24b31dda7d5fc38b170d3126e8382e5b while keeping `floor()` for the default mapping. If exact parity on those negative-integer boundary inputs is needed later, we can expose it as a mapping option. ########## datasketches/src/ddsketch/sketch.rs: ########## @@ -0,0 +1,832 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::fmt; + +use super::DEFAULT_RELATIVE_ACCURACY; +use super::iter::DdSketchIter; +use super::mapping::IndexMapping; +use super::mapping::MappingKind; +use super::serialization::deserialize_compat_sketch; +use super::serialization::deserialize_sketch; +use super::serialization::serialize_compat_sketch; +use super::serialization::serialize_sketch; +use super::store::Store; +use super::store::StoreKind; +use super::store::validate_store_kind; +use crate::error::Error; + +/// Builder for configuring and constructing a [`DdSketch`]. +/// +/// Defaults to `relative_accuracy = 0.01`, [`MappingKind::Cubic`], and +/// [`StoreKind::CollapsingLowestDense`] with `2048` bins per sign. +/// +/// # Examples +/// +/// ``` +/// use datasketches::ddsketch::DdSketchBuilder; +/// use datasketches::ddsketch::MappingKind; +/// use datasketches::ddsketch::StoreKind; +/// +/// let mut sketch = DdSketchBuilder::new(0.005) +/// .mapping(MappingKind::Logarithmic) +/// .store(StoreKind::Sparse) +/// .build()?; +/// sketch.update(42.0); +/// assert_eq!(sketch.total_weight(), 1); +/// # Ok::<(), datasketches::error::Error>(()) +/// ``` +#[derive(Debug, Clone)] +pub struct DdSketchBuilder { + relative_accuracy: f64, + mapping_kind: MappingKind, + store_kind: StoreKind, +} + +impl Default for DdSketchBuilder { + fn default() -> Self { + Self::new(DEFAULT_RELATIVE_ACCURACY) + } +} + +impl DdSketchBuilder { + /// Creates a builder with the given `relative_accuracy` and default mapping and store settings. + pub fn new(relative_accuracy: f64) -> Self { + Self { + relative_accuracy, + mapping_kind: MappingKind::default(), + store_kind: StoreKind::default(), + } + } + + /// Sets the index mapping curve used to assign positive magnitudes to bucket indices. + #[inline] + pub fn mapping(mut self, mapping_kind: MappingKind) -> Self { + self.mapping_kind = mapping_kind; + self + } + + /// Sets the bin storage strategy used for both positive and negative stores. + #[inline] + pub fn store(mut self, store_kind: StoreKind) -> Self { + self.store_kind = store_kind; + self + } + + /// Validates configuration parameters and creates an empty [`DdSketch`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`, or if `store` specifies a collapsing + /// dense store with `max_num_bins` outside `1..=67_108_864`. + pub fn build(self) -> Result<DdSketch, Error> { + validate_store_kind(self.store_kind)?; + let mapping = IndexMapping::from_accuracy(self.mapping_kind, self.relative_accuracy)?; + let negative = Store::new(self.store_kind)?; + let positive = Store::new(self.store_kind)?; + Ok(DdSketch::from_parts(mapping, negative, positive, 0, 0)) + } +} + +/// Mergeable quantile sketch over finite `f64` values with relative-value error guarantees. +/// +/// See the [module documentation](super) for accuracy, memory, and compatibility details. +#[derive(Clone)] +pub struct DdSketch { + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, +} + +impl fmt::Debug for DdSketch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DdSketch") + .field("relative_accuracy", &self.mapping.relative_accuracy()) + .field("mapping_kind", &self.mapping.kind()) + .field("store_kind", &self.positive.kind()) + .field("is_empty", &self.is_empty()) + .field("total_weight", &self.total_weight) + .field("zero_weight", &self.zero_weight) + .field("num_retained", &self.num_retained()) + .field("min_value", &self.min_value()) + .field("max_value", &self.max_value()) + .finish() + } +} + +impl Default for DdSketch { + fn default() -> Self { + DdSketchBuilder::default() + .build() + .expect("default DDSketch configuration is valid") + } +} + +impl DdSketch { + /// Creates an empty sketch with the given `relative_accuracy`, [`MappingKind::Cubic`], and + /// [`StoreKind::default()`]. + /// + /// # Errors + /// + /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) if + /// `relative_accuracy` is NaN or outside `[1e-6, 1.0)`. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let sketch = DdSketch::new(0.01)?; + /// assert!(sketch.is_empty()); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + pub fn new(relative_accuracy: f64) -> Result<Self, Error> { + DdSketchBuilder::new(relative_accuracy).build() + } + + pub(super) fn from_parts( + mapping: IndexMapping, + negative: Store, + positive: Store, + zero_weight: u64, + total_weight: u64, + ) -> Self { + debug_assert_eq!( + negative.total_weight() + zero_weight + positive.total_weight(), + total_weight + ); + Self { + mapping, + negative, + positive, + zero_weight, + total_weight, + } + } + + #[inline] + pub(super) const fn mapping(&self) -> IndexMapping { + self.mapping + } + + #[inline] + pub(super) const fn positive_store(&self) -> &Store { + &self.positive + } + + #[inline] + pub(super) const fn negative_store(&self) -> &Store { + &self.negative + } + + /// Returns the relative value accuracy guaranteed for non-collapsed buckets. + #[inline] + pub fn relative_accuracy(&self) -> f64 { + self.mapping.relative_accuracy() + } + + /// Returns the index mapping curve used by this sketch. + #[inline] + pub fn mapping_kind(&self) -> MappingKind { + self.mapping.kind() + } + + /// Returns the bin storage strategy used by this sketch. + #[inline] + pub fn store_kind(&self) -> StoreKind { + self.positive.kind() + } + + /// Returns the magnitude threshold below or at which inputs map to the zero bucket. + /// + /// Any finite input `x` with `|x| <= self.zero_threshold()` increments + /// [`zero_weight`](Self::zero_weight) and is approximated by `0.0`. + #[inline] + pub fn zero_threshold(&self) -> f64 { + self.mapping.min_indexable_value() + } + + /// Returns `true` if this sketch has not recorded any finite observations. + #[inline] + pub fn is_empty(&self) -> bool { + self.total_weight == 0 + } + + /// Returns the accumulated stream weight across all buckets. + #[inline] + pub fn total_weight(&self) -> u64 { + self.total_weight + } + + /// Returns the accumulated stream weight in the zero bucket. + #[inline] + pub fn zero_weight(&self) -> u64 { + self.zero_weight + } + + /// Returns the number of non-empty buckets currently retained by this sketch, including the + /// zero bucket when [`zero_weight`](Self::zero_weight) is non-zero. + #[inline] + pub fn num_retained(&self) -> usize { + self.negative.num_occupied() + + usize::from(self.zero_weight != 0) + + self.positive.num_occupied() + } + + /// Returns an implementation-dependent estimate of heap memory usage in bytes. + pub fn estimated_size(&self) -> usize { + self.negative + .estimated_size() + .saturating_add(self.positive.estimated_size()) + } + + /// Updates this sketch with a single observation. + /// + /// [`f64::NAN`], [`f64::INFINITY`], and [`f64::NEG_INFINITY`] values are ignored. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update(10.0); + /// assert_eq!(sketch.total_weight(), 1); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update(&mut self, value: f64) { + self.update_with_weight(value, 1); + } + + /// Updates this sketch with `value` repeated `weight` times. + /// + /// [`f64::NAN`], [`f64::INFINITY`], [`f64::NEG_INFINITY`], and a `weight` of `0` are no-ops. + /// + /// # Panics + /// + /// Panics without modifying the sketch if [`total_weight`](Self::total_weight) would exceed + /// [`u64::MAX`], or if [`StoreKind::UnboundedDense`] would exceed addressable slice capacity. + /// + /// # Cross-language compatibility + /// + /// In the reference DDSketch implementations, Go rejects `NaN`, infinite, and negative-count + /// inputs with an error, whereas Java rejects out-of-range finite/infinite and negative-count + /// inputs while counting `NaN` into the zero bucket; both accept fractional `f64` counts. This + /// method ignores non-finite values and accumulates exact `u64` integer weights; keep + /// per-bucket weights (and [`total_weight`](Self::total_weight) for Java quantile readers) at + /// or below `2^53 - 1` when serializing with [`serialize_compat`](Self::serialize_compat). + /// + /// # Examples + /// + /// ``` + /// use datasketches::ddsketch::DdSketch; + /// + /// let mut sketch = DdSketch::new(0.01)?; + /// sketch.update_with_weight(25.0, 100); + /// assert_eq!(sketch.total_weight(), 100); + /// # Ok::<(), datasketches::error::Error>(()) + /// ``` + #[inline] + pub fn update_with_weight(&mut self, value: f64, weight: u64) { Review Comment: For now we prefer keeping concrete `u64` weights on `DdSketch`: it matches `total_weight` and `update_with_weight` across the other sketches in this crate (`KllSketch`, `TDigest`, `FrequentItemsSketch`) without adding a type parameter to every signature, keeps merging associative without floating-point counter drift, and enables compact `uvarint64` native encoding. Happy to revisit fractional weights (via a separate weighted variant or type parameter) once we evaluate concrete workloads; please let us know what you think. ########## datasketches/src/ddsketch/store.rs: ########## @@ -0,0 +1,1269 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::collections::BTreeMap; +use std::collections::btree_map; +use std::iter::FusedIterator; + +use super::DEFAULT_MAX_NUM_BINS; +use super::MAX_DENSE_BINS; +use crate::error::Error; + +const INITIAL_DENSE_OVERHEAD: usize = 64; +const MAX_I32_SPAN: u64 = (i32::MAX as i64 - i32::MIN as i64 + 1) as u64; +const MAX_VEC_U64_LEN: u64 = ((isize::MAX as usize) / size_of::<u64>()) as u64; +/// Maximum number of `u64` slots a `DenseStore` can hold: bounded both by addressable `Vec<u64>` +/// capacity (`isize::MAX / 8` on 32-bit targets) and by the 32-bit bucket index domain (`2^32` on +/// 64-bit targets). +pub const MAX_DENSE_LEN: usize = if MAX_VEC_U64_LEN < MAX_I32_SPAN { + MAX_VEC_U64_LEN as usize +} else { + MAX_I32_SPAN as usize +}; + +/// Bin storage strategy used by the positive and negative stores of a +/// [`DdSketch`](super::DdSketch). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StoreKind { Review Comment: Thanks for the context on `internal-1`'s signed occupied-key budget. With `StoreKind` marked `#[non_exhaustive]` in 51eb4453fc37cef38d42e617c8acb4c433a7b2f5, we have room to explore either a new variant or a sketch-level store layout in a follow-up. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
