Skip to main content

sql_splitter/profile/
sketches.rs

1//! Mergeable, seeded, bounded accumulators that turn an unbounded stream of
2//! column values into fixed-size evidence.
3//!
4//! The guiding invariant: **input size grows scan time, never profile
5//! memory.** Every accumulator here retains at most a budget-derived number of
6//! items and a budget-derived number of bytes, regardless of how many values
7//! it observes. Reservoir sampling, Space-Saving, HyperLogLog, and a streaming
8//! histogram each pay a fixed, provable memory cost.
9//!
10//! All accumulators implement the crate-private [`EvidenceAccumulator`] trait
11//! so [`ColumnSketches`] can drive them uniformly. That trait stays private on
12//! purpose: a second consumer has not yet proven the abstraction, and the
13//! stable surface downstream code depends on is the *evidence* structs in
14//! [`crate::profile::evidence`], not these internals.
15
16use crate::profile::evidence::{
17    BooleanEvidence, CharClasses, ColumnEvidence, NumericEvidence, StringShapeEvidence,
18    TimestampRangeEvidence, TopKEntry,
19};
20use crate::profile::{
21    ProfileBudget, ProfileError, ProfileValue, HISTOGRAM_BIN_BYTES, HLL_PRECISION, HLL_REGISTERS,
22    MAX_AFFIX_BYTES, MAX_SAMPLE_VALUE_BYTES, MAX_TIMESTAMP_BYTES, MAX_TOPK_KEY_BYTES,
23    TOPK_COUNTER_OVERHEAD,
24};
25use rand::RngExt;
26use rand_chacha::rand_core::SeedableRng;
27use rand_chacha::ChaCha8Rng;
28use std::collections::BTreeMap;
29
30// Type tags mixed into the distinct-count hash so that, e.g., the integer `5`
31// and the text `"5"` are not conflated across a mixed column.
32const TAG_BOOL: u8 = 1;
33const TAG_INT: u8 = 2;
34const TAG_DECIMAL: u8 = 3;
35const TAG_TEXT: u8 = 4;
36const TAG_DATETIME: u8 = 5;
37const TAG_JSON: u8 = 6;
38
39/// Crate-private accumulator contract shared by every sketch.
40///
41/// Kept private deliberately (see module docs): only [`ColumnSketches`] drives
42/// these, and freezing the trait shape into the public API before a second
43/// consumer exists would be premature.
44pub(crate) trait EvidenceAccumulator {
45    /// The per-value input this accumulator consumes.
46    type Observation<'a>;
47    /// The bounded summary this accumulator finalizes into.
48    type Evidence;
49
50    /// Fold one observed value in.
51    fn observe(&mut self, value: Self::Observation<'_>);
52    /// Merge another accumulator of the same configuration into this one.
53    fn merge(&mut self, other: Self) -> Result<(), ProfileError>
54    where
55        Self: Sized;
56    /// Consume the accumulator, producing its bounded evidence.
57    fn finish(self) -> Self::Evidence
58    where
59        Self: Sized;
60    /// Bytes currently retained on the heap by this accumulator.
61    fn retained_bytes(&self) -> usize;
62}
63
64// ---------------------------------------------------------------------------
65// Hashing
66// ---------------------------------------------------------------------------
67
68const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
69const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
70
71/// A fixed, version-stable 64-bit hash: FNV-1a for mixing content in, then a
72/// SplitMix64 finalizer for avalanche (FNV alone has weak high bits, which
73/// HyperLogLog's register indexing relies on being well-distributed).
74///
75/// This is deliberately *not* `ahash`/`DefaultHasher`: those publish no
76/// cross-version stability guarantee, and the HLL estimate must be reproducible
77/// for a given input.
78fn stable_hash64(tag: u8, bytes: &[u8]) -> u64 {
79    let mut h = FNV_OFFSET;
80    h ^= tag as u64;
81    h = h.wrapping_mul(FNV_PRIME);
82    for &b in bytes {
83        h ^= b as u64;
84        h = h.wrapping_mul(FNV_PRIME);
85    }
86    // SplitMix64 finalizer.
87    h ^= h >> 30;
88    h = h.wrapping_mul(0xbf58_476d_1ce4_e5b9);
89    h ^= h >> 27;
90    h = h.wrapping_mul(0x94d0_49bb_1331_11eb);
91    h ^= h >> 31;
92    h
93}
94
95// ---------------------------------------------------------------------------
96// Reservoir
97// ---------------------------------------------------------------------------
98
99/// Deterministic reservoir (Algorithm R) over retained string renderings.
100///
101/// Seeded from a per-column seed so the same stream yields the same sample.
102/// The merge produces a uniform sample of the concatenated streams by drawing
103/// a hypergeometric split and subsampling each side.
104pub(crate) struct Reservoir {
105    capacity: usize,
106    seen: u64,
107    items: Vec<String>,
108    rng: ChaCha8Rng,
109}
110
111impl Reservoir {
112    fn new(capacity: usize, seed: u64) -> Self {
113        Self {
114            capacity,
115            seen: 0,
116            items: Vec::new(),
117            rng: ChaCha8Rng::seed_from_u64(seed),
118        }
119    }
120
121    fn len(&self) -> usize {
122        self.items.len()
123    }
124
125    /// Keep a uniform size-`k` subset of `items` in place (partial
126    /// Fisher-Yates), truncating the rest.
127    fn take_sample(items: &mut Vec<String>, k: usize, rng: &mut ChaCha8Rng) {
128        let len = items.len();
129        for i in 0..k.min(len) {
130            let j = i + rng.random_range(0..(len - i) as u64) as usize;
131            items.swap(i, j);
132        }
133        items.truncate(k.min(len));
134    }
135}
136
137impl EvidenceAccumulator for Reservoir {
138    type Observation<'a> = String;
139    type Evidence = Vec<String>;
140
141    fn observe(&mut self, value: String) {
142        self.seen += 1;
143        if self.items.len() < self.capacity {
144            self.items.push(value);
145        } else {
146            let j = self.rng.random_range(0..self.seen) as usize;
147            if j < self.capacity {
148                self.items[j] = value;
149            }
150        }
151    }
152
153    fn merge(&mut self, mut other: Self) -> Result<(), ProfileError> {
154        if self.capacity != other.capacity {
155            return Err(ProfileError::incompatible_merge("reservoir capacity"));
156        }
157        let (n_a, n_b) = (self.seen, other.seen);
158        if n_b == 0 {
159            return Ok(());
160        }
161        if n_a == 0 {
162            self.items = other.items;
163            self.seen = other.seen;
164            return Ok(());
165        }
166        let total = n_a + n_b;
167        let m = self.capacity.min(total as usize);
168
169        // Draw x ~ Hypergeometric(total, n_a, m) by simulating m draws without
170        // replacement from an urn of n_a "A" balls and n_b "B" balls. O(m).
171        let (mut ra, mut rb, mut x) = (n_a, n_b, 0usize);
172        for _ in 0..m {
173            if self.rng.random_range(0..(ra + rb)) < ra {
174                x += 1;
175                ra -= 1;
176            } else {
177                rb -= 1;
178            }
179        }
180
181        // Subsample: a uniform subset of a uniform sample is itself uniform.
182        Self::take_sample(&mut self.items, x, &mut self.rng);
183        Self::take_sample(&mut other.items, m - x, &mut self.rng);
184        self.items.append(&mut other.items);
185        self.seen = total;
186        Ok(())
187    }
188
189    fn finish(self) -> Vec<String> {
190        self.items
191    }
192
193    fn retained_bytes(&self) -> usize {
194        self.items.iter().map(|s| s.len()).sum()
195    }
196}
197
198// ---------------------------------------------------------------------------
199// Space-Saving top-k
200// ---------------------------------------------------------------------------
201
202#[derive(Clone)]
203struct Counter {
204    count: u64,
205    error: u64,
206}
207
208/// Space-Saving heavy hitters (Metwally et al.), bounded to `capacity`
209/// counters. Uses a `BTreeMap` so eviction tie-breaks and the merge are
210/// deterministic across runs.
211pub(crate) struct SpaceSavingTopK {
212    capacity: usize,
213    counters: BTreeMap<String, Counter>,
214}
215
216impl SpaceSavingTopK {
217    fn new(capacity: usize) -> Self {
218        Self {
219            capacity,
220            counters: BTreeMap::new(),
221        }
222    }
223
224    fn len(&self) -> usize {
225        self.counters.len()
226    }
227
228    fn min_count(&self) -> u64 {
229        self.counters.values().map(|c| c.count).min().unwrap_or(0)
230    }
231
232    /// The minimum count a merge should attribute to items *absent* from this
233    /// summary: an item we never tracked could have occurred up to the
234    /// smallest tracked count (0 if the summary is not yet full).
235    fn merge_floor(&self) -> u64 {
236        if self.counters.len() >= self.capacity {
237            self.min_count()
238        } else {
239            0
240        }
241    }
242}
243
244impl EvidenceAccumulator for SpaceSavingTopK {
245    type Observation<'a> = &'a str;
246    type Evidence = Vec<TopKEntry>;
247
248    fn observe(&mut self, key: &str) {
249        if let Some(counter) = self.counters.get_mut(key) {
250            counter.count += 1;
251            return;
252        }
253        if self.counters.len() < self.capacity {
254            self.counters
255                .insert(key.to_owned(), Counter { count: 1, error: 0 });
256            return;
257        }
258        // Evict the smallest counter and reuse its slot; the newcomer inherits
259        // the evicted count as its maximum overestimate.
260        let victim = self
261            .counters
262            .iter()
263            .min_by(|a, b| a.1.count.cmp(&b.1.count).then(a.0.cmp(b.0)))
264            .map(|(k, c)| (k.clone(), c.count));
265        if let Some((victim_key, victim_count)) = victim {
266            self.counters.remove(&victim_key);
267            self.counters.insert(
268                key.to_owned(),
269                Counter {
270                    count: victim_count + 1,
271                    error: victim_count,
272                },
273            );
274        }
275    }
276
277    fn merge(&mut self, other: Self) -> Result<(), ProfileError> {
278        if self.capacity != other.capacity {
279            return Err(ProfileError::incompatible_merge("top-k capacity"));
280        }
281        let a_floor = self.merge_floor();
282        let b_floor = other.merge_floor();
283
284        let mut merged: BTreeMap<String, Counter> = BTreeMap::new();
285        for (key, a) in &self.counters {
286            let (cb, eb) = other
287                .counters
288                .get(key)
289                .map(|c| (c.count, c.error))
290                .unwrap_or((b_floor, b_floor));
291            merged.insert(
292                key.clone(),
293                Counter {
294                    count: a.count + cb,
295                    error: a.error + eb,
296                },
297            );
298        }
299        for (key, b) in &other.counters {
300            if self.counters.contains_key(key) {
301                continue;
302            }
303            merged.insert(
304                key.clone(),
305                Counter {
306                    count: b.count + a_floor,
307                    error: b.error + a_floor,
308                },
309            );
310        }
311
312        if merged.len() > self.capacity {
313            let mut entries: Vec<(String, Counter)> = merged.into_iter().collect();
314            entries.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
315            entries.truncate(self.capacity);
316            merged = entries.into_iter().collect();
317        }
318        self.counters = merged;
319        Ok(())
320    }
321
322    fn finish(self) -> Vec<TopKEntry> {
323        let mut entries: Vec<TopKEntry> = self
324            .counters
325            .into_iter()
326            .map(|(value, c)| TopKEntry {
327                value,
328                count: c.count,
329                error: c.error,
330            })
331            .collect();
332        entries.sort_by(|a, b| b.count.cmp(&a.count).then(a.value.cmp(&b.value)));
333        entries
334    }
335
336    fn retained_bytes(&self) -> usize {
337        self.counters
338            .keys()
339            .map(|k| k.len() + TOPK_COUNTER_OVERHEAD)
340            .sum()
341    }
342}
343
344// ---------------------------------------------------------------------------
345// HyperLogLog
346// ---------------------------------------------------------------------------
347
348/// HyperLogLog distinct-count estimator over precomputed 64-bit hashes.
349///
350/// Fixed `HLL_REGISTERS` registers; merge is register-wise max, which makes the
351/// merged estimate *exactly* equal to a single pass over the concatenated
352/// stream (order- and partition-independent).
353pub(crate) struct HyperLogLog {
354    registers: Vec<u8>,
355}
356
357impl HyperLogLog {
358    fn new() -> Self {
359        Self {
360            registers: vec![0; HLL_REGISTERS],
361        }
362    }
363
364    fn observe_hash(&mut self, h: u64) {
365        let index = (h >> (64 - HLL_PRECISION)) as usize;
366        let w = h << HLL_PRECISION;
367        let rho = if w == 0 {
368            (64 - HLL_PRECISION) as u8 + 1
369        } else {
370            w.leading_zeros() as u8 + 1
371        };
372        if rho > self.registers[index] {
373            self.registers[index] = rho;
374        }
375    }
376
377    fn estimate(&self) -> f64 {
378        let m = HLL_REGISTERS as f64;
379        let alpha = 0.7213 / (1.0 + 1.079 / m);
380        let sum: f64 = self.registers.iter().map(|&r| 2f64.powi(-(r as i32))).sum();
381        let raw = alpha * m * m / sum;
382        // Small-range linear-counting correction. With 64-bit hashing the
383        // large-range (2^32) correction is unnecessary.
384        if raw <= 2.5 * m {
385            let zeros = self.registers.iter().filter(|&&r| r == 0).count();
386            if zeros != 0 {
387                return m * (m / zeros as f64).ln();
388            }
389        }
390        raw
391    }
392}
393
394impl EvidenceAccumulator for HyperLogLog {
395    type Observation<'a> = u64;
396    type Evidence = f64;
397
398    fn observe(&mut self, hash: u64) {
399        self.observe_hash(hash);
400    }
401
402    fn merge(&mut self, other: Self) -> Result<(), ProfileError> {
403        if self.registers.len() != other.registers.len() {
404            return Err(ProfileError::incompatible_merge("hll precision"));
405        }
406        for (slot, incoming) in self.registers.iter_mut().zip(other.registers) {
407            *slot = (*slot).max(incoming);
408        }
409        Ok(())
410    }
411
412    fn finish(self) -> f64 {
413        self.estimate()
414    }
415
416    fn retained_bytes(&self) -> usize {
417        self.registers.len()
418    }
419}
420
421// ---------------------------------------------------------------------------
422// Numeric histogram
423// ---------------------------------------------------------------------------
424
425#[derive(Clone, Copy)]
426struct Bin {
427    value: f64,
428    count: u64,
429}
430
431/// Ben-Haim & Tom-Tov streaming histogram: at most `max_bins` (centroid,
432/// count) bins, adjacent bins merged by nearest centroid when the cap is
433/// exceeded. Mergeable and supports interpolated quantiles.
434pub(crate) struct NumericHistogram {
435    max_bins: usize,
436    bins: Vec<Bin>,
437    min: f64,
438    max: f64,
439    total: u64,
440    sum: f64,
441}
442
443impl NumericHistogram {
444    fn new(max_bins: usize) -> Self {
445        Self {
446            max_bins: max_bins.max(1),
447            bins: Vec::new(),
448            min: f64::INFINITY,
449            max: f64::NEG_INFINITY,
450            total: 0,
451            sum: 0.0,
452        }
453    }
454
455    fn len(&self) -> usize {
456        self.bins.len()
457    }
458
459    fn insert_value(&mut self, value: f64, count: u64) {
460        match self.bins.binary_search_by(|b| {
461            b.value
462                .partial_cmp(&value)
463                .unwrap_or(std::cmp::Ordering::Equal)
464        }) {
465            Ok(i) => self.bins[i].count += count,
466            Err(i) => self.bins.insert(i, Bin { value, count }),
467        }
468    }
469
470    /// Merge the two closest-centroid adjacent bins until within `max_bins`.
471    fn shrink(&mut self) {
472        while self.bins.len() > self.max_bins {
473            let mut best = 0usize;
474            let mut best_gap = f64::INFINITY;
475            for i in 0..self.bins.len() - 1 {
476                let gap = self.bins[i + 1].value - self.bins[i].value;
477                if gap < best_gap {
478                    best_gap = gap;
479                    best = i;
480                }
481            }
482            let right = self.bins[best + 1];
483            let left = self.bins[best];
484            let count = left.count + right.count;
485            let value =
486                (left.value * left.count as f64 + right.value * right.count as f64) / count as f64;
487            self.bins[best] = Bin { value, count };
488            self.bins.remove(best + 1);
489        }
490    }
491
492    fn quantile(&self, q: f64) -> f64 {
493        if self.total == 0 {
494            return f64::NAN;
495        }
496        if self.bins.len() == 1 {
497            return self.bins[0].value;
498        }
499        let n = self.total as f64;
500        let rank = q.clamp(0.0, 1.0) * n;
501
502        // Piecewise-linear inverse CDF anchored at (0, min) .. (n, max) with
503        // interior points at each bin's cumulative centroid.
504        let mut xs = Vec::with_capacity(self.bins.len() + 2);
505        let mut ys = Vec::with_capacity(self.bins.len() + 2);
506        xs.push(0.0);
507        ys.push(self.min);
508        let mut cum = 0.0;
509        for b in &self.bins {
510            let c = b.count as f64;
511            xs.push(cum + c / 2.0);
512            ys.push(b.value);
513            cum += c;
514        }
515        xs.push(n);
516        ys.push(self.max);
517
518        for w in 1..xs.len() {
519            if rank <= xs[w] {
520                let (x0, x1, y0, y1) = (xs[w - 1], xs[w], ys[w - 1], ys[w]);
521                if x1 == x0 {
522                    return y1;
523                }
524                let t = (rank - x0) / (x1 - x0);
525                return y0 + t * (y1 - y0);
526            }
527        }
528        self.max
529    }
530}
531
532impl EvidenceAccumulator for NumericHistogram {
533    type Observation<'a> = f64;
534    type Evidence = NumericEvidence;
535
536    fn observe(&mut self, value: f64) {
537        self.total += 1;
538        self.sum += value;
539        self.min = self.min.min(value);
540        self.max = self.max.max(value);
541        self.insert_value(value, 1);
542        if self.bins.len() > self.max_bins {
543            self.shrink();
544        }
545    }
546
547    fn merge(&mut self, other: Self) -> Result<(), ProfileError> {
548        if self.max_bins != other.max_bins {
549            return Err(ProfileError::incompatible_merge("histogram bins"));
550        }
551        for b in other.bins {
552            self.insert_value(b.value, b.count);
553        }
554        self.total += other.total;
555        self.sum += other.sum;
556        self.min = self.min.min(other.min);
557        self.max = self.max.max(other.max);
558        self.shrink();
559        Ok(())
560    }
561
562    fn finish(self) -> NumericEvidence {
563        let mean = if self.total == 0 {
564            0.0
565        } else {
566            self.sum / self.total as f64
567        };
568        NumericEvidence {
569            min: self.min,
570            max: self.max,
571            mean,
572            p50: self.quantile(0.50),
573            p90: self.quantile(0.90),
574            p99: self.quantile(0.99),
575        }
576    }
577
578    fn retained_bytes(&self) -> usize {
579        self.bins.len() * HISTOGRAM_BIN_BYTES
580    }
581}
582
583// ---------------------------------------------------------------------------
584// String shape
585// ---------------------------------------------------------------------------
586
587/// Length, empty-rate, alphabet, and longest-common prefix/suffix of a text
588/// column. Prefix/suffix are capped at `MAX_AFFIX_BYTES`; everything else is a
589/// running scalar, so memory is fixed regardless of stream length.
590pub(crate) struct StringShapeSketch {
591    count: u64,
592    empty: u64,
593    min_len: usize,
594    max_len: usize,
595    total_len: u128,
596    classes: CharClasses,
597    prefix: Option<String>,
598    suffix: Option<String>,
599    truncated_affix: bool,
600}
601
602impl StringShapeSketch {
603    fn new() -> Self {
604        Self {
605            count: 0,
606            empty: 0,
607            min_len: usize::MAX,
608            max_len: 0,
609            total_len: 0,
610            classes: CharClasses::default(),
611            prefix: None,
612            suffix: None,
613            truncated_affix: false,
614        }
615    }
616
617    fn classify(classes: &mut CharClasses, s: &str) {
618        for ch in s.chars() {
619            if ch.is_ascii_lowercase() {
620                classes.lower = true;
621            } else if ch.is_ascii_uppercase() {
622                classes.upper = true;
623            } else if ch.is_ascii_digit() {
624                classes.digit = true;
625            } else if ch.is_whitespace() {
626                classes.whitespace = true;
627            } else if ch.is_ascii_punctuation() {
628                classes.punctuation = true;
629            } else if !ch.is_ascii() {
630                classes.non_ascii = true;
631            }
632        }
633    }
634
635    /// Longest common prefix of two strings, capped at `MAX_AFFIX_BYTES` bytes
636    /// (on a char boundary). Returns whether the cap was hit.
637    fn common_prefix(a: &str, b: &str) -> (String, bool) {
638        let mut end = 0;
639        for (ca, cb) in a.char_indices().zip(b.chars()) {
640            let (idx, ch) = ca;
641            if ch != cb {
642                break;
643            }
644            let next = idx + ch.len_utf8();
645            if next > MAX_AFFIX_BYTES {
646                return (a[..idx].to_owned(), true);
647            }
648            end = next;
649        }
650        (a[..end].to_owned(), false)
651    }
652
653    fn common_suffix(a: &str, b: &str) -> (String, bool) {
654        let mut bytes = 0usize;
655        let mut ai = a.chars().rev();
656        let mut bi = b.chars().rev();
657        loop {
658            match (ai.next(), bi.next()) {
659                (Some(ca), Some(cb)) if ca == cb => {
660                    if bytes + ca.len_utf8() > MAX_AFFIX_BYTES {
661                        return (a[a.len() - bytes..].to_owned(), true);
662                    }
663                    bytes += ca.len_utf8();
664                }
665                _ => break,
666            }
667        }
668        (a[a.len() - bytes..].to_owned(), false)
669    }
670}
671
672impl EvidenceAccumulator for StringShapeSketch {
673    type Observation<'a> = &'a str;
674    type Evidence = StringShapeEvidence;
675
676    fn observe(&mut self, s: &str) {
677        self.count += 1;
678        if s.is_empty() {
679            self.empty += 1;
680        }
681        let len = s.chars().count();
682        self.min_len = self.min_len.min(len);
683        self.max_len = self.max_len.max(len);
684        self.total_len += len as u128;
685        Self::classify(&mut self.classes, s);
686
687        match &self.prefix {
688            None => {
689                let (p, trunc) = Self::common_prefix(s, s);
690                self.prefix = Some(p);
691                self.truncated_affix |= trunc;
692            }
693            Some(current) => {
694                let (p, trunc) = Self::common_prefix(current, s);
695                self.prefix = Some(p);
696                self.truncated_affix |= trunc;
697            }
698        }
699        match &self.suffix {
700            None => {
701                let (sfx, trunc) = Self::common_suffix(s, s);
702                self.suffix = Some(sfx);
703                self.truncated_affix |= trunc;
704            }
705            Some(current) => {
706                let (sfx, trunc) = Self::common_suffix(current, s);
707                self.suffix = Some(sfx);
708                self.truncated_affix |= trunc;
709            }
710        }
711    }
712
713    fn merge(&mut self, other: Self) -> Result<(), ProfileError> {
714        self.count += other.count;
715        self.empty += other.empty;
716        if other.count > 0 {
717            self.min_len = self.min_len.min(other.min_len);
718            self.max_len = self.max_len.max(other.max_len);
719        }
720        self.total_len += other.total_len;
721        self.classes.lower |= other.classes.lower;
722        self.classes.upper |= other.classes.upper;
723        self.classes.digit |= other.classes.digit;
724        self.classes.whitespace |= other.classes.whitespace;
725        self.classes.punctuation |= other.classes.punctuation;
726        self.classes.non_ascii |= other.classes.non_ascii;
727        self.truncated_affix |= other.truncated_affix;
728
729        self.prefix = match (self.prefix.take(), other.prefix) {
730            (Some(a), Some(b)) => {
731                let (p, trunc) = Self::common_prefix(&a, &b);
732                self.truncated_affix |= trunc;
733                Some(p)
734            }
735            (a, b) => a.or(b),
736        };
737        self.suffix = match (self.suffix.take(), other.suffix) {
738            (Some(a), Some(b)) => {
739                let (s, trunc) = Self::common_suffix(&a, &b);
740                self.truncated_affix |= trunc;
741                Some(s)
742            }
743            (a, b) => a.or(b),
744        };
745        Ok(())
746    }
747
748    fn finish(self) -> StringShapeEvidence {
749        let mean_len = if self.count == 0 {
750            0.0
751        } else {
752            self.total_len as f64 / self.count as f64
753        };
754        StringShapeEvidence {
755            count: self.count,
756            empty_count: self.empty,
757            empty_rate: if self.count == 0 {
758                0.0
759            } else {
760                self.empty as f64 / self.count as f64
761            },
762            min_len: if self.count == 0 { 0 } else { self.min_len },
763            max_len: self.max_len,
764            mean_len,
765            classes: self.classes,
766            common_prefix: self.prefix.unwrap_or_default(),
767            common_suffix: self.suffix.unwrap_or_default(),
768            truncated_affix: self.truncated_affix,
769        }
770    }
771
772    fn retained_bytes(&self) -> usize {
773        self.prefix.as_ref().map_or(0, String::len) + self.suffix.as_ref().map_or(0, String::len)
774    }
775}
776
777// ---------------------------------------------------------------------------
778// Column bundle
779// ---------------------------------------------------------------------------
780
781/// Truncate a string to at most `max` bytes on a char boundary, reporting
782/// whether truncation occurred.
783fn truncate_bytes(s: &str, max: usize) -> (&str, bool) {
784    if s.len() <= max {
785        return (s, false);
786    }
787    let mut end = max;
788    while end > 0 && !s.is_char_boundary(end) {
789        end -= 1;
790    }
791    (&s[..end], true)
792}
793
794/// Render a fixed-point decimal `minor * 10^-scale` as a human-readable string.
795fn format_decimal(minor: i128, scale: u8) -> String {
796    if scale == 0 {
797        return minor.to_string();
798    }
799    let scale = scale as usize;
800    let neg = minor < 0;
801    let digits = minor.unsigned_abs().to_string();
802    let body = if digits.len() <= scale {
803        format!("0.{digits:0>scale$}")
804    } else {
805        let point = digits.len() - scale;
806        format!("{}.{}", &digits[..point], &digits[point..])
807    };
808    if neg {
809        format!("-{body}")
810    } else {
811        body
812    }
813}
814
815/// All per-column accumulators bundled behind one seeded, mergeable, bounded
816/// facade. Feed values with [`observe`](Self::observe); combine partitions with
817/// [`merge`](Self::merge); finalize to [`ColumnEvidence`] with
818/// [`finish`](Self::finish).
819pub struct ColumnSketches {
820    total: u64,
821    nulls: u64,
822    bool_true: u64,
823    bool_false: u64,
824    saw_bool: bool,
825    hll: HyperLogLog,
826    topk: SpaceSavingTopK,
827    reservoir: Reservoir,
828    histogram: NumericHistogram,
829    saw_numeric: bool,
830    max_scale: Option<u8>,
831    string_shape: StringShapeSketch,
832    saw_string: bool,
833    ts_min: Option<String>,
834    ts_max: Option<String>,
835    saw_ts: bool,
836    json_valid: u64,
837    json_total: u64,
838    truncated_samples: u64,
839}
840
841impl ColumnSketches {
842    /// Build a fresh set of accumulators sized to `budget` and seeded by
843    /// `seed` (only the reservoir is randomized; the seed makes its sample
844    /// reproducible).
845    pub fn new(budget: &ProfileBudget, seed: u64) -> Self {
846        Self {
847            total: 0,
848            nulls: 0,
849            bool_true: 0,
850            bool_false: 0,
851            saw_bool: false,
852            hll: HyperLogLog::new(),
853            topk: SpaceSavingTopK::new(budget.top_k),
854            reservoir: Reservoir::new(budget.sample_rows, seed),
855            histogram: NumericHistogram::new(budget.histogram_bins),
856            saw_numeric: false,
857            max_scale: None,
858            string_shape: StringShapeSketch::new(),
859            saw_string: false,
860            ts_min: None,
861            ts_max: None,
862            saw_ts: false,
863            json_valid: 0,
864            json_total: 0,
865            truncated_samples: 0,
866        }
867    }
868
869    /// Fold one column value into every relevant accumulator.
870    pub fn observe(&mut self, value: ProfileValue<'_>) {
871        self.total += 1;
872        match value {
873            ProfileValue::Null => self.nulls += 1,
874            ProfileValue::Boolean(b) => {
875                self.saw_bool = true;
876                if b {
877                    self.bool_true += 1;
878                } else {
879                    self.bool_false += 1;
880                }
881                self.hll.observe(stable_hash64(TAG_BOOL, &[b as u8]));
882            }
883            ProfileValue::Integer(i) => {
884                self.saw_numeric = true;
885                self.histogram.observe(i as f64);
886                self.hll.observe(stable_hash64(TAG_INT, &i.to_le_bytes()));
887                self.record_sample(&i.to_string());
888            }
889            ProfileValue::Decimal { minor, scale } => {
890                self.saw_numeric = true;
891                self.histogram
892                    .observe(minor as f64 / 10f64.powi(scale as i32));
893                self.max_scale = Some(self.max_scale.map_or(scale, |s| s.max(scale)));
894                let rendered = format_decimal(minor, scale);
895                self.hll
896                    .observe(stable_hash64(TAG_DECIMAL, rendered.as_bytes()));
897                self.record_sample(&rendered);
898            }
899            ProfileValue::Text(s) => {
900                self.saw_string = true;
901                self.string_shape.observe(s);
902                self.hll.observe(stable_hash64(TAG_TEXT, s.as_bytes()));
903                self.record_sample(s);
904            }
905            ProfileValue::DateTime(s) => {
906                self.saw_ts = true;
907                self.update_timestamp(s);
908                self.hll.observe(stable_hash64(TAG_DATETIME, s.as_bytes()));
909                self.record_sample(s);
910            }
911            ProfileValue::Json(s) => {
912                self.json_total += 1;
913                if serde_json::from_str::<serde_json::Value>(s).is_ok() {
914                    self.json_valid += 1;
915                }
916                self.hll.observe(stable_hash64(TAG_JSON, s.as_bytes()));
917                self.record_sample(s);
918            }
919        }
920    }
921
922    /// Route a rendered scalar into the byte-bounded reservoir and top-k,
923    /// truncating to the sample/key ceilings and recording truncation.
924    fn record_sample(&mut self, rendered: &str) {
925        let (key, key_trunc) = truncate_bytes(rendered, MAX_TOPK_KEY_BYTES);
926        self.topk.observe(key);
927        let (sample, sample_trunc) = truncate_bytes(rendered, MAX_SAMPLE_VALUE_BYTES);
928        if key_trunc || sample_trunc {
929            self.truncated_samples += 1;
930        }
931        self.reservoir.observe(sample.to_owned());
932    }
933
934    fn update_timestamp(&mut self, s: &str) {
935        let (capped, _) = truncate_bytes(s, MAX_TIMESTAMP_BYTES);
936        match &self.ts_min {
937            Some(current) if current.as_str() <= capped => {}
938            _ => self.ts_min = Some(capped.to_owned()),
939        }
940        match &self.ts_max {
941            Some(current) if current.as_str() >= capped => {}
942            _ => self.ts_max = Some(capped.to_owned()),
943        }
944    }
945
946    /// Merge another partition's sketches into this one. Fails only if the two
947    /// were built with incompatible budgets.
948    pub fn merge(&mut self, other: ColumnSketches) -> Result<(), ProfileError> {
949        self.hll.merge(other.hll)?;
950        self.topk.merge(other.topk)?;
951        self.reservoir.merge(other.reservoir)?;
952        self.histogram.merge(other.histogram)?;
953        self.string_shape.merge(other.string_shape)?;
954
955        self.total += other.total;
956        self.nulls += other.nulls;
957        self.bool_true += other.bool_true;
958        self.bool_false += other.bool_false;
959        self.saw_bool |= other.saw_bool;
960        self.saw_numeric |= other.saw_numeric;
961        self.saw_string |= other.saw_string;
962        self.saw_ts |= other.saw_ts;
963        self.json_valid += other.json_valid;
964        self.json_total += other.json_total;
965        self.truncated_samples += other.truncated_samples;
966        self.max_scale = match (self.max_scale, other.max_scale) {
967            (Some(a), Some(b)) => Some(a.max(b)),
968            (a, b) => a.or(b),
969        };
970        if let Some(min) = other.ts_min {
971            self.update_timestamp(&min);
972        }
973        if let Some(max) = other.ts_max {
974            self.update_timestamp(&max);
975        }
976        Ok(())
977    }
978
979    /// HyperLogLog estimate of distinct non-null values.
980    pub fn distinct_estimate(&self) -> f64 {
981        self.hll.estimate()
982    }
983
984    /// Count of variably-retained items (reservoir + top-k + histogram bins).
985    /// Fixed-size structures (HLL registers) are excluded — they are memory,
986    /// not budget-scaled "items".
987    pub fn retained_items(&self) -> usize {
988        self.reservoir.len() + self.topk.len() + self.histogram.len()
989    }
990
991    /// Honest count of bytes retained across every accumulator.
992    pub fn retained_bytes(&self) -> usize {
993        self.hll.retained_bytes()
994            + self.topk.retained_bytes()
995            + self.reservoir.retained_bytes()
996            + self.histogram.retained_bytes()
997            + self.string_shape.retained_bytes()
998            + self.ts_min.as_ref().map_or(0, String::len)
999            + self.ts_max.as_ref().map_or(0, String::len)
1000    }
1001
1002    fn confidence(&self) -> f64 {
1003        let non_null = self.total.saturating_sub(self.nulls);
1004        1.0 - 1.0 / (1.0 + non_null as f64)
1005    }
1006
1007    /// Consume the sketches into neutral, bounded [`ColumnEvidence`].
1008    pub fn finish(self) -> ColumnEvidence {
1009        let null_rate = if self.total == 0 {
1010            0.0
1011        } else {
1012            self.nulls as f64 / self.total as f64
1013        };
1014        let confidence = self.confidence();
1015        let distinct_estimate = self.hll.estimate();
1016
1017        let boolean = self.saw_bool.then_some(BooleanEvidence {
1018            true_count: self.bool_true,
1019            false_count: self.bool_false,
1020        });
1021        let numeric = self.saw_numeric.then(|| self.histogram.finish());
1022        let string_shape = self.saw_string.then(|| self.string_shape.finish());
1023        let timestamp_range = if self.saw_ts {
1024            match (self.ts_min, self.ts_max) {
1025                (Some(min), Some(max)) => Some(TimestampRangeEvidence { min, max }),
1026                _ => None,
1027            }
1028        } else {
1029            None
1030        };
1031        let json_valid_rate =
1032            (self.json_total > 0).then(|| self.json_valid as f64 / self.json_total as f64);
1033
1034        ColumnEvidence {
1035            name: String::new(),
1036            total_count: self.total,
1037            null_count: self.nulls,
1038            null_rate,
1039            distinct_estimate,
1040            sample_values: self.reservoir.finish(),
1041            truncated_sample_count: self.truncated_samples,
1042            boolean,
1043            numeric,
1044            decimal_scale: self.max_scale,
1045            string_shape,
1046            top_k: self.topk.finish(),
1047            timestamp_range,
1048            json_valid_rate,
1049            confidence,
1050        }
1051    }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056    use super::*;
1057
1058    #[test]
1059    fn hll_merge_equals_single_pass() {
1060        let mut whole = HyperLogLog::new();
1061        let mut left = HyperLogLog::new();
1062        let mut right = HyperLogLog::new();
1063        for i in 0..10_000u64 {
1064            let h = stable_hash64(TAG_INT, &i.to_le_bytes());
1065            whole.observe(h);
1066            if i % 2 == 0 {
1067                left.observe(h);
1068            } else {
1069                right.observe(h);
1070            }
1071        }
1072        left.merge(right).unwrap();
1073        assert_eq!(left.estimate(), whole.estimate());
1074    }
1075
1076    #[test]
1077    fn format_decimal_places_the_point() {
1078        assert_eq!(format_decimal(1050, 2), "10.50");
1079        assert_eq!(format_decimal(5, 3), "0.005");
1080        assert_eq!(format_decimal(-1234, 2), "-12.34");
1081        assert_eq!(format_decimal(42, 0), "42");
1082    }
1083
1084    #[test]
1085    fn truncate_bytes_respects_char_boundaries() {
1086        let (s, trunc) = truncate_bytes("héllo", 2);
1087        assert!(trunc);
1088        assert_eq!(s, "h");
1089    }
1090}