ddsketch.rs

cdk-rsx/crates/cdk-rsx-collections-minima/src/ddsketch.rs

ddsketch.rs523 lines← SDK documentation
1//! Fixed-range DDSketch: logarithmic counters and relative-error quantiles.2//!3//! Independently implements the positive-domain mapping in Masson, Rim and Lee,4//! PVLDB 2019, §2.1: <https://www.vldb.org/pvldb/vol12/p2195-masson.pdf>.5//! Zero is an exact separate counter. Negative, nonfinite and out-of-range6//! observations reject; bins never collapse, so every admitted quantile keeps7//! the configured relative accuracy (subject to floating-point rounding).89const SOURCE_POLICY: [u8; 32] = cdk_rsx_source_policy::source_policy!("ddsketch.rs");1011use crate::{Collection, CollectionId, Error, NODE_BYTES, Result, Storage, Workspace};12use cdk_rsx_engine_nyxus::NyxusData;1314pub const DDSKETCH_MAX_BATCH: usize = 4096;1516/// Supported positive observation interval, inclusive. Zero is always admitted.17/// `relative_accuracy` must be in 1e-6..=0.5; bounds are in 1e-300..=1e300.18#[derive(Clone, Copy, Debug, PartialEq)]19pub struct DDSketchConfig {20    pub relative_accuracy: f64,21    pub minimum: f64,22    pub maximum: f64,23}2425/// Complete retained control; no ordinary heap allocation is persisted.26/// `BINS` is the maximum number of consecutive logarithmic counters, not the27/// number of observations. Counter bytes are allocated lazily in whole blocks.28#[repr(C)]29pub struct DDSketch<const BINS: usize = 2048> {30    collection: Collection,31    accuracy: f64,32    minimum: f64,33    maximum: f64,34    log_gamma: f64,35    first_index: i32,36    used_bins: u32,37    count: u64,38    zeros: u64,39}4041// SAFETY: an owning retained Collection and inline numeric control only.42unsafe impl<const BINS: usize> NyxusData for DDSketch<BINS> {43    const __NYXUS_POLICY: [u8; 32] = Self::CONTRACT;44}4546impl<const BINS: usize> DDSketch<BINS> {47    pub const CONTRACT: [u8; 32] = crate::contract(48        "MinimaDDSketch/fixed-positive-logarithmic/zero/rational-rank/v1",49        &[],50        &[51            crate::MINIMA_POLICY,52            SOURCE_POLICY,53            crate::width_contract("ddsketch-maximum-bins", BINS, &[]),54        ],55    );5657    pub fn new(storage: &mut dyn Storage, config: DDSketchConfig) -> Result<Self> {58        const {59            assert!(60                BINS > 0 && BINS <= 65_536,61                "DDSketch bins must be in 1..=65536"62            );63        }64        let DDSketchConfig {65            relative_accuracy: accuracy,66            minimum,67            maximum,68        } = config;69        if !(1e-6..=0.5).contains(&accuracy)70            || !(1e-300..=1e300).contains(&minimum)71            || !(minimum..=1e300).contains(&maximum)72        {73            return Err(Error::InvalidInput("invalid DDSketch accuracy or range"));74        }75        let log_gamma = (2.0 * accuracy / (1.0 - accuracy)).ln_1p();76        let first_index = bin_index(minimum, log_gamma);77        let last_index = bin_index(maximum, log_gamma);78        let used_bins = (i64::from(last_index) - i64::from(first_index) + 1) as usize;79        if used_bins > BINS {80            return Err(Error::Capacity);81        }82        Ok(Self {83            collection: Collection::new(storage)?,84            accuracy,85            minimum,86            maximum,87            log_gamma,88            first_index,89            used_bins: used_bins as u32,90            count: 0,91            zeros: 0,92        })93    }9495    pub const fn len(&self) -> u64 {96        self.count97    }98    pub const fn is_empty(&self) -> bool {99        self.count == 0100    }101    pub const fn identity(&self) -> CollectionId {102        self.collection.identity()103    }104    pub fn allocated_blocks(&self) -> usize {105        self.collection.block_count()106    }107    pub const fn bins(&self) -> u32 {108        self.used_bins109    }110    pub const fn config(&self) -> DDSketchConfig {111        DDSketchConfig {112            relative_accuracy: self.accuracy,113            minimum: self.minimum,114            maximum: self.maximum,115        }116    }117118    pub fn observe(119        &mut self,120        storage: &mut dyn Storage,121        value: f64,122        workspace: &mut Workspace<'_>,123    ) -> Result<()> {124        self.add(storage, value, 1, workspace)125    }126127    /// Positive integer weights; total-count overflow rejects before writes.128    pub fn add(129        &mut self,130        storage: &mut dyn Storage,131        value: f64,132        weight: u64,133        workspace: &mut Workspace<'_>,134    ) -> Result<()> {135        let slot = self.slot(value)?;136        if weight == 0 {137            return Err(Error::InvalidInput("DDSketch weight must be positive"));138        }139        let count = self.count.checked_add(weight).ok_or(Error::Capacity)?;140        self.collection.validate(storage)?;141        if let Some(slot) = slot {142            let old = if self.collection.block_count() == 0 {143                0144            } else {145                self.collection.read_at(146                    storage,147                    u64::from(slot) * 8,148                    &mut workspace.bytes_mut()[..8],149                )?;150                decode(&workspace.bytes()[..8])151            };152            self.allocate(storage);153            self.collection154                .write_at(storage, u64::from(slot) * 8, &(old + weight).to_le_bytes())155                .expect("DDSketch admitted counter write");156        } else {157            self.zeros += weight;158        }159        self.count = count;160        Ok(())161    }162163    /// Preflight all values and weights, group by node and fetch each selected164    /// node span once. Transient proposed counters are bounded by batch size;165    /// they are next values, not an undo journal. No borrow crosses this call.166    pub fn observe_many(167        &mut self,168        storage: &mut dyn Storage,169        observations: &[(f64, u64)],170        workspace: &mut Workspace<'_>,171    ) -> Result<()> {172        if observations.len() > DDSKETCH_MAX_BATCH {173            return Err(Error::Capacity);174        }175        let mut changes = Vec::<(u32, u64)>::new();176        changes177            .try_reserve_exact(observations.len())178            .map_err(|_| Error::Capacity)?;179        let mut count = self.count;180        let mut zeros = self.zeros;181        for &(value, weight) in observations {182            let slot = self.slot(value)?;183            if weight == 0 {184                return Err(Error::InvalidInput("DDSketch weight must be positive"));185            }186            count = count.checked_add(weight).ok_or(Error::Capacity)?;187            if let Some(slot) = slot {188                changes.push((slot, weight));189            } else {190                zeros += weight;191            }192        }193        self.collection.validate(storage)?;194        changes.sort_unstable_by_key(|entry| entry.0);195        let mut output = 0;196        for input in 0..changes.len() {197            let (slot, weight) = changes[input];198            if output != 0 && changes[output - 1].0 == slot {199                changes[output - 1].1 += weight;200            } else {201                changes[output] = (slot, weight);202                output += 1;203            }204        }205        changes.truncate(output);206        if self.collection.block_count() != 0 {207            let mut first = 0;208            while first < changes.len() {209                let page = changes[first].0 as usize / (NODE_BYTES / 8);210                let end = first211                    + changes[first..]212                        .partition_point(|entry| entry.0 as usize / (NODE_BYTES / 8) == page);213                let low = changes[first].0;214                let span = (changes[end - 1].0 - low + 1) as usize * 8;215                self.collection.read_at(216                    storage,217                    u64::from(low) * 8,218                    &mut workspace.bytes_mut()[..span],219                )?;220                for (slot, value) in &mut changes[first..end] {221                    let at = (*slot - low) as usize * 8;222                    *value += decode(&workspace.bytes()[at..at + 8]);223                }224                first = end;225            }226        }227        if !changes.is_empty() {228            self.allocate(storage);229        }230        let mut first = 0;231        while first < changes.len() {232            let mut end = first + 1;233            while end < changes.len()234                && end - first < NODE_BYTES / 8235                && changes[end].0 == changes[end - 1].0 + 1236            {237                end += 1;238            }239            let values = &changes[first..end];240            for ((_, value), bytes) in values.iter().zip(workspace.bytes_mut().chunks_exact_mut(8))241            {242                bytes.copy_from_slice(&value.to_le_bytes());243            }244            self.collection245                .write_at(246                    storage,247                    u64::from(values[0].0) * 8,248                    &workspace.bytes()[..values.len() * 8],249                )250                .expect("DDSketch admitted batch write");251            first = end;252        }253        self.zeros = zeros;254        self.count = count;255        Ok(())256    }257258    /// Lower quantile at an exact rational probability, e.g. `(99, 100)`.259    /// Integer arithmetic chooses floor((n-1)*numerator/denominator), even above260    /// 2^53 observations. Empty returns None. Invalid probabilities reject.261    pub fn quantile(262        &self,263        storage: &dyn Storage,264        numerator: u64,265        denominator: u64,266        workspace: &mut Workspace<'_>,267    ) -> Result<Option<f64>> {268        if denominator == 0 || numerator > denominator {269            return Err(Error::InvalidInput("invalid DDSketch quantile"));270        }271        self.collection.validate(storage)?;272        if self.count == 0 {273            return Ok(None);274        }275        let rank =276            (u128::from(self.count - 1) * u128::from(numerator) / u128::from(denominator)) as u64;277        self.value_at_rank(storage, rank, workspace).map(Some)278    }279280    /// Answer at most 4096 nondecreasing exact rational probabilities with one281    /// counter scan. Output order matches the probabilities, including repeats.282    /// The caller reuses both the output slice and the normal node workspace;283    /// no counter image or per-query allocation is constructed. Invalid input284    /// rejects before changing output. Empty sketches fill output with None.285    pub fn quantiles_many(286        &self,287        storage: &dyn Storage,288        probabilities: &[(u64, u64)],289        output: &mut [Option<f64>],290        workspace: &mut Workspace<'_>,291    ) -> Result<()> {292        if probabilities.len() > DDSKETCH_MAX_BATCH || output.len() != probabilities.len() {293            return Err(Error::Capacity);294        }295        for &(numerator, denominator) in probabilities {296            if denominator == 0 || numerator > denominator {297                return Err(Error::InvalidInput("invalid DDSketch quantile"));298            }299        }300        if probabilities.windows(2).any(|pair| {301            u128::from(pair[0].0) * u128::from(pair[1].1)302                > u128::from(pair[1].0) * u128::from(pair[0].1)303        }) {304            return Err(Error::InvalidInput("DDSketch quantiles must be sorted"));305        }306        self.collection.validate(storage)?;307        if self.count == 0 {308            output.fill(None);309            return Ok(());310        }311        if probabilities.is_empty() {312            return Ok(());313        }314        let rank_at = |index: usize| {315            let (numerator, denominator) = probabilities[index];316            (u128::from(self.count - 1) * u128::from(numerator) / u128::from(denominator)) as u64317        };318        let mut next = 0;319        let mut rank = rank_at(next);320        while rank < self.zeros {321            output[next] = Some(0.0);322            next += 1;323            if next == output.len() {324                return Ok(());325            }326            rank = rank_at(next);327        }328        let mut cumulative = self.zeros;329        for first in (0..self.used_bins as usize).step_by(NODE_BYTES / 8) {330            let bins = (self.used_bins as usize - first).min(NODE_BYTES / 8);331            self.collection.read_at(332                storage,333                first as u64 * 8,334                &mut workspace.bytes_mut()[..bins * 8],335            )?;336            for index in 0..bins {337                cumulative += decode(&workspace.bytes()[index * 8..index * 8 + 8]);338                if cumulative > rank {339                    let exponent = f64::from(self.first_index) + (first + index) as f64;340                    let value = (exponent * self.log_gamma).exp() * (1.0 - self.accuracy);341                    while cumulative > rank {342                        output[next] = Some(value);343                        next += 1;344                        if next == output.len() {345                            return Ok(());346                        }347                        rank = rank_at(next);348                    }349                }350            }351        }352        panic!("DDSketch count/counter invariant");353    }354355    pub fn merge(356        &mut self,357        storage: &mut dyn Storage,358        other: &Self,359        workspace: &mut Workspace<'_>,360    ) -> Result<()> {361        if self.config() != other.config() {362            return Err(Error::InvalidInput("incompatible DDSketch configuration"));363        }364        let count = self.count.checked_add(other.count).ok_or(Error::Capacity)?;365        self.collection.validate(storage)?;366        other.collection.validate(storage)?;367        if other.count == 0 {368            return Ok(());369        }370        if other.collection.block_count() != 0 {371            let mut proposed = vec![0u64; self.used_bins as usize];372            other.read_counters(storage, &mut proposed, false, workspace)?;373            if self.collection.block_count() != 0 {374                self.read_counters(storage, &mut proposed, true, workspace)?;375            }376            self.allocate(storage);377            self.write_counters(storage, &proposed);378        }379        self.zeros += other.zeros;380        self.count = count;381        Ok(())382    }383384    /// Release all whole payload blocks and reset counts; keep configuration.385    pub fn clear(&mut self, storage: &mut dyn Storage) -> Result<()> {386        self.collection.truncate_nodes(storage, 0)?;387        self.zeros = 0;388        self.count = 0;389        Ok(())390    }391392    fn slot(&self, value: f64) -> Result<Option<u32>> {393        if value == 0.0 {394            return Ok(None);395        }396        if !(self.minimum..=self.maximum).contains(&value) {397            return Err(Error::InvalidInput("DDSketch observation outside range"));398        }399        let slot = bin_index(value, self.log_gamma) - self.first_index;400        Ok(Some(slot as u32))401    }402403    fn allocate(&mut self, storage: &mut dyn Storage) {404        if self.collection.block_count() == 0 {405            self.collection406                .ensure_nodes(407                    storage,408                    (self.used_bins as u64 * 8).div_ceil(NODE_BYTES as u64),409                )410                .expect("DDSketch admitted allocation");411        }412    }413414    fn value_at_rank(415        &self,416        storage: &dyn Storage,417        rank: u64,418        workspace: &mut Workspace<'_>,419    ) -> Result<f64> {420        if rank < self.zeros {421            return Ok(0.0);422        }423        let mut cumulative = self.zeros;424        for first in (0..self.used_bins as usize).step_by(NODE_BYTES / 8) {425            let bins = (self.used_bins as usize - first).min(NODE_BYTES / 8);426            self.collection.read_at(427                storage,428                first as u64 * 8,429                &mut workspace.bytes_mut()[..bins * 8],430            )?;431            for index in 0..bins {432                cumulative += decode(&workspace.bytes()[index * 8..index * 8 + 8]);433                if cumulative > rank {434                    let exponent = f64::from(self.first_index) + (first + index) as f64;435                    return Ok((exponent * self.log_gamma).exp() * (1.0 - self.accuracy));436                }437            }438        }439        panic!("DDSketch count/counter invariant");440    }441442    fn read_counters(443        &self,444        storage: &dyn Storage,445        output: &mut [u64],446        add: bool,447        workspace: &mut Workspace<'_>,448    ) -> Result<()> {449        if !add {450            for (page, bytes) in counter_bytes_mut(output).chunks_mut(NODE_BYTES).enumerate() {451                self.collection452                    .read_at(storage, (page * NODE_BYTES) as u64, bytes)?;453            }454            return Ok(());455        }456        for (page, counters) in output.chunks_mut(NODE_BYTES / 8).enumerate() {457            self.collection.read_at(458                storage,459                (page * NODE_BYTES) as u64,460                &mut workspace.bytes_mut()[..counters.len() * 8],461            )?;462            for (counter, bytes) in counters.iter_mut().zip(workspace.bytes().chunks_exact(8)) {463                let value = decode(bytes);464                *counter += value;465            }466        }467        Ok(())468    }469470    fn write_counters(&self, storage: &mut dyn Storage, counters: &[u64]) {471        self.collection472            .write_at(storage, 0, counter_bytes(counters))473            .expect("DDSketch admitted merge write");474    }475}476477fn counter_bytes(values: &[u64]) -> &[u8] {478    const {479        assert!(480            cfg!(target_endian = "little"),481            "DDSketch requires a little-endian target"482        )483    };484    // SAFETY: initialized u64s have no padding. On supported LE targets their485    // object bytes are exactly the frozen counter encoding; the view is an486    // immutable synchronous loan bounded by the input slice.487    unsafe { core::slice::from_raw_parts(values.as_ptr().cast(), core::mem::size_of_val(values)) }488}489490fn counter_bytes_mut(values: &mut [u64]) -> &mut [u8] {491    const {492        assert!(493            cfg!(target_endian = "little"),494            "DDSketch requires a little-endian target"495        )496    };497    // SAFETY: every u64 bit pattern is valid and the initialized, exclusive498    // slice has no padding. No typed access overlaps this bounded byte loan.499    unsafe {500        core::slice::from_raw_parts_mut(values.as_mut_ptr().cast(), core::mem::size_of_val(values))501    }502}503504fn decode(bytes: &[u8]) -> u64 {505    u64::from_le_bytes(bytes.try_into().unwrap())506}507508fn bin_index(value: f64, log_gamma: f64) -> i32 {509    let mut index = (value.ln() / log_gamma).ceil() as i32;510    // Correct log/exp rounding at exact bin boundaries. Supported finite range511    // and accuracy keep exponent/index arithmetic far from overflow.512    while value > (f64::from(index) * log_gamma).exp() {513        index += 1;514    }515    while value <= (f64::from(index - 1) * log_gamma).exp() {516        index -= 1;517    }518    index519}520521#[cfg(test)]522#[path = "ddsketch_tests.rs"]523mod tests;