1use relate_core::Value;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
16pub enum Provenance {
17 Sketched,
20 UpperBound,
24 Exact,
29}
30
31impl Provenance {
32 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#[derive(Clone, Debug, PartialEq)]
46pub struct HeavyValue {
47 pub value: Value,
48 pub count: u64,
49}
50
51#[derive(Clone, Debug, PartialEq)]
54pub struct KeyStats {
55 pub provenance: Provenance,
57 pub count: u64,
59 pub declined: u64,
61 pub distinct: u64,
63 pub min: Option<Value>,
65 pub max: Option<Value>,
67 pub numeric_count: u64,
69 pub int_sum: i128,
71 pub float_sum: f64,
73 pub heavy: Vec<HeavyValue>,
75}
76
77impl KeyStats {
78 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 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#[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 #[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 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}