From d7746cb4c5c97dd9f9363ac7030851f9e624294a Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:23:01 -0800 Subject: [PATCH] refactor: build the full match inverse in PruningPredicateBuilder A scan proves that every row of a row group passes a filter by pruning with the inverse of the filter. The inverse must keep a container that can hold a NULL, because a row where the filter is NULL does not pass. The Parquet crate adds these null checks to the source expression, as one `IS NULL` term for each nullable column of the filter, before PruningPredicate rewrites it. That needs a source expression for every input of the predicate, so it works for columns only. Add PruningPredicateBuilder::try_build_inverse. It adds the null checks after the rewrite, as one `null_count > 0` term for each nullable column in RequiredColumns. Nothing has to collect the inputs of the predicate. Two details change: - Only the columns that the inverse reads get a null check. The rewrite replaces a comparison that it cannot use with `true`, so it prunes only if the comparisons that it reads are FALSE on their own, and `FALSE AND x` is FALSE also for a NULL `x`. The scan proves a full match in a few more cases. - The inverse has no literal guarantees. A guarantee prunes a container before a null check can keep it. Co-Authored-By: Claude Fable 5.2 --- datafusion/datasource-parquet/src/mod.rs | 1 - .../datasource-parquet/src/page_filter.rs | 8 +- datafusion/datasource-parquet/src/pruning.rs | 58 ----- .../src/row_group_filter.rs | 11 +- datafusion/pruning/src/pruning_predicate.rs | 232 +++++++++++++++++- 5 files changed, 238 insertions(+), 72 deletions(-) delete mode 100644 datafusion/datasource-parquet/src/pruning.rs diff --git a/datafusion/datasource-parquet/src/mod.rs b/datafusion/datasource-parquet/src/mod.rs index 4bb7166fac1e1..03eb960b6ab78 100644 --- a/datafusion/datasource-parquet/src/mod.rs +++ b/datafusion/datasource-parquet/src/mod.rs @@ -22,7 +22,6 @@ mod nested_schema_pruning; mod opener; mod page_filter; mod projection_read_plan; -mod pruning; mod push_decoder; mod reader; mod row_filter; diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index 0e2962e43e451..f93f84fb0d230 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -9,7 +9,6 @@ use std::sync::Arc; use super::metrics::ParquetFileMetrics; use crate::metadata::has_untrusted_min_max_order; -use crate::pruning::build_inverted_predicate; use crate::{ParquetAccessPlan, RowGroupAccess}; use arrow::array::BooleanArray; @@ -253,7 +252,12 @@ impl PagePruningAccessPlanFilter { self.predicates .iter() .map(|predicate| { - let inverted = build_inverted_predicate(predicate, arrow_schema)?; + let inverted = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(predicate.schema())) + .with_max_in_list_size(predicate.max_in_list_size()) + .try_build_inverse(Arc::clone(predicate.orig_expr())) + .ok() + .flatten()?; inverted .required_columns() .single_column() diff --git a/datafusion/datasource-parquet/src/pruning.rs b/datafusion/datasource-parquet/src/pruning.rs deleted file mode 100644 index 8e3d79bf1ba3e..0000000000000 --- a/datafusion/datasource-parquet/src/pruning.rs +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership -// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements - -//! Shared predicate construction for row-group and page-index pruning. - -use std::sync::Arc; - -use arrow::datatypes::Schema; -use datafusion_expr::Operator; -use datafusion_physical_expr::expressions::{BinaryExpr, IsNullExpr, NotExpr}; -use datafusion_physical_expr::utils::collect_columns; -use datafusion_physical_expr::{PhysicalExpr, PhysicalExprSimplifier}; -use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; - -/// Build a null-safe inverse used to prove every row matches `predicate`. -/// -/// Rows where a filter evaluates to NULL do not pass it, so nullable referenced -/// columns are included in the inverse. If the inverse can be pruned, every row -/// is guaranteed to satisfy the original predicate. -pub(crate) fn build_inverted_predicate( - predicate: &PruningPredicate, - arrow_schema: &Schema, -) -> Option { - // Some pruning rewrites preserve only whether rows can be TRUE, while - // full-match inference must distinguish FALSE from UNKNOWN. - if !predicate.can_be_inverted_for_full_match() { - return None; - } - let mut inverted_expr: Arc = - Arc::new(NotExpr::new(Arc::clone(predicate.orig_expr()))); - - let mut columns = collect_columns(predicate.orig_expr()) - .into_iter() - .filter(|column| arrow_schema.field(column.index()).is_nullable()) - .collect::>(); - columns.sort_by(|a, b| { - a.index() - .cmp(&b.index()) - .then_with(|| a.name().cmp(b.name())) - }); - - for column in columns { - inverted_expr = Arc::new(BinaryExpr::new( - inverted_expr, - Operator::Or, - Arc::new(IsNullExpr::new(Arc::new(column))), - )); - } - - let simplifier = PhysicalExprSimplifier::new(arrow_schema); - let inverted_expr = simplifier.simplify(inverted_expr).ok()?; - PruningPredicateBuilder::new() - .with_file_schema(Arc::clone(predicate.schema())) - .with_max_in_list_size(predicate.max_in_list_size()) - .try_build(inverted_expr) - .ok() -} diff --git a/datafusion/datasource-parquet/src/row_group_filter.rs b/datafusion/datasource-parquet/src/row_group_filter.rs index 97600a7ae374a..1bd83cba3e71f 100644 --- a/datafusion/datasource-parquet/src/row_group_filter.rs +++ b/datafusion/datasource-parquet/src/row_group_filter.rs @@ -8,7 +8,6 @@ use std::sync::Arc; use super::{ParquetAccessPlan, ParquetFileMetrics, RowGroupAccess}; use crate::bloom_filter::BloomFilterStatistics; use crate::metadata::{has_untrusted_byte_array_stats, has_untrusted_min_max_order}; -use crate::pruning::build_inverted_predicate; use arrow::array::{ArrayRef, BooleanArray, UInt64Array}; use arrow::compute::nullif; use arrow::datatypes::Schema; @@ -16,7 +15,7 @@ use datafusion_common::parquet_config::RowGroupRangeAssignment; use datafusion_common::pruning::PruningStatistics; use datafusion_common::{Column, Result, ScalarValue}; use datafusion_datasource::FileRange; -use datafusion_pruning::PruningPredicate; +use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; use parquet::basic::ColumnOrder; use parquet::file::metadata::{ParquetMetaData, RowGroupMetaData}; @@ -410,7 +409,12 @@ impl RowGroupAccessPlanFilter { } let arrow_schema = pruning_stats.arrow_schema; - let Some(inverted_predicate) = build_inverted_predicate(predicate, arrow_schema) + let Some(inverted_predicate) = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(predicate.schema())) + .with_max_in_list_size(predicate.max_in_list_size()) + .try_build_inverse(Arc::clone(predicate.orig_expr())) + .ok() + .flatten() else { return; }; @@ -656,7 +660,6 @@ mod tests { expressions::{BinaryExpr, CastExpr, Column as PhysicalColumn, Literal}, }; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; - use datafusion_pruning::PruningPredicateBuilder; use parquet::arrow::ArrowSchemaConverter; use parquet::arrow::arrow_reader::{RowSelection, RowSelector}; use parquet::basic::LogicalType; diff --git a/datafusion/pruning/src/pruning_predicate.rs b/datafusion/pruning/src/pruning_predicate.rs index b7325d90d5672..dd8170f726b21 100644 --- a/datafusion/pruning/src/pruning_predicate.rs +++ b/datafusion/pruning/src/pruning_predicate.rs @@ -557,6 +557,49 @@ impl<'a> PruningPredicateBuilder<'a> { can_be_inverted_for_full_match: !properties.has_filter_semantics_only, }) } + + /// Builds the predicate that proves that every row of a container passes + /// `predicate`. If the result prunes a container, every row of the + /// container passes `predicate`. + /// + /// Returns `Ok(None)` if no inverse can prove a full match, see + /// [`PruningPredicate::can_be_inverted_for_full_match`]. + /// + /// A row passes a filter only if the filter is TRUE. So the result must + /// keep a container that can hold a row for which `predicate` is FALSE + /// or NULL: + /// + /// ```text + /// rewrite(NOT predicate) OR x_null_count > 0 OR y_null_count > 0 ... + /// \___________________/ \________________________________/ + /// a row can be FALSE a row can be NULL: one term for each + /// nullable column `x`, `y` that + /// `rewrite(NOT predicate)` reads + /// ``` + /// + /// A column that the rewrite does not read needs no term. The rewrite + /// replaces a comparison that it cannot use with `true`. So it prunes a + /// container only if the comparisons that it reads are FALSE on their own, + /// and `FALSE AND x` is FALSE for every `x`, also for NULL. + pub fn try_build_inverse( + self, + predicate: Arc, + ) -> Result> { + let file_schema = self.file_schema.clone().ok_or_else(|| { + _internal_datafusion_err!( + "PruningPredicateBuilder requires a file schema (call `with_file_schema`)" + ) + })?; + let inverted: Arc = + Arc::new(phys_expr::NotExpr::new(predicate)); + let inverted = PhysicalExprSimplifier::new(&file_schema).simplify(inverted)?; + let mut inverse = self.try_build(inverted)?; + if !inverse.can_be_inverted_for_full_match { + return Ok(None); + } + inverse.keep_containers_with_nulls()?; + Ok(Some(inverse)) + } } /// Rewrites predicates that [`PredicateRewriter`] can not handle, e.g. certain @@ -738,6 +781,46 @@ impl PruningPredicate { self.can_be_inverted_for_full_match } + /// Changes this predicate to keep every container that can hold a NULL in + /// a column that the predicate reads. + fn keep_containers_with_nulls(&mut self) -> Result<()> { + let mut columns: Vec = vec![]; + for (column, _, _) in self.required_columns.iter() { + if !columns.contains(column) { + columns.push(column.clone()); + } + } + for column in columns { + let field = self.schema.field_with_name(column.name())?; + if !field.is_nullable() { + continue; + } + let null_count_field = Field::new(field.name(), DataType::UInt64, true); + let column_expr = Arc::new(column.clone()) as _; + let null_count = self.required_columns.null_count_column_expr( + &column, + &column_expr, + &null_count_field, + )?; + // A missing null count makes this term NULL, which keeps the + // container. + let has_nulls = Arc::new(phys_expr::BinaryExpr::new( + null_count, + Operator::Gt, + Arc::new(phys_expr::Literal::new(ScalarValue::UInt64(Some(0)))), + )); + self.predicate_expr = Arc::new(phys_expr::BinaryExpr::new( + Arc::clone(&self.predicate_expr), + Operator::Or, + has_nulls, + )); + } + // A literal guarantee prunes a container on its own, before the + // null count terms can keep it. + self.literal_guarantees.clear(); + Ok(()) + } + pub fn required_columns(&self) -> &RequiredColumns { &self.required_columns } @@ -2895,6 +2978,91 @@ mod tests { } } + /// Returns the inverse of the predicate of `expr`, see + /// [`PruningPredicateBuilder::try_build_inverse`]. + fn full_match_inverse(expr: Expr, schema: &SchemaRef) -> PruningPredicate { + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(schema)) + .try_build_inverse(logical2physical(&expr, schema)) + .unwrap() + .unwrap() + } + + #[test] + fn full_match_inverse_keeps_containers_with_nulls() { + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)])); + let inverse = full_match_inverse(col("i").gt(lit(5)), &schema); + assert_eq!( + inverse.predicate_expr().to_string(), + "i_null_count@1 != row_count@2 AND i_min@0 <= 5 OR i_null_count@1 > 0" + ); + // `false` means that every row of the container passes `i > 5`. + let statistics = TestStatistics::new().with( + "i", + ContainerStats::new_i32( + vec![Some(6), Some(6), Some(6), Some(1)], // min + vec![Some(9), Some(9), Some(9), Some(9)], // max + ) + // Container 1 has a NULL row. Container 2 has no null count. + .with_null_counts(vec![Some(0), Some(1), None, Some(0)]) + .with_row_counts(vec![Some(4); 4]), + ); + assert_eq!( + inverse.prune(&statistics).unwrap(), + [false, true, true, true] + ); + } + + #[test] + fn full_match_inverse_has_no_null_term_for_a_non_nullable_column() { + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)])); + let inverse = full_match_inverse(col("i").gt(lit(5)), &schema); + assert_eq!( + inverse.predicate_expr().to_string(), + "i_null_count@1 != row_count@2 AND i_min@0 <= 5" + ); + } + + #[test] + fn full_match_inverse_ignores_columns_that_it_does_not_read() { + let schema = Arc::new(Schema::new(vec![ + Field::new("i", DataType::Int32, true), + Field::new("j", DataType::Int32, true), + ])); + // The rewrite cannot use `j + 1 > 3`. + let expr = col("i").gt(lit(5)).or((col("j") + lit(1)).gt(lit(3))); + let inverse = full_match_inverse(expr, &schema); + assert_eq!( + inverse.predicate_expr().to_string(), + "i_null_count@1 != row_count@2 AND i_min@0 <= 5 OR i_null_count@1 > 0" + ); + // Every `i` is greater than 5, so every row passes the predicate: + // `TRUE OR x` is TRUE, also if `j` is NULL. + let statistics = TestStatistics::new() + .with( + "i", + ContainerStats::new_i32(vec![Some(6)], vec![Some(9)]) + .with_null_counts(vec![Some(0)]) + .with_row_counts(vec![Some(4)]), + ) + .with( + "j", + ContainerStats::new_i32(vec![Some(0)], vec![Some(0)]) + .with_null_counts(vec![Some(2)]) + .with_row_counts(vec![Some(4)]), + ); + assert_eq!(inverse.prune(&statistics).unwrap(), [false]); + } + + #[test] + fn full_match_inverse_has_no_literal_guarantees() { + let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)])); + // The inverse is `i = 1`. Its guarantee `i IN (1)` would prune a + // container that holds a NULL and no 1, where `i != 1` is NULL. + let inverse = full_match_inverse(col("i").not_eq(lit(1)), &schema); + assert!(inverse.literal_guarantees().is_empty()); + } + #[test] fn prune_all_rows_null_counts() { // if null_count = row_count then we should prune the container for i = 0 @@ -3857,6 +4025,16 @@ mod tests { .try_build(expr) } + fn large_in_list_inverse( + expr: PhysicalExprRef, + schema: SchemaRef, + ) -> Result> { + PruningPredicateBuilder::new() + .with_file_schema(schema) + .with_max_in_list_size(10_000) + .try_build_inverse(expr) + } + fn assert_per_value_fallback( predicate: &PruningPredicate, expected_literals: &[ScalarValue], @@ -4487,6 +4665,14 @@ mod tests { "negated={negated}, limit={limit}" ); assert!(predicate.can_be_inverted_for_full_match()); + assert!( + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_max_in_list_size(limit) + .try_build_inverse(Arc::clone(&expr))? + .is_some(), + "negated={negated}, limit={limit}" + ); assert_eq!(predicate.max_in_list_size(), limit); } @@ -4530,12 +4716,14 @@ mod tests { let positive_or = col("c1") .in_list(with_null.clone(), false) .or(col("c1").eq(lit("middle"))); + let positive_or = logical2physical(&positive_or, &schema); let predicate = large_in_list_pruning_predicate( - logical2physical(&positive_or, &schema), + Arc::clone(&positive_or), Arc::clone(&schema), )?; assert_eq!(predicate.prune(&or_stats)?, [true, false]); assert!(!predicate.can_be_inverted_for_full_match()); + assert!(large_in_list_inverse(positive_or, Arc::clone(&schema))?.is_none()); for negated in [false, true] { let expr = col("c1").in_list(with_null.clone(), negated); @@ -4546,9 +4734,23 @@ mod tests { assert!(is_always_true(default.predicate_expr()), "{expr}"); assert_eq!(default.prune(&stats)?, [true, true]); assert!(default.can_be_inverted_for_full_match()); + assert!( + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .try_build_inverse(Arc::clone(&physical))? + .is_some(), + "{expr}" + ); - let raised = large_in_list_pruning_predicate(physical, Arc::clone(&schema))?; + let raised = large_in_list_pruning_predicate( + Arc::clone(&physical), + Arc::clone(&schema), + )?; assert!(!raised.can_be_inverted_for_full_match()); + assert!( + large_in_list_inverse(physical, Arc::clone(&schema))?.is_none(), + "{expr}" + ); if negated { assert!(is_always_false(raised.predicate_expr()), "{expr}"); assert_eq!(raised.prune(&stats)?, [false, false]); @@ -4568,22 +4770,29 @@ mod tests { std::iter::repeat_n(lit(ScalarValue::Utf8(None)), 21).collect::>(); for negated in [false, true] { let expr = col("c1").in_list(all_null.clone(), negated); + let physical = logical2physical(&expr, &schema); let predicate = large_in_list_pruning_predicate( - logical2physical(&expr, &schema), + Arc::clone(&physical), Arc::clone(&schema), )?; assert!(is_always_false(predicate.predicate_expr()), "{expr}"); assert_eq!(predicate.prune(&stats)?, [false, false]); assert!(!predicate.can_be_inverted_for_full_match()); + assert!( + large_in_list_inverse(physical, Arc::clone(&schema))?.is_none(), + "{expr}" + ); } let integer_schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Int32, true)])); let mut integer_values = (0..21).map(lit).collect::>(); integer_values.push(lit(ScalarValue::Int32(None))); + let integer_expr = + logical2physical(&col("c1").in_list(integer_values, false), &integer_schema); let integer_predicate = large_in_list_pruning_predicate( - logical2physical(&col("c1").in_list(integer_values, false), &integer_schema), - integer_schema, + Arc::clone(&integer_expr), + Arc::clone(&integer_schema), )?; assert!( integer_predicate @@ -4592,6 +4801,7 @@ mod tests { .contains("IN_SET_INTERSECTS") ); assert!(!integer_predicate.can_be_inverted_for_full_match()); + assert!(large_in_list_inverse(integer_expr, integer_schema)?.is_none()); // The compact false predicate has the same filter result as the original // NOT IN expression, which returns UNKNOWN for values outside the list. @@ -4641,9 +4851,13 @@ mod tests { &true, &schema, )?; - let predicate = large_in_list_pruning_predicate(not_in, Arc::clone(&schema))?; + let predicate = large_in_list_pruning_predicate( + Arc::clone(¬_in), + Arc::clone(&schema), + )?; assert!(is_always_false(predicate.predicate_expr())); assert!(!predicate.can_be_inverted_for_full_match()); + assert!(large_in_list_inverse(not_in, Arc::clone(&schema))?.is_none()); assert!(predicate.required_columns.columns.is_empty()); let all_null = phys_expr::in_list( @@ -4656,9 +4870,13 @@ mod tests { &false, &schema, )?; - let predicate = large_in_list_pruning_predicate(all_null, schema)?; + let predicate = large_in_list_pruning_predicate( + Arc::clone(&all_null), + Arc::clone(&schema), + )?; assert!(is_always_false(predicate.predicate_expr())); assert!(!predicate.can_be_inverted_for_full_match()); + assert!(large_in_list_inverse(all_null, schema)?.is_none()); assert!(predicate.required_columns.columns.is_empty()); } Ok(())