adriangb commented on code in PR #19609:
URL: https://github.com/apache/datafusion/pull/19609#discussion_r2658117712


##########
datafusion/physical-expr-common/src/physical_expr/pruning.rs:
##########
@@ -0,0 +1,539 @@
+// 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.
+
+// Pruner Common Structs/Utilities
+
+//! This is the top-level comment for pruning via statistics propagation.
+//!
+//! TODO: This is a concise draft; it should be polished for readers with less
+//! prior background.
+//!
+//! # Introduction
+//!
+//! This module helps skip scanning data micro-partitions by evaluating 
predicates
+//! against container-level statistics.
+//!
+//! It supports pruning for complex and nested predicates through statistics
+//! propagation.
+//!
+//! For examples of pruning nested predicates via statistics propagation, see:
+//! <https://github.com/apache/datafusion/issues/19487>
+//!
+//!
+//!
+//! # Vectorized pruning intermediate representation
+//!
+//! Source statistics and intermediate pruning results are stored in Arrow 
arrays,
+//! enabling vectorized evaluation across many containers.
+//!
+//!
+//!
+//! # Difference from [`super::PhysicalExpr::evaluate_bounds`]
+//!
+//! `evaluate_bounds()` derives per-column statistics for a single plan, aimed 
at
+//! tasks like cardinality estimation and other planner fast paths. It reasons
+//! about one container and may track richer distribution details.
+//! Pruning must reason about *all* containers (potentially thousands) to 
decide
+//! which to skip, so it favors a vectorized, array-backed representation with
+//! lighter-weight stats. These are intentionally separate interfaces.
+//!
+//!
+//!
+//! # Core API/Data Structures
+//!
+//! The key structures involved in pruning are:
+//! - [`PruningStatistics`]: the input source statistics for all containers
+//! - [`super::PhysicalExpr::evaluate_pruning()`]: evaluates pruning behavior 
for predicates
+//! - [`PruningIntermediate`]: the intermediate result produced during 
statistics propagation for pruning. Its internal representation uses Arrow 
Arrays, enabling vectorized evaluation for performance.
+
+use std::{iter::repeat_n, sync::Arc};
+
+use arrow::array::{Array, ArrayRef, BooleanArray, BooleanBuilder, UInt64Array};
+use arrow::compute::kernels::boolean::and_kleene;
+use datafusion_common::pruning::PruningStatistics;
+use datafusion_common::{Result, ScalarValue, assert_eq_or_internal_err};
+
+/// Physical representation of pruning outcomes for each container:
+/// `true` = KeepAll, `false` = SkipAll, `null` = Unknown.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+///
+/// # Pruning results
+/// - KeepAll: The pruning predicate evaluates to true for all rows within a 
micro
+///   partition. Future filter evaluation can be skipped for that partition.
+/// - SkipAll: The pruning predicate evaluates to false for all rows within a 
micro
+///   partition. The partition can be skipped at scan time.
+/// - UnknownOrMixed: The statistics are insufficient to prove 
KeepAll/SkipAll, or
+///   the predicate is mixed. The predicate must be evaluated row-wise.
+///
+/// Example (`SELECT * FROM t WHERE x >= 0`):
+/// - micro_partition_a(min=0, max=10): KeepAll — can pass through `FilterExec`
+///   without re-evaluating `x >= 0`.
+/// - micro_partition_b(min=-10, max=-1): SkipAll — skip the partition 
entirely.
+/// - micro_partition_c(min=-5, max=5): Unknown — must evaluate the predicate 
on rows.
+///
+/// `PruningOutcome` provides utilities to convert between this semantic
+/// representation and its tri-state boolean encoding.
+///
+/// # Important invariants
+/// Pruning results must be sound, but need not be complete:
+/// - If a container is labeled `KeepAll` or `SkipAll`, that label must be 
correct.
+/// - If a container is labeled `Unknown` but is actually `KeepAll`/`SkipAll`,
+///   correctness is still preserved; it just means pruning was conservative.
+///
+/// Propagation implementation can be refined to reduce `Unknown` cases to 
improve
+/// pruning effectiveness.
+#[derive(Debug, Clone)]
+pub struct PruningResults {
+    results: Option<BooleanArray>,
+    /// Number of containers. Needed to infer result if all stats types are 
`None`.
+    pub num_containers: usize,
+}
+
+/// Semantic representation for items inside `PruningResults::results`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PruningOutcome {
+    KeepAll,
+    SkipAll,
+    UnknownOrMixed,
+}
+
+impl PruningResults {
+    pub fn new(array: Option<BooleanArray>, num_containers: usize) -> Self {
+        debug_assert_eq!(
+            array.as_ref().map(|a| a.len()).unwrap_or(num_containers),
+            num_containers
+        );
+        Self {
+            results: array,
+            num_containers,
+        }
+    }
+
+    pub fn none(num_containers: usize) -> Self {
+        Self::new(None, num_containers)
+    }
+
+    pub fn as_ref(&self) -> Option<&BooleanArray> {
+        self.results.as_ref()
+    }
+
+    pub fn into_inner(self) -> Option<BooleanArray> {
+        self.results
+    }
+
+    pub fn len(&self) -> usize {
+        self.results
+            .as_ref()
+            .map(|a| a.len())
+            .unwrap_or(self.num_containers)
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+}
+
+impl PruningOutcome {
+    /// Convert to/from the tri-state boolean encoding stored in 
`PruningResults`.
+    /// - Some(true)=KeepAll
+    /// - Some(false)=SkipAll
+    /// - None=(Unknown/mixed)
+    pub fn from_result_item(result_item: Option<bool>) -> Self {
+        match result_item {
+            Some(true) => PruningOutcome::KeepAll,
+            Some(false) => PruningOutcome::SkipAll,
+            None => PruningOutcome::UnknownOrMixed,
+        }
+    }
+
+    pub fn to_result_item(&self) -> Option<bool> {
+        match self {
+            PruningOutcome::KeepAll => Some(true),
+            PruningOutcome::SkipAll => Some(false),
+            PruningOutcome::UnknownOrMixed => None,
+        }
+    }
+}
+
+impl From<BooleanArray> for PruningResults {
+    fn from(array: BooleanArray) -> Self {
+        let len = array.len();
+        PruningResults::new(Some(array), len)
+    }
+}
+
+#[derive(Debug, Clone)]
+pub enum RangeStats {
+    /// Ranges for all containers in array form.
+    /// - If `mins`/`maxs` are `None`, all containers have unknown statistics.
+    /// - Each entry (per-container) may be a bound or null. Null means 
missing or
+    ///   unbounded (null in `mins` = -inf; treating missing/unbounded the same
+    ///   does not change pruning results).
+    Array {
+        mins: Option<ArrayRef>,
+        maxs: Option<ArrayRef>,
+        length: usize,
+    },
+    /// Represents a uniform literal value across all containers.
+    /// This variant make it easy to compare between literals and normal 
ranges representing
+    /// each containers' value range.
+    Scalar { value: ScalarValue, length: usize },
+}
+
+/// Null-related statistics for each container stored as a BooleanArray:
+/// `true` = NoNull, `false` = AllNull, `null` = Unknown/mixed.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+/// `NullPresence` provides utility to convert between its semantics 
representation
+/// and physical encoding.
+#[derive(Debug, Clone)]
+pub struct NullStats {
+    presence: BooleanArray,
+}
+
+/// Semantic representation for items inside `NullStats::presence`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NullPresence {
+    NoNull,
+    AllNull,
+    UnknownOrMixed,
+}
+
+impl NullPresence {
+    /// Convert to/from the tri-state boolean encoding stored in 
`NullStats.presence`
+    /// - Some(true)=NoNull
+    /// - Some(false)=AllNull
+    /// - None=(Unknown/mixed)
+    pub fn from_presence_item(presence_item: Option<bool>) -> Self {
+        match presence_item {
+            Some(true) => NullPresence::NoNull,
+            Some(false) => NullPresence::AllNull,
+            None => NullPresence::UnknownOrMixed,
+        }
+    }
+
+    pub fn to_presence_item(&self) -> Option<bool> {
+        match self {
+            NullPresence::NoNull => Some(true),
+            NullPresence::AllNull => Some(false),
+            NullPresence::UnknownOrMixed => None,
+        }
+    }
+}
+
+/// Column statistics that propagate through the `PhysicalExpr` tree nodes
+///
+/// # Important invariants
+/// Non-null stats (e.g., ranges) describe only the value bounds for non-null
+/// rows; they DO NOT include nulls. For example, a partition with `min=0,
+/// max=10` may still contain nulls outside that range. Predicate pruning must
+/// combine decisions from non-null stats with null stats to derive the final
+/// outcome.
+#[derive(Debug, Clone)]
+pub struct ColumnStats {
+    pub range_stats: Option<RangeStats>,
+    pub null_stats: Option<NullStats>,

Review Comment:
   I think it's important to point out that if null stats or missing 
(`NullPresence::UnknownOrMixed`) we cannot make any inferences from the min/max 
values, they should be treated as missing as well.



##########
datafusion/physical-expr-common/src/physical_expr/pruning.rs:
##########
@@ -0,0 +1,539 @@
+// 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.
+
+// Pruner Common Structs/Utilities
+
+//! This is the top-level comment for pruning via statistics propagation.
+//!
+//! TODO: This is a concise draft; it should be polished for readers with less
+//! prior background.
+//!
+//! # Introduction
+//!
+//! This module helps skip scanning data micro-partitions by evaluating 
predicates
+//! against container-level statistics.
+//!
+//! It supports pruning for complex and nested predicates through statistics
+//! propagation.
+//!
+//! For examples of pruning nested predicates via statistics propagation, see:
+//! <https://github.com/apache/datafusion/issues/19487>
+//!
+//!
+//!
+//! # Vectorized pruning intermediate representation
+//!
+//! Source statistics and intermediate pruning results are stored in Arrow 
arrays,
+//! enabling vectorized evaluation across many containers.
+//!
+//!
+//!
+//! # Difference from [`super::PhysicalExpr::evaluate_bounds`]
+//!
+//! `evaluate_bounds()` derives per-column statistics for a single plan, aimed 
at
+//! tasks like cardinality estimation and other planner fast paths. It reasons
+//! about one container and may track richer distribution details.
+//! Pruning must reason about *all* containers (potentially thousands) to 
decide
+//! which to skip, so it favors a vectorized, array-backed representation with
+//! lighter-weight stats. These are intentionally separate interfaces.
+//!
+//!
+//!
+//! # Core API/Data Structures
+//!
+//! The key structures involved in pruning are:
+//! - [`PruningStatistics`]: the input source statistics for all containers
+//! - [`super::PhysicalExpr::evaluate_pruning()`]: evaluates pruning behavior 
for predicates
+//! - [`PruningIntermediate`]: the intermediate result produced during 
statistics propagation for pruning. Its internal representation uses Arrow 
Arrays, enabling vectorized evaluation for performance.
+
+use std::{iter::repeat_n, sync::Arc};
+
+use arrow::array::{Array, ArrayRef, BooleanArray, BooleanBuilder, UInt64Array};
+use arrow::compute::kernels::boolean::and_kleene;
+use datafusion_common::pruning::PruningStatistics;
+use datafusion_common::{Result, ScalarValue, assert_eq_or_internal_err};
+
+/// Physical representation of pruning outcomes for each container:
+/// `true` = KeepAll, `false` = SkipAll, `null` = Unknown.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+///
+/// # Pruning results
+/// - KeepAll: The pruning predicate evaluates to true for all rows within a 
micro
+///   partition. Future filter evaluation can be skipped for that partition.
+/// - SkipAll: The pruning predicate evaluates to false for all rows within a 
micro
+///   partition. The partition can be skipped at scan time.
+/// - UnknownOrMixed: The statistics are insufficient to prove 
KeepAll/SkipAll, or
+///   the predicate is mixed. The predicate must be evaluated row-wise.
+///
+/// Example (`SELECT * FROM t WHERE x >= 0`):
+/// - micro_partition_a(min=0, max=10): KeepAll — can pass through `FilterExec`
+///   without re-evaluating `x >= 0`.
+/// - micro_partition_b(min=-10, max=-1): SkipAll — skip the partition 
entirely.
+/// - micro_partition_c(min=-5, max=5): Unknown — must evaluate the predicate 
on rows.
+///
+/// `PruningOutcome` provides utilities to convert between this semantic
+/// representation and its tri-state boolean encoding.
+///
+/// # Important invariants
+/// Pruning results must be sound, but need not be complete:
+/// - If a container is labeled `KeepAll` or `SkipAll`, that label must be 
correct.
+/// - If a container is labeled `Unknown` but is actually `KeepAll`/`SkipAll`,
+///   correctness is still preserved; it just means pruning was conservative.
+///
+/// Propagation implementation can be refined to reduce `Unknown` cases to 
improve
+/// pruning effectiveness.
+#[derive(Debug, Clone)]
+pub struct PruningResults {
+    results: Option<BooleanArray>,
+    /// Number of containers. Needed to infer result if all stats types are 
`None`.
+    pub num_containers: usize,
+}
+
+/// Semantic representation for items inside `PruningResults::results`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PruningOutcome {
+    KeepAll,
+    SkipAll,
+    UnknownOrMixed,
+}
+
+impl PruningResults {
+    pub fn new(array: Option<BooleanArray>, num_containers: usize) -> Self {
+        debug_assert_eq!(
+            array.as_ref().map(|a| a.len()).unwrap_or(num_containers),
+            num_containers
+        );
+        Self {
+            results: array,
+            num_containers,
+        }
+    }
+
+    pub fn none(num_containers: usize) -> Self {
+        Self::new(None, num_containers)
+    }
+
+    pub fn as_ref(&self) -> Option<&BooleanArray> {
+        self.results.as_ref()
+    }
+
+    pub fn into_inner(self) -> Option<BooleanArray> {
+        self.results
+    }
+
+    pub fn len(&self) -> usize {
+        self.results
+            .as_ref()
+            .map(|a| a.len())
+            .unwrap_or(self.num_containers)
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+}

Review Comment:
   Maybe an `iter_results(&self) -> impl Iterator<Item = PruningOutcome>`?



##########
datafusion/physical-expr-common/src/physical_expr/pruning.rs:
##########
@@ -0,0 +1,539 @@
+// 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.
+
+// Pruner Common Structs/Utilities
+
+//! This is the top-level comment for pruning via statistics propagation.
+//!
+//! TODO: This is a concise draft; it should be polished for readers with less
+//! prior background.
+//!
+//! # Introduction
+//!
+//! This module helps skip scanning data micro-partitions by evaluating 
predicates
+//! against container-level statistics.
+//!
+//! It supports pruning for complex and nested predicates through statistics
+//! propagation.
+//!
+//! For examples of pruning nested predicates via statistics propagation, see:
+//! <https://github.com/apache/datafusion/issues/19487>
+//!
+//!
+//!
+//! # Vectorized pruning intermediate representation
+//!
+//! Source statistics and intermediate pruning results are stored in Arrow 
arrays,
+//! enabling vectorized evaluation across many containers.
+//!
+//!
+//!
+//! # Difference from [`super::PhysicalExpr::evaluate_bounds`]
+//!
+//! `evaluate_bounds()` derives per-column statistics for a single plan, aimed 
at
+//! tasks like cardinality estimation and other planner fast paths. It reasons
+//! about one container and may track richer distribution details.
+//! Pruning must reason about *all* containers (potentially thousands) to 
decide
+//! which to skip, so it favors a vectorized, array-backed representation with
+//! lighter-weight stats. These are intentionally separate interfaces.
+//!
+//!
+//!
+//! # Core API/Data Structures
+//!
+//! The key structures involved in pruning are:
+//! - [`PruningStatistics`]: the input source statistics for all containers
+//! - [`super::PhysicalExpr::evaluate_pruning()`]: evaluates pruning behavior 
for predicates
+//! - [`PruningIntermediate`]: the intermediate result produced during 
statistics propagation for pruning. Its internal representation uses Arrow 
Arrays, enabling vectorized evaluation for performance.
+
+use std::{iter::repeat_n, sync::Arc};
+
+use arrow::array::{Array, ArrayRef, BooleanArray, BooleanBuilder, UInt64Array};
+use arrow::compute::kernels::boolean::and_kleene;
+use datafusion_common::pruning::PruningStatistics;
+use datafusion_common::{Result, ScalarValue, assert_eq_or_internal_err};
+
+/// Physical representation of pruning outcomes for each container:
+/// `true` = KeepAll, `false` = SkipAll, `null` = Unknown.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+///
+/// # Pruning results
+/// - KeepAll: The pruning predicate evaluates to true for all rows within a 
micro
+///   partition. Future filter evaluation can be skipped for that partition.
+/// - SkipAll: The pruning predicate evaluates to false for all rows within a 
micro
+///   partition. The partition can be skipped at scan time.
+/// - UnknownOrMixed: The statistics are insufficient to prove 
KeepAll/SkipAll, or
+///   the predicate is mixed. The predicate must be evaluated row-wise.
+///
+/// Example (`SELECT * FROM t WHERE x >= 0`):
+/// - micro_partition_a(min=0, max=10): KeepAll — can pass through `FilterExec`
+///   without re-evaluating `x >= 0`.
+/// - micro_partition_b(min=-10, max=-1): SkipAll — skip the partition 
entirely.
+/// - micro_partition_c(min=-5, max=5): Unknown — must evaluate the predicate 
on rows.
+///
+/// `PruningOutcome` provides utilities to convert between this semantic
+/// representation and its tri-state boolean encoding.
+///
+/// # Important invariants
+/// Pruning results must be sound, but need not be complete:
+/// - If a container is labeled `KeepAll` or `SkipAll`, that label must be 
correct.
+/// - If a container is labeled `Unknown` but is actually `KeepAll`/`SkipAll`,
+///   correctness is still preserved; it just means pruning was conservative.
+///
+/// Propagation implementation can be refined to reduce `Unknown` cases to 
improve
+/// pruning effectiveness.
+#[derive(Debug, Clone)]
+pub struct PruningResults {
+    results: Option<BooleanArray>,

Review Comment:
   A comment here explaining the meaning of each one of the 3 boolean states 
would be helpful, maybe linking to `PruningOutcome`



##########
datafusion/physical-expr-common/src/physical_expr/pruning.rs:
##########
@@ -0,0 +1,539 @@
+// 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.
+
+// Pruner Common Structs/Utilities
+
+//! This is the top-level comment for pruning via statistics propagation.
+//!
+//! TODO: This is a concise draft; it should be polished for readers with less
+//! prior background.
+//!
+//! # Introduction
+//!
+//! This module helps skip scanning data micro-partitions by evaluating 
predicates
+//! against container-level statistics.
+//!
+//! It supports pruning for complex and nested predicates through statistics
+//! propagation.
+//!
+//! For examples of pruning nested predicates via statistics propagation, see:
+//! <https://github.com/apache/datafusion/issues/19487>
+//!
+//!
+//!
+//! # Vectorized pruning intermediate representation
+//!
+//! Source statistics and intermediate pruning results are stored in Arrow 
arrays,
+//! enabling vectorized evaluation across many containers.
+//!
+//!
+//!
+//! # Difference from [`super::PhysicalExpr::evaluate_bounds`]
+//!
+//! `evaluate_bounds()` derives per-column statistics for a single plan, aimed 
at
+//! tasks like cardinality estimation and other planner fast paths. It reasons
+//! about one container and may track richer distribution details.
+//! Pruning must reason about *all* containers (potentially thousands) to 
decide
+//! which to skip, so it favors a vectorized, array-backed representation with
+//! lighter-weight stats. These are intentionally separate interfaces.
+//!
+//!
+//!
+//! # Core API/Data Structures
+//!
+//! The key structures involved in pruning are:
+//! - [`PruningStatistics`]: the input source statistics for all containers
+//! - [`super::PhysicalExpr::evaluate_pruning()`]: evaluates pruning behavior 
for predicates
+//! - [`PruningIntermediate`]: the intermediate result produced during 
statistics propagation for pruning. Its internal representation uses Arrow 
Arrays, enabling vectorized evaluation for performance.
+
+use std::{iter::repeat_n, sync::Arc};
+
+use arrow::array::{Array, ArrayRef, BooleanArray, BooleanBuilder, UInt64Array};
+use arrow::compute::kernels::boolean::and_kleene;
+use datafusion_common::pruning::PruningStatistics;
+use datafusion_common::{Result, ScalarValue, assert_eq_or_internal_err};
+
+/// Physical representation of pruning outcomes for each container:
+/// `true` = KeepAll, `false` = SkipAll, `null` = Unknown.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+///
+/// # Pruning results
+/// - KeepAll: The pruning predicate evaluates to true for all rows within a 
micro
+///   partition. Future filter evaluation can be skipped for that partition.
+/// - SkipAll: The pruning predicate evaluates to false for all rows within a 
micro
+///   partition. The partition can be skipped at scan time.
+/// - UnknownOrMixed: The statistics are insufficient to prove 
KeepAll/SkipAll, or
+///   the predicate is mixed. The predicate must be evaluated row-wise.
+///
+/// Example (`SELECT * FROM t WHERE x >= 0`):
+/// - micro_partition_a(min=0, max=10): KeepAll — can pass through `FilterExec`
+///   without re-evaluating `x >= 0`.
+/// - micro_partition_b(min=-10, max=-1): SkipAll — skip the partition 
entirely.
+/// - micro_partition_c(min=-5, max=5): Unknown — must evaluate the predicate 
on rows.
+///
+/// `PruningOutcome` provides utilities to convert between this semantic
+/// representation and its tri-state boolean encoding.
+///
+/// # Important invariants
+/// Pruning results must be sound, but need not be complete:
+/// - If a container is labeled `KeepAll` or `SkipAll`, that label must be 
correct.
+/// - If a container is labeled `Unknown` but is actually `KeepAll`/`SkipAll`,
+///   correctness is still preserved; it just means pruning was conservative.
+///
+/// Propagation implementation can be refined to reduce `Unknown` cases to 
improve
+/// pruning effectiveness.
+#[derive(Debug, Clone)]
+pub struct PruningResults {
+    results: Option<BooleanArray>,
+    /// Number of containers. Needed to infer result if all stats types are 
`None`.
+    pub num_containers: usize,
+}
+
+/// Semantic representation for items inside `PruningResults::results`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PruningOutcome {
+    KeepAll,
+    SkipAll,
+    UnknownOrMixed,
+}
+
+impl PruningResults {
+    pub fn new(array: Option<BooleanArray>, num_containers: usize) -> Self {
+        debug_assert_eq!(
+            array.as_ref().map(|a| a.len()).unwrap_or(num_containers),
+            num_containers
+        );
+        Self {
+            results: array,
+            num_containers,
+        }
+    }
+
+    pub fn none(num_containers: usize) -> Self {
+        Self::new(None, num_containers)
+    }
+
+    pub fn as_ref(&self) -> Option<&BooleanArray> {
+        self.results.as_ref()
+    }
+
+    pub fn into_inner(self) -> Option<BooleanArray> {
+        self.results
+    }
+
+    pub fn len(&self) -> usize {
+        self.results
+            .as_ref()
+            .map(|a| a.len())
+            .unwrap_or(self.num_containers)
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+}
+
+impl PruningOutcome {
+    /// Convert to/from the tri-state boolean encoding stored in 
`PruningResults`.
+    /// - Some(true)=KeepAll
+    /// - Some(false)=SkipAll
+    /// - None=(Unknown/mixed)
+    pub fn from_result_item(result_item: Option<bool>) -> Self {
+        match result_item {
+            Some(true) => PruningOutcome::KeepAll,
+            Some(false) => PruningOutcome::SkipAll,
+            None => PruningOutcome::UnknownOrMixed,
+        }
+    }
+
+    pub fn to_result_item(&self) -> Option<bool> {
+        match self {
+            PruningOutcome::KeepAll => Some(true),
+            PruningOutcome::SkipAll => Some(false),
+            PruningOutcome::UnknownOrMixed => None,
+        }
+    }
+}
+
+impl From<BooleanArray> for PruningResults {
+    fn from(array: BooleanArray) -> Self {
+        let len = array.len();
+        PruningResults::new(Some(array), len)
+    }
+}

Review Comment:
   This seems like it might be a bit magic and an explicit constructor is better



##########
datafusion/physical-expr-common/src/physical_expr/pruning.rs:
##########
@@ -0,0 +1,539 @@
+// 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.
+
+// Pruner Common Structs/Utilities
+
+//! This is the top-level comment for pruning via statistics propagation.
+//!
+//! TODO: This is a concise draft; it should be polished for readers with less
+//! prior background.
+//!
+//! # Introduction
+//!
+//! This module helps skip scanning data micro-partitions by evaluating 
predicates
+//! against container-level statistics.
+//!
+//! It supports pruning for complex and nested predicates through statistics
+//! propagation.
+//!
+//! For examples of pruning nested predicates via statistics propagation, see:
+//! <https://github.com/apache/datafusion/issues/19487>
+//!
+//!
+//!
+//! # Vectorized pruning intermediate representation
+//!
+//! Source statistics and intermediate pruning results are stored in Arrow 
arrays,
+//! enabling vectorized evaluation across many containers.
+//!
+//!
+//!
+//! # Difference from [`super::PhysicalExpr::evaluate_bounds`]
+//!
+//! `evaluate_bounds()` derives per-column statistics for a single plan, aimed 
at
+//! tasks like cardinality estimation and other planner fast paths. It reasons
+//! about one container and may track richer distribution details.
+//! Pruning must reason about *all* containers (potentially thousands) to 
decide
+//! which to skip, so it favors a vectorized, array-backed representation with
+//! lighter-weight stats. These are intentionally separate interfaces.
+//!
+//!
+//!
+//! # Core API/Data Structures
+//!
+//! The key structures involved in pruning are:
+//! - [`PruningStatistics`]: the input source statistics for all containers
+//! - [`super::PhysicalExpr::evaluate_pruning()`]: evaluates pruning behavior 
for predicates
+//! - [`PruningIntermediate`]: the intermediate result produced during 
statistics propagation for pruning. Its internal representation uses Arrow 
Arrays, enabling vectorized evaluation for performance.
+
+use std::{iter::repeat_n, sync::Arc};
+
+use arrow::array::{Array, ArrayRef, BooleanArray, BooleanBuilder, UInt64Array};
+use arrow::compute::kernels::boolean::and_kleene;
+use datafusion_common::pruning::PruningStatistics;
+use datafusion_common::{Result, ScalarValue, assert_eq_or_internal_err};
+
+/// Physical representation of pruning outcomes for each container:
+/// `true` = KeepAll, `false` = SkipAll, `null` = Unknown.
+///
+/// Use `BooleanArray` so the propagation steps can use existing Arrow kernels 
for
+/// both simplicity and performance.
+///
+/// # Pruning results
+/// - KeepAll: The pruning predicate evaluates to true for all rows within a 
micro
+///   partition. Future filter evaluation can be skipped for that partition.
+/// - SkipAll: The pruning predicate evaluates to false for all rows within a 
micro
+///   partition. The partition can be skipped at scan time.
+/// - UnknownOrMixed: The statistics are insufficient to prove 
KeepAll/SkipAll, or
+///   the predicate is mixed. The predicate must be evaluated row-wise.
+///
+/// Example (`SELECT * FROM t WHERE x >= 0`):
+/// - micro_partition_a(min=0, max=10): KeepAll — can pass through `FilterExec`
+///   without re-evaluating `x >= 0`.
+/// - micro_partition_b(min=-10, max=-1): SkipAll — skip the partition 
entirely.
+/// - micro_partition_c(min=-5, max=5): Unknown — must evaluate the predicate 
on rows.
+///
+/// `PruningOutcome` provides utilities to convert between this semantic
+/// representation and its tri-state boolean encoding.
+///
+/// # Important invariants
+/// Pruning results must be sound, but need not be complete:
+/// - If a container is labeled `KeepAll` or `SkipAll`, that label must be 
correct.
+/// - If a container is labeled `Unknown` but is actually `KeepAll`/`SkipAll`,
+///   correctness is still preserved; it just means pruning was conservative.
+///
+/// Propagation implementation can be refined to reduce `Unknown` cases to 
improve
+/// pruning effectiveness.
+#[derive(Debug, Clone)]
+pub struct PruningResults {
+    results: Option<BooleanArray>,
+    /// Number of containers. Needed to infer result if all stats types are 
`None`.
+    pub num_containers: usize,
+}
+
+/// Semantic representation for items inside `PruningResults::results`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PruningOutcome {
+    KeepAll,
+    SkipAll,
+    UnknownOrMixed,
+}
+
+impl PruningResults {
+    pub fn new(array: Option<BooleanArray>, num_containers: usize) -> Self {
+        debug_assert_eq!(
+            array.as_ref().map(|a| a.len()).unwrap_or(num_containers),
+            num_containers
+        );
+        Self {
+            results: array,
+            num_containers,
+        }
+    }

Review Comment:
   When would this be called with `(None, 123)`? It seems like that usage is 
only ever internal from `pub fn none()`. I would make the public constructor 
`new(array: BooleanArrray)` and make `none()` initialize the struct itself.



##########
datafusion/physical-expr/src/expressions/binary.rs:
##########
@@ -746,6 +968,106 @@ fn check_short_circuit<'a>(
     ShortCircuitStrategy::None
 }
 
+/// For expressions like `left OP right`, calculate the `PruningOutcome` given 
child
+/// expression's range statistics, and operator type.
+///
+/// The supported operators are: >, <, =, >=, <=
+///
+/// Bounds encoding: each bound uses an `Option` to encode a NULL range value;
+/// `None` means the bound is NULL, and `Some` must contain a non-null 
`ScalarValue`.
+/// This is due to the existing ScalarValue comparison having unexpected null 
behavior:
+/// <https://github.com/apache/datafusion/issues/19579>
+///
+/// Type compatibility: if all bound data types are not equal, return
+/// `PruningOutcome::UnknownOrMixed` as a safe fallback. For different but
+/// compatible types (e.g., lhs is Int32, rhs is Int64), the type coercion
+/// optimizer rule should already handle them before evaluating pruning.
+///
+/// # Errors
+/// Returns Internal Error if unsupported operator is provided.
+fn compare_ranges(

Review Comment:
   Some unit tests for this method specifically that ensure 100% coverage would 
be great



-- 
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]


Reply via email to