sketch_oxide 0.1.6

State-of-the-art DataSketches library (2025) - UltraLogLog, Binary Fuse Filters, DDSketch, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Conservative Update Count-Min Sketch (Estan & Varghese 2002)
//!
//! A modification of Count-Min Sketch that improves accuracy by up to 10x
//! by only incrementing counters to the minimum necessary value.
//!
//! # Algorithm
//!
//! Standard CM sketch increments all k hash positions by 1.
//! Conservative update only increments to max(current_min + 1, current_value).
//!
//! # Trade-offs
//!
//! | Aspect | Standard CM | Conservative CM |
//! |--------|-------------|-----------------|
//! | Accuracy | Baseline | Up to 10x better |
//! | Deletions | Supported | Not supported |
//! | Point queries | Overestimates | Less overestimation |
//!
//! # Use Cases
//!
//! - When deletions are NOT needed
//! - High-accuracy frequency estimation
//! - Heavy hitter detection
//!
//! # References
//!
//! - Estan & Varghese "New Directions in Traffic Measurement and Accounting" (SIGCOMM 2002)
//!
//! # Examples
//!
//! ```
//! use sketch_oxide::frequency::ConservativeCountMin;
//!
//! let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
//!
//! cms.update(&"apple");
//! cms.update(&"apple");
//! cms.update(&"banana");
//!
//! // Estimates are more accurate than standard Count-Min
//! assert!(cms.estimate(&"apple") >= 2);
//! assert!(cms.estimate(&"banana") >= 1);
//! ```

use crate::common::hash::hash_value;
use crate::common::SketchError;
use std::hash::Hash;

/// Conservative Update Count-Min Sketch
///
/// Provides improved accuracy over standard Count-Min Sketch by using
/// conservative updates that only increment counters to the minimum necessary.
///
/// # Trade-off
///
/// Cannot support deletions or negative updates, but offers significantly
/// better accuracy for point queries.
///
/// # Examples
///
/// ```
/// use sketch_oxide::frequency::ConservativeCountMin;
///
/// let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
/// cms.update(&"hello");
/// assert!(cms.estimate(&"hello") >= 1);
/// ```
#[derive(Clone, Debug)]
pub struct ConservativeCountMin {
    /// Width of each row: w = ⌈e/ε⌉
    width: usize,
    /// Number of rows (hash functions): d = ⌈ln(1/δ)⌉
    depth: usize,
    /// 2D table of counters: depth × width
    table: Vec<Vec<u64>>,
    /// Independent hash seeds for each row
    hash_seeds: Vec<u32>,
    /// Epsilon parameter (error bound)
    epsilon: f64,
    /// Delta parameter (failure probability)
    delta: f64,
    /// Total count of all updates
    total_count: u64,
}

impl ConservativeCountMin {
    /// Creates a new Conservative Update Count-Min Sketch
    ///
    /// # Arguments
    ///
    /// * `epsilon` - Error bound (ε): estimates are within εN of true value
    /// * `delta` - Failure probability (δ): guarantee holds with probability 1-δ
    ///
    /// # Errors
    ///
    /// Returns error if parameters are invalid
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::frequency::ConservativeCountMin;
    ///
    /// let cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
    /// ```
    pub fn new(epsilon: f64, delta: f64) -> Result<Self, SketchError> {
        if epsilon <= 0.0 || epsilon >= 1.0 {
            return Err(SketchError::InvalidParameter {
                param: "epsilon".to_string(),
                value: epsilon.to_string(),
                constraint: "must be in (0, 1)".to_string(),
            });
        }

        if delta <= 0.0 || delta >= 1.0 {
            return Err(SketchError::InvalidParameter {
                param: "delta".to_string(),
                value: delta.to_string(),
                constraint: "must be in (0, 1)".to_string(),
            });
        }

        // Width: w = ⌈e/ε⌉
        const E: f64 = std::f64::consts::E;
        let width = (E / epsilon).ceil() as usize;
        let width = width.max(2);

        // Depth: d = ⌈ln(1/δ)⌉
        let depth = (1.0 / delta).ln().ceil() as usize;
        let depth = depth.max(1);

        let table = vec![vec![0u64; width]; depth];

        let hash_seeds: Vec<u32> = (0..depth)
            .map(|i| (i as u32).wrapping_mul(0x9e3779b9))
            .collect();

        Ok(ConservativeCountMin {
            width,
            depth,
            table,
            hash_seeds,
            epsilon,
            delta,
            total_count: 0,
        })
    }

    /// Creates a sketch with specific dimensions
    ///
    /// # Arguments
    ///
    /// * `width` - Width of the table
    /// * `depth` - Number of hash functions
    pub fn with_dimensions(width: usize, depth: usize) -> Result<Self, SketchError> {
        if width == 0 {
            return Err(SketchError::InvalidParameter {
                param: "width".to_string(),
                value: "0".to_string(),
                constraint: "must be > 0".to_string(),
            });
        }

        if depth == 0 {
            return Err(SketchError::InvalidParameter {
                param: "depth".to_string(),
                value: "0".to_string(),
                constraint: "must be > 0".to_string(),
            });
        }

        let table = vec![vec![0u64; width]; depth];

        let hash_seeds: Vec<u32> = (0..depth)
            .map(|i| (i as u32).wrapping_mul(0x9e3779b9))
            .collect();

        // Calculate theoretical epsilon and delta from dimensions
        const E: f64 = std::f64::consts::E;
        let epsilon = E / width as f64;
        let delta = (-(depth as f64)).exp();

        Ok(ConservativeCountMin {
            width,
            depth,
            table,
            hash_seeds,
            epsilon,
            delta,
            total_count: 0,
        })
    }

    /// Updates the sketch with an item using conservative update
    ///
    /// Unlike standard Count-Min, only increments counters to the minimum
    /// necessary value, reducing overestimation.
    ///
    /// # Arguments
    ///
    /// * `item` - The item to add
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::frequency::ConservativeCountMin;
    ///
    /// let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
    /// cms.update(&"apple");
    /// cms.update(&"apple");
    /// ```
    pub fn update<T: Hash>(&mut self, item: &T) {
        self.update_count(item, 1);
    }

    /// Updates with a specific count
    ///
    /// # Arguments
    ///
    /// * `item` - The item to add
    /// * `count` - Number of occurrences to add
    pub fn update_count<T: Hash>(&mut self, item: &T, count: u64) {
        if count == 0 {
            return;
        }

        self.total_count += count;

        // First pass: find current minimum estimate
        let indices: Vec<usize> = self
            .hash_seeds
            .iter()
            .map(|&seed| {
                let hash = hash_value(item, seed);
                (hash as usize) % self.width
            })
            .collect();

        let current_min = indices
            .iter()
            .enumerate()
            .map(|(row, &col)| self.table[row][col])
            .min()
            .unwrap_or(0);

        // Second pass: conservative update
        // Set each counter to max(current_value, current_min + count)
        let new_value = current_min.saturating_add(count);

        for (row, &col) in indices.iter().enumerate() {
            if self.table[row][col] < new_value {
                self.table[row][col] = new_value;
            }
        }
    }

    /// Estimates the frequency of an item
    ///
    /// # Arguments
    ///
    /// * `item` - The item to query
    ///
    /// # Returns
    ///
    /// Estimated frequency (always >= true frequency)
    pub fn estimate<T: Hash>(&self, item: &T) -> u64 {
        self.hash_seeds
            .iter()
            .enumerate()
            .map(|(row, &seed)| {
                let hash = hash_value(item, seed);
                let col = (hash as usize) % self.width;
                self.table[row][col]
            })
            .min()
            .unwrap_or(0)
    }

    /// Returns the width of the table
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the depth (number of hash functions)
    pub fn depth(&self) -> usize {
        self.depth
    }

    /// Returns the epsilon parameter
    pub fn epsilon(&self) -> f64 {
        self.epsilon
    }

    /// Returns the delta parameter
    pub fn delta(&self) -> f64 {
        self.delta
    }

    /// Returns the total count of all updates
    pub fn total_count(&self) -> u64 {
        self.total_count
    }

    /// Clears all counters
    pub fn clear(&mut self) {
        for row in &mut self.table {
            row.fill(0);
        }
        self.total_count = 0;
    }

    /// Returns memory usage in bytes
    pub fn memory_usage(&self) -> usize {
        std::mem::size_of::<Self>()
            + self.width * self.depth * std::mem::size_of::<u64>()
            + self.depth * std::mem::size_of::<u32>()
    }

    /// Serializes the sketch to bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        bytes.extend_from_slice(&(self.width as u64).to_le_bytes());
        bytes.extend_from_slice(&(self.depth as u64).to_le_bytes());
        bytes.extend_from_slice(&self.epsilon.to_le_bytes());
        bytes.extend_from_slice(&self.delta.to_le_bytes());
        bytes.extend_from_slice(&self.total_count.to_le_bytes());

        for seed in &self.hash_seeds {
            bytes.extend_from_slice(&seed.to_le_bytes());
        }

        for row in &self.table {
            for &val in row {
                bytes.extend_from_slice(&val.to_le_bytes());
            }
        }

        bytes
    }

    /// Deserializes a sketch from bytes
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SketchError> {
        if bytes.len() < 40 {
            return Err(SketchError::DeserializationError(
                "Insufficient data for ConservativeCountMin header".to_string(),
            ));
        }

        let width = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize;
        let depth = u64::from_le_bytes(bytes[8..16].try_into().unwrap()) as usize;
        let epsilon = f64::from_le_bytes(bytes[16..24].try_into().unwrap());
        let delta = f64::from_le_bytes(bytes[24..32].try_into().unwrap());
        let total_count = u64::from_le_bytes(bytes[32..40].try_into().unwrap());

        let expected_len = 40 + depth * 4 + width * depth * 8;
        if bytes.len() < expected_len {
            return Err(SketchError::DeserializationError(format!(
                "Expected {} bytes, got {}",
                expected_len,
                bytes.len()
            )));
        }

        let mut offset = 40;
        let mut hash_seeds = Vec::with_capacity(depth);
        for _ in 0..depth {
            hash_seeds.push(u32::from_le_bytes(
                bytes[offset..offset + 4].try_into().unwrap(),
            ));
            offset += 4;
        }

        let mut table = vec![vec![0u64; width]; depth];
        for row in &mut table {
            for val in row.iter_mut() {
                *val = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
                offset += 8;
            }
        }

        Ok(ConservativeCountMin {
            width,
            depth,
            table,
            hash_seeds,
            epsilon,
            delta,
            total_count,
        })
    }

    /// Merges another sketch into this one
    ///
    /// Takes the maximum of corresponding counters.
    ///
    /// # Errors
    ///
    /// Returns error if dimensions don't match
    pub fn merge(&mut self, other: &Self) -> Result<(), SketchError> {
        if self.width != other.width || self.depth != other.depth {
            return Err(SketchError::InvalidParameter {
                param: "dimensions".to_string(),
                value: format!(
                    "{}x{} vs {}x{}",
                    self.width, self.depth, other.width, other.depth
                ),
                constraint: "must have same dimensions to merge".to_string(),
            });
        }

        for (row_idx, (self_row, other_row)) in
            self.table.iter_mut().zip(other.table.iter()).enumerate()
        {
            for (col_idx, (self_val, &other_val)) in
                self_row.iter_mut().zip(other_row.iter()).enumerate()
            {
                // Conservative merge: take maximum
                *self_val = (*self_val).max(other_val);
                let _ = (row_idx, col_idx); // Silence unused variable warning
            }
        }

        self.total_count += other.total_count;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new() {
        let cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
        assert!(cms.width() > 0);
        assert!(cms.depth() > 0);
    }

    #[test]
    fn test_invalid_params() {
        assert!(ConservativeCountMin::new(0.0, 0.01).is_err());
        assert!(ConservativeCountMin::new(1.0, 0.01).is_err());
        assert!(ConservativeCountMin::new(0.01, 0.0).is_err());
        assert!(ConservativeCountMin::new(0.01, 1.0).is_err());
    }

    #[test]
    fn test_with_dimensions() {
        let cms = ConservativeCountMin::with_dimensions(100, 5).unwrap();
        assert_eq!(cms.width(), 100);
        assert_eq!(cms.depth(), 5);
    }

    #[test]
    fn test_update_and_estimate() {
        let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms.update(&"apple");
        cms.update(&"apple");
        cms.update(&"banana");

        assert!(cms.estimate(&"apple") >= 2);
        assert!(cms.estimate(&"banana") >= 1);
        assert_eq!(cms.estimate(&"cherry"), 0);
    }

    #[test]
    fn test_update_count() {
        let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms.update_count(&"apple", 5);
        cms.update_count(&"banana", 3);

        assert!(cms.estimate(&"apple") >= 5);
        assert!(cms.estimate(&"banana") >= 3);
    }

    #[test]
    fn test_total_count() {
        let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms.update(&"a");
        cms.update(&"b");
        cms.update_count(&"c", 5);

        assert_eq!(cms.total_count(), 7);
    }

    #[test]
    fn test_clear() {
        let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms.update(&"apple");
        cms.update(&"banana");

        cms.clear();

        assert_eq!(cms.estimate(&"apple"), 0);
        assert_eq!(cms.estimate(&"banana"), 0);
        assert_eq!(cms.total_count(), 0);
    }

    #[test]
    fn test_serialization() {
        let mut cms = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms.update(&"apple");
        cms.update(&"apple");
        cms.update(&"banana");

        let bytes = cms.to_bytes();
        let restored = ConservativeCountMin::from_bytes(&bytes).unwrap();

        assert_eq!(cms.width(), restored.width());
        assert_eq!(cms.depth(), restored.depth());
        assert_eq!(cms.estimate(&"apple"), restored.estimate(&"apple"));
        assert_eq!(cms.estimate(&"banana"), restored.estimate(&"banana"));
    }

    #[test]
    fn test_merge() {
        let mut cms1 = ConservativeCountMin::new(0.01, 0.01).unwrap();
        let mut cms2 = ConservativeCountMin::new(0.01, 0.01).unwrap();

        cms1.update(&"apple");
        cms1.update(&"apple");
        cms2.update(&"banana");
        cms2.update(&"banana");

        cms1.merge(&cms2).unwrap();

        assert!(cms1.estimate(&"apple") >= 2);
        assert!(cms1.estimate(&"banana") >= 2);
    }

    #[test]
    fn test_conservative_vs_standard_accuracy() {
        // Conservative update should be more accurate
        let mut cms = ConservativeCountMin::with_dimensions(100, 5).unwrap();

        // Insert same item many times
        for _ in 0..100 {
            cms.update(&"frequent");
        }

        // Insert many different items to create collisions
        for i in 0..1000 {
            cms.update(&format!("item_{}", i));
        }

        let estimate = cms.estimate(&"frequent");

        // Conservative update should keep estimate closer to 100
        // Standard CM would have much higher overestimation
        assert!(estimate >= 100, "Estimate {} should be >= 100", estimate);
        assert!(
            estimate < 200,
            "Estimate {} should be < 200 due to conservative update",
            estimate
        );
    }

    #[test]
    fn test_memory_usage() {
        let cms = ConservativeCountMin::new(0.01, 0.01).unwrap();
        assert!(cms.memory_usage() > 0);
    }
}