Skip to main content

relate_planner/stats/
key_stats.rs

1//! Per-key value statistics as the planner reads them (the per-key
2//! statistics ADR): the figures of one `(label, property)` over a label's
3//! nodes, and the row estimate an equality predicate on the key derives
4//! from them, each tagged with how it was produced.
5//!
6//! The collector lives in the executor; these types are the contract the
7//! [`super::PatternStats`] methods `key_stats` and `equality_estimate`
8//! return, so the planner never depends on how a figure was measured.
9
10use relate_core::Value;
11
12/// How a figure was produced, ordered by trust: a larger variant is more
13/// trustworthy, so a planner level can ask `provenance >= UpperBound`
14/// without matching.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
16pub enum Provenance {
17    /// A sketch: the distinct count is an estimate and the heavy-hitter
18    /// counts are upper bounds.
19    Sketched,
20    /// Read off a declared index or a built equality pair: the postings
21    /// are a superset of the live values (superseded versions stay until
22    /// the next prune), so counts are upper bounds.
23    UpperBound,
24    /// Reserved: no producer yet. The equality-pair bridge that reads a
25    /// built pair with no write since its build will produce it. A
26    /// declared index's answer is [`Provenance::UpperBound`], since its
27    /// postings keep superseded versions until the next prune.
28    Exact,
29}
30
31impl Provenance {
32    /// The name a surface reports the provenance under: the one spelling,
33    /// so no consumer matches the variants to invent its own.
34    pub fn name(self) -> &'static str {
35        match self {
36            Provenance::Sketched => "sketched",
37            Provenance::UpperBound => "upperBound",
38            Provenance::Exact => "exact",
39        }
40    }
41}
42
43/// A value a key holds more often than most, with a count that is an upper
44/// bound on how many admitted values equal it.
45#[derive(Clone, Debug, PartialEq)]
46pub struct HeavyValue {
47    pub value: Value,
48    pub count: u64,
49}
50
51/// The statistics of one `(label, property)`, over the values the
52/// collector's type gate admitted.
53#[derive(Clone, Debug, PartialEq)]
54pub struct KeyStats {
55    /// How the figures were produced.
56    pub provenance: Provenance,
57    /// Admitted values read.
58    pub count: u64,
59    /// Values of this key the type gate declined (long text, lists).
60    pub declined: u64,
61    /// Estimated distinct admitted values, never above `count`.
62    pub distinct: u64,
63    /// Smallest value, for a key whose values share one orderable family.
64    pub min: Option<Value>,
65    /// Largest value, under the same condition as `min`.
66    pub max: Option<Value>,
67    /// Values that are numbers: the denominator of [`KeyStats::mean`].
68    pub numeric_count: u64,
69    /// Sum of the integer values (saturating).
70    pub int_sum: i128,
71    /// Sum of the float values.
72    pub float_sum: f64,
73    /// The most frequent values, most frequent first.
74    pub heavy: Vec<HeavyValue>,
75}
76
77impl KeyStats {
78    /// The mean of the numeric values, `None` when there are none or the
79    /// sum is not finite (a key holding an infinity, or `+inf` with `-inf`,
80    /// has no meaningful mean).
81    pub fn mean(&self) -> Option<f64> {
82        if self.numeric_count == 0 {
83            return None;
84        }
85        let sum = self.int_sum as f64 + self.float_sum;
86        sum.is_finite().then(|| sum / self.numeric_count as f64)
87    }
88
89    /// The row estimate of an equality on this key, for a label of
90    /// `label_rows` nodes: the value's own count when the caller found it
91    /// among the heavy values (by the store's equality identity, which a
92    /// plain `Value` comparison does not share: an integer and an equal
93    /// float are one value there), otherwise the admitted values spread
94    /// over the distinct count. Never zero for a label that has rows (a
95    /// value the sketch did not see may still exist) and never above the
96    /// label's rows.
97    pub fn equality_rows(&self, heavy_count: Option<u64>, label_rows: u64) -> u64 {
98        let rows = heavy_count.unwrap_or_else(|| self.count.div_ceil(self.distinct.max(1)));
99        rows.clamp(u64::from(label_rows > 0), label_rows)
100    }
101}
102
103/// A row-count estimate with its provenance: the planner's reading of an
104/// equality predicate on a key.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub struct RowEstimate {
107    pub rows: u64,
108    pub provenance: Provenance,
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    fn stats(count: u64, distinct: u64, heavy: Vec<HeavyValue>) -> KeyStats {
116        KeyStats {
117            provenance: Provenance::Sketched,
118            count,
119            declined: 0,
120            distinct,
121            min: None,
122            max: None,
123            numeric_count: 0,
124            int_sum: 0,
125            float_sum: 0.0,
126            heavy,
127        }
128    }
129
130    #[test]
131    fn provenance_orders_by_trust() {
132        assert!(Provenance::Sketched < Provenance::UpperBound);
133        assert!(Provenance::UpperBound < Provenance::Exact);
134        assert!(Provenance::Exact >= Provenance::UpperBound);
135    }
136
137    #[test]
138    fn a_heavy_value_answers_with_its_own_count() {
139        let s = stats(1000, 50, Vec::new());
140        assert_eq!(s.equality_rows(Some(400), 1000), 400);
141    }
142
143    #[test]
144    fn other_values_spread_over_the_distinct_count() {
145        let s = stats(1000, 50, Vec::new());
146        assert_eq!(s.equality_rows(None, 1000), 20);
147    }
148
149    #[test]
150    fn the_estimate_is_bounded_by_the_label_and_never_zero_on_a_populated_label() {
151        let skew = stats(1000, 2, Vec::new());
152        assert_eq!(skew.equality_rows(Some(900), 500), 500);
153        let sparse = stats(3, 1_000_000, Vec::new());
154        assert_eq!(sparse.equality_rows(None, 3), 1);
155        assert_eq!(sparse.equality_rows(None, 0), 0);
156    }
157
158    #[test]
159    fn the_mean_needs_numeric_values() {
160        let mut s = stats(4, 4, Vec::new());
161        assert_eq!(s.mean(), None);
162        s.numeric_count = 4;
163        s.int_sum = 10;
164        s.float_sum = 2.0;
165        assert_eq!(s.mean(), Some(3.0));
166    }
167
168    #[test]
169    fn a_non_finite_sum_has_no_mean() {
170        let mut s = stats(2, 2, Vec::new());
171        s.numeric_count = 2;
172        s.float_sum = f64::INFINITY;
173        assert_eq!(s.mean(), None, "an infinity");
174        s.float_sum = f64::NAN;
175        assert_eq!(s.mean(), None, "+inf and -inf cancel to NaN");
176    }
177
178    use std::cell::Cell;
179    use std::sync::Arc;
180
181    use relate_ir::Expr;
182    use relate_names::{NamedToken, SmallName, Token};
183
184    use crate::stats::memo::StatsMemo;
185    use crate::stats::{ContainsCount, NoPatternStats, PatternStats};
186
187    fn named(name: &str) -> NamedToken {
188        (SmallName::from_name(name), Token::Unresolved)
189    }
190
191    /// Answers both new consults and counts how often each reached it.
192    #[derive(Default)]
193    struct Fake {
194        key_calls: Cell<u32>,
195        estimate_calls: Cell<u32>,
196        built: bool,
197    }
198
199    impl PatternStats for Fake {
200        fn label_rows(&self, _: &NamedToken) -> Option<u64> {
201            None
202        }
203        fn equality_rows(&self, _: &NamedToken, _: &NamedToken, _: &Expr) -> Option<u64> {
204            None
205        }
206        fn contains_rows(&self, _: &NamedToken, _: &NamedToken, _: &Expr) -> Option<ContainsCount> {
207            None
208        }
209        fn rel_type_rows(&self, _: &NamedToken) -> Option<u64> {
210            None
211        }
212        fn key_stats(&self, _: &NamedToken, _: &NamedToken) -> Option<Arc<KeyStats>> {
213            self.key_calls.set(self.key_calls.get() + 1);
214            self.built.then(|| Arc::new(stats(10, 5, Vec::new())))
215        }
216        fn equality_estimate(
217            &self,
218            _: &NamedToken,
219            _: &NamedToken,
220            _: &Expr,
221        ) -> Option<RowEstimate> {
222            self.estimate_calls.set(self.estimate_calls.get() + 1);
223            self.built.then_some(RowEstimate {
224                rows: 2,
225                provenance: Provenance::Sketched,
226            })
227        }
228    }
229
230    #[test]
231    fn the_defaults_are_unmeasured() {
232        let (l, p) = (named("City"), named("country"));
233        assert_eq!(NoPatternStats.key_stats(&l, &p), None);
234        assert_eq!(
235            NoPatternStats.equality_estimate(&l, &p, &Expr::Int(1)),
236            None
237        );
238    }
239
240    #[test]
241    fn the_memo_answers_repeats_of_a_built_key_from_its_table() {
242        let fake = Fake {
243            built: true,
244            ..Fake::default()
245        };
246        let memo = StatsMemo::new(&fake);
247        let (l, p) = (named("City"), named("country"));
248        for _ in 0..3 {
249            assert_eq!(memo.key_stats(&l, &p).map(|s| s.distinct), Some(5));
250            assert_eq!(
251                memo.equality_estimate(&l, &p, &Expr::Int(1))
252                    .map(|e| e.rows),
253                Some(2)
254            );
255        }
256        assert_eq!(fake.key_calls.get(), 1);
257        assert_eq!(fake.estimate_calls.get(), 1);
258        // A different operand is a different question.
259        memo.equality_estimate(&l, &p, &Expr::Int(2));
260        assert_eq!(fake.estimate_calls.get(), 2);
261    }
262
263    #[test]
264    fn the_memo_never_stores_an_unmeasured_answer() {
265        let fake = Fake::default();
266        let memo = StatsMemo::new(&fake);
267        let (l, p) = (named("City"), named("country"));
268        assert_eq!(memo.key_stats(&l, &p), None);
269        assert_eq!(memo.key_stats(&l, &p), None);
270        assert_eq!(memo.equality_estimate(&l, &p, &Expr::Int(1)), None);
271        assert_eq!(memo.equality_estimate(&l, &p, &Expr::Int(1)), None);
272        assert_eq!(fake.key_calls.get(), 2);
273        assert_eq!(fake.estimate_calls.get(), 2);
274    }
275}