diff --git a/datafusion/core/tests/fuzz_cases/leaf_pushdown_fuzz.rs b/datafusion/core/tests/fuzz_cases/leaf_pushdown_fuzz.rs index 67cb481126160..7c8be0c7de8e3 100644 --- a/datafusion/core/tests/fuzz_cases/leaf_pushdown_fuzz.rs +++ b/datafusion/core/tests/fuzz_cases/leaf_pushdown_fuzz.rs @@ -35,6 +35,9 @@ use arrow::datatypes::{DataType, Field, Fields, Int32Type, Schema}; use arrow::util::pretty::pretty_format_batches; use datafusion::prelude::{ParquetReadOptions, SessionConfig, SessionContext}; use datafusion_common::Result; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; +use datafusion_datasource::source::DataSourceExec; +use datafusion_physical_plan::displayable; use parquet::arrow::ArrowWriter; use rand::rngs::SmallRng; use rand::{Rng, SeedableRng}; @@ -786,6 +789,55 @@ async fn leaf_pushdown_parquet_fuzz() { .await; } +#[tokio::test] +async fn leaf_pushdown_prunes_filter_only_columns() -> Result<()> { + let dir = TempDir::new()?; + let reference = memory_ctx(false); + for seed in seed()..seed() + env_usize("LEAF_PUSHDOWN_FUZZ_CASES", 64) as u64 { + let mut rng = SmallRng::seed_from_u64(seed); + let mut cfg = config(true, true).with_batch_size(1); + cfg.options_mut().execution.target_partitions = rng.random_range(2..=4); + let ctx = SessionContext::new_with_config(cfg); + let path = dir.path().join(format!("{seed}.parquet")); + write_parquet(&path, &table_batch(0)); + ctx.register_parquet("t1", path.to_str().unwrap(), ParquetReadOptions::default()) + .await?; + + let left = pick(&mut rng, &["b", "s['a']", "t['x']"]); + let right = pick(&mut rng, &["b", "s['a']", "t['x']"]); + let op = pick(&mut rng, &["+", "-", "*"]); + let threshold = rng.random_range(-4..=1); + let sql = format!( + "SELECT {left} {op} {right} AS result, CAST({right} AS BIGINT) AS other \ + FROM t1 WHERE a > {threshold} AND lower(s['b']) <> 'never'" + ); + let plan = ctx.sql(&sql).await?.create_physical_plan().await?; + let text = displayable(plan.as_ref()).indent(true).to_string(); + assert!( + text.contains("RoundRobinBatch"), + "seed {seed}: {sql}\n{text}" + ); + let mut scans = 0; + plan.apply(|node| { + if node.downcast_ref::().is_some() { + scans += 1; + assert!( + node.schema().field_with_name("a").is_err(), + "seed {seed}: filter-only column remains: {sql}\n{text}" + ); + } + Ok(TreeNodeRecursion::Continue) + })?; + assert_eq!(scans, 1, "seed {seed}: {sql}\n{text}"); + assert_eq!( + normalize(&collect(&reference, &sql).await?), + normalize(&collect(&ctx, &sql).await?), + "seed {seed}: {sql}\n{text}" + ); + } + Ok(()) +} + #[rstest] #[case::p0(0)] #[case::p1(1)] diff --git a/datafusion/physical-expr/src/expressions/column.rs b/datafusion/physical-expr/src/expressions/column.rs index 56bbca5ce4687..8b0c42b6a1ee9 100644 --- a/datafusion/physical-expr/src/expressions/column.rs +++ b/datafusion/physical-expr/src/expressions/column.rs @@ -106,7 +106,7 @@ impl PhysicalExpr for Column { /// Evaluate the expression fn evaluate(&self, batch: &RecordBatch) -> Result { - self.bounds_check(batch.schema().as_ref())?; + self.bounds_check(batch.schema_ref())?; Ok(ColumnarValue::Array(Arc::clone(batch.column(self.index)))) } diff --git a/datafusion/physical-expr/src/projection.rs b/datafusion/physical-expr/src/projection.rs index 41113c14efe8b..089dd26e0d529 100644 --- a/datafusion/physical-expr/src/projection.rs +++ b/datafusion/physical-expr/src/projection.rs @@ -27,7 +27,6 @@ use datafusion_physical_expr_common::metrics::ExecutionPlanMetricsSet; use datafusion_physical_expr_common::metrics::ExpressionEvaluatorMetrics; use datafusion_physical_expr_common::physical_expr::fmt_sql; use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr}; -use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays_with_metrics; use indexmap::IndexMap; use itertools::Itertools; @@ -1107,6 +1106,26 @@ pub struct Projector { } impl Projector { + /// Replace expressions after a rewrite that preserves output field names, + /// types, nullability, and metadata. Expression metrics are reset. + /// + /// # Public Only for Internal Use: + /// + /// This is not a public API and is for internal use only; see [API policy] for details. + /// + /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis + #[doc(hidden)] + pub fn with_new_projection_preserving_schema( + &self, + projection: ProjectionExprs, + ) -> Self { + Self { + projection, + output_schema: Arc::clone(&self.output_schema), + expression_metrics: None, + } + } + /// Construct the projector with metrics. After execution, related metrics will /// be tracked inside `ExecutionPlanMetricsSet` /// @@ -1133,11 +1152,27 @@ impl Projector { /// or if the output schema of the resulting record batch does not match /// the pre-computed output schema of the projector. pub fn project_batch(&self, batch: &RecordBatch) -> Result { - let arrays = evaluate_expressions_to_arrays_with_metrics( - self.projection.exprs.iter().map(|p| &p.expr), - batch, - self.expression_metrics.as_ref(), - )?; + let arrays = self + .projection + .exprs + .iter() + .enumerate() + .map(|(position, projection)| { + let _timer = self + .expression_metrics + .as_ref() + .and_then(|metrics| metrics.scoped_timer(position)); + if let Some(column) = projection.expr.downcast_ref::() + && let Some(array) = batch.columns().get(column.index()) + { + return Ok(Arc::clone(array)); + } + projection + .expr + .evaluate(batch)? + .into_array_of_size(batch.num_rows()) + }) + .collect::>>()?; if arrays.is_empty() { let options = diff --git a/datafusion/physical-plan/src/projection.rs b/datafusion/physical-plan/src/projection.rs index 3d6e729937c6e..57e943a02f279 100644 --- a/datafusion/physical-plan/src/projection.rs +++ b/datafusion/physical-plan/src/projection.rs @@ -169,6 +169,34 @@ impl ProjectionExec { Self::try_from_projector(projector, input, overrides_metadata) } + pub(crate) fn with_pruned_input( + &self, + exprs: Vec, + input: Arc, + ) -> Result { + // Input pruning must preserve output values, metadata, ordering, and partitioning. + let projector = self + .projector + .with_new_projection_preserving_schema(ProjectionExprs::new(exprs)); + debug_assert_eq!( + projector.output_schema(), + projector + .projection() + .make_projector_with_schema_metadata( + &input.schema(), + self.schema().as_ref() + )? + .output_schema() + ); + Ok(Self { + projector, + input, + metrics: ExecutionPlanMetricsSet::new(), + cache: Arc::clone(&self.cache), + overrides_metadata: self.overrides_metadata, + }) + } + fn try_from_projector( projector: Projector, input: Arc, diff --git a/datafusion/physical-plan/src/repartition/mod.rs b/datafusion/physical-plan/src/repartition/mod.rs index 98c70093a9daf..a3454155ccc41 100644 --- a/datafusion/physical-plan/src/repartition/mod.rs +++ b/datafusion/physical-plan/src/repartition/mod.rs @@ -22,7 +22,10 @@ use crate::coalesce::LimitedBatchCoalescer; use crate::execution_plan::{CardinalityEffect, EvaluationType, SchedulingType}; use crate::hash_utils::create_hashes; use crate::metrics::{BaselineMetrics, SpillMetrics}; -use crate::projection::{ProjectionExec, all_columns, make_with_child, update_expr}; +use crate::projection::{ + ProjectionExec, ProjectionExpr, ProjectionExprs, all_columns, make_with_child, + update_expr, +}; use crate::sorts::streaming_merge::StreamingMergeBuilder; use crate::spill::spill_manager::SpillManager; use crate::spill::spill_pool::{self, SpillPoolSink, SpillPoolWriter}; @@ -1951,6 +1954,37 @@ impl ExecutionPlan for RepartitionExec { &self, projection: &ProjectionExec, ) -> Result>> { + if !all_columns(projection.expr()) + && matches!(self.partitioning(), Partitioning::RoundRobinBatch(_)) + { + let indices = projection.projection_expr().column_indices(); + if indices.len() >= self.input().schema().fields().len() { + return Ok(None); + } + + // Keep computations above repartitioning so they retain its parallelism. + let columns = ProjectionExprs::from_indices(&indices, &self.input().schema()); + let mut exprs = Vec::with_capacity(projection.expr().len()); + for expr in projection.expr() { + let Some(rewritten) = update_expr(&expr.expr, columns.as_ref(), false)? + else { + return Ok(None); + }; + exprs.push(ProjectionExpr::new(rewritten, expr.alias.clone())); + } + let input = Arc::new(ProjectionExec::try_new( + columns.iter().cloned(), + Arc::clone(self.input()), + )?); + let repartition = Arc::new(self.clone()).replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + return Ok(Some(Arc::new( + projection.with_pruned_input(exprs, repartition)?, + ))); + } + // If the projection does not narrow the schema, we should not try to push it down. if projection.expr().len() >= projection.input().schema().fields().len() { return Ok(None); diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..4b2e85508e18b 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2864,6 +2864,28 @@ physical_plan statement ok DROP TABLE leaf_split_mem; +# https://github.com/apache/datafusion/issues/27776 +# The predicate still reads id, but the scan must not output it through repartition. +query TT +EXPLAIN SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2; +---- +logical_plan +01)Projection: __datafusion_extracted_1 + Int64(1) AS v +02)--Filter: leaf_split.id > Int64(2) +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split.id +04)------TableScan: leaf_split projection=[id, s], partial_filters=[leaf_split.id > Int64(2)] +physical_plan +01)ProjectionExec: expr=[__datafusion_extracted_1@0 + 1 as v] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1], file_type=parquet, predicate=id@0 > 2, pruning_predicate=id_null_count@1 != row_count@2 AND id_max@0 > 2, required_guarantees=[] + +query I rowsort +SELECT s['value'] + 1 AS v FROM leaf_split WHERE id > 2; +---- +151 +251 +301 + statement ok SET datafusion.execution.batch_size = 8192;