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 eight physical forms, so sixty four 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; 8] = [
99 Form::Flat,
100 Form::Constant,
101 Form::Sequence,
102 Form::Dictionary,
103 Form::Rle,
104 Form::BitPacked,
105 Form::StringView,
106 Form::Fsst,
107];
108
109/// The name of a form, for the report.
110fn form_name(form: Form) -> &'static str {
111 match form {
112 Form::Flat => "flat",
113 Form::Constant => "constant",
114 Form::Sequence => "sequence",
115 Form::Dictionary => "dictionary",
116 Form::Rle => "rle",
117 Form::BitPacked => "bit-packed",
118 Form::StringView => "string-view",
119 Form::Fsst => "fsst",
120 // `Form` is not exhaustive as far as this crate is concerned, and more encodings are coming
121 // to it. A name rather than a panic means the day one lands is a day the report says
122 // `other` for a while, not a day the report aborts the process.
123 _ => "other",
124 }
125}
126
127/// The position of a form in [`FORMS`], or the slot past the end for one this build does not know.
128fn form_index(form: Form) -> usize {
129 FORMS.iter().position(|&known| known == form).unwrap_or(FORMS.len())
130}
131
132/// One counter per kernel per form pair, plus a row and a column for a form added later.
133const WIDTH: usize = FORMS.len() + 1;
134const CELLS: usize = Kernel::ALL.len() * WIDTH * WIDTH;
135
136#[cfg(not(test))]
137static COUNTS: [AtomicU64; CELLS] = [const { AtomicU64::new(0) }; CELLS];
138
139// One table per thread in a test build, and one table for the process everywhere else.
140//
141// The counts a harness wants are the counts for a run, so the table the library keeps is process
142// wide. The counts a test wants are its own, and the test harness runs tests in parallel in one
143// process, so under `cfg(test)` every thread gets a table of its own and a test sees nothing but
144// what it recorded. A test binary here is a hundred and twenty tests of which fourteen read these
145// counters and the rest call kernels, so with one shared table the fourteen fail whenever one of
146// the other hundred happens to fall through at the same moment. That is what took the 0.2.12
147// release down and it did it by failing on a machine nobody was watching.
148//
149// A lock is the other way to write this and it was the way this was written. It does not work,
150// because it only serializes the tests that take it, and the test that has to take it is every
151// test that calls a kernel rather than the ones that read the counters.
152#[cfg(test)]
153thread_local! {
154 static COUNTS: [AtomicU64; CELLS] = const { [const { AtomicU64::new(0) }; CELLS] };
155}
156
157/// Reads the table this thread counts into.
158#[cfg(not(test))]
159fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
160 read(&COUNTS)
161}
162
163/// Reads the table this thread counts into.
164#[cfg(test)]
165fn with_counts<T>(read: impl FnOnce(&[AtomicU64; CELLS]) -> T) -> T {
166 COUNTS.with(read)
167}
168
169/// Where a kernel and a form pair live in the table.
170fn cell(kernel: Kernel, left: Form, right: Form) -> usize {
171 kernel.index() * WIDTH * WIDTH + form_index(left) * WIDTH + form_index(right)
172}
173
174/// Records that a kernel took the row at a time path on this pair of forms.
175///
176/// `Relaxed` because nothing reads this to make a decision while a query is running. It is a
177/// diagnostic that is read once, after, by a harness, and paying for ordering on it would be
178/// paying for a guarantee nobody uses.
179pub fn record(kernel: Kernel, left: Form, right: Form) {
180 with_counts(|counts| counts[cell(kernel, left, right)].fetch_add(1, Ordering::Relaxed));
181 slow::took(kernel.cause());
182}
183
184/// How many times a kernel fell through on this pair of forms.
185#[must_use]
186pub fn count(kernel: Kernel, left: Form, right: Form) -> u64 {
187 with_counts(|counts| counts[cell(kernel, left, right)].load(Ordering::Relaxed))
188}
189
190/// Every combination that has fallen through at least once, most frequent first.
191#[must_use]
192pub fn hot() -> Vec<(Kernel, Form, Form, u64)> {
193 let mut out = Vec::new();
194 for kernel in Kernel::ALL {
195 for left in FORMS {
196 for right in FORMS {
197 let seen = count(kernel, left, right);
198 if seen > 0 {
199 out.push((kernel, left, right, seen));
200 }
201 }
202 }
203 }
204 out.sort_by_key(|entry| std::cmp::Reverse(entry.3));
205 out
206}
207
208/// Sets every counter back to zero.
209///
210/// For a harness that wants the counts for one query rather than for a process, and for the tests
211/// below. It is not synchronized against a running query, because a diagnostic that took a lock
212/// would be a diagnostic that changed what it measures.
213pub fn reset() {
214 with_counts(|counts| {
215 for counter in counts {
216 counter.store(0, Ordering::Relaxed);
217 }
218 });
219}
220
221/// The counts as a table, or a line saying there are none.
222#[must_use]
223pub fn report() -> String {
224 let hot = hot();
225 if hot.is_empty() {
226 return "every kernel call took a specialized path".to_owned();
227 }
228 let mut out = String::from("kernel calls that fell through to the row at a time path\n");
229 for (kernel, left, right, seen) in hot {
230 out.push_str(&format!(
231 " {:<10} {:<10} against {:<10} {seen}\n",
232 kernel.name(),
233 form_name(left),
234 form_name(right)
235 ));
236 }
237 out
238}
239
240#[cfg(test)]
241mod tests {
242 use rudb_common::slow;
243
244 use super::{Cause, Form, Kernel, count, hot, record, report, reset};
245
246 #[test]
247 fn a_fall_through_is_counted_by_form_pair_here_and_by_kernel_where_the_document_reads_it() {
248 reset();
249 slow::reset();
250 record(Kernel::Select, Form::Dictionary, Form::Flat);
251 record(Kernel::Select, Form::Constant, Form::Flat);
252 assert_eq!(count(Kernel::Select, Form::Dictionary, Form::Flat), 1);
253 assert_eq!(count(Kernel::Select, Form::Constant, Form::Flat), 1);
254 // The other counter does not split by form, because the question it answers is which
255 // operator is paying rather than which specialization is missing.
256 assert_eq!(slow::here().get(Cause::Select), 2);
257 assert_eq!(slow::here().total(), 2);
258 reset();
259 slow::reset();
260 }
261
262 #[test]
263 fn every_kernel_names_a_cause_of_its_own() {
264 let mut named: Vec<&str> = Kernel::ALL.iter().map(|kernel| kernel.cause().name()).collect();
265 named.sort_unstable();
266 named.dedup();
267 assert_eq!(named.len(), Kernel::ALL.len());
268 for kernel in Kernel::ALL {
269 assert_eq!(kernel.name(), kernel.cause().name(), "one kernel, one name");
270 }
271 }
272
273 #[test]
274 fn a_fall_through_lands_in_the_cell_for_its_own_form_pair() {
275 reset();
276 record(Kernel::Compare, Form::Sequence, Form::Constant);
277 record(Kernel::Compare, Form::Sequence, Form::Constant);
278 record(Kernel::Cast, Form::Dictionary, Form::Flat);
279 assert_eq!(count(Kernel::Compare, Form::Sequence, Form::Constant), 2);
280 assert_eq!(count(Kernel::Cast, Form::Dictionary, Form::Flat), 1);
281 assert_eq!(count(Kernel::Compare, Form::Constant, Form::Sequence), 0);
282 assert_eq!(count(Kernel::Compare, Form::Flat, Form::Flat), 0);
283 reset();
284 }
285
286 #[test]
287 fn the_report_names_the_combination_rather_than_a_number_on_its_own() {
288 reset();
289 assert!(report().contains("every kernel call took a specialized path"));
290 for _ in 0..7 {
291 record(Kernel::Compare, Form::Sequence, Form::Constant);
292 }
293 record(Kernel::Logic, Form::Flat, Form::Dictionary);
294 let text = report();
295 assert!(text.contains("compare"), "{text}");
296 assert!(text.contains("sequence"), "{text}");
297 assert!(text.contains('7'), "{text}");
298 // Most frequent first, because the point of the table is to say what to specialize next.
299 assert_eq!(hot().first().map(|entry| entry.3), Some(7));
300 reset();
301 }
302}