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 four physical forms, so sixteen form pairs per kernel, and
5//! writing a hand tuned loop for all sixteen is both a lot of code and a lot of places for a wrong
6//! answer to hide. Writing three of them and a correct slow path for the rest is the right amount
7//! of code, but only if there is a way to find out that the fourth is on the hot path of a real
8//! 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
20use std::sync::atomic::{AtomicU64, Ordering};
21
22use rudb_vector::Form;
23
24/// Which kernel fell through.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum Kernel {
27 /// The comparisons, in `compare`.
28 Compare,
29 /// The scalar functions, in `scalar`.
30 Scalar,
31 /// Three-valued logic, in `logic`.
32 Logic,
33 /// The conversions, in `cast`.
34 Cast,
35 /// The aggregates.
36 Aggregate,
37 /// Turning a vector of flags into the rows it keeps, in `select`.
38 Select,
39}
40
41impl Kernel {
42 /// Every kernel that reports, in the order the table prints them.
43 const ALL: [Self; 6] =
44 [Self::Compare, Self::Scalar, Self::Logic, Self::Cast, Self::Aggregate, Self::Select];
45
46 /// The name used in the report.
47 #[must_use]
48 pub fn name(self) -> &'static str {
49 match self {
50 Self::Compare => "compare",
51 Self::Scalar => "scalar",
52 Self::Logic => "logic",
53 Self::Cast => "cast",
54 Self::Aggregate => "aggregate",
55 Self::Select => "select",
56 }
57 }
58
59 fn index(self) -> usize {
60 match self {
61 Self::Compare => 0,
62 Self::Scalar => 1,
63 Self::Logic => 2,
64 Self::Cast => 3,
65 Self::Aggregate => 4,
66 Self::Select => 5,
67 }
68 }
69}
70
71/// Every physical form, in the order the table prints them.
72const FORMS: [Form; 4] = [Form::Flat, Form::Constant, Form::Sequence, Form::Dictionary];
73
74/// The name of a form, for the report.
75fn form_name(form: Form) -> &'static str {
76 match form {
77 Form::Flat => "flat",
78 Form::Constant => "constant",
79 Form::Sequence => "sequence",
80 Form::Dictionary => "dictionary",
81 // `Form` is not exhaustive as far as this crate is concerned, and layer three adds
82 // `Encoded` to it. A name rather than a panic means the day that lands is a day the report
83 // says `other` for a while, not a day the report aborts the process.
84 _ => "other",
85 }
86}
87
88/// The position of a form in [`FORMS`], or four for one this build does not know about.
89fn form_index(form: Form) -> usize {
90 FORMS.iter().position(|&known| known == form).unwrap_or(FORMS.len())
91}
92
93/// One counter per kernel per form pair, plus a row and a column for a form added later.
94const WIDTH: usize = FORMS.len() + 1;
95const CELLS: usize = Kernel::ALL.len() * WIDTH * WIDTH;
96
97#[cfg(not(test))]
98static COUNTS: [AtomicU64; CELLS] = [const { AtomicU64::new(0) }; CELLS];
99
100// One table per thread in a test build, and one table for the process everywhere else.
101//
102// The counts a harness wants are the counts for a run, so the table the library keeps is process
103// wide. The counts a test wants are its own, and the test harness runs tests in parallel in one
104// process, so under `cfg(test)` every thread gets a table of its own and a test sees nothing but
105// what it recorded. A test binary here is a hundred and twenty tests of which fourteen read these
106// counters and the rest call kernels, so with one shared table the fourteen fail whenever one of
107// the other hundred happens to fall through at the same moment. That is what took the 0.2.12
108// release down and it did it by failing on a machine nobody was watching.
109//
110// A lock is the other way to write this and it was the way this was written. It does not work,
111// because it only serializes the tests that take it, and the test that has to take it is every
112// test that calls a kernel rather than the ones that read the counters.
113#[cfg(test)]
114thread_local! {
115 static COUNTS: [AtomicU64; CELLS] = const { [const { AtomicU64::new(0) }; CELLS] };
116}
117
118/// Reads the table this thread counts into.
119#[cfg(not(test))]
120fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
121 read(&COUNTS)
122}
123
124/// Reads the table this thread counts into.
125#[cfg(test)]
126fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
127 COUNTS.with(read)
128}
129
130/// Where a kernel and a form pair live in the table.
131fn cell(kernel: Kernel, left: Form, right: Form) -> usize {
132 kernel.index() * WIDTH * WIDTH + form_index(left) * WIDTH + form_index(right)
133}
134
135/// Records that a kernel took the row at a time path on this pair of forms.
136///
137/// `Relaxed` because nothing reads this to make a decision while a query is running. It is a
138/// diagnostic that is read once, after, by a harness, and paying for ordering on it would be
139/// paying for a guarantee nobody uses.
140pub fn record(kernel: Kernel, left: Form, right: Form) {
141 with_counts(|counts| counts[cell(kernel, left, right)].fetch_add(1, Ordering::Relaxed));
142}
143
144/// How many times a kernel fell through on this pair of forms.
145#[must_use]
146pub fn count(kernel: Kernel, left: Form, right: Form) -> u64 {
147 with_counts(|counts| counts[cell(kernel, left, right)].load(Ordering::Relaxed))
148}
149
150/// Every combination that has fallen through at least once, most frequent first.
151#[must_use]
152pub fn hot() -> Vec<(Kernel, Form, Form, u64)> {
153 let mut out = Vec::new();
154 for kernel in Kernel::ALL {
155 for left in FORMS {
156 for right in FORMS {
157 let seen = count(kernel, left, right);
158 if seen > 0 {
159 out.push((kernel, left, right, seen));
160 }
161 }
162 }
163 }
164 out.sort_by_key(|entry| std::cmp::Reverse(entry.3));
165 out
166}
167
168/// Sets every counter back to zero.
169///
170/// For a harness that wants the counts for one query rather than for a process, and for the tests
171/// below. It is not synchronized against a running query, because a diagnostic that took a lock
172/// would be a diagnostic that changed what it measures.
173pub fn reset() {
174 with_counts(|counts| {
175 for counter in counts {
176 counter.store(0, Ordering::Relaxed);
177 }
178 });
179}
180
181/// The counts as a table, or a line saying there are none.
182#[must_use]
183pub fn report() -> String {
184 let hot = hot();
185 if hot.is_empty() {
186 return "every kernel call took a specialized path".to_owned();
187 }
188 let mut out = String::from("kernel calls that fell through to the row at a time path\n");
189 for (kernel, left, right, seen) in hot {
190 out.push_str(&format!(
191 " {:<10} {:<10} against {:<10} {seen}\n",
192 kernel.name(),
193 form_name(left),
194 form_name(right)
195 ));
196 }
197 out
198}
199
200#[cfg(test)]
201mod tests {
202 use super::{Form, Kernel, count, hot, record, report, reset};
203
204 #[test]
205 fn a_fall_through_lands_in_the_cell_for_its_own_form_pair() {
206 reset();
207 record(Kernel::Compare, Form::Sequence, Form::Constant);
208 record(Kernel::Compare, Form::Sequence, Form::Constant);
209 record(Kernel::Cast, Form::Dictionary, Form::Flat);
210 assert_eq!(count(Kernel::Compare, Form::Sequence, Form::Constant), 2);
211 assert_eq!(count(Kernel::Cast, Form::Dictionary, Form::Flat), 1);
212 assert_eq!(count(Kernel::Compare, Form::Constant, Form::Sequence), 0);
213 assert_eq!(count(Kernel::Compare, Form::Flat, Form::Flat), 0);
214 reset();
215 }
216
217 #[test]
218 fn the_report_names_the_combination_rather_than_a_number_on_its_own() {
219 reset();
220 assert!(report().contains("every kernel call took a specialized path"));
221 for _ in 0..7 {
222 record(Kernel::Compare, Form::Sequence, Form::Constant);
223 }
224 record(Kernel::Logic, Form::Flat, Form::Dictionary);
225 let text = report();
226 assert!(text.contains("compare"), "{text}");
227 assert!(text.contains("sequence"), "{text}");
228 assert!(text.contains('7'), "{text}");
229 // Most frequent first, because the point of the table is to say what to specialize next.
230 assert_eq!(hot().first().map(|entry| entry.3), Some(7));
231 reset();
232 }
233}