Skip to main content

hawdb_core/
histogram.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! Frequency-bearing property distributions. Counts inside the distribution
5//! describe the retained row sample, not a set of distinct values.
6
7use crate::Value;
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11pub const MAX_COMPRESSED_HISTOGRAM_BUCKETS: usize = 64;
12pub const MAX_COMPRESSED_HISTOGRAM_MCV: usize = 16;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct MostCommonValue {
16    pub value: Value,
17    pub sample_count: u64,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct HistogramBucket {
22    pub lower: Value,
23    pub upper: Value,
24    pub sample_count: u64,
25    /// Distinct values in this sample bucket; never a population NDV.
26    pub sample_distinct_count: u64,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct CompressedHistogram {
31    pub population_count: u64,
32    pub non_null_count: u64,
33    pub null_count: u64,
34    pub missing_count: u64,
35    pub sample_size: u64,
36    pub most_common: Arc<[MostCommonValue]>,
37    pub buckets: Arc<[HistogramBucket]>,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PropertyEstimateSource {
42    MostCommonValue,
43    ResidualDistinctCount,
44    CompressedHistogram,
45    NullCount,
46    SampleFallback,
47}
48
49impl PropertyEstimateSource {
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::MostCommonValue => "mcv",
53            Self::ResidualDistinctCount => "residual_ndv",
54            Self::CompressedHistogram => "compressed_histogram",
55            Self::NullCount => "null_count",
56            Self::SampleFallback => "sample_fallback",
57        }
58    }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct PropertyCardinalityEstimate {
63    pub rows: u64,
64    pub source: PropertyEstimateSource,
65    pub sample_size: u64,
66    pub population_count: u64,
67}
68
69crate::impl_retained_heap_for_struct!(MostCommonValue {
70    value,
71    sample_count
72});
73crate::impl_retained_heap_for_struct!(HistogramBucket {
74    lower,
75    upper,
76    sample_count,
77    sample_distinct_count
78});
79crate::impl_retained_heap_for_struct!(CompressedHistogram {
80    population_count,
81    non_null_count,
82    null_count,
83    missing_count,
84    sample_size,
85    most_common,
86    buckets
87});
88
89impl CompressedHistogram {
90    /// Builds disjoint MCV and approximately equal-depth residual buckets.
91    /// Sampling, ownership and byte admission belong to the storage collector.
92    pub fn from_sample(
93        population_count: u64,
94        non_null_count: u64,
95        null_count: u64,
96        missing_count: u64,
97        sample: Vec<Value>,
98    ) -> Option<Self> {
99        if population_count == 0
100            || non_null_count
101                .checked_add(null_count)?
102                .checked_add(missing_count)?
103                != population_count
104            || sample.len() as u64 > non_null_count
105            || (sample.is_empty() && non_null_count != 0)
106            || sample.iter().any(|value| matches!(value, Value::Null))
107        {
108            return None;
109        }
110        let sample_size = sample.len() as u64;
111        let mut frequencies = BTreeMap::<Value, u64>::new();
112        for value in sample {
113            *frequencies.entry(value).or_default() += 1;
114        }
115        let mut most_common = Vec::new();
116        if sample_size == non_null_count && frequencies.len() <= MAX_COMPRESSED_HISTOGRAM_BUCKETS {
117            most_common.extend(frequencies.into_iter().map(|(value, sample_count)| {
118                MostCommonValue {
119                    value,
120                    sample_count,
121                }
122            }));
123            return Some(Self {
124                population_count,
125                non_null_count,
126                null_count,
127                missing_count,
128                sample_size,
129                most_common: most_common.into(),
130                buckets: Arc::from([]),
131            });
132        }
133        let threshold = sample_size.div_ceil(MAX_COMPRESSED_HISTOGRAM_BUCKETS as u64);
134        let mut hot = frequencies
135            .iter()
136            .filter(|(_, count)| **count > threshold)
137            .map(|(value, count)| (value.clone(), *count))
138            .collect::<Vec<_>>();
139        hot.sort_by(|(left_value, left_count), (right_value, right_count)| {
140            right_count
141                .cmp(left_count)
142                .then_with(|| left_value.cmp(right_value))
143        });
144        hot.truncate(MAX_COMPRESSED_HISTOGRAM_MCV);
145        for (value, sample_count) in hot {
146            frequencies.remove(&value);
147            most_common.push(MostCommonValue {
148                value,
149                sample_count,
150            });
151        }
152        most_common.sort_by(|left, right| left.value.cmp(&right.value));
153        let residual_count = frequencies.values().sum::<u64>();
154        let bucket_limit = MAX_COMPRESSED_HISTOGRAM_BUCKETS - most_common.len();
155        let target = residual_count.div_ceil(bucket_limit as u64).max(1);
156        let mut buckets = Vec::<HistogramBucket>::new();
157        for (value, count) in frequencies {
158            let at_limit = buckets.len() == bucket_limit;
159            if let Some(bucket) = buckets.last_mut()
160                && (bucket.sample_count < target || at_limit)
161            {
162                bucket.upper = value;
163                bucket.sample_count += count;
164                bucket.sample_distinct_count += 1;
165            } else {
166                buckets.push(HistogramBucket {
167                    lower: value.clone(),
168                    upper: value,
169                    sample_count: count,
170                    sample_distinct_count: 1,
171                });
172            }
173        }
174        Some(Self {
175            population_count,
176            non_null_count,
177            null_count,
178            missing_count,
179            sample_size,
180            most_common: most_common.into(),
181            buckets: buckets.into(),
182        })
183    }
184
185    pub fn is_sampled(&self) -> bool {
186        self.sample_size < self.non_null_count
187    }
188
189    /// Recovered metadata is optional derived state, never a semantic proof.
190    pub fn is_valid(&self) -> bool {
191        if self.population_count == 0
192            || self
193                .non_null_count
194                .checked_add(self.null_count)
195                .and_then(|count| count.checked_add(self.missing_count))
196                != Some(self.population_count)
197            || self.sample_size > self.non_null_count
198            || (self.sample_size == 0 && self.non_null_count != 0)
199            || self.most_common.len() + self.buckets.len() > MAX_COMPRESSED_HISTOGRAM_BUCKETS
200            || self
201                .most_common
202                .windows(2)
203                .any(|pair| pair[0].value >= pair[1].value)
204            || self
205                .buckets
206                .windows(2)
207                .any(|pair| pair[0].upper >= pair[1].lower)
208        {
209            return false;
210        }
211        let mut weight = 0_u64;
212        for entry in self.most_common.iter() {
213            if entry.sample_count == 0 || matches!(entry.value, Value::Null) {
214                return false;
215            }
216            let Some(next) = weight.checked_add(entry.sample_count) else {
217                return false;
218            };
219            weight = next;
220        }
221        for bucket in self.buckets.iter() {
222            if bucket.lower > bucket.upper
223                || bucket.sample_count == 0
224                || bucket.sample_distinct_count == 0
225                || bucket.sample_distinct_count > bucket.sample_count
226                || (bucket.lower == bucket.upper && bucket.sample_distinct_count != 1)
227                || self
228                    .most_common
229                    .binary_search_by(|entry| entry.value.cmp(&bucket.lower))
230                    .is_ok()
231                || self
232                    .most_common
233                    .binary_search_by(|entry| entry.value.cmp(&bucket.upper))
234                    .is_ok()
235                || matches!(bucket.lower, Value::Null)
236                || matches!(bucket.upper, Value::Null)
237            {
238                return false;
239            }
240            let Some(next) = weight.checked_add(bucket.sample_count) else {
241                return false;
242            };
243            weight = next;
244        }
245        weight == self.sample_size
246    }
247
248    fn estimate(
249        &self,
250        input_rows: u64,
251        numerator: u64,
252        denominator: u64,
253        source: PropertyEstimateSource,
254    ) -> PropertyCardinalityEstimate {
255        let rows = if denominator == 0 {
256            0
257        } else {
258            (u128::from(input_rows) * u128::from(numerator))
259                .div_ceil(u128::from(denominator))
260                .min(u128::from(input_rows)) as u64
261        };
262        PropertyCardinalityEstimate {
263            rows,
264            source,
265            sample_size: self.sample_size,
266            population_count: self.population_count,
267        }
268    }
269
270    fn sample_estimate(
271        &self,
272        input_rows: u64,
273        sample_weight: u64,
274        source: PropertyEstimateSource,
275    ) -> PropertyCardinalityEstimate {
276        // First scale to the non-NULL population, then apply the sample fraction.
277        let non_null_rows = self
278            .estimate(
279                input_rows,
280                self.non_null_count,
281                self.population_count,
282                source,
283            )
284            .rows;
285        self.estimate(non_null_rows, sample_weight, self.sample_size, source)
286    }
287
288    pub fn equality(
289        &self,
290        value: &Value,
291        input_rows: u64,
292        distinct_count: Option<u64>,
293    ) -> PropertyCardinalityEstimate {
294        if matches!(value, Value::Null) {
295            return self.estimate(input_rows, 0, 1, PropertyEstimateSource::NullCount);
296        }
297        if let Ok(index) = self
298            .most_common
299            .binary_search_by(|entry| entry.value.cmp(value))
300        {
301            return self.sample_estimate(
302                input_rows,
303                self.most_common[index].sample_count,
304                PropertyEstimateSource::MostCommonValue,
305            );
306        }
307        let hot_weight = self
308            .most_common
309            .iter()
310            .map(|entry| entry.sample_count)
311            .sum::<u64>();
312        let residual_weight = self.sample_size.saturating_sub(hot_weight);
313        let source = if distinct_count.is_some() {
314            PropertyEstimateSource::ResidualDistinctCount
315        } else {
316            PropertyEstimateSource::SampleFallback
317        };
318        if let Some(ndv) = distinct_count
319            .or(Some(self.non_null_count))
320            .and_then(|ndv| ndv.checked_sub(self.most_common.len() as u64))
321            .filter(|ndv| *ndv > 0)
322        {
323            let mut estimate = self.sample_estimate(input_rows, residual_weight, source);
324            estimate.rows = estimate.rows.div_ceil(ndv);
325            if estimate.rows != 0 || !self.is_sampled() {
326                return estimate;
327            }
328        }
329        // An unobserved sample value is unknown, not evidence of absence.
330        if self.is_sampled() {
331            self.sample_estimate(input_rows, 1, PropertyEstimateSource::SampleFallback)
332        } else {
333            self.estimate(
334                input_rows,
335                0,
336                1,
337                PropertyEstimateSource::ResidualDistinctCount,
338            )
339        }
340    }
341
342    pub fn nulls(&self, input_rows: u64) -> PropertyCardinalityEstimate {
343        self.estimate(
344            input_rows,
345            self.null_count.saturating_add(self.missing_count),
346            self.population_count,
347            PropertyEstimateSource::NullCount,
348        )
349    }
350
351    pub fn range(
352        &self,
353        lower: Option<(&Value, bool)>,
354        upper: Option<(&Value, bool)>,
355        input_rows: u64,
356    ) -> PropertyCardinalityEstimate {
357        let accepts = |value: &Value| {
358            lower.is_none_or(|(bound, inclusive)| value > bound || (inclusive && value == bound))
359                && upper
360                    .is_none_or(|(bound, inclusive)| value < bound || (inclusive && value == bound))
361        };
362        let mut weight = self
363            .most_common
364            .iter()
365            .filter(|entry| accepts(&entry.value))
366            .map(|entry| entry.sample_count as f64)
367            .sum::<f64>();
368        for bucket in self.buckets.iter() {
369            let fraction = bucket_fraction(bucket, lower, upper);
370            weight += bucket.sample_count as f64 * fraction;
371        }
372        self.sample_estimate(
373            input_rows,
374            (weight.ceil() as u64).min(self.sample_size),
375            PropertyEstimateSource::CompressedHistogram,
376        )
377    }
378}
379
380fn numeric_position(lower: &Value, upper: &Value, value: &Value) -> Option<f64> {
381    let position = match (lower, upper, value) {
382        (Value::Int(low), Value::Int(high), Value::Int(value)) if high > low => {
383            (i128::from(*value) - i128::from(*low)) as f64
384                / (i128::from(*high) - i128::from(*low)) as f64
385        }
386        (Value::Float(low), Value::Float(high), Value::Float(value))
387            if low.is_finite() && high.is_finite() && value.is_finite() && high > low =>
388        {
389            if (high - low).is_finite() {
390                (value - low) / (high - low)
391            } else {
392                (value * 0.5 - low * 0.5) / (high * 0.5 - low * 0.5)
393            }
394        }
395        _ => return None,
396    };
397    position.is_finite().then(|| position.clamp(0.0, 1.0))
398}
399
400fn bucket_fraction(
401    bucket: &HistogramBucket,
402    lower: Option<(&Value, bool)>,
403    upper: Option<(&Value, bool)>,
404) -> f64 {
405    let cdf = |value: &Value, inclusive: bool| {
406        if value < &bucket.lower {
407            return 0.0;
408        }
409        if value > &bucket.upper {
410            return 1.0;
411        }
412        if bucket.lower == bucket.upper {
413            return if inclusive { 1.0 } else { 0.0 };
414        }
415        let atom = 1.0 / bucket.sample_distinct_count as f64;
416        if value == &bucket.lower {
417            return if inclusive { atom } else { 0.0 };
418        }
419        if value == &bucket.upper {
420            return if inclusive { 1.0 } else { 1.0 - atom };
421        }
422        let position = numeric_position(&bucket.lower, &bucket.upper, value).unwrap_or(0.5);
423        (position * (1.0 - atom) + if inclusive { atom } else { 0.0 }).clamp(0.0, 1.0)
424    };
425    let low = lower.map_or(0.0, |(value, inclusive)| cdf(value, !inclusive));
426    let high = upper.map_or(1.0, |(value, inclusive)| cdf(value, inclusive));
427    (high - low).clamp(0.0, 1.0)
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn residual_endpoints_and_wide_float_interpolation_keep_full_and_empty_ranges() {
436        let strings = HistogramBucket {
437            lower: Value::String("a".into()),
438            upper: Value::String("z".into()),
439            sample_count: 10,
440            sample_distinct_count: 10,
441        };
442        assert_eq!(
443            bucket_fraction(&strings, None, Some((&strings.lower, false))),
444            0.0
445        );
446        assert_eq!(
447            bucket_fraction(&strings, Some((&strings.upper, false)), None),
448            0.0
449        );
450        assert_eq!(
451            bucket_fraction(&strings, None, Some((&strings.upper, true))),
452            1.0
453        );
454        let floats = HistogramBucket {
455            lower: Value::Float(-f64::MAX),
456            upper: Value::Float(f64::MAX),
457            sample_count: 10,
458            sample_distinct_count: 10,
459        };
460        assert_eq!(
461            bucket_fraction(&floats, None, Some((&floats.lower, false))),
462            0.0
463        );
464        assert_eq!(
465            bucket_fraction(&floats, None, Some((&floats.upper, true))),
466            1.0
467        );
468        let middle = bucket_fraction(&floats, None, Some((&Value::Float(0.0), true)));
469        assert!(middle > 0.5 && middle < 0.6, "{middle}");
470    }
471
472    #[test]
473    fn complete_nulls_and_singletons_conserve_population() {
474        let nulls = CompressedHistogram::from_sample(10, 0, 4, 6, vec![]).unwrap();
475        assert!(nulls.is_valid());
476        assert_eq!(nulls.nulls(100).rows, 100);
477        assert_eq!(nulls.range(None, None, 100).rows, 0);
478        let histogram = CompressedHistogram::from_sample(
479            10,
480            6,
481            2,
482            2,
483            vec![
484                Value::Int(1),
485                Value::Int(1),
486                Value::Int(2),
487                Value::Int(3),
488                Value::Int(3),
489                Value::Int(3),
490            ],
491        )
492        .unwrap();
493        assert!(histogram.is_valid());
494        assert_eq!(histogram.equality(&Value::Int(3), 10, Some(3)).rows, 3);
495        assert_eq!(
496            histogram
497                .range(
498                    Some((&Value::Int(1), false)),
499                    Some((&Value::Int(3), false)),
500                    10
501                )
502                .rows,
503            1
504        );
505        assert_eq!(
506            histogram
507                .range(
508                    Some((&Value::Int(3), true)),
509                    Some((&Value::Int(1), true)),
510                    10
511                )
512                .rows,
513            0
514        );
515        assert_eq!(
516            histogram.range(None, None, 10).rows + histogram.nulls(10).rows,
517            10
518        );
519    }
520
521    #[test]
522    fn rare_sample_values_are_not_population_mcv_or_ndv() {
523        let histogram = CompressedHistogram::from_sample(
524            10_000,
525            10_000,
526            0,
527            0,
528            (0..64).map(Value::Int).collect(),
529        )
530        .unwrap();
531        assert!(histogram.most_common.is_empty());
532        assert!(histogram.is_sampled());
533        assert_eq!(
534            histogram
535                .equality(&Value::Int(1), 10_000, Some(10_000))
536                .rows,
537            1
538        );
539        assert!(histogram.equality(&Value::Int(10_001), 10_000, None).rows > 0);
540    }
541
542    #[test]
543    fn hot_values_are_separate_from_residual_buckets() {
544        let sample = std::iter::repeat_n(Value::Int(1000), 900)
545            .chain((0..100).map(Value::Int))
546            .collect();
547        let histogram = CompressedHistogram::from_sample(1000, 1000, 0, 0, sample).unwrap();
548        assert!(histogram.is_valid());
549        assert_eq!(
550            histogram.equality(&Value::Int(1000), 1000, Some(101)).rows,
551            900
552        );
553        assert_eq!(
554            histogram
555                .range(None, Some((&Value::Int(100), false)), 1000)
556                .rows,
557            100
558        );
559        assert_eq!(histogram.most_common.len(), 1);
560        assert!(histogram
561            .buckets
562            .iter()
563            .all(|bucket| bucket.upper < Value::Int(1000)));
564    }
565
566    #[test]
567    fn null_missing_and_unobserved_sample_values_are_distinct_cases() {
568        let histogram =
569            CompressedHistogram::from_sample(1000, 800, 100, 100, vec![Value::Bool(true); 64])
570                .unwrap();
571        assert!(histogram.is_sampled());
572        assert_eq!(histogram.nulls(1000).rows, 200);
573        assert_eq!(
574            histogram.equality(&Value::Bool(true), 1000, Some(2)).rows,
575            800
576        );
577        assert!(histogram.equality(&Value::Bool(false), 1000, Some(2)).rows > 0);
578        assert_eq!(histogram.equality(&Value::Null, 1000, Some(2)).rows, 0);
579    }
580
581    #[test]
582    fn integer_ranges_near_i64_max_keep_monotone_estimates() {
583        let sample = (0..256).map(|i| Value::Int(i64::MAX - 255 + i)).collect();
584        let histogram = CompressedHistogram::from_sample(256, 256, 0, 0, sample).unwrap();
585        let mut previous = 0;
586        for offset in 0..256 {
587            let rows = histogram
588                .range(
589                    None,
590                    Some((&Value::Int(i64::MAX - 255 + offset), true)),
591                    256,
592                )
593                .rows;
594            assert!(rows >= previous && rows <= 256);
595            previous = rows;
596        }
597        assert_eq!(previous, 256);
598    }
599}