From fff6f8afc123613fd786033aa4e8db0ab3ed736d Mon Sep 17 00:00:00 2001 From: Frederic Branczyk Date: Thu, 26 Nov 2026 14:29:24 +0000 Subject: [PATCH 1/3] fix: prune unused inputs beneath computed repartition projections # Why Logical leaf extraction can retain predicate-only columns after filter pushdown. Round-robin repartitioning then separates the projections that would otherwise remove them. # What Prune unused inputs below round-robin repartitioning while keeping computations above it. Add a seeded differential property test for scan output pruning and result equivalence. Part of https://linear.app/dash0/issue/DAT-514 Generated-by: Amp Co-authored-by: Amp Amp-Thread-ID: https://ampcode.com/threads/T-a4855d83-222b-4ccc-ba56-7a950a7d22a6 --- .../tests/fuzz_cases/leaf_pushdown_fuzz.rs | 52 +++++++++++++++++++ .../physical-plan/src/repartition/mod.rs | 40 +++++++++++++- 2 files changed, 91 insertions(+), 1 deletion(-) 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-plan/src/repartition/mod.rs b/datafusion/physical-plan/src/repartition/mod.rs index 98c70093a9daf..624308438cbad 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,41 @@ 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( + ProjectionExec::try_new_with_schema_metadata( + exprs, + repartition, + projection.schema().as_ref(), + )?, + ))); + } + // 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); From 858edefa812454dc98b6e1d5b06de62c368a91d9 Mon Sep 17 00:00:00 2001 From: Frederic Branczyk Date: Fri, 27 Nov 2026 15:45:19 +0000 Subject: [PATCH 2/3] perf: reduce projection costs without an index cache # Why Pruning unused inputs beneath a computed repartition projection can add a column-only projection. Per-expression schema Arc clones and rebuilding the unchanged upper output schema and plan properties add to its execution and planning cost. Reuse the indices already stored in Column rather than introducing a second index list and its construction/invalidation overhead. # What Select existing column arrays directly, retaining expression timers and the generic evaluation/error path for other expressions or invalid indices. Borrow the input schema for Column bounds checks. During input pruning, reuse the upper output schema and plan properties, remap expressions and reset metrics. The schema-preserving Projector method is public only for cross-crate internal use. No absorption gate or new persistent cache is included. # Measurements Five alternating paired Criterion blocks compare this no-cache composition with the preceding pruning fix, fff6f8afc123613fd786033aa4e8db0ab3ed736d. Release builds use CPU 2, 60 samples, 300 ms warmup and 1 s measurements. Absolute times are medians of block medians; changes are geometric means of paired ratios with 95% block-bootstrap intervals, not ratios of those medians. - 32-column batch with metrics: 3685.85 -> 2863.76 ns; -22.24% [-22.45%, -22.03%]. - Mixed-expression batch: 563.55 -> 501.36 ns; -9.40% [-11.60%, -7.13%]. - Unpredictable column/mixed selection: 420.29 -> 370.22 ns; -12.42% [-13.68%, -10.82%]. - 32-column pruning rewrite: 120.80 -> 59.05 us; -51.62% [-52.83%, -50.48%], from upper schema/property reuse. - Two-column construction: 340.46 -> 341.66 ns; +0.45% [+0.17%, +0.74%], despite unchanged constructor code. - 128-column construction with a computed expression last: +0.32% [-0.04%, +0.65%]. A separate ten-paired-block SQL run compares the complete no-cache branch against unpatched upstream main 053386b43480bfbf1a09e9ac3d03b5ca9fafe501, not against the preceding PR commit. Four workers use CPUs 0-3, five warmups, at least 20 executions over 1 s, and 100 separate planning samples per run. The MemTable/window workloads deliberately retain the extra projection. Execution / planning change, each with its 95% interval: - Tiny: +7.22% [+5.27%, +9.12%] / +5.88% [+2.83%, +10.02%]. - Narrow large: -1.17% [-3.64%, +1.43%] / -0.77% [-6.07%, +4.48%]. - Narrow small batches: +9.00% [+3.73%, +13.35%] / +5.69% [+2.84%, +8.74%]. - Wide passthrough: -1.50% [-7.19%, +7.90%] / +8.06% [+4.37%, +11.73%]. - String payload: -0.20% [-4.03%, +3.34%] / +9.11% [+1.98%, +18.48%]. - Unchanged-plan control: -5.17% [-17.77%, +3.54%] / -0.05% [-11.41%, +11.94%]. This reduces isolated operator costs, not all whole-query regressions. The tiny and small-batch slowdowns remain. WindowAggExec slices output to the session batch size; the small-batch case exercises 4096 output batches. These are shared-orb synthetic measurements, not Vortex I/O or memory savings. Do not subtract changes from independently run benchmark rounds. The earlier DF56/Vortex snapshot check covered the original pruning fix, not this follow-up. Part of https://linear.app/dash0/issue/DAT-514 Generated-by: Amp Amp-Thread-ID: https://ampcode.com/threads/T-a4855d83-222b-4ccc-ba56-7a950a7d22a6 Co-authored-by: Amp Co-authored-by: Ivan Kiselev --- .../physical-expr/src/expressions/column.rs | 2 +- datafusion/physical-expr/src/projection.rs | 47 ++++++++++++++++--- datafusion/physical-plan/src/projection.rs | 28 +++++++++++ .../physical-plan/src/repartition/mod.rs | 6 +-- 4 files changed, 71 insertions(+), 12 deletions(-) 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 624308438cbad..a3454155ccc41 100644 --- a/datafusion/physical-plan/src/repartition/mod.rs +++ b/datafusion/physical-plan/src/repartition/mod.rs @@ -1981,11 +1981,7 @@ impl ExecutionPlan for RepartitionExec { ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), )?; return Ok(Some(Arc::new( - ProjectionExec::try_new_with_schema_metadata( - exprs, - repartition, - projection.schema().as_ref(), - )?, + projection.with_pruned_input(exprs, repartition)?, ))); } From 4a1550663b9100ca6fbd926a587746b76f167a18 Mon Sep 17 00:00:00 2001 From: Frederic Branczyk Date: Mon, 30 Nov 2026 09:48:26 +0000 Subject: [PATCH 3/3] test: show filter-only scan column pruning in EXPLAIN # Why The fuzz regression test does not give reviewers a deterministic plan showing the scan output narrowed across round-robin repartitioning. # What Add an EXPLAIN and result check using the existing Parquet fixture. The predicate keeps reading id while the scan outputs only the value needed by the computed projection above repartitioning. With the implementation reverted to the PR base, the test fails solely because id remains in the scan projection. With the fix it passes, along with all 310 SQLLogicTest files and 13,650 Rust tests (8 ignored). Formatting and all-target/all-feature Clippy also pass. Review: https://github.com/apache/datafusion/pull/27777#discussion_r4731582420 Amp-Thread-ID: https://ampcode.com/threads/T-a4855d83-222b-4ccc-ba56-7a950a7d22a6 Co-authored-by: Amp Co-authored-by: Ivan Kiselev --- .../test_files/projection_pushdown.slt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) 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;