Skip to main content

rudb_native/
zones.rs

1//! Showing the planner what a native table already wrote down about itself.
2//!
3//! Every stripe carries the two ends and the null count of every column, in the directory, in
4//! memory from the moment the file is opened. The scan has been reading them since the format
5//! existed and the planner has never seen them, so a query over a native table was ordered from the
6//! same constants a query over a table nobody had measured would get.
7//!
8//! Two things come out of that directory here. [`Stripes`] answers how many rows a set of tests
9//! keeps, which is what a filter's estimate rests on. [`distincts`] answers how many values a column
10//! holds, which is what a join's estimate rests on. They are in one module because they are one
11//! idea, and because TPC-H q05 needs both of them and is the reason either exists.
12//!
13//! [`Common`] came later and is not out of the directory. It answers how many rows hold one
14//! particular value, off the frequency synopsis the writer takes per column, and it belongs here
15//! because it is the same idea pointed at the same reader: a number the file already holds that the
16//! planner was assuming its way past.
17//!
18//! # What q05 actually needed
19//!
20//! The filter is the easy half. The `o_orderdate` range over SF1 keeps 227,597 rows of 1,500,000.
21//! Through Parquet the footer gives 227,556 and through the native file the estimate was 60,000,
22//! which is the constant for a range nobody could read. [`Stripes`] closes that: the same query now
23//! estimates 227,556 from the stripe bounds, off the true answer by forty one rows in two hundred
24//! thousand.
25//!
26//! Closing it changed nothing. q05 measured 5,217 ms with the filter estimate fixed against 4,491
27//! before, which is the same plan and a loaded laptop. The join order was never reading the filter.
28//! It was reading the distinct counts, and the containment assumption in `estimate::matched` only
29//! gives way to `left * right / keys` where both key columns have one. DuckDB writes distinct counts
30//! into a Parquet footer, so the Parquet plan divides the customer against supplier join by the 25
31//! nations and scores it at sixty million, which is enough for the search to put customer against
32//! orders first instead. The native file stated no count for an integer column, the divisor fell
33//! back to the table's own row count, and the same join scored 150,000. So the search took it first
34//! and built the twelve million row intermediate that is the whole of q05's time.
35//!
36//! # Why the stripe and not the part
37//!
38//! A stripe's bounds are in the directory and a part's are a page in the file. The planner is
39//! deciding what to read and reading a page per column per stripe to decide it would be the scan
40//! run twice, so this answers from the stripe alone and never touches the file. The loss is smaller
41//! than it sounds: the interpolation below is what the estimate mostly rests on, and interpolating
42//! inside sixteen stripes and inside nine hundred parts of the same column give nearly the same
43//! fraction when the rows are in no particular order, which is the case this exists for. A part
44//! bound is worth reading when the question is which parts to skip, and that question is the scan's
45//! and is already answered by [`Reader::skips`].
46
47use std::cmp::Ordering;
48
49use rudb_common::Result;
50use rudb_common::bounds::{Bound, End, Frequencies, Remainder, Spread, Test, Zones, kept};
51use rudb_common::stat::{Direction, Provenance};
52use rudb_common::{Stat, Value};
53use rudb_storage::Probe;
54
55use crate::Reader;
56
57/// The bounds of a committed native table, as the planner asks for them.
58///
59/// Holds the reader rather than a copy of the bounds. A reader is a handful of reference counts and
60/// cloning one shares the caches it has already filled, where copying the bounds out would be every
61/// stripe of every column of the table per statement bound.
62#[derive(Debug, Clone)]
63pub struct Stripes {
64    reader: Reader,
65}
66
67impl Stripes {
68    /// The bounds of a table somebody has open.
69    #[must_use]
70    pub fn new(reader: Reader) -> Self {
71        Self { reader }
72    }
73}
74
75impl Zones for Stripes {
76    fn column(&self, name: &str) -> Option<usize> {
77        self.reader.table().fields().iter().position(|field| field.name == name)
78    }
79
80    fn surviving(&self, tests: &[Test]) -> Option<u64> {
81        let probes = probes(tests);
82        let mut total: u64 = 0;
83        for (at, stripe) in self.reader.table().stripes().iter().enumerate() {
84            if self.reader.stripe_skips(at, &probes) {
85                continue;
86            }
87            total = total.checked_add(u64::try_from(stripe.rows()).ok()?)?;
88        }
89        Some(total)
90    }
91
92    fn spread(&self, tests: &[Test]) -> Option<Spread> {
93        let mut passing = 0.0_f64;
94        let mut whole = 0.0_f64;
95        let mut read = 0;
96        for stripe in self.reader.table().stripes() {
97            let rows = rows(stripe.rows());
98            let spread = fraction(tests, stripe.zone());
99            whole += rows;
100            passing += rows * spread.fraction;
101            // The most any one stripe could read rather than a total of them, the same as the
102            // Parquet footer does it and for the same reason: the caller is charging its constant
103            // for the tests nobody answered, so the question is whether anybody answered this one.
104            read = read.max(spread.read);
105        }
106        (read > 0 && whole > 0.0)
107            .then(|| Spread { fraction: (passing / whole).clamp(0.0, 1.0), read })
108    }
109
110    fn nulls(&self, column: usize) -> Stat<u64> {
111        // Every stripe of a native file states its null count, so this is exact or the column is
112        // not there. A reader that cannot answer its own directory fails the scan a moment later
113        // with the same error, and the planner is not the place to raise it.
114        self.reader
115            .null_count(column)
116            .map_or(Stat::Unknown, |nulls| Stat::exact(nulls, Provenance::NullCount))
117    }
118
119    fn extreme(&self, column: usize, end: End) -> Stat<Bound> {
120        // The reader folds the stripes itself and answers only where every one of them wrote a
121        // bound its writer called exact, which is the same promise this has to make. A column whose
122        // ends were widened, or whose stripes do not compare against each other, comes back `None`
123        // there and unknown here.
124        match self.reader.exact_extremes(column) {
125            Ok(Some((low, high))) => {
126                Stat::exact(if end == End::Low { low } else { high }, Provenance::ZoneMap)
127            }
128            _ => Stat::Unknown,
129        }
130    }
131}
132
133/// How many distinct values each column of a native table holds, for the columns it can say.
134///
135/// Two sources, and a column with neither is left out rather than guessed at. An absent column
136/// reads back as unknown and the estimator falls back to the table's row count, which is what every
137/// column did before this existed.
138///
139/// A string column has a global dictionary and the directory records how many codes any row of it
140/// actually holds, so that count is exact and comes back as such. The dictionary page is not opened
141/// to answer, which matters: this runs once per table per statement bound.
142///
143/// Every other column is answered from its two ends, where they are integers. A column of integers
144/// between `low` and `high` cannot hold more than `high - low + 1` distinct values, so the span is a
145/// ceiling, and on the columns that decide a join order it is a tight one. TPC-H nationkey runs 0 to
146/// 24 and holds 25 values, regionkey 0 to 4 and holds 5. On `l_orderkey` the span is six million
147/// against a true one and a half, which is loose and still safe, for the reason below.
148///
149/// # Why a ceiling is the safe end here
150///
151/// The two readers of a distinct count both divide by it. A divisor that is too large makes the
152/// join look smaller, and `estimate::matched` takes the larger of that and the containment
153/// assumption, so too large a span can only fail to raise an estimate and can never lower one below
154/// what shape alone already said. Too small a divisor is the dangerous direction and a span cannot
155/// be too small: a widened bound is wider than the truth, never narrower, so the span it implies is
156/// a ceiling however the bound was written.
157///
158/// A span at or above the table's row count is dropped rather than recorded. The row count is what
159/// the estimator already falls back to for a column nobody counted, so recording it would be an
160/// entry that says what its own absence says.
161///
162/// # Errors
163///
164/// Never, today. The two reads it makes are indexed by a column this loop produced, so neither can
165/// be out of range, and the signature carries the `Result` because both of them do.
166pub fn distincts(reader: &Reader) -> Result<Vec<(String, Stat<u64>)>> {
167    let table = reader.table();
168    let rows = u64::try_from(table.rows()).unwrap_or(u64::MAX);
169    let mut counted = Vec::new();
170    for (at, field) in table.fields().iter().enumerate() {
171        if let Some(exact) = reader.distinct_values(at)? {
172            counted.push((field.name.clone(), Stat::exact(exact, Provenance::Dictionary)));
173            continue;
174        }
175        let Some((Bound::Int(low), Bound::Int(high))) = reader.exact_extremes(at)? else {
176            continue;
177        };
178        let Some(span) = high.checked_sub(low).and_then(|span| u64::try_from(span).ok()) else {
179            continue;
180        };
181        let Some(span) = span.checked_add(1).filter(|&span| span < rows) else {
182            continue;
183        };
184        // The weakest certificate there is: certain from above with the relative error unbounded,
185        // which is the class a ceiling with nothing under it takes everywhere else in the tree.
186        counted.push((
187            field.name.clone(),
188            Stat::certified(span, 1.0, Direction::AtMost, Provenance::ZoneMap),
189        ));
190    }
191    Ok(counted)
192}
193
194/// The columns whose values never go down in row order and hold no null, by name.
195///
196/// This is what lets an aggregate grouped on one of them close a group as soon as the key changes,
197/// and the claim it rests on is the summary's, which read every value in rid order when the table
198/// was written. A summary that is stale, missing or one this build cannot decode leaves its column
199/// out, so the answer can only be too short and a column left out is grouped the way it always was.
200/// A null anywhere is also out, since the summary's order only speaks for the values that are there
201/// and a null that sat between two of them would split a run the grouping thinks is whole.
202#[must_use]
203pub fn ascending(reader: &Reader) -> Vec<String> {
204    reader
205        .table()
206        .fields()
207        .iter()
208        .enumerate()
209        .filter(|&(at, _)| {
210            crate::stats::summary(reader, at).is_some_and(|summary| {
211                summary.nulls == 0 && summary.order == rudb_stats::summary::Order::Ascending
212            })
213        })
214        .map(|(_, field)| field.name.clone())
215        .collect()
216}
217
218/// What a native table's frequency synopsis says about one value, as the planner asks for it.
219///
220/// Holds the reader for the reason [`Stripes`] does. The synopsis is small where it exists at all,
221/// but it exists per column and copying every column's into every plan would be paying for the
222/// columns nothing filters on, which is most of them.
223#[derive(Debug, Clone)]
224pub struct Common {
225    reader: Reader,
226}
227
228impl Common {
229    /// The frequencies of a table somebody has open.
230    #[must_use]
231    pub fn new(reader: Reader) -> Self {
232        Self { reader }
233    }
234}
235
236impl Frequencies for Common {
237    fn column(&self, name: &str) -> Option<usize> {
238        self.reader.table().fields().iter().position(|field| field.name == name)
239    }
240
241    fn rows(&self) -> u64 {
242        u64::try_from(self.reader.table().rows()).unwrap_or(u64::MAX)
243    }
244
245    fn rows_with(&self, column: usize, value: &Bound) -> Stat<u64> {
246        // The prefix and not only the complete list, because the counts in it are exact either way.
247        // The writer recounts the candidates that survive its pass, so what an incomplete synopsis
248        // lost is values rather than counts, and a value it kept is one of the leading values of the
249        // column, which is the one an equality would otherwise guess worst about.
250        let Ok(Some(prefix)) = self.reader.frequency_prefix(column) else {
251            return Stat::Unknown;
252        };
253        let mut comparable = false;
254        for (held, count) in prefix.entries {
255            // A null entry is the column's nulls, and no equality matches a null. Skipping it is
256            // both the right answer and the only one available, since a null has no bound.
257            let Some(bound) = Bound::of_value(&held) else {
258                continue;
259            };
260            match bound.order(value) {
261                Some(Ordering::Equal) => return Stat::exact(count, Provenance::FrequencySynopsis),
262                Some(_) => comparable = true,
263                None => {}
264            }
265        }
266        // Nothing in the list was the value. That is a count of zero when the list left nothing out
267        // and the constant was in the same domain, because a complete synopsis accounts for every
268        // row. Where the list left something out, the value is somewhere between no rows and the
269        // bound the writer recorded, and a prefix has nothing to say about which. Where not one
270        // entry would even compare, the constant is of another type and the zero would be an
271        // artefact of that rather than a fact about the rows.
272        if prefix.omitted_max == 0 && comparable {
273            Stat::exact(0, Provenance::FrequencySynopsis)
274        } else {
275            Stat::Unknown
276        }
277    }
278
279    fn remainder(&self, column: usize) -> Option<Remainder> {
280        let Ok(Some(prefix)) = self.reader.frequency_prefix(column) else {
281            return None;
282        };
283        // A complete list has nothing outside it, and saying so as a remainder of no rows over no
284        // values would hand the caller a division it has to special case. `rows_with` answers that
285        // column outright.
286        if prefix.omitted_max == 0 {
287            return None;
288        }
289        let mut held: u64 = 0;
290        let mut listed: u64 = 0;
291        for (value, count) in &prefix.entries {
292            held = held.saturating_add(*count);
293            // The null entry's rows come out of the pool and the null itself is not one of the
294            // values, because the counts this is subtracted from do not count it as one. A null in
295            // the list is also the common case rather than an edge: a column with nulls in it usually
296            // has more of them than of anything else.
297            if !matches!(value, Value::Null) {
298                listed += 1;
299            }
300        }
301        // Saturating because two reads of one table disagreeing about its rows is not a reason to
302        // report a tail larger than the column.
303        let rows = Frequencies::rows(self).saturating_sub(held);
304        Some(Remainder { rows, listed, most: prefix.omitted_max })
305    }
306}
307
308/// The tests as the storage layer spells them, which is the same three fields under another name.
309fn probes(tests: &[Test]) -> Vec<Probe> {
310    tests
311        .iter()
312        .map(|test| Probe { column: test.column, op: test.op, value: test.value.clone() })
313        .collect()
314}
315
316/// A stripe's row count as a weight, and zero for one that does not read as a count.
317#[expect(clippy::cast_precision_loss, reason = "a row count is a weight here and not an identity")]
318fn rows(count: usize) -> f64 {
319    count as f64
320}
321
322/// The fraction of one stripe these tests are expected to keep, and how many of them said so.
323///
324/// Tests on one column are intersected by [`kept`] and tests on different columns are multiplied
325/// here, which assumes the columns are independent of each other. That is the assumption the
326/// estimator makes everywhere else and the one that fails first, and a pair of bounds cannot do
327/// anything about it either way.
328///
329/// A stripe this cannot read keeps a fraction of one rather than dropping out of the total. Leaving
330/// it out would report the fraction of the stripes that were read as the fraction of the table.
331fn fraction(tests: &[Test], zone: &rudb_storage::Zone) -> Spread {
332    let mut spread = Spread { fraction: 1.0, read: 0 };
333    for (position, test) in tests.iter().enumerate() {
334        // Once per column rather than once per test, because `kept` is handed every test on the
335        // column and answers for all of them at once. The first mention of a column is the one that
336        // asks and the rest are already in that answer.
337        if tests[..position].iter().any(|earlier| earlier.column == test.column) {
338            continue;
339        }
340        let Some(range) = zone.column(test.column) else { continue };
341        let (Some(low), Some(high)) = (range.low.as_ref(), range.high.as_ref()) else { continue };
342        let Some(kept) = kept(tests, test.column, low, high) else { continue };
343        spread.fraction *= kept.fraction;
344        spread.read += kept.read;
345    }
346    spread
347}