Skip to main content

waratah_stats/
cms.rs

1//! Count-Min Sketch: probabilistic frequency counter.
2
3use crate::StatsError;
4
5/// Default depth (`δ ≈ e^{-d}`).
6pub const DEFAULT_DEPTH: usize = 4;
7/// Default width (`ε ≈ e/w`).
8pub const DEFAULT_WIDTH: usize = 2048;
9
10/// Count-Min Sketch over 128-bit item keys.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CountMinSketch {
13    depth: usize,
14    width: usize,
15    /// Row-major `depth * width` counters.
16    counters: Vec<u64>,
17    /// Total increments (for ε·N error bound discussions).
18    total: u64,
19}
20
21impl CountMinSketch {
22    /// Empty sketch with the given dimensions.
23    pub fn new(depth: usize, width: usize) -> Self {
24        assert!(depth > 0 && width > 0, "CMS dimensions must be positive");
25        Self {
26            depth,
27            width,
28            counters: vec![0; depth * width],
29            total: 0,
30        }
31    }
32
33    /// Default planner-sized sketch (`d=4`, `w=2048`).
34    pub fn default_params() -> Self {
35        Self::new(DEFAULT_DEPTH, DEFAULT_WIDTH)
36    }
37
38    /// Depth (number of hash rows).
39    pub fn depth(&self) -> usize {
40        self.depth
41    }
42
43    /// Width (buckets per row).
44    pub fn width(&self) -> usize {
45        self.width
46    }
47
48    /// Total increments observed.
49    pub fn total(&self) -> u64 {
50        self.total
51    }
52
53    /// Increment the counters for `key` by `delta` (usually 1).
54    pub fn add(&mut self, key: u128, delta: u64) {
55        if delta == 0 {
56            return;
57        }
58        for row in 0..self.depth {
59            let col = bucket(key, row, self.width);
60            self.counters[row * self.width + col] =
61                self.counters[row * self.width + col].saturating_add(delta);
62        }
63        self.total = self.total.saturating_add(delta);
64    }
65
66    /// Estimated frequency of `key` (min across rows; never underestimates
67    /// relative to true count in the absence of wraparound).
68    pub fn estimate(&self, key: u128) -> u64 {
69        let mut min = u64::MAX;
70        for row in 0..self.depth {
71            let col = bucket(key, row, self.width);
72            min = min.min(self.counters[row * self.width + col]);
73        }
74        if min == u64::MAX { 0 } else { min }
75    }
76
77    /// Element-wise add; dimensions must match.
78    pub fn merge(&mut self, other: &Self) -> Result<(), StatsError> {
79        if self.depth != other.depth || self.width != other.width {
80            return Err(StatsError::Corrupt(format!(
81                "CMS dimension mismatch {}x{} vs {}x{}",
82                self.depth, self.width, other.depth, other.width
83            )));
84        }
85        for (a, b) in self.counters.iter_mut().zip(other.counters.iter()) {
86            *a = a.saturating_add(*b);
87        }
88        self.total = self.total.saturating_add(other.total);
89        Ok(())
90    }
91
92    pub(crate) fn encode_body(&self, out: &mut Vec<u8>) {
93        out.extend_from_slice(&(self.depth as u32).to_le_bytes());
94        out.extend_from_slice(&(self.width as u32).to_le_bytes());
95        out.extend_from_slice(&self.total.to_le_bytes());
96        for c in &self.counters {
97            out.extend_from_slice(&c.to_le_bytes());
98        }
99    }
100
101    pub(crate) fn decode_body(buf: &mut &[u8]) -> Result<Self, StatsError> {
102        let depth = take_u32(buf)? as usize;
103        let width = take_u32(buf)? as usize;
104        let total = take_u64(buf)?;
105        if depth == 0 || width == 0 {
106            return Err(StatsError::Corrupt("CMS zero dimension".into()));
107        }
108        let need = depth
109            .checked_mul(width)
110            .ok_or_else(|| StatsError::Corrupt("CMS size overflow".into()))?;
111        let mut counters = Vec::with_capacity(need);
112        for _ in 0..need {
113            counters.push(take_u64(buf)?);
114        }
115        Ok(Self {
116            depth,
117            width,
118            counters,
119            total,
120        })
121    }
122}
123
124fn bucket(key: u128, row: usize, width: usize) -> usize {
125    // Splitmix-style mix with row salt — independent enough for CMS rows.
126    let mut z = key ^ ((row as u128).wrapping_mul(0x9E37_79B9_7F4A_7C15));
127    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
128    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
129    z ^= z >> 31;
130    (z as usize) % width
131}
132
133pub(crate) fn take_u32(buf: &mut &[u8]) -> Result<u32, StatsError> {
134    if buf.len() < 4 {
135        return Err(StatsError::Corrupt("truncated u32".into()));
136    }
137    let v = u32::from_le_bytes(buf[..4].try_into().unwrap());
138    *buf = &buf[4..];
139    Ok(v)
140}
141
142pub(crate) fn take_u64(buf: &mut &[u8]) -> Result<u64, StatsError> {
143    if buf.len() < 8 {
144        return Err(StatsError::Corrupt("truncated u64".into()));
145    }
146    let v = u64::from_le_bytes(buf[..8].try_into().unwrap());
147    *buf = &buf[8..];
148    Ok(v)
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use pretty_assertions::assert_eq;
155
156    #[test]
157    fn exact_when_no_collision_pressure() {
158        let mut cms = CountMinSketch::new(4, 512);
159        cms.add(1, 10);
160        cms.add(2, 3);
161        assert_eq!(cms.estimate(1), 10);
162        assert_eq!(cms.estimate(2), 3);
163        assert_eq!(cms.estimate(99), 0);
164    }
165
166    #[test]
167    fn merge_is_element_wise_add() {
168        let mut a = CountMinSketch::new(4, 64);
169        let mut b = CountMinSketch::new(4, 64);
170        a.add(7, 5);
171        b.add(7, 8);
172        b.add(9, 1);
173        a.merge(&b).unwrap();
174        assert_eq!(a.estimate(7), 13);
175        assert_eq!(a.estimate(9), 1);
176        assert_eq!(a.total(), 14);
177    }
178
179    #[test]
180    fn overestimate_from_collisions_is_bounded_on_synthetic() {
181        // Tiny width forces collisions; estimate must be ≥ truth.
182        let mut cms = CountMinSketch::new(3, 8);
183        for i in 0..200u128 {
184            cms.add(i, 1);
185        }
186        assert!(cms.estimate(0) >= 1);
187        // ε ≈ e/w ≈ 0.34, N=200 → additive slack ~68; stay under a loose cap.
188        assert!(cms.estimate(0) < 200);
189    }
190}