alamb commented on code in PR #24102: URL: https://github.com/apache/datafusion/pull/24102#discussion_r3851941679
########## datafusion/physical-expr/src/expressions/in_list/fixed_size_binary_filter.rs: ########## @@ -0,0 +1,371 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Optimized filters for fixed-size binary `IN` lists. +//! +//! Supported widths use an Arrow primitive representation with the same +//! in-memory size: +//! +//! | Width | Primitive representation | +//! |------:|--------------------------| +//! | 1 | `UInt8` | +//! | 2 | `UInt16` | +//! | 4 | `UInt32` | +//! | 8 | `UInt64` | +//! | 16 | `Decimal128` | +//! +//! The shared primitive selector applies the native primitive branchless cutoffs +//! and chooses the bitmap or hash-set fallback. +//! +//! The list and input bytes are read the same way, so each primitive value is +//! an exact key for comparison, bitmap lookup, or hashing. No arithmetic, +//! ordering, or decimal operations are used. +//! +//! Reinterpreting an aligned Arrow buffer is zero-copy. An unaligned buffer is +//! copied into aligned primitive storage before filter construction or probing. + +use std::marker::PhantomData; +use std::mem::size_of; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanArray, FixedSizeBinaryArray, PrimitiveArray, +}; +use arrow::buffer::{Buffer, ScalarBuffer}; +use arrow::datatypes::{ + ArrowPrimitiveType, DataType, Decimal128Type, UInt8Type, UInt16Type, UInt32Type, + UInt64Type, +}; +use datafusion_common::{Result, exec_datafusion_err, internal_datafusion_err}; + +use super::primitive_filter::instantiate_primitive_filter; +use super::static_filter::{StaticFilter, StaticFilterRef, handle_dictionary}; + +/// Reinterpret fixed-size binary values as same-width primitive values. +/// +/// Arrow buffers are normally sufficiently aligned, making this zero-copy. A +/// valid Arrow array can still be constructed from a sliced, unaligned buffer; +/// in that case, copy each value into aligned primitive storage. +fn reinterpret_as_primitive<T>(array: &FixedSizeBinaryArray) -> Result<PrimitiveArray<T>> +where + T: ArrowPrimitiveType, +{ + let width = size_of::<T::Native>(); + if array.value_size() != width { + return Err(internal_datafusion_err!( + "FixedSizeBinary filter: expected {width}-byte values, got {}", + array.value_size() + )); + } + + let source = array.values(); + let values = if source.as_ptr().cast::<T::Native>().is_aligned() { + ScalarBuffer::new(source.clone(), 0, array.len()) + } else { + // `Buffer::from(&[u8])` copies into Arrow-aligned storage. + ScalarBuffer::new(Buffer::from(source.as_slice()), 0, array.len()) + }; + + Ok(PrimitiveArray::<T>::new(values, array.nulls().cloned())) +} + +/// Adapts a primitive filter to concrete, same-width `FixedSizeBinary` arrays. +struct FixedSizeBinaryFilter<T: ArrowPrimitiveType> { Review Comment: I wonder if we really need this to be generic as it also creates a large number of monomorphized functions that basically do type dispatch. For example, here is one potential fix (from claude) that avoids the templates and simply dispatches at runtime (claude claims it requires 1/3 of the code gen) ```diff --- a/datafusion/physical-expr/src/expressions/in_list/fixed_size_binary_filter.rs +++ b/datafusion/physical-expr/src/expressions/in_list/fixed_size_binary_filter.rs @@ -38,7 +38,6 @@ //! Reinterpreting an aligned Arrow buffer is zero-copy. An unaligned buffer is //! copied into aligned primitive storage before filter construction or probing. -use std::marker::PhantomData; use std::mem::size_of; use std::sync::Arc; @@ -84,16 +83,12 @@ where } /// Adapts a primitive filter to concrete, same-width `FixedSizeBinary` arrays. -struct FixedSizeBinaryFilter<T: ArrowPrimitiveType> { +struct FixedSizeBinaryFilter { data_type: DataType, inner: StaticFilterRef, - _marker: PhantomData<T>, } -impl<T> StaticFilter for FixedSizeBinaryFilter<T> -where - T: ArrowPrimitiveType + Send + Sync + 'static, -{ +impl StaticFilter for FixedSizeBinaryFilter { fn null_count(&self) -> usize { self.inner.null_count() } @@ -114,27 +109,25 @@ where self.data_type ) })?; - let primitive = reinterpret_as_primitive::<T>(array)?; - self.inner.contains(&primitive, negated) + let primitive = reinterpret(array)?; + self.inner.contains(primitive.as_ref(), negated) } } -fn instantiate_for_primitive<T>(array: &FixedSizeBinaryArray) -> Result<StaticFilterRef> -where - T: ArrowPrimitiveType + Send + Sync + 'static, -{ - let primitive: ArrayRef = Arc::new(reinterpret_as_primitive::<T>(array)?); - let inner = instantiate_primitive_filter(&primitive)?.ok_or_else(|| { - internal_datafusion_err!( - "FixedSizeBinary filter: no primitive filter for {}", - primitive.data_type() - ) - })?; - Ok(Arc::new(FixedSizeBinaryFilter::<T> { - data_type: array.data_type().clone(), - inner, - _marker: PhantomData, - })) - +/// Reinterprets a supported-width array as its same-width primitive array. +fn reinterpret(array: &FixedSizeBinaryArray) -> Result<ArrayRef> { + Ok(match array.value_size() { + 1 => Arc::new(reinterpret_as_primitive::<UInt8Type>(array)?) as ArrayRef, + 2 => Arc::new(reinterpret_as_primitive::<UInt16Type>(array)?), + 4 => Arc::new(reinterpret_as_primitive::<UInt32Type>(array)?), + 8 => Arc::new(reinterpret_as_primitive::<UInt64Type>(array)?), + 16 => Arc::new(reinterpret_as_primitive::<Decimal128Type>(array)?), + width => { + return Err(internal_datafusion_err!( + "FixedSizeBinary filter: unsupported width {width}" + )); + } + }) } /// Creates an optimized filter for supported concrete `FixedSizeBinary` arrays. @@ -144,19 +137,24 @@ pub(super) fn instantiate_fixed_size_binary_filter( let DataType::FixedSizeBinary(width) = in_array.data_type() else { return Ok(None); }; + if !matches!(width, 1 | 2 | 4 | 8 | 16) { + return Ok(None); + } let Some(array) = in_array.as_fixed_size_binary_opt() else { return Ok(None); }; - let filter = match width { - 1 => instantiate_for_primitive::<UInt8Type>(array)?, - 2 => instantiate_for_primitive::<UInt16Type>(array)?, - 4 => instantiate_for_primitive::<UInt32Type>(array)?, - 8 => instantiate_for_primitive::<UInt64Type>(array)?, - 16 => instantiate_for_primitive::<Decimal128Type>(array)?, - _ => return Ok(None), - }; - Ok(Some(filter)) + let primitive = reinterpret(array)?; + let inner = instantiate_primitive_filter(&primitive)?.ok_or_else(|| { + internal_datafusion_err!( + "FixedSizeBinary filter: no primitive filter for {}", + primitive.data_type() + ) + })?; + Ok(Some(Arc::new(FixedSizeBinaryFilter { + data_type: in_array.data_type().clone(), + inner, + }))) } #[cfg(test)] ``` ########## datafusion/physical-expr/src/expressions/in_list/fixed_size_binary_filter.rs: ########## @@ -0,0 +1,371 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Optimized filters for fixed-size binary `IN` lists. +//! +//! Supported widths use an Arrow primitive representation with the same +//! in-memory size: +//! +//! | Width | Primitive representation | +//! |------:|--------------------------| +//! | 1 | `UInt8` | +//! | 2 | `UInt16` | +//! | 4 | `UInt32` | +//! | 8 | `UInt64` | +//! | 16 | `Decimal128` | +//! +//! The shared primitive selector applies the native primitive branchless cutoffs +//! and chooses the bitmap or hash-set fallback. +//! +//! The list and input bytes are read the same way, so each primitive value is +//! an exact key for comparison, bitmap lookup, or hashing. No arithmetic, +//! ordering, or decimal operations are used. +//! +//! Reinterpreting an aligned Arrow buffer is zero-copy. An unaligned buffer is +//! copied into aligned primitive storage before filter construction or probing. + +use std::marker::PhantomData; +use std::mem::size_of; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanArray, FixedSizeBinaryArray, PrimitiveArray, +}; +use arrow::buffer::{Buffer, ScalarBuffer}; +use arrow::datatypes::{ + ArrowPrimitiveType, DataType, Decimal128Type, UInt8Type, UInt16Type, UInt32Type, + UInt64Type, +}; +use datafusion_common::{Result, exec_datafusion_err, internal_datafusion_err}; + +use super::primitive_filter::instantiate_primitive_filter; +use super::static_filter::{StaticFilter, StaticFilterRef, handle_dictionary}; + +/// Reinterpret fixed-size binary values as same-width primitive values. +/// +/// Arrow buffers are normally sufficiently aligned, making this zero-copy. A +/// valid Arrow array can still be constructed from a sliced, unaligned buffer; +/// in that case, copy each value into aligned primitive storage. +fn reinterpret_as_primitive<T>(array: &FixedSizeBinaryArray) -> Result<PrimitiveArray<T>> +where + T: ArrowPrimitiveType, +{ + let width = size_of::<T::Native>(); + if array.value_size() != width { + return Err(internal_datafusion_err!( + "FixedSizeBinary filter: expected {width}-byte values, got {}", + array.value_size() + )); + } + + let source = array.values(); + let values = if source.as_ptr().cast::<T::Native>().is_aligned() { + ScalarBuffer::new(source.clone(), 0, array.len()) + } else { + // `Buffer::from(&[u8])` copies into Arrow-aligned storage. + ScalarBuffer::new(Buffer::from(source.as_slice()), 0, array.len()) + }; + + Ok(PrimitiveArray::<T>::new(values, array.nulls().cloned())) +} + +/// Adapts a primitive filter to concrete, same-width `FixedSizeBinary` arrays. +struct FixedSizeBinaryFilter<T: ArrowPrimitiveType> { + data_type: DataType, + inner: StaticFilterRef, + _marker: PhantomData<T>, +} + +impl<T> StaticFilter for FixedSizeBinaryFilter<T> +where + T: ArrowPrimitiveType + Send + Sync + 'static, +{ + fn null_count(&self) -> usize { + self.inner.null_count() + } + + fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> { + handle_dictionary!(self, v, negated); Review Comment: I filed this idea as an issue for follow up: - https://github.com/apache/datafusion/issues/24658 ########## datafusion/physical-expr/src/expressions/in_list/fixed_size_binary_filter.rs: ########## @@ -0,0 +1,371 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Optimized filters for fixed-size binary `IN` lists. +//! +//! Supported widths use an Arrow primitive representation with the same +//! in-memory size: +//! +//! | Width | Primitive representation | +//! |------:|--------------------------| +//! | 1 | `UInt8` | +//! | 2 | `UInt16` | +//! | 4 | `UInt32` | +//! | 8 | `UInt64` | +//! | 16 | `Decimal128` | +//! +//! The shared primitive selector applies the native primitive branchless cutoffs +//! and chooses the bitmap or hash-set fallback. +//! +//! The list and input bytes are read the same way, so each primitive value is +//! an exact key for comparison, bitmap lookup, or hashing. No arithmetic, +//! ordering, or decimal operations are used. +//! +//! Reinterpreting an aligned Arrow buffer is zero-copy. An unaligned buffer is +//! copied into aligned primitive storage before filter construction or probing. + +use std::marker::PhantomData; +use std::mem::size_of; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanArray, FixedSizeBinaryArray, PrimitiveArray, +}; +use arrow::buffer::{Buffer, ScalarBuffer}; +use arrow::datatypes::{ + ArrowPrimitiveType, DataType, Decimal128Type, UInt8Type, UInt16Type, UInt32Type, + UInt64Type, +}; +use datafusion_common::{Result, exec_datafusion_err, internal_datafusion_err}; + +use super::primitive_filter::instantiate_primitive_filter; +use super::static_filter::{StaticFilter, StaticFilterRef, handle_dictionary}; + +/// Reinterpret fixed-size binary values as same-width primitive values. +/// +/// Arrow buffers are normally sufficiently aligned, making this zero-copy. A +/// valid Arrow array can still be constructed from a sliced, unaligned buffer; +/// in that case, copy each value into aligned primitive storage. +fn reinterpret_as_primitive<T>(array: &FixedSizeBinaryArray) -> Result<PrimitiveArray<T>> +where + T: ArrowPrimitiveType, +{ + let width = size_of::<T::Native>(); + if array.value_size() != width { + return Err(internal_datafusion_err!( + "FixedSizeBinary filter: expected {width}-byte values, got {}", + array.value_size() + )); + } + + let source = array.values(); + let values = if source.as_ptr().cast::<T::Native>().is_aligned() { + ScalarBuffer::new(source.clone(), 0, array.len()) + } else { + // `Buffer::from(&[u8])` copies into Arrow-aligned storage. + ScalarBuffer::new(Buffer::from(source.as_slice()), 0, array.len()) + }; + + Ok(PrimitiveArray::<T>::new(values, array.nulls().cloned())) +} + +/// Adapts a primitive filter to concrete, same-width `FixedSizeBinary` arrays. +struct FixedSizeBinaryFilter<T: ArrowPrimitiveType> { + data_type: DataType, + inner: StaticFilterRef, + _marker: PhantomData<T>, +} + +impl<T> StaticFilter for FixedSizeBinaryFilter<T> +where + T: ArrowPrimitiveType + Send + Sync + 'static, +{ + fn null_count(&self) -> usize { + self.inner.null_count() + } + + fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> { + handle_dictionary!(self, v, negated); Review Comment: One thing I noticed while reviewing this that probably would reduce the code size in general, including here, is to avoid handling dictionaries **within** each type (which results in many different copies of each of the filter types). Instead, we can probably reduce the code by handling it the top level somehow So instead of `FixedSizeBinaryFilter` handling all the dictionary types itself, instead we might instead instantiate the FixedSizeBinaryFilter` for only values, and do the dictionary handling at a higher layer Maybe something like ```rust // dictionary_filter.rs pub(super) struct DictionaryFilter { /// The haystack's (non-dictionary) value type. values_type: DataType, inner: StaticFilterRef, } impl StaticFilter for DictionaryFilter { fn null_count(&self) -> usize { self.inner.null_count() } fn contains(&self, v: &dyn Array, negated: bool) -> Result<BooleanArray> { downcast_dictionary_array! { v => { if v.values().data_type() == &self.values_type { let values_contains = self.inner.contains(v.values().as_ref(), negated)?; let result = take(&values_contains, v.keys(), None)?; return Ok(downcast_array(result.as_ref())); } } _ => {} } self.inner.contains(v, negated) } } ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
