This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11918-25dd364d307d5517664197145a77b3c3c2caa7c8 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 8330865ef4350cc415550a63fece2b64aaac79f4 Author: RIchard Baah <[email protected]> AuthorDate: Sat Nov 7 18:03:11 2026 +0000 perf(arrow): fuse Boolean filter copying (#11918) # Which issue does this PR close? Closes #11920. # Rationale for this change The Boolean coalescer previously filtered into temporary value and validity buffers, copied those buffers into its builders, and then discarded them. The builders can append packed words directly, so that intermediate allocation is unnecessary. # What changes are included in this PR? The Boolean coalescer now compresses selected value and validity bits directly into its output builders. It skips empty filter words before reading the corresponding source words and handles sliced inputs and trailing partial words in the same loop. Precomputed sparse `Indices` predicates keep the existing gather path. The regular Boolean filter also uses the shared packer for middle-density predicates, while very dense predicates and precomputed sparse indices retain their strategy-based paths. # Example Take this eight-row input: ```text row: 0 1 2 3 4 5 6 7 value: true false true true false false true false valid: yes yes no yes yes no yes yes predicate: false true true null true false true false ``` The null predicate at row 3 is normalized to `false`, so rows 1, 2, 4, and 6 are selected. With row 0 in the least-significant bit: ```text values: 0b01001101 validity: 0b11011011 filter: 0b01010110 ``` The compression kernel produces: ```text compress(values, filter) = 0b1010 compress(validity, filter) = 0b1101 ``` Those four bits are appended directly to the output builders. The result is: ```text [false, null, false, true] ``` Larger inputs use the same operation on each 64-row chunk, carrying partial words between chunks. # Are these changes tested? The tests compare coalescer output with the Boolean filter kernel for nullable, non-null, and all-valid inputs. They cover sliced bitmaps, null predicates, word boundaries, carry between words, short filters, sparse indices, and oversized filters. The final-head [coalescer run](https://github.com/apache/arrow-rs/pull/11918#issuecomment-6614638123) shows the largest gains at low selectivity. The corresponding [filter-kernel run](https://github.com/apache/arrow-rs/pull/11918#issuecomment-6614858375) is effectively flat to slightly faster. # Are there any significant user-facing changes? No. --- arrow-select/src/coalesce/boolean.rs | 322 ++++++++++++++++++++++++++++++++++- arrow-select/src/filter.rs | 138 +++++++++------ arrow/benches/filter_kernels.rs | 13 ++ 3 files changed, 414 insertions(+), 59 deletions(-) diff --git a/arrow-select/src/coalesce/boolean.rs b/arrow-select/src/coalesce/boolean.rs index b922ea3958..125ff496e5 100644 --- a/arrow-select/src/coalesce/boolean.rs +++ b/arrow-select/src/coalesce/boolean.rs @@ -3,13 +3,97 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use super::InProgressArray; -use crate::filter::FilterPredicate; +use crate::filter::{FilterPredicate, Packer}; use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, BooleanArray}; +use arrow_buffer::bit_chunk_iterator::BitChunks; use arrow_buffer::{BooleanBuffer, BooleanBufferBuilder, NullBufferBuilder}; use arrow_schema::ArrowError; use std::sync::Arc; +fn copy_filter_words_without_nulls( + output_values: &mut BooleanBufferBuilder, + source_value_chunks: &BitChunks<'_>, + filter_chunks: &BitChunks<'_>, +) { + let mut value_packer = Packer::default(); + + // Check the mask first so sparse filters skip reading most source words. + for (index, filter_mask) in filter_chunks.iter().enumerate() { + if filter_mask == 0 { + continue; + } + + if let Some(complete_word) = + value_packer.push(source_value_chunks.chunk(index), filter_mask) + { + output_values.append_word(complete_word, 64); + } + } + + let filter_mask = filter_chunks.remainder_bits(); + if filter_mask != 0 + && let Some(complete_word) = + value_packer.push(source_value_chunks.remainder_bits(), filter_mask) + { + output_values.append_word(complete_word, 64); + } + + if let Some((pending_bits, pending_len)) = value_packer.finish() { + output_values.append_word(pending_bits, pending_len); + } +} + +fn copy_filter_words_with_nulls( + output_values: &mut BooleanBufferBuilder, + output_validity: &mut NullBufferBuilder, + source_value_chunks: &BitChunks<'_>, + source_validity_chunks: &BitChunks<'_>, + filter_chunks: &BitChunks<'_>, +) { + let mut value_packer = Packer::default(); + let mut validity_packer = Packer::default(); + + // Check the mask first so sparse filters skip reading most source words. + for (index, filter_mask) in filter_chunks.iter().enumerate() { + if filter_mask == 0 { + continue; + } + + if let Some(complete_word) = + value_packer.push(source_value_chunks.chunk(index), filter_mask) + { + output_values.append_word(complete_word, 64); + } + if let Some(complete_word) = + validity_packer.push(source_validity_chunks.chunk(index), filter_mask) + { + output_validity.append_word(complete_word, 64); + } + } + + let filter_mask = filter_chunks.remainder_bits(); + if filter_mask != 0 { + if let Some(complete_word) = + value_packer.push(source_value_chunks.remainder_bits(), filter_mask) + { + output_values.append_word(complete_word, 64); + } + if let Some(complete_word) = + validity_packer.push(source_validity_chunks.remainder_bits(), filter_mask) + { + output_validity.append_word(complete_word, 64); + } + } + + if let Some((pending_bits, pending_len)) = value_packer.finish() { + output_values.append_word(pending_bits, pending_len); + } + if let Some((pending_bits, pending_len)) = validity_packer.finish() { + output_validity.append_word(pending_bits, pending_len); + } +} + #[derive(Debug)] pub(crate) struct InProgressBooleanArray { source: Option<ArrayRef>, @@ -64,8 +148,58 @@ impl InProgressArray for InProgressBooleanArray { source: ArrayRef, filter: &FilterPredicate, ) -> Result<(), ArrowError> { - let filtered = filter.filter(source.as_ref())?; - self.append_array(filtered.as_boolean()); + if filter.filter_len() > source.len() { + return Err(ArrowError::InvalidArgumentError(format!( + "Filter predicate of length {} is larger than target array of length {}", + filter.filter_len(), + source.len() + ))); + } + + if filter.uses_sparse_indices() { + let filtered = filter.filter(source.as_ref())?; + self.append_array(filtered.as_boolean()); + return Ok(()); + } + + let source = source.as_boolean(); + // Read values and mask in aligned words even when the source is sliced. + let filter_chunks = filter.filter_mask().bit_chunks(); + let source_values = source.values(); + let source_value_chunks = BitChunks::new( + source_values.values(), + source_values.offset(), + filter.filter_len(), + ); + // Ignore present-but-all-valid buffers to avoid allocating output validity + // for data with no actual nulls. + let source_validity_chunks = + source + .nulls() + .filter(|nulls| nulls.null_count() != 0) + .map(|nulls| { + let nulls = nulls.inner(); + BitChunks::new(nulls.values(), nulls.offset(), filter.filter_len()) + }); + + let output_values = self + .values + .get_or_insert_with(|| BooleanBufferBuilder::new(self.batch_size)); + + // Branch once here so non-null inputs avoid validity work in the chunk loop. + let selected_count = filter.count(); + if let Some(source_validity_chunks) = &source_validity_chunks { + copy_filter_words_with_nulls( + output_values, + &mut self.nulls, + &source_value_chunks, + source_validity_chunks, + &filter_chunks, + ); + } else { + copy_filter_words_without_nulls(output_values, &source_value_chunks, &filter_chunks); + self.nulls.append_n_non_nulls(selected_count); + } Ok(()) } @@ -96,6 +230,7 @@ impl InProgressArray for InProgressBooleanArray { mod tests { use super::*; use crate::filter::FilterBuilder; + use arrow_buffer::NullBuffer; #[test] fn copies_slices_and_sparse_filters() { @@ -143,4 +278,185 @@ mod tests { assert_eq!(second.as_boolean(), &source.slice(2, 2)); assert_eq!(in_progress.finish().unwrap().len(), 0); } + + const FILTER_LEN: usize = 269; + const SOURCE_OFFSET: usize = 3; + + #[test] + fn filtered_words_without_nulls_match_filter_kernel() { + let len = SOURCE_OFFSET + FILTER_LEN; + let values = (0..len).map(source_value).collect(); + let all_valid = BooleanArray::new(values, Some(NullBuffer::new_valid(len))) + .slice(SOURCE_OFFSET, FILTER_LEN); + let without_validity = non_null_source(); + assert!(without_validity.nulls().is_none()); + assert!(all_valid.nulls().is_some()); + + for (case, source) in [ + ("without validity", without_validity), + ("all-valid validity", all_valid), + ] { + assert_eq!(source.null_count(), 0); + assert_filtered_words_match_filter_kernel(case, source); + } + } + + #[test] + fn filtered_words_with_nulls_match_filter_kernel() { + let source = BooleanArray::from_iter( + (0..SOURCE_OFFSET + FILTER_LEN) + .map(|index| (index % 11 != 0).then_some(index % 3 == 0 || index % 7 == 0)), + ) + .slice(SOURCE_OFFSET, FILTER_LEN); + assert!(source.null_count() > 0); + + assert_filtered_words_match_filter_kernel("with nulls", source); + } + + #[test] + fn filtered_words_with_unaligned_validity_match_filter_kernel() { + let values: BooleanBuffer = (0..SOURCE_OFFSET + FILTER_LEN).map(source_value).collect(); + let validity: BooleanBuffer = (0..FILTER_LEN + 11).map(|index| index % 11 != 0).collect(); + let source = BooleanArray::new( + values.slice(SOURCE_OFFSET, FILTER_LEN), + Some(NullBuffer::new(validity.slice(11, FILTER_LEN))), + ); + assert_ne!(source.values().offset(), source.nulls().unwrap().offset()); + + assert_filtered_words_match_filter_kernel("unaligned validity", source); + } + + fn assert_filtered_words_match_filter_kernel(source_case: &str, source: BooleanArray) { + for (filter_case, filter) in filter_cases() { + assert_filter_copy_matches_kernel(source_case, filter_case, &source, &filter); + } + } + + fn filter_cases() -> Vec<(&'static str, BooleanArray)> { + let selections = [ + ("none", vec![]), + ("all", (0..FILTER_LEN).collect()), + ( + "word boundaries", + vec![0, 1, 7, 63, 64, 65, 127, 128, 191, 192, 255, 256, 268], + ), + ( + "carry across source words", + // The first two chunks leave 24 carried bits; the third completes a word. + (0..40).chain(64..112).chain(128..168).collect(), + ), + ("alternating", (0..FILTER_LEN).step_by(2).collect()), + ]; + let mut filters: Vec<(&str, BooleanArray)> = selections + .into_iter() + .map(|(case, selected_indices)| { + let filter = (0..FILTER_LEN) + .map(|index| selected_indices.contains(&index)) + .collect(); + (case, filter) + }) + .collect(); + + const FILTER_OFFSET: usize = 5; + let sliced_filter: BooleanArray = std::iter::repeat_n(false, FILTER_OFFSET) + .chain((0..FILTER_LEN).map(|index| index.is_multiple_of(20))) + .collect(); + let sliced_filter = sliced_filter.slice(FILTER_OFFSET, FILTER_LEN); + assert_eq!(sliced_filter.values().offset(), FILTER_OFFSET); + filters.push(("sliced filter", sliced_filter)); + + let shorter_filter = (0_usize..197) + .map(|index| index.is_multiple_of(17)) + .collect(); + filters.push(("shorter than source", shorter_filter)); + + let aligned_filter = (0_usize..256) + .map(|index| index.is_multiple_of(19)) + .collect(); + filters.push(("empty remainder", aligned_filter)); + + let mut filter_values = vec![false; FILTER_LEN]; + for index in [1, 65, 129, 268] { + filter_values[index] = true; + } + let mut filter_validity = vec![true; FILTER_LEN]; + filter_validity[65] = false; + let filter_with_null = BooleanArray::new( + BooleanBuffer::from(filter_values), + Some(NullBuffer::new(BooleanBuffer::from(filter_validity))), + ); + assert!(filter_with_null.value(65)); + assert!(filter_with_null.is_null(65)); + filters.push(("null filter entry", filter_with_null)); + filters + } + + fn assert_filter_copy_matches_kernel( + source_case: &str, + filter_case: &str, + source: &BooleanArray, + filter: &BooleanArray, + ) { + const PREFIX_LEN: usize = 5; + let expect_lazy_validity = source.null_count() == 0; + + for optimize in [false, true] { + let builder = FilterBuilder::new(filter); + let predicate = if optimize { + builder.optimize().build() + } else { + builder.build() + }; + let filtered = predicate.filter(source).unwrap(); + let prefix = source.slice(0, PREFIX_LEN); + let expected = crate::concat::concat(&[&prefix, filtered.as_ref()]).unwrap(); + + let source = Arc::new(source.clone()) as ArrayRef; + let mut in_progress = InProgressBooleanArray::new(FILTER_LEN); + in_progress.set_source(Some(Arc::clone(&source))); + in_progress.copy_rows(0, PREFIX_LEN).unwrap(); + in_progress.set_source(None); + in_progress + .copy_rows_by_filter_from(source, &predicate) + .unwrap(); + + let output = in_progress.finish().unwrap(); + assert_eq!( + output.as_boolean(), + expected.as_boolean(), + "{source_case}, {filter_case}, optimize={optimize}" + ); + if expect_lazy_validity { + assert!( + output.nulls().is_none(), + "{source_case}, {filter_case}, optimize={optimize} should preserve lazy validity" + ); + } + } + } + + fn non_null_source() -> BooleanArray { + let source: BooleanArray = (0..SOURCE_OFFSET + FILTER_LEN).map(source_value).collect(); + source.slice(SOURCE_OFFSET, FILTER_LEN) + } + + fn source_value(index: usize) -> bool { + index.is_multiple_of(3) || index.is_multiple_of(7) + } + + #[test] + fn filter_longer_than_source_returns_error() { + let source = Arc::new(BooleanArray::from(vec![true, false])) as ArrayRef; + let filter_mask = BooleanArray::from(vec![true, false, true]); + let predicate = FilterBuilder::new(&filter_mask).build(); + let mut in_progress = InProgressBooleanArray::new(8); + + let error = in_progress + .copy_rows_by_filter_from(source, &predicate) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Invalid argument error: Filter predicate of length 3 is larger than target array of length 2" + ); + } } diff --git a/arrow-select/src/filter.rs b/arrow-select/src/filter.rs index db71418453..ea337b675f 100644 --- a/arrow-select/src/filter.rs +++ b/arrow-select/src/filter.rs @@ -517,6 +517,17 @@ impl FilterPredicate { self.filter.len() } + /// Returns the normalized filter mask, with nulls replaced by `false`. + pub(crate) fn filter_mask(&self) -> &BooleanBuffer { + self.filter.values() + } + + /// Returns whether bit filtering should gather precomputed indices instead of compressing. + pub(crate) fn uses_sparse_indices(&self) -> bool { + self.count <= self.filter.len() / 64 + && matches!(self.strategy, IterationStrategy::Indices(_)) + } + /// Return a [`FilterSelection`] for iterating over the rows selected by /// this [`FilterPredicate`]. pub(crate) fn selection(&self) -> FilterSelection<'_> { @@ -738,8 +749,7 @@ fn filter_bits(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> Buffer { let len = predicate.filter.len(); let count = predicate.count; let dense = count >= len - len / 64; - let sparse_indices = - count <= len / 64 && matches!(predicate.strategy, IterationStrategy::Indices(_)); + let sparse_indices = predicate.uses_sparse_indices(); if !dense && !sparse_indices { return filter_bits_compress(buffer, predicate); } @@ -790,62 +800,61 @@ fn filter_bits_strategy(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> } } +/// Packs bits selected from successive words into complete output words. +#[derive(Default)] +pub(crate) struct Packer { + /// Bits waiting to be written. + current: u64, + /// Number of populated low bits in `current`. + filled: u32, +} + +impl Packer { + #[inline(always)] + pub(crate) fn push(&mut self, values: u64, mask: u64) -> Option<u64> { + let bits = bit_util::compress(values, mask); + self.current |= bits << self.filled; + let total = self.filled + mask.count_ones(); + if total < 64 { + self.filled = total; + return None; + } + + let complete = self.current; + // `bits >> (64 - filled)`, written so that `filled == 0` + // shifts everything out + self.current = (bits >> 1) >> (63 - self.filled); + self.filled = total - 64; + Some(complete) + } + + #[inline] + pub(crate) fn finish(self) -> Option<(u64, usize)> { + (self.filled != 0).then_some((self.current, self.filled as usize)) + } +} + /// Filter the packed bitmask `buffer` with `predicate` by extracting the kept -/// bits of each 64-bit word with [`bit_util::compress`] (`pext`) +/// bits of each 64-bit word with [`bit_util::compress`] (`pext`). /// -/// Not inlined: within `filter_array` the packing state spills to the stack +/// Not inlined: within `filter_array` the packing state spills to the stack. #[inline(never)] fn filter_bits_compress(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> Buffer { - /// Packs the bits extracted from successive words into the low `filled` - /// bits of `current`; once complete it is written at `idx` and restarts - /// from the bits that did not fit - struct Packer { - ptr: *mut u64, - idx: usize, - current: u64, - filled: u32, - } - - impl Packer { - #[inline(always)] - fn push(&mut self, values: u64, mask: u64) { - let bits = bit_util::compress(values, mask); - self.current |= bits << self.filled; - let total = self.filled + mask.count_ones(); - if total < 64 { - self.filled = total; - } else { - // SAFETY: `count` is the number of set bits in the filter, so - // at most `count / 64` words are ever completed and the - // buffer holds `count / 64 + 1` - unsafe { self.ptr.add(self.idx).write(self.current) }; - self.idx += 1; - // `bits >> (64 - filled)`, written so that `filled == 0` - // shifts everything out - self.current = (bits >> 1) >> (63 - self.filled); - self.filled = total - 64; - } - } - } - assert!(buffer.len() >= predicate.filter.len()); let mask_chunks = predicate.filter.values().bit_chunks(); let value_chunks = BitChunks::new(buffer.values(), buffer.offset(), predicate.filter.len()); - // `count` is the filter's set bit count, which the buffer size and the - // raw writes below rely on, and both chunk views cover + // `predicate.count` is the filter's set bit count, which determines the + // output capacity and bounds the raw writes below. Both chunk views cover // `predicate.filter.len()` bits, so indexing `value_chunks` by the - // position in `mask_chunks` stays in bounds + // position in `mask_chunks` stays in bounds. debug_assert_eq!(predicate.count, predicate.filter.true_count()); debug_assert_eq!(mask_chunks.chunk_len(), value_chunks.chunk_len()); // One word beyond the complete ones for the trailing partial word let mut out: Vec<u64> = Vec::with_capacity(predicate.count / 64 + 1); - let mut packer = Packer { - ptr: out.as_mut_ptr(), - idx: 0, - current: 0, - filled: 0, - }; + let ptr = out.as_mut_ptr(); + let mut idx = 0; + let mut packer = Packer::default(); for (index, mask) in mask_chunks.iter().enumerate() { // Words with no kept bits are skipped before the corresponding values @@ -853,18 +862,35 @@ fn filter_bits_compress(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> if mask == 0 { continue; } - packer.push(value_chunks.chunk(index), mask); - } - packer.push(value_chunks.remainder_bits(), mask_chunks.remainder_bits()); - - // The trailing partial word; its bits above `filled` are zero - // SAFETY: `idx <= count / 64`, so this and every word below it is - // within the buffer and written - debug_assert!(packer.idx < out.capacity()); - unsafe { - packer.ptr.add(packer.idx).write(packer.current); - out.set_len(packer.idx + 1); + if let Some(complete) = packer.push(value_chunks.chunk(index), mask) { + debug_assert!(idx < out.capacity()); + // SAFETY: `complete` contains 64 of the `predicate.count` selected + // bits. Therefore `idx < predicate.count / 64` before this write, + // while `out` has capacity at least `predicate.count / 64 + 1`. + unsafe { ptr.add(idx).write(complete) }; + idx += 1; + } } + if let Some(complete) = packer.push(value_chunks.remainder_bits(), mask_chunks.remainder_bits()) + { + debug_assert!(idx < out.capacity()); + // SAFETY: this completed word also contains 64 of the + // `predicate.count` selected bits, so the same + // `idx < predicate.count / 64 < out.capacity()` bound applies. + unsafe { ptr.add(idx).write(complete) }; + idx += 1; + } + + if let Some((pending, _)) = packer.finish() { + debug_assert!(idx < out.capacity()); + // SAFETY: `pending` exists only when the selected bit count is not a + // multiple of 64. All prior writes were complete words, so + // `idx == predicate.count / 64 < out.capacity()`. + unsafe { ptr.add(idx).write(pending) }; + idx += 1; + } + // SAFETY: every word below `idx` was initialized above + unsafe { out.set_len(idx) }; let mut out = MutableBuffer::from(out); out.truncate(bit_util::ceil(predicate.count, 8)); out.into() diff --git a/arrow/benches/filter_kernels.rs b/arrow/benches/filter_kernels.rs index 20d9c38c09..8a09ea7a3b 100644 --- a/arrow/benches/filter_kernels.rs +++ b/arrow/benches/filter_kernels.rs @@ -105,6 +105,19 @@ fn add_benchmark(c: &mut Criterion) { b.iter(|| bench_built_filter(&data_array, &sparse_filter)) }); + let data_array = create_boolean_array(size, 0.0, 0.5); + c.bench_function("filter context boolean (kept 1/2)", |b| { + b.iter(|| bench_built_filter(&data_array, &filter)) + }); + c.bench_function( + "filter context boolean high selectivity (kept 1023/1024)", + |b| b.iter(|| bench_built_filter(&data_array, &dense_filter)), + ); + c.bench_function( + "filter context boolean low selectivity (kept 1/1024)", + |b| b.iter(|| bench_built_filter(&data_array, &sparse_filter)), + ); + let data_array = create_primitive_array::<Int32Type>(size, 0.0); c.bench_function("filter i32 (kept 1/2)", |b| { b.iter(|| bench_filter(&data_array, &filter_array))
