tisonkun commented on code in PR #400: URL: https://github.com/apache/datasketches-rust/pull/400#discussion_r4658950914
########## 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 { Review Comment: Addressed in dba717e537dc0743678fca54c73a9a93bc9ba6f4: when exact summary statistics are present, `quantile` and `quantiles` return exact `min_value` at `q = 0.0`, exact `max_value` at `q = 1.0`, and clamp interior estimates to `[min_value, max_value]` (so `p0([1.0]) == 1.0`). Please take another look. ########## datasketches/src/ddsketch/serialization.rs: ########## @@ -0,0 +1,1405 @@ +// 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 super::MAX_DENSE_BINS; +use super::mapping::IndexMapping; +use super::mapping::MappingKind; +use super::sketch::DdSketch; +use super::store::MAX_DENSE_LEN; +use super::store::Store; +use super::store::StoreKind; +use super::store::span_u64; +use crate::codec::SketchBytes; +use crate::codec::SketchSlice; +use crate::codec::assert::ensure_preamble_longs_in; +use crate::codec::assert::ensure_serial_version_is; +use crate::codec::assert::insufficient_data; +use crate::codec::family::Family; +use crate::error::Error; + +// Native DDSKETCH preamble constants (3 longs = 24 bytes). +// `PREAMBLE_LONGS = 3` (`0x03`) is also disjoint from every valid leading flag byte of the +// reference DDSketch format (`flag_type = 0b11` defines no `subflag = 0`), ensuring cross-format +// inputs fail cleanly on the first header check. +const PREAMBLE_LONGS: u8 = 3; +const SERIAL_VERSION: u8 = 1; +const PREAMBLE_BYTES: usize = (PREAMBLE_LONGS as usize) * size_of::<u64>(); + +const MAPPING_MASK: u8 = 0b0000_0011; +const MAPPING_TAG_LOGARITHMIC: u8 = 0; +const MAPPING_TAG_LINEAR: u8 = 1; +const MAPPING_TAG_CUBIC: u8 = 2; + +const STORE_SHIFT: u8 = 2; +const STORE_MASK: u8 = 0b0000_0011; +const STORE_TAG_COLLAPSING_LOWEST: u8 = 0; +const STORE_TAG_COLLAPSING_HIGHEST: u8 = 1; +const STORE_TAG_UNBOUNDED_DENSE: u8 = 2; +const STORE_TAG_SPARSE: u8 = 3; + +const FLAG_IS_EMPTY: u8 = 1 << 4; +const FLAG_NEG_COLLAPSED: u8 = 1 << 5; +const FLAG_POS_COLLAPSED: u8 = 1 << 6; +const FLAG_RESERVED_MASK: u8 = 1 << 7; + +const NATIVE_STORE_EMPTY: u8 = 0; +const NATIVE_STORE_CONTIGUOUS_COUNTS: u8 = 1; +const NATIVE_STORE_INDEX_DELTAS: u8 = 2; +const NATIVE_STORE_DELTAS_AND_COUNTS: u8 = 3; +// Dense stores wider than 65,536 bins (~512 KiB per sign) always serialize as contiguous counts so +// input byte length naturally bounds dense allocation on decode without rejecting valid wide +// `UnboundedDense` round-trips. +const MAX_SPARSE_ENCODED_DENSE_SPAN: usize = 65_536; + +// Reference (Datadog) block-stream wire constants. +const DD_FLAG_TYPE_MASK: u8 = 0b0000_0011; +const DD_FLAG_TYPE_SKETCH_FEATURES: u8 = 0b00; +const DD_FLAG_TYPE_POSITIVE_STORE: u8 = 0b01; +const DD_FLAG_TYPE_INDEX_MAPPING: u8 = 0b10; +const DD_FLAG_TYPE_NEGATIVE_STORE: u8 = 0b11; + +const DD_SUBFLAG_ZERO_COUNT: u8 = 1 << 2; +const DD_SUBFLAG_EXACT_SUM: u8 = 0x21 << 2; +const DD_SUBFLAG_EXACT_MIN: u8 = 0x22 << 2; +const DD_SUBFLAG_EXACT_MAX: u8 = 0x23 << 2; +const DD_SUBFLAG_EXACT_COUNT: u8 = 0x28 << 2; + +const DD_SUBFLAG_MAPPING_LOGARITHMIC: u8 = 0 << 2; +const DD_SUBFLAG_MAPPING_LINEAR: u8 = 1 << 2; +const DD_SUBFLAG_MAPPING_CUBIC: u8 = 3 << 2; + +const DD_SUBFLAG_BINS_DELTAS_AND_COUNTS: u8 = 1 << 2; +const DD_SUBFLAG_BINS_INDEX_DELTAS: u8 = 2 << 2; +const DD_SUBFLAG_BINS_CONTIGUOUS_COUNTS: u8 = 3 << 2; + +const MAX_VAR_LEN_64: usize = 9; +const VARFLOAT_ROTATE: u32 = 6; +const ONE_F64_BITS: u64 = 0x3ff0_0000_0000_0000; +const MAX_COMPAT_WEIGHT: u64 = (1 << 53) - 1; +const TWO_POW_64: f64 = 18_446_744_073_709_551_616.0; + +pub fn serialize_sketch(sketch: &DdSketch) -> Vec<u8> { + let mapping = sketch.mapping(); + let is_empty = sketch.is_empty(); + let (store_tag, max_bins_u32) = encode_store_kind(sketch.store_kind()); + let mapping_tag = match mapping.kind() { + MappingKind::Logarithmic => MAPPING_TAG_LOGARITHMIC, + MappingKind::Linear => MAPPING_TAG_LINEAR, + MappingKind::Cubic => MAPPING_TAG_CUBIC, + }; + + let mut flags = mapping_tag | (store_tag << STORE_SHIFT); + if is_empty { + flags |= FLAG_IS_EMPTY; + } else { + if sketch.negative_store().is_collapsed() { + flags |= FLAG_NEG_COLLAPSED; + } + if sketch.positive_store().is_collapsed() { + flags |= FLAG_POS_COLLAPSED; + } + } + + let (neg_choice, neg_bytes) = if is_empty { + (NativeBinChoice::Empty, 0) + } else { + choose_native_bin_encoding(sketch.negative_store()) + }; + let (pos_choice, pos_bytes) = if is_empty { + (NativeBinChoice::Empty, 0) + } else { + choose_native_bin_encoding(sketch.positive_store()) + }; + let payload_bytes = if is_empty { + 0 + } else { + uvarint64_size(sketch.zero_weight()) + neg_bytes + pos_bytes + }; + + let mut out = SketchBytes::with_capacity(PREAMBLE_BYTES + payload_bytes); + out.write_u8(PREAMBLE_LONGS); + out.write_u8(SERIAL_VERSION); + out.write_u8(Family::DDSKETCH.id); + out.write_u8(flags); + out.write_u32_le(max_bins_u32); + out.write_f64_le(mapping.gamma()); + out.write_f64_le(mapping.index_offset()); + + if is_empty { + return out.into_bytes(); + } + + encode_uvarint64(&mut out, sketch.zero_weight()); + encode_native_store(&mut out, sketch.negative_store(), neg_choice); + encode_native_store(&mut out, sketch.positive_store(), pos_choice); + + out.into_bytes() +} + +pub fn deserialize_sketch(bytes: &[u8]) -> Result<DdSketch, Error> { + deserialize_native(bytes) +} + +pub fn serialize_compat_sketch(sketch: &DdSketch) -> Result<Vec<u8>, Error> { + let mapping = sketch.mapping(); + let mapping_subflag = match mapping.kind() { + MappingKind::Logarithmic => DD_SUBFLAG_MAPPING_LOGARITHMIC, + MappingKind::Linear => DD_SUBFLAG_MAPPING_LINEAR, + MappingKind::Cubic => DD_SUBFLAG_MAPPING_CUBIC, + }; + + let zero_weight = sketch.zero_weight(); + if zero_weight > MAX_COMPAT_WEIGHT { + return Err(Error::invalid_argument(format!( + "DDSketch zero_weight ({zero_weight}) exceeds maximum exact compatibility count ({MAX_COMPAT_WEIGHT})" + ))); + } + let zero_bytes = if zero_weight == 0 { + 0 + } else { + 1 + varfloat64_size(zero_weight as f64) + }; + let (neg_choice, neg_bytes) = choose_compat_bin_encoding(sketch.negative_store())?; + let (pos_choice, pos_bytes) = choose_compat_bin_encoding(sketch.positive_store())?; + + let mut out = SketchBytes::with_capacity(17 + zero_bytes + neg_bytes + pos_bytes); + out.write_u8(mapping_subflag | DD_FLAG_TYPE_INDEX_MAPPING); + out.write_f64_le(mapping.gamma()); + out.write_f64_le(mapping.index_offset()); + + if zero_weight != 0 { + out.write_u8(DD_SUBFLAG_ZERO_COUNT | DD_FLAG_TYPE_SKETCH_FEATURES); + encode_varfloat64(&mut out, zero_weight as f64); + } + if let Some(choice) = neg_choice { + encode_compat_store( + &mut out, + sketch.negative_store(), + DD_FLAG_TYPE_NEGATIVE_STORE, + choice, + ); + } + if let Some(choice) = pos_choice { + encode_compat_store( + &mut out, + sketch.positive_store(), + DD_FLAG_TYPE_POSITIVE_STORE, + choice, + ); + } + + Ok(out.into_bytes()) +} + +pub fn deserialize_compat_sketch(bytes: &[u8], store_kind: StoreKind) -> Result<DdSketch, Error> { + deserialize_datadog(bytes, store_kind) +} + +fn encode_store_kind(kind: StoreKind) -> (u8, u32) { + match kind { + StoreKind::CollapsingLowestDense { max_num_bins } => ( + STORE_TAG_COLLAPSING_LOWEST, + u32::try_from(max_num_bins).expect("validated max_num_bins fits in u32"), + ), + StoreKind::CollapsingHighestDense { max_num_bins } => ( + STORE_TAG_COLLAPSING_HIGHEST, + u32::try_from(max_num_bins).expect("validated max_num_bins fits in u32"), + ), + StoreKind::UnboundedDense => (STORE_TAG_UNBOUNDED_DENSE, 0), + StoreKind::Sparse => (STORE_TAG_SPARSE, 0), + } +} + +fn decode_store_kind(store_tag: u8, max_bins_u32: u32) -> Result<StoreKind, Error> { + match store_tag { + STORE_TAG_COLLAPSING_LOWEST | STORE_TAG_COLLAPSING_HIGHEST => { + let max_num_bins = max_bins_u32 as usize; + if !(1..=MAX_DENSE_BINS).contains(&max_num_bins) { + return Err(Error::deserial(format!( + "DDSketch max_num_bins must be in [1, {MAX_DENSE_BINS}], got {max_bins_u32}" + ))); + } + if store_tag == STORE_TAG_COLLAPSING_LOWEST { + Ok(StoreKind::CollapsingLowestDense { max_num_bins }) + } else { + Ok(StoreKind::CollapsingHighestDense { max_num_bins }) + } + } + STORE_TAG_UNBOUNDED_DENSE => { + if max_bins_u32 != 0 { + return Err(Error::deserial(format!( + "expected max_num_bins = 0 for UnboundedDense, got {max_bins_u32}" + ))); + } + Ok(StoreKind::UnboundedDense) + } + STORE_TAG_SPARSE => { + if max_bins_u32 != 0 { + return Err(Error::deserial(format!( + "expected max_num_bins = 0 for Sparse, got {max_bins_u32}" + ))); + } + Ok(StoreKind::Sparse) + } + _ => unreachable!("2-bit store tag only produces 0..=3"), + } +} + +fn deserialize_native(bytes: &[u8]) -> Result<DdSketch, Error> { + let mut cursor = SketchSlice::new(bytes); + let preamble_longs = cursor + .read_u8() + .map_err(insufficient_data("preamble_longs"))?; + let serial_version = cursor + .read_u8() + .map_err(insufficient_data("serial_version"))?; + let family_id = cursor.read_u8().map_err(insufficient_data("family_id"))?; + + Family::DDSKETCH.validate_id(family_id)?; + ensure_serial_version_is(SERIAL_VERSION, serial_version)?; + ensure_preamble_longs_in(&[PREAMBLE_LONGS], preamble_longs)?; + + let flags = cursor.read_u8().map_err(insufficient_data("flags"))?; + if (flags & FLAG_RESERVED_MASK) != 0 { + return Err(Error::deserial(format!( + "unsupported DDSketch flags: {flags:#04x}" + ))); + } + let max_bins_u32 = cursor + .read_u32_le() + .map_err(insufficient_data("max_num_bins"))?; + let gamma = cursor.read_f64_le().map_err(insufficient_data("gamma"))?; + let index_offset = cursor + .read_f64_le() + .map_err(insufficient_data("index_offset"))?; + + let mapping_kind = match flags & MAPPING_MASK { + MAPPING_TAG_LOGARITHMIC => MappingKind::Logarithmic, + MAPPING_TAG_LINEAR => MappingKind::Linear, + MAPPING_TAG_CUBIC => MappingKind::Cubic, + other => { + return Err(Error::deserial(format!( + "invalid DDSketch mapping tag: {other}" + ))); + } + }; + let encoded_store_kind = decode_store_kind((flags >> STORE_SHIFT) & STORE_MASK, max_bins_u32)?; + let mapping = IndexMapping::from_gamma_offset(mapping_kind, gamma, index_offset)?; + + let is_empty = (flags & FLAG_IS_EMPTY) != 0; + let neg_collapsed = (flags & FLAG_NEG_COLLAPSED) != 0; + let pos_collapsed = (flags & FLAG_POS_COLLAPSED) != 0; + let encoded_max_bins = match encoded_store_kind { + StoreKind::CollapsingLowestDense { max_num_bins } + | StoreKind::CollapsingHighestDense { max_num_bins } => Some(max_num_bins), + StoreKind::UnboundedDense | StoreKind::Sparse => None, + }; + if encoded_max_bins.is_none() && (neg_collapsed || pos_collapsed) { + return Err(Error::deserial( + "collapsed flags cannot be set for non-collapsing DDSketch store", + )); + } + + let mut negative = Store::new(encoded_store_kind)?; + let mut positive = Store::new(encoded_store_kind)?; + + if is_empty { + if neg_collapsed || pos_collapsed { + return Err(Error::deserial( + "collapsed flags cannot be set on an empty DDSketch", + )); + } + let trailing = cursor.remaining().len(); + if trailing != 0 { + return Err(Error::deserial(format!( + "expected end of empty DDSketch image, found {trailing} trailing bytes" + ))); + } + return Ok(DdSketch::from_parts(mapping, negative, positive, 0, 0)); + } + + let is_dense_target = !matches!(encoded_store_kind, StoreKind::Sparse); + let zero_weight = decode_uvarint64(&mut cursor, "zero_weight")?; + let (neg_weight, neg_span) = decode_native_store( + &mut cursor, + &mut negative, + &mapping, + is_dense_target, + encoded_max_bins, + )?; + let (pos_weight, pos_span) = decode_native_store( + &mut cursor, + &mut positive, + &mapping, + is_dense_target, + encoded_max_bins, + )?; + + validate_encoded_sign_store(neg_weight, neg_span, neg_collapsed, encoded_max_bins)?; + validate_encoded_sign_store(pos_weight, pos_span, pos_collapsed, encoded_max_bins)?; + + let total_weight = zero_weight + .checked_add(neg_weight) + .and_then(|acc| acc.checked_add(pos_weight)) + .ok_or_else(|| Error::deserial("total_weight overflows u64"))?; + if total_weight == 0 { + return Err(Error::deserial( + "non-empty DDSketch image must have positive total_weight", + )); + } + + let trailing = cursor.remaining().len(); + if trailing != 0 { + return Err(Error::deserial(format!( + "unexpected {trailing} trailing bytes after DDSketch payload" + ))); + } + + if neg_collapsed { + negative.set_collapsed(true); + } + if pos_collapsed { + positive.set_collapsed(true); + } + + Ok(DdSketch::from_parts( + mapping, + negative, + positive, + zero_weight, + total_weight, + )) +} + +fn validate_encoded_sign_store( + weight: u64, + wire_span: u64, + collapsed: bool, + encoded_max_bins: Option<usize>, +) -> Result<(), Error> { + if collapsed && weight == 0 { + return Err(Error::deserial( + "collapsed flag set on an empty DDSketch sign store", + )); + } + if let Some(max_bins) = encoded_max_bins { + let max_bins_u64 = max_bins as u64; + if wire_span > max_bins_u64 { + return Err(Error::deserial(format!( + "DDSketch sign store span ({wire_span}) exceeds encoded max_num_bins ({max_bins})" + ))); + } + if collapsed && wire_span != max_bins_u64 { + return Err(Error::deserial(format!( + "collapsed DDSketch sign store span ({wire_span}) must equal max_num_bins ({max_bins})" + ))); + } + } + Ok(()) +} + +#[derive(Clone, Copy)] +enum NativeBinChoice { + Empty, + ContiguousCounts { num_bins: u64, min_index: i32 }, + IndexDeltas { num_bins: u64 }, + IndexDeltasAndCounts { num_bins: u64 }, +} + +fn choose_native_bin_encoding(store: &Store) -> (NativeBinChoice, usize) { + if store.is_empty() { + return (NativeBinChoice::Empty, 1); + } + + let num_non_empty = store.num_occupied() as u64; + let mut sparse_deltas_bytes = 1 + uvarint64_size(num_non_empty); + let mut sparse_counts_bytes = 0_usize; + let mut all_unit_weights = true; + let mut prev_index = 0_i64; + + for (idx, weight) in store.iter_asc() { + let idx64 = i64::from(idx); + sparse_deltas_bytes += varint64_size(idx64 - prev_index); + sparse_counts_bytes += uvarint64_size(weight); + if weight != 1 { + all_unit_weights = false; + } + prev_index = idx64; + } + + let (best_sparse, best_sparse_bytes) = if all_unit_weights { + ( + NativeBinChoice::IndexDeltas { + num_bins: num_non_empty, + }, + sparse_deltas_bytes, + ) + } else { + ( + NativeBinChoice::IndexDeltasAndCounts { + num_bins: num_non_empty, + }, + sparse_deltas_bytes + sparse_counts_bytes, + ) + }; + + if let Some((min_index, contiguous)) = store.dense_contiguous_slice() { + let num_bins = contiguous.len() as u64; + let num_zero_bins = contiguous.len() - store.num_occupied(); + // Zero weight encodes as single byte `0x00` in uvarint64. + let dense_bytes = 1 + + uvarint64_size(num_bins) + + varint64_size(i64::from(min_index)) + + sparse_counts_bytes + + num_zero_bins; + if contiguous.len() > MAX_SPARSE_ENCODED_DENSE_SPAN || dense_bytes <= best_sparse_bytes { + return ( + NativeBinChoice::ContiguousCounts { + num_bins, + min_index, + }, + dense_bytes, + ); + } + } + + (best_sparse, best_sparse_bytes) +} + +fn encode_native_store(out: &mut SketchBytes, store: &Store, choice: NativeBinChoice) { + match choice { + NativeBinChoice::Empty => out.write_u8(NATIVE_STORE_EMPTY), + NativeBinChoice::ContiguousCounts { + num_bins, + min_index, + } => { + let (_, slice) = store + .dense_contiguous_slice() + .expect("contiguous encoding only selected for non-empty dense store"); + out.write_u8(NATIVE_STORE_CONTIGUOUS_COUNTS); + encode_uvarint64(out, num_bins); + encode_varint64(out, i64::from(min_index)); + for &weight in slice { + encode_uvarint64(out, weight); + } + } + NativeBinChoice::IndexDeltas { num_bins } => { + out.write_u8(NATIVE_STORE_INDEX_DELTAS); + encode_uvarint64(out, num_bins); + let mut prev = 0_i64; + for (idx, _) in store.iter_asc() { + let idx64 = i64::from(idx); + encode_varint64(out, idx64 - prev); + prev = idx64; + } + } + NativeBinChoice::IndexDeltasAndCounts { num_bins } => { + out.write_u8(NATIVE_STORE_DELTAS_AND_COUNTS); + encode_uvarint64(out, num_bins); + let mut prev = 0_i64; + for (idx, weight) in store.iter_asc() { + let idx64 = i64::from(idx); + encode_varint64(out, idx64 - prev); + encode_uvarint64(out, weight); + prev = idx64; + } + } + } +} + +fn validate_mapping_bounds(mapping: &IndexMapping, lo: i32, hi: i32) -> Result<(), Error> { + if !mapping.contains_valid_index(lo) || !mapping.contains_valid_index(hi) { + return Err(Error::deserial(format!( + "DDSketch bucket index range [{lo}, {hi}] is outside valid domain for mapping" + ))); + } + Ok(()) +} + +fn decode_native_store( + cursor: &mut SketchSlice<'_>, + store: &mut Store, + mapping: &IndexMapping, + is_dense_target: bool, + encoded_max_bins: Option<usize>, +) -> Result<(u64, u64), Error> { + let mode = cursor.read_u8().map_err(insufficient_data("store_mode"))?; + let max_delta_dense_span = encoded_max_bins.map_or(MAX_SPARSE_ENCODED_DENSE_SPAN, |m| { + m.min(MAX_SPARSE_ENCODED_DENSE_SPAN) + }) as u64; + match mode { + NATIVE_STORE_EMPTY => Ok((0, 0)), + NATIVE_STORE_CONTIGUOUS_COUNTS => { + let num_bins = decode_uvarint64(cursor, "num_bins")?; + if num_bins == 0 { + return Err(Error::deserial( + "contiguous DDSketch store block must have num_bins >= 1", + )); + } + let first_index = decode_varint64(cursor, "first_index")?; + if num_bins > cursor.remaining().len() as u64 { + return Err(Error::insufficient_data_of( + "contiguous_bins", + format!( + "declared {num_bins} bins exceeds remaining {} bytes", + cursor.remaining().len() + ), + )); + } + validate_contiguous_bounds(first_index, num_bins, 1)?; + let last_index = first_index + (num_bins as i64) - 1; + validate_mapping_bounds(mapping, first_index as i32, last_index as i32)?; + if let Some(max_bins) = encoded_max_bins { + if num_bins > max_bins as u64 { + return Err(Error::deserial(format!( + "DDSketch contiguous store length ({num_bins}) exceeds encoded max_num_bins ({max_bins})" + ))); + } + } + if is_dense_target && num_bins > MAX_DENSE_LEN as u64 { + return Err(Error::deserial(format!( + "DDSketch contiguous dense store length ({num_bins}) exceeds maximum dense capacity ({MAX_DENSE_LEN})" + ))); + } + let (sum, bounds) = + store.decode_contiguous_unit_step(first_index as i32, num_bins as usize, || { + decode_uvarint64(cursor, "bin_weight") + })?; + let Some((lo, hi)) = bounds else { + return Err(Error::deserial( + "non-empty DDSketch contiguous store block must contain positive weight", + )); + }; + Ok((sum, span_u64(lo, hi))) + } + NATIVE_STORE_INDEX_DELTAS => { + let num_bins = decode_uvarint64(cursor, "num_bins")?; + if num_bins == 0 { + return Err(Error::deserial( + "DDSketch delta store block must have num_bins >= 1", + )); + } + if num_bins > cursor.remaining().len() as u64 { + return Err(Error::insufficient_data_of( + "store_bins", + format!( + "declared {num_bins} bins exceeds remaining {} bytes", + cursor.remaining().len() + ), + )); + } + let max_valid_index = mapping.max_indexable_index(); + let mut first_index = 0_i64; + let mut index = 0_i64; + for step in 0..num_bins { + let delta = decode_varint64(cursor, "index_delta")?; + if step > 0 && delta <= 0 { + return Err(Error::deserial( + "DDSketch delta store indices must be strictly increasing", + )); + } + index = index + .checked_add(delta) + .ok_or_else(|| Error::deserial("DDSketch bin index delta overflow"))?; + let idx32 = i32::try_from(index).map_err(|_| { + Error::deserial(format!("DDSketch bin index {index} overflows 32-bit range")) + })?; + if step == 0 { + if !mapping.contains_valid_index(idx32) { + return Err(Error::deserial(format!( + "DDSketch bin index {idx32} is outside valid domain for mapping" + ))); + } + first_index = index; + } else if idx32 > max_valid_index { + return Err(Error::deserial(format!( + "DDSketch bin index {idx32} exceeds maximum indexable domain ({max_valid_index})" + ))); + } + let wire_span = (index - first_index) as u64 + 1; + if is_dense_target && wire_span > max_delta_dense_span { + return Err(Error::deserial(format!( + "DDSketch delta-encoded dense store span ({wire_span}) exceeds dense limit ({max_delta_dense_span})" + ))); + } + store.add(idx32, 1); + } + let wire_span = (index - first_index) as u64 + 1; + Ok((num_bins, wire_span)) + } + NATIVE_STORE_DELTAS_AND_COUNTS => { + let num_bins = decode_uvarint64(cursor, "num_bins")?; + if num_bins == 0 { + return Err(Error::deserial( + "DDSketch delta-and-count store block must have num_bins >= 1", + )); + } + if num_bins > (cursor.remaining().len() / 2) as u64 { + return Err(Error::insufficient_data_of( + "store_bins", + format!( + "declared {num_bins} bins exceeds remaining {} bytes", + cursor.remaining().len() + ), + )); + } + let max_valid_index = mapping.max_indexable_index(); + let mut first_index = 0_i64; + let mut index = 0_i64; + let mut sum = 0_u64; + for step in 0..num_bins { + let delta = decode_varint64(cursor, "index_delta")?; + if step > 0 && delta <= 0 { + return Err(Error::deserial( + "DDSketch delta store indices must be strictly increasing", + )); + } + let weight = decode_uvarint64(cursor, "bin_weight")?; + if weight == 0 { + return Err(Error::deserial( + "DDSketch delta-and-count store block cannot contain zero weight", + )); + } + index = index + .checked_add(delta) + .ok_or_else(|| Error::deserial("DDSketch bin index delta overflow"))?; + let idx32 = i32::try_from(index).map_err(|_| { + Error::deserial(format!("DDSketch bin index {index} overflows 32-bit range")) + })?; + if step == 0 { + if !mapping.contains_valid_index(idx32) { + return Err(Error::deserial(format!( + "DDSketch bin index {idx32} is outside valid domain for mapping" + ))); + } + first_index = index; + } else if idx32 > max_valid_index { + return Err(Error::deserial(format!( + "DDSketch bin index {idx32} exceeds maximum indexable domain ({max_valid_index})" + ))); + } + let wire_span = (index - first_index) as u64 + 1; + if is_dense_target && wire_span > max_delta_dense_span { + return Err(Error::deserial(format!( + "DDSketch delta-encoded dense store span ({wire_span}) exceeds dense limit ({max_delta_dense_span})" + ))); + } + sum = sum + .checked_add(weight) + .ok_or_else(|| Error::deserial("total_weight overflows u64"))?; + store.add(idx32, weight); + } + let wire_span = (index - first_index) as u64 + 1; + Ok((sum, wire_span)) + } + _ => Err(Error::deserial(format!( + "unsupported DDSketch store encoding mode: {mode:#04x}" + ))), + } +} + +#[derive(Clone, Copy)] +enum CompatBinChoice { + ContiguousCounts { num_bins: u64, min_index: i32 }, + IndexDeltas { num_bins: u64 }, + IndexDeltasAndCounts { num_bins: u64 }, +} + +fn choose_compat_bin_encoding(store: &Store) -> Result<(Option<CompatBinChoice>, usize), Error> { + if store.is_empty() { + return Ok((None, 0)); + } + + let num_non_empty = store.num_occupied() as u64; + let mut sparse_deltas_bytes = 1 + uvarint64_size(num_non_empty); + let mut sparse_counts_bytes = 0_usize; + let mut all_unit_weights = true; + let mut prev_index = 0_i64; + + for (idx, weight) in store.iter_asc() { + if weight > MAX_COMPAT_WEIGHT { + return Err(Error::invalid_argument(format!( + "DDSketch bucket weight ({weight}) exceeds maximum exact compatibility count ({MAX_COMPAT_WEIGHT})" + ))); + } + let idx64 = i64::from(idx); + sparse_deltas_bytes += varint64_size(idx64 - prev_index); + sparse_counts_bytes += varfloat64_size(weight as f64); + if weight != 1 { + all_unit_weights = false; + } + prev_index = idx64; + } + + let (best_sparse, best_sparse_bytes) = if all_unit_weights { + ( + CompatBinChoice::IndexDeltas { + num_bins: num_non_empty, + }, + sparse_deltas_bytes, + ) + } else { + ( + CompatBinChoice::IndexDeltasAndCounts { + num_bins: num_non_empty, + }, + sparse_deltas_bytes + sparse_counts_bytes, + ) + }; + + if let Some((min_index, contiguous)) = store.dense_contiguous_slice() { + let num_bins = contiguous.len() as u64; + let num_zero_bins = contiguous.len() - store.num_occupied(); + // `index_delta = 1` encodes as single byte `0x02`, and `0.0` encodes as single byte `0x00`. + let dense_bytes = 1 + + uvarint64_size(num_bins) + + varint64_size(i64::from(min_index)) + + 1 + + sparse_counts_bytes + + num_zero_bins; + if dense_bytes <= best_sparse_bytes { + return Ok(( + Some(CompatBinChoice::ContiguousCounts { + num_bins, + min_index, + }), + dense_bytes, + )); + } + } + + Ok((Some(best_sparse), best_sparse_bytes)) +} + +fn encode_compat_store( + out: &mut SketchBytes, + store: &Store, + flag_type: u8, + choice: CompatBinChoice, +) { + match choice { + CompatBinChoice::ContiguousCounts { + num_bins, + min_index, + } => { + let (_, slice) = store + .dense_contiguous_slice() + .expect("contiguous encoding only selected for non-empty dense store"); + out.write_u8(DD_SUBFLAG_BINS_CONTIGUOUS_COUNTS | flag_type); + encode_uvarint64(out, num_bins); + encode_varint64(out, i64::from(min_index)); + encode_varint64(out, 1); + for &weight in slice { + encode_varfloat64(out, weight as f64); + } + } + CompatBinChoice::IndexDeltas { num_bins } => { + out.write_u8(DD_SUBFLAG_BINS_INDEX_DELTAS | flag_type); + encode_uvarint64(out, num_bins); + let mut prev = 0_i64; + for (idx, _) in store.iter_asc() { + let idx64 = i64::from(idx); + encode_varint64(out, idx64 - prev); + prev = idx64; + } + } + CompatBinChoice::IndexDeltasAndCounts { num_bins } => { + out.write_u8(DD_SUBFLAG_BINS_DELTAS_AND_COUNTS | flag_type); + encode_uvarint64(out, num_bins); + let mut prev = 0_i64; + for (idx, weight) in store.iter_asc() { + let idx64 = i64::from(idx); + encode_varint64(out, idx64 - prev); + encode_varfloat64(out, weight as f64); + prev = idx64; + } + } + } +} + +#[derive(Clone, Copy)] +enum Sign { + Negative, + Positive, +} + +struct DatadogScan { + mapping: IndexMapping, + zero_weight: u64, + total_weight: u64, + neg_bounds: Option<(i32, i32)>, + pos_bounds: Option<(i32, i32)>, +} + +fn deserialize_datadog(bytes: &[u8], store_kind: StoreKind) -> Result<DdSketch, Error> { + let enforce_span_limit = matches!(store_kind, StoreKind::UnboundedDense); + let scan = scan_datadog_stream(bytes, enforce_span_limit, |_, _, _| {})?; + + let mut negative = Store::with_wire_bounds(store_kind, scan.neg_bounds)?; + let mut positive = Store::with_wire_bounds(store_kind, scan.pos_bounds)?; + if scan.neg_bounds.is_some() || scan.pos_bounds.is_some() { + scan_datadog_stream(bytes, false, |sign, idx, count| match sign { + Sign::Negative => negative.add_in_bounds(idx, count), + Sign::Positive => positive.add_in_bounds(idx, count), + })?; + } + + Ok(DdSketch::from_parts( + scan.mapping, + negative, + positive, + scan.zero_weight, + scan.total_weight, + )) +} + +fn scan_datadog_stream( + bytes: &[u8], + enforce_span_limit: bool, + mut on_bin: impl FnMut(Sign, i32, u64), +) -> Result<DatadogScan, Error> { + let mut pos_range = IndexRangeTracker::new(enforce_span_limit); + let mut neg_range = IndexRangeTracker::new(enforce_span_limit); + let mut mapping: Option<IndexMapping> = None; + let mut zero_weight = 0_u64; + let mut total_weight = 0_u64; + + let mut cursor = SketchSlice::new(bytes); + while !cursor.remaining().is_empty() { + let flag = cursor.read_u8().map_err(insufficient_data("flag"))?; + let flag_type = flag & DD_FLAG_TYPE_MASK; + let subflag = flag & !DD_FLAG_TYPE_MASK; + + match flag_type { + DD_FLAG_TYPE_INDEX_MAPPING => { + let kind = match subflag { + DD_SUBFLAG_MAPPING_LOGARITHMIC => MappingKind::Logarithmic, + DD_SUBFLAG_MAPPING_LINEAR => MappingKind::Linear, + DD_SUBFLAG_MAPPING_CUBIC => MappingKind::Cubic, + _ => { + return Err(Error::deserial(format!( + "unsupported reference DDSketch index mapping flag: {flag:#04x}" + ))); + } + }; + let gamma = cursor.read_f64_le().map_err(insufficient_data("gamma"))?; + let index_offset = cursor + .read_f64_le() + .map_err(insufficient_data("index_offset"))?; + let decoded = IndexMapping::from_gamma_offset(kind, gamma, index_offset)?; + if let Some(existing) = mapping { + if !existing.is_compatible(&decoded) { + return Err(Error::deserial( + "conflicting index mapping blocks in reference DDSketch", + )); + } + } else { + mapping = Some(decoded); + } + } + DD_FLAG_TYPE_POSITIVE_STORE => { + scan_datadog_store_block( + &mut cursor, + subflag, + Sign::Positive, + &mut pos_range, + &mut total_weight, + &mut on_bin, + )?; + } + DD_FLAG_TYPE_NEGATIVE_STORE => { + scan_datadog_store_block( + &mut cursor, + subflag, + Sign::Negative, + &mut neg_range, + &mut total_weight, + &mut on_bin, + )?; + } + DD_FLAG_TYPE_SKETCH_FEATURES => match subflag { + DD_SUBFLAG_ZERO_COUNT => { + let count = decode_datadog_count(&mut cursor, "zero_count")?; + zero_weight = zero_weight + .checked_add(count) + .ok_or_else(|| Error::deserial("zero_count overflows u64"))?; + total_weight = total_weight + .checked_add(count) + .ok_or_else(|| Error::deserial("total_weight overflows u64"))?; + } + DD_SUBFLAG_EXACT_COUNT => { + let raw = decode_varfloat64(&mut cursor, "exact_count")?; + if !raw.is_finite() || raw < 0.0 { + return Err(Error::deserial(format!( + "invalid exact_count summary statistic: {raw}" + ))); + } + } + DD_SUBFLAG_EXACT_SUM | DD_SUBFLAG_EXACT_MIN | DD_SUBFLAG_EXACT_MAX => { + let _ = cursor + .read_f64_le() + .map_err(insufficient_data("summary_statistic"))?; + } + _ => { + return Err(Error::deserial(format!( + "unsupported reference DDSketch feature flag: {flag:#04x}" + ))); + } + }, + _ => unreachable!("2-bit mask only produces 0..=3"), + } + } + + let Some(mapping) = mapping else { + return Err(Error::deserial( + "missing index mapping in reference DDSketch", + )); + }; + + if let Some((lo, hi)) = neg_range.bounds { + validate_mapping_bounds(&mapping, lo, hi)?; + } + if let Some((lo, hi)) = pos_range.bounds { + validate_mapping_bounds(&mapping, lo, hi)?; + } + if enforce_span_limit { + let neg_span = neg_range.bounds.map_or(0, |(lo, hi)| span_u64(lo, hi)); + let pos_span = pos_range.bounds.map_or(0, |(lo, hi)| span_u64(lo, hi)); + let combined_span = neg_span + pos_span; + if combined_span > MAX_DENSE_BINS as u64 { Review Comment: Because the compact reference format does not record `StoreKind` and encodes wide two-bin sketches as index deltas, tightening the `UnboundedDense` span cap by input byte length would reject legitimate wide `UnboundedDense` compatibility inputs. In e80fc28e24b31dda7d5fc38b170d3126e8382e5b we documented on both `StoreKind::UnboundedDense` and `DdSketch::deserialize_compat` that untrusted compatibility payloads can allocate up to 512 MiB under `UnboundedDense` and should be decoded into a bounded collapsing store or `StoreKind::Sparse`. Let us know how that looks. -- 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]
