Skip to main content

rudb_kernels/
fallback.rs

1//! How often a kernel took the row at a time path, and for which shape of input.
2//!
3//! `spec/engine/03-data-plane.md` asks for this by name, and the reason is that the alternative to
4//! counting is guessing. There are six physical forms, so thirty six form pairs per kernel, and
5//! writing a hand tuned loop for all of them is both a lot of code and a lot of places for a wrong
6//! answer to hide. Writing the handful a real query hits and a correct slow path for the rest is
7//! the right amount of code, but only if there is a way to find out that one of the rest is on the
8//! hot path of a real query. That way is this.
9//!
10//! What gets counted is the fall through, not the fast path. A counter on the fast path would cost
11//! an atomic increment per vector on the loop this whole layer exists to make fast, and it would
12//! measure something nobody needs to know. A counter on the slow path costs an atomic increment on
13//! a loop that is already allocating a `Value` per row, which is not measurable next to what it
14//! sits on.
15//!
16//! The counts are process wide and never reset by the library. A benchmark harness reads them at
17//! the end of a run and prints the ones that are not zero, which turns "we should probably
18//! specialize sequence against constant" into either a number or silence.
19//!
20//! There is a second counter and [`record`] bumps both. This one answers which form pair to go and
21//! write a specialization for, which is a question about a build rather than about a query, so it is
22//! process wide and has no idea which operator was running. [`rudb_common::slow`] answers which
23//! operator in this query is the one paying, which needs the count to be per thread so that the
24//! instrumentation shim can take a difference around a call. Neither number can be worked out from
25//! the other, they cost an add each, and the alternative to having both is reading one of them and
26//! guessing the other.
27
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use rudb_common::{Cause, slow};
31use rudb_vector::Form;
32
33/// Which kernel fell through.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum Kernel {
36    /// The comparisons, in `compare`.
37    Compare,
38    /// The scalar functions, in `scalar`.
39    Scalar,
40    /// Three-valued logic, in `logic`.
41    Logic,
42    /// The conversions, in `cast`.
43    Cast,
44    /// The aggregates.
45    Aggregate,
46    /// Turning a vector of flags into the rows it keeps, in `select`.
47    Select,
48}
49
50impl Kernel {
51    /// Every kernel that reports, in the order the table prints them.
52    const ALL: [Self; 6] =
53        [Self::Compare, Self::Scalar, Self::Logic, Self::Cast, Self::Aggregate, Self::Select];
54
55    /// The name used in the report.
56    #[must_use]
57    pub fn name(self) -> &'static str {
58        match self {
59            Self::Compare => "compare",
60            Self::Scalar => "scalar",
61            Self::Logic => "logic",
62            Self::Cast => "cast",
63            Self::Aggregate => "aggregate",
64            Self::Select => "select",
65        }
66    }
67
68    fn index(self) -> usize {
69        match self {
70            Self::Compare => 0,
71            Self::Scalar => 1,
72            Self::Logic => 2,
73            Self::Cast => 3,
74            Self::Aggregate => 4,
75            Self::Select => 5,
76        }
77    }
78
79    /// The same kernel as the metrics document names it.
80    ///
81    /// Two enums for one list of kernels is not ideal and it is the layer rule rather than a
82    /// preference. The document is written at rank 4 and this crate is at rank 3, so the vocabulary
83    /// the document is spelled in has to be somewhere both can see, which is rank 0. The test below
84    /// is what keeps the two lists the same list.
85    const fn cause(self) -> Cause {
86        match self {
87            Self::Compare => Cause::Compare,
88            Self::Scalar => Cause::Scalar,
89            Self::Logic => Cause::Logic,
90            Self::Cast => Cause::Cast,
91            Self::Aggregate => Cause::Aggregate,
92            Self::Select => Cause::Select,
93        }
94    }
95}
96
97/// Every physical form, in the order the table prints them.
98const FORMS: [Form; 6] =
99    [Form::Flat, Form::Constant, Form::Sequence, Form::Dictionary, Form::Rle, Form::BitPacked];
100
101/// The name of a form, for the report.
102fn form_name(form: Form) -> &'static str {
103    match form {
104        Form::Flat => "flat",
105        Form::Constant => "constant",
106        Form::Sequence => "sequence",
107        Form::Dictionary => "dictionary",
108        Form::Rle => "rle",
109        Form::BitPacked => "bit-packed",
110        // `Form` is not exhaustive as far as this crate is concerned, and more encodings are coming
111        // to it. A name rather than a panic means the day one lands is a day the report says
112        // `other` for a while, not a day the report aborts the process.
113        _ => "other",
114    }
115}
116
117/// The position of a form in [`FORMS`], or the slot past the end for one this build does not know.
118fn form_index(form: Form) -> usize {
119    FORMS.iter().position(|&known| known == form).unwrap_or(FORMS.len())
120}
121
122/// One counter per kernel per form pair, plus a row and a column for a form added later.
123const WIDTH: usize = FORMS.len() + 1;
124const CELLS: usize = Kernel::ALL.len() * WIDTH * WIDTH;
125
126#[cfg(not(test))]
127static COUNTS: [AtomicU64; CELLS] = [const { AtomicU64::new(0) }; CELLS];
128
129// One table per thread in a test build, and one table for the process everywhere else.
130//
131// The counts a harness wants are the counts for a run, so the table the library keeps is process
132// wide. The counts a test wants are its own, and the test harness runs tests in parallel in one
133// process, so under `cfg(test)` every thread gets a table of its own and a test sees nothing but
134// what it recorded. A test binary here is a hundred and twenty tests of which fourteen read these
135// counters and the rest call kernels, so with one shared table the fourteen fail whenever one of
136// the other hundred happens to fall through at the same moment. That is what took the 0.2.12
137// release down and it did it by failing on a machine nobody was watching.
138//
139// A lock is the other way to write this and it was the way this was written. It does not work,
140// because it only serializes the tests that take it, and the test that has to take it is every
141// test that calls a kernel rather than the ones that read the counters.
142#[cfg(test)]
143thread_local! {
144    static COUNTS: [AtomicU64; CELLS] = const { [const { AtomicU64::new(0) }; CELLS] };
145}
146
147/// Reads the table this thread counts into.
148#[cfg(not(test))]
149fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
150    read(&COUNTS)
151}
152
153/// Reads the table this thread counts into.
154#[cfg(test)]
155fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
156    COUNTS.with(read)
157}
158
159/// Where a kernel and a form pair live in the table.
160fn cell(kernel: Kernel, left: Form, right: Form) -> usize {
161    kernel.index() * WIDTH * WIDTH + form_index(left) * WIDTH + form_index(right)
162}
163
164/// Records that a kernel took the row at a time path on this pair of forms.
165///
166/// `Relaxed` because nothing reads this to make a decision while a query is running. It is a
167/// diagnostic that is read once, after, by a harness, and paying for ordering on it would be
168/// paying for a guarantee nobody uses.
169pub fn record(kernel: Kernel, left: Form, right: Form) {
170    with_counts(|counts| counts[cell(kernel, left, right)].fetch_add(1, Ordering::Relaxed));
171    slow::took(kernel.cause());
172}
173
174/// How many times a kernel fell through on this pair of forms.
175#[must_use]
176pub fn count(kernel: Kernel, left: Form, right: Form) -> u64 {
177    with_counts(|counts| counts[cell(kernel, left, right)].load(Ordering::Relaxed))
178}
179
180/// Every combination that has fallen through at least once, most frequent first.
181#[must_use]
182pub fn hot() -> Vec<(Kernel, Form, Form, u64)> {
183    let mut out = Vec::new();
184    for kernel in Kernel::ALL {
185        for left in FORMS {
186            for right in FORMS {
187                let seen = count(kernel, left, right);
188                if seen > 0 {
189                    out.push((kernel, left, right, seen));
190                }
191            }
192        }
193    }
194    out.sort_by_key(|entry| std::cmp::Reverse(entry.3));
195    out
196}
197
198/// Sets every counter back to zero.
199///
200/// For a harness that wants the counts for one query rather than for a process, and for the tests
201/// below. It is not synchronized against a running query, because a diagnostic that took a lock
202/// would be a diagnostic that changed what it measures.
203pub fn reset() {
204    with_counts(|counts| {
205        for counter in counts {
206            counter.store(0, Ordering::Relaxed);
207        }
208    });
209}
210
211/// The counts as a table, or a line saying there are none.
212#[must_use]
213pub fn report() -> String {
214    let hot = hot();
215    if hot.is_empty() {
216        return "every kernel call took a specialized path".to_owned();
217    }
218    let mut out = String::from("kernel calls that fell through to the row at a time path\n");
219    for (kernel, left, right, seen) in hot {
220        out.push_str(&format!(
221            "  {:<10} {:<10} against {:<10} {seen}\n",
222            kernel.name(),
223            form_name(left),
224            form_name(right)
225        ));
226    }
227    out
228}
229
230#[cfg(test)]
231mod tests {
232    use rudb_common::slow;
233
234    use super::{Cause, Form, Kernel, count, hot, record, report, reset};
235
236    #[test]
237    fn a_fall_through_is_counted_by_form_pair_here_and_by_kernel_where_the_document_reads_it() {
238        reset();
239        slow::reset();
240        record(Kernel::Select, Form::Dictionary, Form::Flat);
241        record(Kernel::Select, Form::Constant, Form::Flat);
242        assert_eq!(count(Kernel::Select, Form::Dictionary, Form::Flat), 1);
243        assert_eq!(count(Kernel::Select, Form::Constant, Form::Flat), 1);
244        // The other counter does not split by form, because the question it answers is which
245        // operator is paying rather than which specialization is missing.
246        assert_eq!(slow::here().get(Cause::Select), 2);
247        assert_eq!(slow::here().total(), 2);
248        reset();
249        slow::reset();
250    }
251
252    #[test]
253    fn every_kernel_names_a_cause_of_its_own() {
254        let mut named: Vec<&str> = Kernel::ALL.iter().map(|kernel| kernel.cause().name()).collect();
255        named.sort_unstable();
256        named.dedup();
257        assert_eq!(named.len(), Kernel::ALL.len());
258        for kernel in Kernel::ALL {
259            assert_eq!(kernel.name(), kernel.cause().name(), "one kernel, one name");
260        }
261    }
262
263    #[test]
264    fn a_fall_through_lands_in_the_cell_for_its_own_form_pair() {
265        reset();
266        record(Kernel::Compare, Form::Sequence, Form::Constant);
267        record(Kernel::Compare, Form::Sequence, Form::Constant);
268        record(Kernel::Cast, Form::Dictionary, Form::Flat);
269        assert_eq!(count(Kernel::Compare, Form::Sequence, Form::Constant), 2);
270        assert_eq!(count(Kernel::Cast, Form::Dictionary, Form::Flat), 1);
271        assert_eq!(count(Kernel::Compare, Form::Constant, Form::Sequence), 0);
272        assert_eq!(count(Kernel::Compare, Form::Flat, Form::Flat), 0);
273        reset();
274    }
275
276    #[test]
277    fn the_report_names_the_combination_rather_than_a_number_on_its_own() {
278        reset();
279        assert!(report().contains("every kernel call took a specialized path"));
280        for _ in 0..7 {
281            record(Kernel::Compare, Form::Sequence, Form::Constant);
282        }
283        record(Kernel::Logic, Form::Flat, Form::Dictionary);
284        let text = report();
285        assert!(text.contains("compare"), "{text}");
286        assert!(text.contains("sequence"), "{text}");
287        assert!(text.contains('7'), "{text}");
288        // Most frequent first, because the point of the table is to say what to specialize next.
289        assert_eq!(hot().first().map(|entry| entry.3), Some(7));
290        reset();
291    }
292}