rudb_vector/validity.rs
1//! Which values in a vector are not null.
2//!
3//! `spec/07-execution.md` section 7.1: validity has three representations and the distinction is
4//! load-bearing. All valid is the absence of a mask and gets the fastest kernels. All invalid is a
5//! flag and short circuits entirely. Anything else is a bitmap.
6//!
7//! Photon's published result is that separate no-null kernels are worth a measurable amount on
8//! real data, because real data is mostly not null. The cost of knowing which case you are in is
9//! one branch per vector rather than one per value, which is why the three cases are an enum here
10//! rather than a bitmap that happens to be all ones.
11
12/// Which values in a vector are valid.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum Validity {
15 /// Nothing is null. No mask is stored and the kernels that read this take the fast path.
16 AllValid,
17 /// Everything is null. Most operators can answer without looking at the data at all.
18 AllInvalid,
19 /// Some of each, one bit per value, set meaning valid.
20 Mask(Bitmap),
21}
22
23/// A [`Validity`] borrowed as a `Copy` value, so a row loop can decide the case once.
24///
25/// The three cases are the same three. The difference is that this is a small `Copy` value rather
26/// than a shared reference to one, and that is what lets the compiler lift the match out of a row
27/// loop. Through a `&Validity` it cannot: the loops that ask row by row also call into code the
28/// compiler cannot see through, it has to assume one of those calls could write through the
29/// reference, and so it reloads the discriminant and re-decides the case on every row.
30///
31/// The note at the top of this file says the cost of knowing which case you are in is one branch
32/// per vector rather than one per value. Read through [`Validity::is_valid`] that is true wherever
33/// the compiler can see the whole loop and false wherever it cannot. Read through this it is true
34/// either way, because there is no reference left for a call inside the loop to have written
35/// through.
36///
37/// How much that is worth is small and worth saying plainly. On q01 it is 0.54 percent of the
38/// query, which is the one place it shows up at all, because q01's decimals arrive as a dictionary
39/// over a packed run and the four packed loops are where the reference was surviving. q10 and q18
40/// both come out inside their own control spread, which is to say unchanged.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Live<'l> {
43 /// Nothing is null.
44 All,
45 /// Everything is null.
46 None,
47 /// Some of each, one bit per value, set meaning valid.
48 Mask(&'l Bitmap),
49}
50
51impl Live<'_> {
52 /// Whether the value at `index` is not null.
53 ///
54 /// The same answer [`Validity::is_valid`] gives for the same row, including reporting invalid
55 /// rather than panicking for a read past the end of a partially filled vector.
56 #[must_use]
57 #[inline]
58 pub fn at(self, index: usize) -> bool {
59 match self {
60 Self::All => true,
61 Self::None => false,
62 Self::Mask(mask) => mask.get(index),
63 }
64 }
65}
66
67impl Validity {
68 /// This validity as the `Copy` value a row loop should hold. See [`Live`].
69 #[must_use]
70 #[inline]
71 pub fn live(&self) -> Live<'_> {
72 match self {
73 Self::AllValid => Live::All,
74 Self::AllInvalid => Live::None,
75 Self::Mask(mask) => Live::Mask(mask),
76 }
77 }
78
79 /// How many bytes of memory this representation is holding.
80 ///
81 /// The two cheap arms hold none at all, which is the point of having them.
82 #[must_use]
83 pub fn footprint(&self) -> usize {
84 match self {
85 Self::AllValid | Self::AllInvalid => 0,
86 Self::Mask(mask) => mask.footprint(),
87 }
88 }
89
90 /// Whether the value at `index` is not null.
91 ///
92 /// Out of range reads report invalid rather than panicking, because this is called from
93 /// kernels that are allowed to read past the end of a partially filled vector.
94 #[must_use]
95 pub fn is_valid(&self, index: usize) -> bool {
96 match self {
97 Self::AllValid => true,
98 Self::AllInvalid => false,
99 Self::Mask(mask) => mask.get(index),
100 }
101 }
102
103 /// Whether any value in the first `len` is null.
104 #[must_use]
105 pub fn has_nulls(&self, len: usize) -> bool {
106 match self {
107 Self::AllValid => false,
108 Self::AllInvalid => len > 0,
109 Self::Mask(mask) => mask.count_valid(len) != len,
110 }
111 }
112
113 /// How many of the first `len` values are not null.
114 #[must_use]
115 pub fn count_valid(&self, len: usize) -> usize {
116 match self {
117 Self::AllValid => len,
118 Self::AllInvalid => 0,
119 Self::Mask(mask) => mask.count_valid(len),
120 }
121 }
122
123 /// Collapses a mask that turned out to be uniform back to one of the flag cases.
124 ///
125 /// Worth doing at the end of any operation that builds a mask, because every kernel
126 /// downstream then gets to take the branch it wants rather than walking a bitmap to find out
127 /// what it already could have been told.
128 #[must_use]
129 pub fn normalize(self, len: usize) -> Self {
130 match self {
131 Self::Mask(ref mask) => {
132 let valid = mask.count_valid(len);
133 if valid == len {
134 Self::AllValid
135 } else if valid == 0 {
136 Self::AllInvalid
137 } else {
138 self
139 }
140 }
141 other => other,
142 }
143 }
144
145 /// The validity of a vector where `index` has just been made null.
146 ///
147 /// Takes and returns by value because setting a null on an `AllValid` vector has to
148 /// materialize a mask, and hiding that behind `&mut self` hides an allocation.
149 #[must_use]
150 pub fn with_null(self, index: usize, len: usize) -> Self {
151 let mut mask = match self {
152 Self::AllValid => Bitmap::all_valid(len),
153 Self::AllInvalid => return Self::AllInvalid,
154 Self::Mask(mask) => mask,
155 };
156 mask.set(index, false);
157 Self::Mask(mask)
158 }
159
160 /// Validity built from a per-value predicate, normalized.
161 pub fn from_iter(len: usize, valid: impl Fn(usize) -> bool) -> Self {
162 let mut mask = Bitmap::all_valid(len);
163 for index in 0..len {
164 if !valid(index) {
165 mask.set(index, false);
166 }
167 }
168 Self::Mask(mask).normalize(len)
169 }
170
171 /// Validity packed from one byte a row, which is what a kernel that accumulated its answer in a
172 /// `Vec<bool>` is holding when it finishes.
173 ///
174 /// The difference from [`Self::from_iter`] is the shape rather than the answer. `from_iter`
175 /// calls a closure and then a read modify write on a byte of the bitmap, once per row, and the
176 /// read modify write is a dependency on the row before it. This reads sixty four bytes and
177 /// writes one word, which has no dependency in it at all and is what the compiler needs to see
178 /// before it will use a vector instruction. On a thousand row vector that is the difference
179 /// between two nanoseconds a row and something too small to measure.
180 /// The bits past the end of the last word are set rather than clear, which looks like a detail
181 /// and is not. [`Bitmap`] does not carry a length, so its equality is over whole words, and
182 /// [`Bitmap::all_valid`] leaves those bits set. A constructor that left them clear would build
183 /// a validity that says exactly the same thing about every row that exists and still compares
184 /// unequal to the one [`Self::from_iter`] builds, which is a test failure with no wrong answer
185 /// in it and an afternoon to work out.
186 #[must_use]
187 pub fn from_run(valid: &[bool]) -> Self {
188 let len = valid.len();
189 let mut words = vec![0u64; len.div_ceil(64)];
190 for (word, run) in words.iter_mut().zip(valid.chunks(64)) {
191 // Only the last run can be short, and the shift is written around rather than as
192 // `u64::MAX << 64`, which is not a shift this machine has.
193 let mut packed = if run.len() == 64 { 0 } else { u64::MAX << run.len() };
194 for (bit, &live) in run.iter().enumerate() {
195 packed |= u64::from(live) << bit;
196 }
197 *word = packed;
198 }
199 Self::Mask(Bitmap { words }).normalize(len)
200 }
201
202 /// The validity of `len` rows starting at `at`.
203 ///
204 /// The two flag arms are the point. A cut of a column with no nulls in it has no nulls in it,
205 /// and answering that with a flag rather than by building a mask and collapsing it again is the
206 /// difference between a cut costing nothing and costing a pass over the rows. Every column of
207 /// `hits` that is not nullable takes this, and a page is cut into chunk sized pieces, so it is
208 /// taken once per chunk per column of every scan.
209 #[must_use]
210 pub fn slice(&self, at: usize, len: usize) -> Self {
211 match self {
212 Self::AllValid => Self::AllValid,
213 Self::AllInvalid => Self::AllInvalid,
214 Self::Mask(mask) => Self::Mask(mask.slice(at, len)).normalize(len),
215 }
216 }
217
218 /// The validity of a value that is valid in both inputs, which is what almost every binary
219 /// operator wants and is worth having in one place.
220 #[must_use]
221 pub fn and(&self, other: &Self, len: usize) -> Self {
222 match (self, other) {
223 (Self::AllInvalid, _) | (_, Self::AllInvalid) => Self::AllInvalid,
224 (Self::AllValid, Self::AllValid) => Self::AllValid,
225 (Self::AllValid, right) => right.clone().normalize(len),
226 (left, Self::AllValid) => left.clone().normalize(len),
227 (Self::Mask(left), Self::Mask(right)) => {
228 let mut result = left.clone();
229 result.and_with(right);
230 Self::Mask(result).normalize(len)
231 }
232 }
233 }
234}
235
236/// One bit per value, set meaning valid.
237///
238/// Words are `u64` because that is the width the popcount and the mask tests want, and because a
239/// 1024 value vector is exactly 16 of them, which fits in a quarter of a cache line pair and is
240/// the reason the vector size is 1024 rather than DuckDB's 2048.
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct Bitmap {
243 words: Vec<u64>,
244}
245
246impl Bitmap {
247 /// How many bytes of memory this bitmap is holding.
248 #[must_use]
249 pub fn footprint(&self) -> usize {
250 self.words.capacity() * size_of::<u64>()
251 }
252
253 /// A bitmap with room for `len` values, all valid.
254 #[must_use]
255 pub fn all_valid(len: usize) -> Self {
256 Self { words: vec![u64::MAX; len.div_ceil(64)] }
257 }
258
259 /// A bitmap with room for `len` values, all null.
260 #[must_use]
261 pub fn all_invalid(len: usize) -> Self {
262 Self { words: vec![0; len.div_ceil(64)] }
263 }
264
265 /// Whether the value at `index` is valid. Past the end reads as invalid.
266 #[must_use]
267 pub fn get(&self, index: usize) -> bool {
268 let word = index / 64;
269 self.words.get(word).is_some_and(|w| w >> (index % 64) & 1 == 1)
270 }
271
272 /// Sets whether the value at `index` is valid, growing the bitmap if it has to.
273 pub fn set(&mut self, index: usize, valid: bool) {
274 let word = index / 64;
275 if word >= self.words.len() {
276 self.words.resize(word + 1, 0);
277 }
278 let bit = 1u64 << (index % 64);
279 if valid {
280 self.words[word] |= bit;
281 } else {
282 self.words[word] &= !bit;
283 }
284 }
285
286 /// How many of the first `len` values are valid.
287 #[must_use]
288 pub fn count_valid(&self, len: usize) -> usize {
289 let mut count = 0usize;
290 let full_words = len / 64;
291 for word in self.words.iter().take(full_words) {
292 count += word.count_ones() as usize;
293 }
294 let tail = len % 64;
295 if tail > 0 {
296 // A let chain would read better here, but let chains want Rust 1.88 and the declared
297 // minimum in the manifest is 1.85.0. Written the long way rather than moving the
298 // minimum, since nothing about this needs a newer compiler.
299 if let Some(word) = self.words.get(full_words) {
300 // Mask off the bits past the end, which are whatever the last resize left there.
301 let keep = u64::MAX >> (64 - tail);
302 count += (word & keep).count_ones() as usize;
303 }
304 }
305 count
306 }
307
308 /// Sixty four validity bits at once, the lowest numbered row in the lowest bit.
309 ///
310 /// Past the end reads as all null, which is the same answer [`Self::get`] gives one bit at a
311 /// time. This exists because a kernel that asks [`Self::get`] once per row pays a bounds check,
312 /// a divide and a shift for each of them, and the word it wants was already in a register for
313 /// the previous sixty three. A loop that reads the word once and walks its bits is the same
314 /// answer at a fraction of the cost, and the three call sites that do that are the difference
315 /// between a nullable column being free and being the slowest thing in the kernel.
316 #[must_use]
317 pub fn word(&self, at: usize) -> u64 {
318 self.words.get(at).copied().unwrap_or(0)
319 }
320
321 /// The `len` bits starting at `at`, moved down to start at bit zero.
322 ///
323 /// A word at a time, because a cut is almost never on a word boundary and doing it a bit at a
324 /// time is a divide, a shift and a read modify write per row. Each output word is the high part
325 /// of one input word and the low part of the next, which is two loads and three shifts for
326 /// sixty four rows.
327 ///
328 /// The bits past `len` in the last word are set rather than clear, for the reason
329 /// [`Validity::from_run`] gives: this type has no length, so its equality is over whole words
330 /// and a constructor that left them clear would compare unequal to one that did not.
331 #[must_use]
332 pub fn slice(&self, at: usize, len: usize) -> Self {
333 let skip = at / 64;
334 let shift = (at % 64) as u32;
335 let mut words = Vec::with_capacity(len.div_ceil(64));
336 for index in 0..len.div_ceil(64) {
337 let low = self.word(skip + index) >> shift;
338 // Written around rather than as a shift by sixty four, which is not a shift this
339 // machine has, and when the cut is word aligned there is no next word to take from.
340 let high = if shift == 0 { 0 } else { self.word(skip + index + 1) << (64 - shift) };
341 words.push(low | high);
342 }
343 if let Some(last) = words.last_mut() {
344 let used = len % 64;
345 if used != 0 {
346 *last |= u64::MAX << used;
347 }
348 }
349 Self { words }
350 }
351
352 /// Intersects this bitmap with another, in place.
353 pub fn and_with(&mut self, other: &Self) {
354 for (index, word) in self.words.iter_mut().enumerate() {
355 *word &= other.words.get(index).copied().unwrap_or(0);
356 }
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::{Bitmap, Validity};
363
364 #[test]
365 fn the_three_cases_answer_the_same_question_the_same_way() {
366 let mut mask = Bitmap::all_valid(8);
367 assert!(Validity::AllValid.is_valid(3));
368 assert!(!Validity::AllInvalid.is_valid(3));
369 assert!(Validity::Mask(mask.clone()).is_valid(3));
370 mask.set(3, false);
371 assert!(!Validity::Mask(mask).is_valid(3));
372 }
373
374 #[test]
375 fn a_cut_of_a_mask_says_what_reading_it_a_bit_at_a_time_says() {
376 // Every start and every length over a pattern with no period in common with sixty four, so
377 // that the word boundary lands in a different place in the pattern for every cut. The word
378 // at a time cut and the bit at a time one have to agree bit for bit, including the bits
379 // past the end of the last word, since this type compares by whole words.
380 let rows = 200;
381 let mut mask = Bitmap::all_valid(rows);
382 // row at a time: building the pattern the test reads, not a path anything runs.
383 for row in 0..rows {
384 mask.set(row, row % 7 != 0 && row % 11 != 3);
385 }
386 let whole = Validity::Mask(mask.clone());
387 for at in 0..70 {
388 for len in 0..70 {
389 let wanted = Validity::from_iter(len, |row| whole.is_valid(at + row));
390 assert_eq!(whole.slice(at, len), wanted, "rows {at} to {}", at + len);
391 }
392 }
393 }
394
395 #[test]
396 fn a_cut_of_a_column_with_no_nulls_has_no_nulls_and_no_mask() {
397 assert_eq!(Validity::AllValid.slice(17, 33), Validity::AllValid);
398 assert_eq!(Validity::AllInvalid.slice(17, 33), Validity::AllInvalid);
399 // And a cut of a mask that happens to be uniform over the range collapses the same way.
400 let mut mask = Bitmap::all_valid(128);
401 mask.set(100, false);
402 assert_eq!(Validity::Mask(mask).slice(0, 64), Validity::AllValid);
403 }
404
405 #[test]
406 fn a_uniform_mask_collapses_to_the_flag_it_should_have_been() {
407 // The point of doing this at the end of every operation that builds a mask: the kernel
408 // downstream gets to branch once rather than walk a bitmap to learn what it was told.
409 assert_eq!(Validity::Mask(Bitmap::all_valid(64)).normalize(64), Validity::AllValid);
410 assert_eq!(Validity::Mask(Bitmap::all_invalid(64)).normalize(64), Validity::AllInvalid);
411 let mut mask = Bitmap::all_valid(64);
412 mask.set(7, false);
413 assert!(matches!(Validity::Mask(mask).normalize(64), Validity::Mask(_)));
414 }
415
416 #[test]
417 fn a_word_of_validity_says_the_same_thing_the_bits_do_one_at_a_time() {
418 let mut mask = Bitmap::all_valid(200);
419 mask.set(0, false);
420 mask.set(63, false);
421 mask.set(64, false);
422 mask.set(199, false);
423 for index in 0..200 {
424 let from_word = mask.word(index / 64) >> (index % 64) & 1 == 1;
425 assert_eq!(from_word, mask.get(index), "{index}");
426 }
427 // Past the end is all null, which is what reading one bit past the end says too.
428 assert_eq!(mask.word(9), 0);
429 assert!(!mask.get(9 * 64));
430 }
431
432 #[test]
433 fn packing_a_run_of_bytes_says_the_same_thing_as_setting_the_bits() {
434 // Two lengths that are not a whole number of words, because the bits past the end of the
435 // last word are the part of this that is easy to get wrong.
436 for len in [0, 1, 63, 64, 65, 100, 1024] {
437 let live: Vec<bool> = (0..len).map(|index| index % 7 != 0).collect();
438 let packed = Validity::from_run(&live);
439 let set = Validity::from_iter(len, |index| live[index]);
440 assert_eq!(packed, set, "{len}");
441 for (index, &want) in live.iter().enumerate() {
442 assert_eq!(packed.is_valid(index), want, "{len} at {index}");
443 }
444 }
445 // The bits past the end of the last word have to match what every other constructor
446 // leaves there, because a bitmap does not carry a length and its equality is over whole
447 // words. This is the assertion that caught it.
448 assert_eq!(
449 Validity::from_run(&[true, false, true]),
450 Validity::from_iter(3, |index| index != 1)
451 );
452 // And it collapses the uniform cases the same way everything else does.
453 assert_eq!(Validity::from_run(&[true; 64]), Validity::AllValid);
454 assert_eq!(Validity::from_run(&[false; 64]), Validity::AllInvalid);
455 assert_eq!(Validity::from_run(&[]), Validity::AllValid);
456 }
457
458 #[test]
459 fn counting_stops_at_the_length_and_not_at_the_word_boundary() {
460 // A 1024 vector is 16 words exactly, but a partially filled one is not, and the bits past
461 // the end are whatever the last resize left there. Getting this wrong makes a count that
462 // is right in tests of length 64 and wrong on real data.
463 let mask = Bitmap::all_valid(100);
464 assert_eq!(mask.count_valid(100), 100);
465 assert_eq!(mask.count_valid(65), 65);
466 assert_eq!(mask.count_valid(1), 1);
467 assert_eq!(mask.count_valid(0), 0);
468 }
469
470 #[test]
471 fn setting_a_null_on_an_all_valid_vector_materializes_a_mask() {
472 let validity = Validity::AllValid.with_null(5, 64);
473 assert!(!validity.is_valid(5));
474 assert!(validity.is_valid(4));
475 assert_eq!(validity.count_valid(64), 63);
476 assert!(validity.has_nulls(64));
477 }
478
479 #[test]
480 fn setting_a_null_on_an_all_invalid_vector_changes_nothing() {
481 assert_eq!(Validity::AllInvalid.with_null(5, 64), Validity::AllInvalid);
482 }
483
484 #[test]
485 fn intersection_short_circuits_on_the_flags() {
486 let mut left = Bitmap::all_valid(8);
487 left.set(0, false);
488 let mut right = Bitmap::all_valid(8);
489 right.set(1, false);
490 let both = Validity::Mask(left.clone()).and(&Validity::Mask(right), 8);
491 assert!(!both.is_valid(0));
492 assert!(!both.is_valid(1));
493 assert!(both.is_valid(2));
494 assert_eq!(both.count_valid(8), 6);
495
496 assert_eq!(Validity::AllValid.and(&Validity::AllValid, 8), Validity::AllValid);
497 assert_eq!(Validity::AllInvalid.and(&Validity::Mask(left), 8), Validity::AllInvalid);
498 }
499
500 #[test]
501 fn validity_from_a_predicate_normalizes_itself() {
502 assert_eq!(Validity::from_iter(16, |_| true), Validity::AllValid);
503 assert_eq!(Validity::from_iter(16, |_| false), Validity::AllInvalid);
504 let mixed = Validity::from_iter(16, |i| i % 2 == 0);
505 assert_eq!(mixed.count_valid(16), 8);
506 }
507
508 #[test]
509 fn the_borrowed_view_answers_what_the_owned_one_does() {
510 // Including past the end of the vector, which the kernels rely on and which is the one
511 // answer a reader would not guess from the three case names.
512 for validity in
513 [Validity::AllValid, Validity::AllInvalid, Validity::from_iter(16, |i| i % 3 == 0)]
514 {
515 let live = validity.live();
516 for row in 0..24 {
517 assert_eq!(live.at(row), validity.is_valid(row), "row {row} of {validity:?}");
518 }
519 }
520 }
521}