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
//! Theta Sketch - Set Operations
//!
//! Apache DataSketches Theta Sketch implementation.
//! **The only sketch supporting intersection/difference operations.**
//!
//! # Overview
//!
//! Theta Sketch is a probabilistic data structure for cardinality estimation
//! that uniquely supports set operations:
//! - Union: |A ∪ B|
//! - Intersection: |A ∩ B|
//! - Difference: |A - B| (A-not-B)
//!
//! # Algorithm
//!
//! 1. Hash items to uniform u64 values
//! 2. Keep hashes < theta (sampling threshold)
//! 3. When |entries| > k, reduce theta (sampling)
//! 4. Estimate: count * (u64::MAX / theta)
//!
//! # Set Operations
//!
//! - **Union**: Merge entries, use min(theta_a, theta_b)
//! - **Intersection**: Keep common entries, use min(theta_a, theta_b)
//! - **Difference**: Keep A entries not in B, use min(theta_a, theta_b)
//!
//! # Accuracy
//!
//! - Relative error: ~1/sqrt(k) where k = 2^lg_k
//! - Example: lg_k=12 (k=4096) → ~1.6% error
//! - Exact mode when n < k (no sampling)
//!
//! # Production Usage
//!
//! - LinkedIn: 10+ years in production
//! - ClickHouse: 24.1+ (AggregateFunctionThetaSketch)
//! - Yahoo: Large-scale analytics
//!
//! # References
//!
//! - Paper: "Theta Sketch Framework" (Apache DataSketches)
//! - Source: https://datasketches.apache.org/docs/Theta/ThetaSketchFramework.html

use crate::error::{Result, SketchError};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

/// Theta Sketch for cardinality estimation with set operations.
///
/// # Examples
///
/// ```
/// use sketch_oxide::cardinality::ThetaSketch;
///
/// let mut sketch_a = ThetaSketch::new(12).unwrap(); // k = 4096
/// let mut sketch_b = ThetaSketch::new(12).unwrap();
///
/// // Add items
/// for i in 0..100 {
///     sketch_a.update(&i);
/// }
/// for i in 50..150 {
///     sketch_b.update(&i);
/// }
///
/// // Set operations
/// let union = sketch_a.union(&sketch_b).unwrap();
/// let intersection = sketch_a.intersect(&sketch_b).unwrap();
/// let difference = sketch_a.difference(&sketch_b).unwrap();
///
/// println!("Union: {}", union.estimate());
/// println!("Intersection: {}", intersection.estimate());
/// println!("Difference: {}", difference.estimate());
/// ```
#[derive(Clone, Debug)]
pub struct ThetaSketch {
    /// log2(k) - nominal entries capacity
    lg_k: u8,

    /// Nominal entries (k = 2^lg_k)
    k: usize,

    /// Hash values < theta (retained entries)
    entries: HashSet<u64>,

    /// Sampling threshold (initially u64::MAX, decreases with sampling)
    theta: u64,

    /// Hash seed for consistency across operations
    seed: u64,
}

impl ThetaSketch {
    /// Valid range for lg_k parameter
    const MIN_LG_K: u8 = 4;
    const MAX_LG_K: u8 = 26;

    /// Default hash seed (same as Apache DataSketches)
    const DEFAULT_SEED: u64 = 9001;

    /// Creates a new Theta Sketch with specified lg_k.
    ///
    /// # Parameters
    ///
    /// - `lg_k`: log2(k), determines accuracy and memory
    ///   - Valid range: [4, 26]
    ///   - k = 2^lg_k (nominal entries)
    ///   - Memory: ~8k bytes
    ///   - Error: ~1/sqrt(k)
    ///
    /// # Recommended Values
    ///
    /// - lg_k=12 (k=4096): ~1.6% error, 32KB
    /// - lg_k=14 (k=16384): ~0.8% error, 128KB
    /// - lg_k=16 (k=65536): ~0.4% error, 512KB
    ///
    /// # Errors
    ///
    /// Returns `SketchError::InvalidParameter` if lg_k is out of range.
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let sketch = ThetaSketch::new(12).unwrap();
    /// ```
    pub fn new(lg_k: u8) -> Result<Self> {
        if !(Self::MIN_LG_K..=Self::MAX_LG_K).contains(&lg_k) {
            return Err(SketchError::InvalidParameter {
                param: "lg_k".to_string(),
                value: lg_k.to_string(),
                constraint: format!("must be in range [{}, {}]", Self::MIN_LG_K, Self::MAX_LG_K),
            });
        }

        let k = 1_usize << lg_k; // 2^lg_k

        Ok(Self {
            lg_k,
            k,
            entries: HashSet::with_capacity(k),
            theta: u64::MAX,
            seed: Self::DEFAULT_SEED,
        })
    }

    /// Creates a sketch with custom seed (for advanced use).
    pub fn with_seed(lg_k: u8, seed: u64) -> Result<Self> {
        let mut sketch = Self::new(lg_k)?;
        sketch.seed = seed;
        Ok(sketch)
    }

    /// Updates the sketch with a new item.
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let mut sketch = ThetaSketch::new(12).unwrap();
    /// sketch.update(&"item1");
    /// sketch.update(&42);
    /// sketch.update(&3.14_f64.to_bits());
    /// ```
    pub fn update<T: Hash>(&mut self, item: &T) {
        let hash = self.hash_item(item);

        // Only consider hashes below theta (sampling)
        if hash < self.theta {
            self.entries.insert(hash);

            // Check if we need to reduce theta (enforce capacity)
            if self.entries.len() > self.k {
                self.rebuild_with_lower_theta();
            }
        }
    }

    /// Estimates the cardinality.
    ///
    /// # Formula
    ///
    /// - If theta = u64::MAX (no sampling): count
    /// - Otherwise: count * (u64::MAX / theta)
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let mut sketch = ThetaSketch::new(12).unwrap();
    /// for i in 0..1000 {
    ///     sketch.update(&i);
    /// }
    /// let estimate = sketch.estimate();
    /// assert!((estimate - 1000.0).abs() < 20.0);
    /// ```
    pub fn estimate(&self) -> f64 {
        if self.entries.is_empty() {
            return 0.0;
        }

        if self.theta == u64::MAX {
            // Exact mode (no sampling)
            self.entries.len() as f64
        } else {
            // Sampling mode: scale by sampling rate
            let count = self.entries.len() as f64;
            let scale = u64::MAX as f64 / self.theta as f64;
            count * scale
        }
    }

    /// Returns true if the sketch is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns the number of retained entries.
    pub fn num_retained(&self) -> usize {
        self.entries.len()
    }

    /// Returns the current theta value.
    ///
    /// - u64::MAX: No sampling (exact mode)
    /// - < u64::MAX: Sampling active
    pub fn get_theta(&self) -> u64 {
        self.theta
    }

    /// Returns the nominal capacity (k).
    pub fn capacity(&self) -> usize {
        self.k
    }

    /// Computes union with another sketch: |A ∪ B|
    ///
    /// # Compatibility
    ///
    /// Both sketches must have:
    /// - Same lg_k
    /// - Same seed
    ///
    /// # Algorithm
    ///
    /// 1. new_theta = min(self.theta, other.theta)
    /// 2. new_entries = (self.entries ∪ other.entries) where hash < new_theta
    /// 3. Estimate from merged sketch
    ///
    /// # Properties
    ///
    /// - Commutative: A∪B = B∪A
    /// - Associative: (A∪B)∪C = A∪(B∪C)
    /// - Idempotent: A∪A = A
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let mut sketch_a = ThetaSketch::new(12).unwrap();
    /// let mut sketch_b = ThetaSketch::new(12).unwrap();
    ///
    /// for i in 0..50 {
    ///     sketch_a.update(&i);
    /// }
    /// for i in 50..100 {
    ///     sketch_b.update(&i);
    /// }
    ///
    /// let union = sketch_a.union(&sketch_b).unwrap();
    /// assert!((union.estimate() - 100.0).abs() < 5.0);
    /// ```
    pub fn union(&self, other: &Self) -> Result<Self> {
        self.check_compatibility(other)?;

        let new_theta = self.theta.min(other.theta);
        let mut new_entries = HashSet::with_capacity(self.k);

        // Merge entries from both sketches
        for &hash in &self.entries {
            if hash < new_theta {
                new_entries.insert(hash);
            }
        }
        for &hash in &other.entries {
            if hash < new_theta {
                new_entries.insert(hash);
            }
        }

        Ok(Self {
            lg_k: self.lg_k,
            k: self.k,
            entries: new_entries,
            theta: new_theta,
            seed: self.seed,
        })
    }

    /// Computes intersection with another sketch: |A ∩ B|
    ///
    /// # Algorithm
    ///
    /// 1. new_theta = min(self.theta, other.theta)
    /// 2. new_entries = (self.entries ∩ other.entries) where hash < new_theta
    /// 3. Estimate from intersection sketch
    ///
    /// # Properties
    ///
    /// - Commutative: A∩B = B∩A
    /// - Associative: (A∩B)∩C = A∩(B∩C)
    /// - Idempotent: A∩A = A
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let mut sketch_a = ThetaSketch::new(12).unwrap();
    /// let mut sketch_b = ThetaSketch::new(12).unwrap();
    ///
    /// for i in 0..75 {
    ///     sketch_a.update(&i);
    /// }
    /// for i in 25..100 {
    ///     sketch_b.update(&i);
    /// }
    ///
    /// let intersection = sketch_a.intersect(&sketch_b).unwrap();
    /// assert!((intersection.estimate() - 50.0).abs() < 5.0);
    /// ```
    pub fn intersect(&self, other: &Self) -> Result<Self> {
        self.check_compatibility(other)?;

        let new_theta = self.theta.min(other.theta);
        let mut new_entries = HashSet::with_capacity(self.k);

        // Keep only common entries
        for &hash in &self.entries {
            if hash < new_theta && other.entries.contains(&hash) {
                new_entries.insert(hash);
            }
        }

        Ok(Self {
            lg_k: self.lg_k,
            k: self.k,
            entries: new_entries,
            theta: new_theta,
            seed: self.seed,
        })
    }

    /// Computes difference: |A - B| (items in A but not in B)
    ///
    /// # Algorithm
    ///
    /// 1. new_theta = min(self.theta, other.theta)
    /// 2. new_entries = (self.entries - other.entries) where hash < new_theta
    /// 3. Estimate from difference sketch
    ///
    /// # Properties
    ///
    /// - NOT commutative: A-B ≠ B-A (in general)
    /// - A-A = ∅
    /// - A-∅ = A
    /// - ∅-B = ∅
    ///
    /// # Examples
    ///
    /// ```
    /// use sketch_oxide::cardinality::ThetaSketch;
    ///
    /// let mut sketch_a = ThetaSketch::new(12).unwrap();
    /// let mut sketch_b = ThetaSketch::new(12).unwrap();
    ///
    /// for i in 0..75 {
    ///     sketch_a.update(&i);
    /// }
    /// for i in 25..100 {
    ///     sketch_b.update(&i);
    /// }
    ///
    /// let difference = sketch_a.difference(&sketch_b).unwrap();
    /// assert!((difference.estimate() - 25.0).abs() < 5.0);
    /// ```
    pub fn difference(&self, other: &Self) -> Result<Self> {
        self.check_compatibility(other)?;

        let new_theta = self.theta.min(other.theta);
        let mut new_entries = HashSet::with_capacity(self.k);

        // Keep entries in self but not in other
        for &hash in &self.entries {
            if hash < new_theta && !other.entries.contains(&hash) {
                new_entries.insert(hash);
            }
        }

        Ok(Self {
            lg_k: self.lg_k,
            k: self.k,
            entries: new_entries,
            theta: new_theta,
            seed: self.seed,
        })
    }

    // ============================================================================
    // Private Methods
    // ============================================================================

    /// Checks if two sketches are compatible for operations.
    fn check_compatibility(&self, other: &Self) -> Result<()> {
        if self.lg_k != other.lg_k {
            return Err(SketchError::IncompatibleSketches {
                reason: format!("lg_k mismatch: {} vs {}", self.lg_k, other.lg_k),
            });
        }

        if self.seed != other.seed {
            return Err(SketchError::IncompatibleSketches {
                reason: format!("seed mismatch: {} vs {}", self.seed, other.seed),
            });
        }

        Ok(())
    }

    /// Hashes an item to u64 using xxHash-like algorithm.
    fn hash_item<T: Hash>(&self, item: &T) -> u64 {
        use std::collections::hash_map::DefaultHasher;

        let mut hasher = DefaultHasher::new();
        self.seed.hash(&mut hasher);
        item.hash(&mut hasher);
        hasher.finish()
    }

    /// Reduces theta to enforce capacity constraint.
    ///
    /// # Algorithm
    ///
    /// 1. Sort entries
    /// 2. Find new theta at position k (kth smallest)
    /// 3. Remove entries >= new theta
    ///
    /// This maintains uniform sampling property.
    fn rebuild_with_lower_theta(&mut self) {
        // Sort entries to find new threshold
        let mut sorted_entries: Vec<u64> = self.entries.iter().copied().collect();
        sorted_entries.sort_unstable();

        // New theta is the (k+1)th smallest entry
        // This ensures we keep exactly k entries
        if sorted_entries.len() > self.k {
            let new_theta = sorted_entries[self.k - 1];

            // Remove entries >= new_theta
            self.entries.retain(|&hash| hash < new_theta);
            self.theta = new_theta;
        }
    }
}

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

    #[test]
    fn test_basic_creation() {
        let sketch = ThetaSketch::new(12).unwrap();
        assert_eq!(sketch.lg_k, 12);
        assert_eq!(sketch.k, 4096);
        assert_eq!(sketch.theta, u64::MAX);
        assert!(sketch.is_empty());
    }

    #[test]
    fn test_hash_consistency() {
        let sketch = ThetaSketch::new(12).unwrap();
        let hash1 = sketch.hash_item(&"test");
        let hash2 = sketch.hash_item(&"test");
        assert_eq!(hash1, hash2, "Hash should be deterministic");
    }

    #[test]
    fn test_seed_affects_hash() {
        let sketch1 = ThetaSketch::new(12).unwrap();
        let sketch2 = ThetaSketch::with_seed(12, 1234).unwrap();

        let hash1 = sketch1.hash_item(&"test");
        let hash2 = sketch2.hash_item(&"test");

        assert_ne!(
            hash1, hash2,
            "Different seeds should produce different hashes"
        );
    }
}