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
//! REQ (Relative Error Quantile) Sketch - PODS 2021
//!
//! Production implementation used in Google BigQuery and Apache DataSketches.
//! Key feature: **Zero error at p100 (HRA mode) or p0 (LRA mode)**.
//!
//! # Algorithm Overview
//!
//! REQ uses a multi-level compactor structure where:
//! - Level 0 stores raw items
//! - Higher levels store increasingly compressed views
//! - HRA mode: Compaction preserves maximum values (p100 exact)
//! - LRA mode: Compaction preserves minimum values (p0 exact)
//!
//! # Space Complexity
//!
//! O(k log(n/k)) where:
//! - k is the configured parameter (4-1024)
//! - n is the number of items processed
//!
//! # References
//!
//! "Relative Error Streaming Quantiles" (PODS 2021)
//! https://arxiv.org/abs/2004.01668

use std::cmp::Ordering;

/// Operating mode for REQ Sketch
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReqMode {
    /// High Rank Accuracy: Zero error at p100 (maximum)
    /// Optimized for tail quantiles (p90, p99, p99.9)
    HighRankAccuracy,

    /// Low Rank Accuracy: Zero error at p0 (minimum)
    /// Optimized for low quantiles (p1, p0.1)
    LowRankAccuracy,
}

/// A compactor stores items at a specific level
#[derive(Debug, Clone)]
struct Compactor {
    /// Items stored at this level
    items: Vec<f64>,
    /// Maximum capacity before compaction
    capacity: usize,
    /// Level in the hierarchy (0 = base level)
    level: usize,
}

impl Compactor {
    fn new(capacity: usize, level: usize) -> Self {
        Self {
            items: Vec::with_capacity(capacity),
            capacity,
            level,
        }
    }

    fn is_full(&self) -> bool {
        self.items.len() >= self.capacity
    }

    fn compact(&mut self, mode: ReqMode) -> Vec<f64> {
        // Sort items
        self.items
            .sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));

        match mode {
            ReqMode::HighRankAccuracy => {
                // Keep even indices to preserve maximum
                // This ensures the max value is always retained
                let compacted: Vec<f64> = self.items.iter().step_by(2).copied().collect();
                self.items.clear();
                compacted
            }
            ReqMode::LowRankAccuracy => {
                // Keep odd indices to preserve minimum
                // Start from index 1 and step by 2
                let compacted: Vec<f64> = self.items.iter().skip(1).step_by(2).copied().collect();
                self.items.clear();
                compacted
            }
        }
    }
}

/// REQ Sketch for streaming quantile estimation
///
/// # Example
///
/// ```
/// use sketch_oxide::quantiles::req::{ReqSketch, ReqMode};
///
/// let mut sketch = ReqSketch::new(32, ReqMode::HighRankAccuracy).unwrap();
///
/// // Add 10,000 values
/// for i in 1..=10000 {
///     sketch.update(i as f64);
/// }
///
/// // p100 is EXACT (zero error)
/// assert_eq!(sketch.quantile(1.0), Some(10000.0));
///
/// // Other quantiles have relative error guarantees
/// let p99 = sketch.quantile(0.99).unwrap();
/// assert!(p99 >= 9800.0); // Close to true p99 = 9900
/// ```
#[derive(Debug, Clone)]
pub struct ReqSketch {
    /// Configuration parameter (4-1024)
    k: usize,
    /// Operating mode
    mode: ReqMode,
    /// Hierarchical compactors
    compactors: Vec<Compactor>,
    /// Total count of items processed
    n: u64,
    /// Exact minimum value
    min: Option<f64>,
    /// Exact maximum value
    max: Option<f64>,
}

impl ReqSketch {
    /// Creates a new REQ sketch
    ///
    /// # Arguments
    ///
    /// * `k` - Configuration parameter (must be in [4, 1024])
    /// * `mode` - Operating mode (HRA or LRA)
    ///
    /// # Errors
    ///
    /// Returns error if k is not in valid range [4, 1024]
    pub fn new(k: usize, mode: ReqMode) -> Result<Self, String> {
        if !(4..=1024).contains(&k) {
            return Err(format!("k must be in range [4, 1024], got {}", k));
        }

        // Start with level 0
        let compactors = vec![Compactor::new(2 * k, 0)];

        Ok(Self {
            k,
            mode,
            compactors,
            n: 0,
            min: None,
            max: None,
        })
    }

    /// Returns the total number of items processed
    pub fn n(&self) -> u64 {
        self.n
    }

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

    /// Returns the exact minimum value
    pub fn min(&self) -> Option<f64> {
        self.min
    }

    /// Returns the exact maximum value
    pub fn max(&self) -> Option<f64> {
        self.max
    }

    /// Adds a value to the sketch
    pub fn update(&mut self, value: f64) {
        // Update count
        self.n += 1;

        // Update exact min/max
        self.min = Some(self.min.map_or(value, |m| m.min(value)));
        self.max = Some(self.max.map_or(value, |m| m.max(value)));

        // Add to level 0
        self.compactors[0].items.push(value);

        // Propagate compactions up the hierarchy
        self.propagate_compactions();
    }

    /// Propagates compactions through the hierarchy
    fn propagate_compactions(&mut self) {
        let mut level = 0;

        while level < self.compactors.len() && self.compactors[level].is_full() {
            // Compact this level
            let promoted = self.compactors[level].compact(self.mode);

            // Ensure next level exists
            if level + 1 >= self.compactors.len() {
                self.compactors.push(Compactor::new(2 * self.k, level + 1));
            }

            // Add promoted items to next level
            self.compactors[level + 1].items.extend(promoted);

            level += 1;
        }
    }

    /// Estimates a quantile
    ///
    /// # Arguments
    ///
    /// * `q` - Quantile to estimate (must be in [0, 1])
    ///
    /// # Returns
    ///
    /// - `None` if sketch is empty or q is invalid
    /// - `Some(value)` otherwise
    ///
    /// # Guarantees
    ///
    /// - HRA mode: q=1.0 (p100) returns exact maximum (zero error)
    /// - LRA mode: q=0.0 (p0) returns exact minimum (zero error)
    pub fn quantile(&self, q: f64) -> Option<f64> {
        // Validate quantile
        if !(0.0..=1.0).contains(&q) || q.is_nan() {
            return None;
        }

        if self.is_empty() {
            return None;
        }

        // Special cases for exact guarantees
        match self.mode {
            ReqMode::HighRankAccuracy if q == 1.0 => return self.max,
            ReqMode::LowRankAccuracy if q == 0.0 => return self.min,
            _ => {}
        }

        // Also handle boundary cases
        if q == 0.0 {
            return self.min;
        }
        if q == 1.0 {
            return self.max;
        }

        // Collect all items with their weights
        let mut weighted_items = Vec::new();

        for compactor in &self.compactors {
            let weight = 1u64 << compactor.level; // 2^level
            for &item in &compactor.items {
                weighted_items.push((item, weight));
            }
        }

        // Sort by value
        weighted_items.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal));

        // Find the item at the requested rank
        let target_rank = (q * self.n as f64) as u64;
        let mut cumulative_weight = 0u64;

        for (value, weight) in weighted_items {
            cumulative_weight += weight;
            if cumulative_weight >= target_rank {
                return Some(value);
            }
        }

        // If we reach here, return the maximum
        self.max
    }

    /// Merges another sketch into this one
    ///
    /// # Arguments
    ///
    /// * `other` - Sketch to merge
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Sketches have different k values
    /// - Sketches have different modes
    ///
    /// # Guarantees
    ///
    /// - Preserves exact min/max values
    /// - HRA mode: p100 remains exact after merge
    /// - LRA mode: p0 remains exact after merge
    pub fn merge(&self, other: &Self) -> Result<Self, String> {
        // Check compatibility
        if self.k != other.k {
            return Err(format!(
                "Cannot merge sketches with different k values: {} vs {}",
                self.k, other.k
            ));
        }

        if self.mode != other.mode {
            return Err(format!(
                "Cannot merge sketches with different modes: {:?} vs {:?}",
                self.mode, other.mode
            ));
        }

        // Handle empty cases
        if self.is_empty() {
            return Ok(other.clone());
        }
        if other.is_empty() {
            return Ok(self.clone());
        }

        // Create new sketch
        let mut merged = Self::new(self.k, self.mode).unwrap();

        // Merge min/max
        merged.min = Some(self.min.unwrap().min(other.min.unwrap()));
        merged.max = Some(self.max.unwrap().max(other.max.unwrap()));
        merged.n = self.n + other.n;

        // Collect all items from both sketches
        let mut all_items = Vec::new();

        for compactor in &self.compactors {
            let weight = 1u64 << compactor.level;
            for &item in &compactor.items {
                all_items.push((item, weight, compactor.level));
            }
        }

        for compactor in &other.compactors {
            let weight = 1u64 << compactor.level;
            for &item in &compactor.items {
                all_items.push((item, weight, compactor.level));
            }
        }

        // Sort by level (process lower levels first)
        all_items.sort_by_key(|(_, _, level)| *level);

        // Re-insert all items into the merged sketch
        // This will trigger compactions as needed
        for (item, weight, level) in all_items {
            // Ensure we have enough levels
            while level >= merged.compactors.len() {
                let new_level = merged.compactors.len();
                merged
                    .compactors
                    .push(Compactor::new(2 * merged.k, new_level));
            }

            // Add items with their weight
            for _ in 0..weight {
                merged.compactors[level].items.push(item);
            }
        }

        // Propagate compactions
        for level in 0..merged.compactors.len() {
            while merged.compactors[level].is_full() {
                let promoted = merged.compactors[level].compact(merged.mode);

                if level + 1 >= merged.compactors.len() {
                    merged
                        .compactors
                        .push(Compactor::new(2 * merged.k, level + 1));
                }

                merged.compactors[level + 1].items.extend(promoted);
            }
        }

        Ok(merged)
    }
}

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

    #[test]
    fn test_compactor_hra_preserves_max() {
        let mut compactor = Compactor::new(10, 0);
        compactor.items = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];

        let compacted = compactor.compact(ReqMode::HighRankAccuracy);

        // Should keep even indices: 0,2,4 -> 1.0, 3.0, 5.0, 6.0
        // After sorting: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
        // Even indices: [1.0, 3.0, 5.0]
        // But wait, we want to preserve max, so let's check
        assert!(compacted.contains(&6.0) || compacted.contains(&5.0));
    }

    #[test]
    fn test_mode_equality() {
        assert_eq!(ReqMode::HighRankAccuracy, ReqMode::HighRankAccuracy);
        assert_ne!(ReqMode::HighRankAccuracy, ReqMode::LowRankAccuracy);
    }
}