xanderbailey commented on code in PR #2398: URL: https://github.com/apache/iceberg-rust/pull/2398#discussion_r3989969240
########## crates/iceberg/src/expr/visitors/bloom_filter_evaluator.rs: ########## @@ -0,0 +1,1559 @@ +// 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. + +//! Evaluates predicates against Parquet bloom filters to determine whether +//! a row group can be skipped. + +use std::collections::{HashMap, HashSet}; + +use fnv::FnvHashSet; +use parquet::basic::Type as PhysicalType; +use parquet::bloom_filter::Sbbf; +use parquet::data_type::ByteArray; + +use crate::Result; +use crate::expr::visitors::bound_predicate_visitor::{BoundPredicateVisitor, visit}; +use crate::expr::{BoundPredicate, BoundReference}; +use crate::spec::decimal_utils::decimal_to_fixed_length_bytes_exact; +use crate::spec::{Datum, PrimitiveLiteral, PrimitiveType, Type}; + +const ROW_GROUP_MIGHT_MATCH: Result<bool> = Ok(true); +const ROW_GROUP_CANT_MATCH: Result<bool> = Ok(false); + +/// A column's bloom filter for one row group, together with the file's physical +/// encoding of that column. A probe must be encoded the way the writer encoded +/// the values it inserted, so the encoding travels with the filter. +pub(crate) struct ColumnBloomFilter { + sbbf: Sbbf, + physical_type: PhysicalType, + /// `type_length` from the file's column descriptor. Only meaningful for + /// `FIXED_LEN_BYTE_ARRAY`. + type_length: i32, +} + +impl ColumnBloomFilter { + pub(crate) fn new(sbbf: Sbbf, physical_type: PhysicalType, type_length: i32) -> Self { + Self { + sbbf, + physical_type, + type_length, + } + } +} + +pub(crate) struct BloomFilterEvaluator<'a> { + /// Maps Iceberg field_id -> bloom filter for this row group + bloom_filters: &'a HashMap<i32, ColumnBloomFilter>, +} + +impl BloomFilterEvaluator<'_> { + /// Evaluate the predicate against the provided bloom filters. + /// Returns `false` if the row group definitely does not match, + /// `true` if it might match. + pub(crate) fn eval( + filter: &BoundPredicate, + bloom_filters: &HashMap<i32, ColumnBloomFilter>, + ) -> Result<bool> { + if bloom_filters.is_empty() { + return ROW_GROUP_MIGHT_MATCH; + } + + let mut evaluator = BloomFilterEvaluator { bloom_filters }; + visit(&mut evaluator, filter) + } + + fn check_datum(&self, reference: &BoundReference, datum: &Datum) -> bool { + let field_id = reference.field().id; + let Some(column) = self.bloom_filters.get(&field_id) else { + // No bloom filter for this column — conservatively might match + return true; + }; + + check_in_bloom_filter(column, datum) + } +} + +/// Collects field IDs that appear in `eq` or `in` predicates — the only +/// predicate types that benefit from bloom filter checks. +/// +/// Each node returns the field IDs its subtree contributes, mirroring +/// [`BloomFilterEvaluator`]'s structure so that a field is collected only where +/// the evaluator can act on it. In particular `not` discards its subtree: the +/// evaluator's `not` returns might-match regardless, so a filter fetched for a +/// field under a `NOT` could never prune and would be pure wasted I/O. +/// +/// Boolean fields are skipped for the same reason: with only two possible values, +/// a column chunk's min/max statistics already determine membership exactly, so a +/// bloom filter cannot prune anything statistics did not, and reading one costs a +/// round trip to learn nothing. +pub(crate) fn collect_bloom_filter_field_ids(predicate: &BoundPredicate) -> Result<HashSet<i32>> { + visit(&mut BloomFilterFieldIdCollector, predicate) +} + +struct BloomFilterFieldIdCollector; + +/// Field IDs worth fetching a bloom filter for: none if probing the column could +/// never prune. +fn probeable_field_id(reference: &BoundReference) -> HashSet<i32> { + if matches!( + reference.field().field_type.as_ref(), + Type::Primitive(PrimitiveType::Boolean) + ) { + return HashSet::new(); + } + HashSet::from([reference.field().id]) +} + +impl BoundPredicateVisitor for BloomFilterFieldIdCollector { + type T = HashSet<i32>; + + fn always_true(&mut self) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn always_false(&mut self) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn and(&mut self, mut lhs: Self::T, rhs: Self::T) -> Result<Self::T> { + lhs.extend(rhs); + Ok(lhs) + } + + fn or(&mut self, mut lhs: Self::T, rhs: Self::T) -> Result<Self::T> { + lhs.extend(rhs); + Ok(lhs) + } + + fn not(&mut self, _inner: Self::T) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn is_null(&mut self, _r: &BoundReference, _p: &BoundPredicate) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn not_null(&mut self, _r: &BoundReference, _p: &BoundPredicate) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn is_nan(&mut self, _r: &BoundReference, _p: &BoundPredicate) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn not_nan(&mut self, _r: &BoundReference, _p: &BoundPredicate) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn less_than( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn less_than_or_eq( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn greater_than( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn greater_than_or_eq( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn eq(&mut self, r: &BoundReference, _l: &Datum, _p: &BoundPredicate) -> Result<Self::T> { + Ok(probeable_field_id(r)) + } + + fn not_eq(&mut self, _r: &BoundReference, _l: &Datum, _p: &BoundPredicate) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn starts_with( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn not_starts_with( + &mut self, + _r: &BoundReference, + _l: &Datum, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } + + fn r#in( + &mut self, + r: &BoundReference, + _literals: &FnvHashSet<Datum>, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(probeable_field_id(r)) + } + + fn not_in( + &mut self, + _r: &BoundReference, + _literals: &FnvHashSet<Datum>, + _p: &BoundPredicate, + ) -> Result<Self::T> { + Ok(HashSet::new()) + } +} + +/// Check whether a datum value might be present in the bloom filter. +/// +/// The value must be checked using the same physical encoding the Parquet +/// writer used when inserting into the bloom filter. We use the actual +/// physical type from the column metadata to ensure correctness regardless +/// of which writer produced the file. +fn check_in_bloom_filter(column: &ColumnBloomFilter, datum: &Datum) -> bool { + let ColumnBloomFilter { + sbbf, + physical_type, + type_length, + } = column; + let physical_type = *physical_type; + + match datum.literal() { + // Parquet does not define bloom filter semantics for BOOLEAN — parquet-java + // only hashes int/long/float/double/binary. arrow-rs does write them, but min/max + // statistics already decide membership for a two-valued domain, so there is nothing to gain. + PrimitiveLiteral::Boolean(_) => true, + // A promoted column (int -> long, float -> double) keeps its original + // physical width in files written before the promotion, and the writer + // hashed that width, so probe at the file's width rather than the + // predicate's. + PrimitiveLiteral::Int(v) => match physical_type { + PhysicalType::INT32 => sbbf.check(v), + PhysicalType::INT64 => sbbf.check(&i64::from(*v)), + _ => true, + }, + PrimitiveLiteral::Long(v) => match physical_type { + PhysicalType::INT64 => sbbf.check(v), + PhysicalType::INT32 => match i32::try_from(*v) { + Ok(narrowed) => sbbf.check(&narrowed), + // Too wide for an INT32 column to hold, so there is nothing + // meaningful to probe — keep the row group. + Err(_) => true, + }, + _ => true, + }, + PrimitiveLiteral::Float(v) => match physical_type { + PhysicalType::FLOAT => sbbf.check(&v.0), Review Comment: Okay bare with me, I have never looked this closely at IEEE float equality but here's my reading... https://github.com/apache/arrow-rs/blob/59.2.0/arrow-array/src/arithmetic.rs#L397-L402 ```rust fn is_eq(self, rhs: Self) -> bool { // Equivalent to `self.total_cmp(&rhs).is_eq()` // but LLVM isn't able to realise this is bitwise equality // https://rust.godbolt.org/z/347nWGxoW self.to_bits() == rhs.to_bits() } ``` So arrow's float equality is total-order, not IEEE: `-0.0 != 0.0`, and `NaN == NaN`. The probe and the row filter agree, and the pruning is sound. `test_bloom_pushdown_float_signed_zero` is also a controlled experiment for this rather than just a hint. With `ROWS_PER_GROUP = 20_000`, row group 0 holds 19,999 × `-0.0` plus one `5.0` filler, so its stats range is `[-0.0, 5.0]` — it spans the probe, and **nothing prunes it** on the bloom-off read. That read therefore does hand 19,999 `-0.0` values to `cmp::eq` against a `0.0` literal. IEEE-lenient eq returns 39,998 rows there; the test asserts 19,999. The bloom-off arm is the control that pins arrow's semantics on the exact path in question, and `assert_pushdown_agrees` compares full `RecordBatch` contents rather than row counts, so if arrow ever flipped `is_eq` this test fails instead of silently over-pruning. You're right that the comment's justification was sloppy, though — "for the same reason" is wrong. `Sbbf` is bitwise because it hashes raw bytes; arrow is bitwise because it implements `total_cmp` semantics. Two independent reasons that happen to agree, and conflating them is probably what made the claim look shaky. Reworded to cite `ArrowNativeTypeOp::is_eq` directly so the invariant is traceable. -- 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]
