From 0a1b8cf6c7001399f8c6f6d7c28b83741bb9f64c Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Mon, 23 Nov 2026 15:24:02 +0800 Subject: [PATCH 1/6] fix: file_row_index() and input_file_name() error under OFFSET n LIMIT m With both a skip and a fetch against a source that supports skip pushdown, the skip is pushed into the scan, which wraps it in a `GlobalLimitExec`, and with more than one file group a `CoalescePartitionsExec` sits under that limit as well. Those nodes land between the scan and the projection the leaf-extraction rules placed directly on it, and no projection swaps past a `GlobalLimitExec`, so `file_row_index()` and `input_file_name()` are evaluated above the scan, where they cannot be resolved. #27152 added a split that moves leaf expressions past a round-robin `RepartitionExec`, testing for that one node inline. The nodes a leaf projection may descend are now named in one place, `split_host_child`, with `GlobalLimitExec` and `CoalescePartitionsExec` added, and `split_host_chain` walks a stack of them so the leaf descends past all of them in one pass. A node qualifies only if it neither references its input's columns nor changes them on the way out; the arms are an allowlist, so meeting that is necessary rather than sufficient, and `LocalLimitExec` is deliberately left off. Only the leaf expressions descend. Ones that must stay in place are left in the outer projection above the limit, so they are evaluated on the rows that survive the skip rather than on the ones it discards. The same change lets `get_field` reach the scan under an `OFFSET`, which is the enhancement #27495 asks for; its end-to-end coverage is a follow-on PR. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 492 ++++++++++++++++++ .../src/projection_pushdown.rs | 104 +++- .../test_files/file_row_index.slt | 202 +++++++ 3 files changed, 776 insertions(+), 22 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index c0936eb929b37..f12e9434d94ef 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; use std::sync::Arc; +use arrow::array::RecordBatch; use arrow::compute::SortOptions; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use datafusion::datasource::listing::PartitionedFile; @@ -35,6 +36,7 @@ use datafusion_physical_expr_common::sort_expr::{ use datafusion_physical_optimizer::PhysicalOptimizerRule; use datafusion_physical_optimizer::output_requirements::OutputRequirementExec; use datafusion_physical_optimizer::projection_pushdown::ProjectionPushdown; +use datafusion_physical_plan::buffer::BufferExec; use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion_physical_plan::coop::CooperativeExec; use datafusion_physical_plan::filter::{FilterExec, FilterExecBuilder}; @@ -43,6 +45,7 @@ use datafusion_physical_plan::joins::{ HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec, StreamJoinPartitionMode, SymmetricHashJoinExec, }; +use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; use datafusion_physical_plan::projection::{ProjectionExec, ProjectionExpr, update_expr}; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::sorts::sort::SortExec; @@ -52,6 +55,8 @@ use datafusion_physical_plan::union::UnionExec; use datafusion_physical_plan::{ExecutionPlan, displayable}; use insta::assert_snapshot; + +use crate::physical_optimizer::test_utils::OptimizationTest; use itertools::Itertools; /// Mocked UDF @@ -2035,3 +2040,490 @@ async fn split_declines_hash_repartition() -> Result<()> { ); Ok(()) } + +fn limit_split_scan() -> Result<(SchemaRef, Arc)> { + let schema: SchemaRef = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new( + "s", + DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), + true, + ), + ])); + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::parse("test:///").unwrap(), + Arc::new(ParquetSource::new(Arc::clone(&schema))), + ) + .with_file(PartitionedFile::new("x".to_string(), 100)) + .build(); + Ok((schema, DataSourceExec::from_data_source(config))) +} + +fn limit_split_exprs(schema: &SchemaRef) -> Result> { + let leaf: Arc = Arc::new(ScalarFunctionExpr::new( + "get_field", + datafusion_functions::core::get_field(), + vec![ + col("s", schema)?, + Arc::new(Literal::new(ScalarValue::from("value"))), + ], + Arc::new(Field::new("v", DataType::Int64, true)), + Arc::new(ConfigOptions::default()), + )); + Ok(vec![ + ProjectionExpr { + expr: leaf, + alias: "v".to_string(), + }, + ProjectionExpr { + expr: binary( + col("id", schema)?, + Operator::Plus, + Arc::new(Literal::new(ScalarValue::Int64(Some(1)))), + schema, + )?, + alias: "w".to_string(), + }, + ]) +} + +#[tokio::test] +async fn split_descends_through_global_limit() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + // `skip` and `fetch` differ so that swapping them would show. + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// The no-leaf `EXPLAIN` in the `.slt` cannot pin this, because the plan is the +/// same either way. +#[tokio::test] +async fn split_declines_global_limit_without_leaf() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); + let exprs = vec![limit_split_exprs(&schema)?.swap_remove(1)]; + let projection: Arc = + Arc::new(ProjectionExec::try_new(exprs, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + " + ); + Ok(()) +} + +/// `LocalLimitExec` is left out of `split_host_child`: no query in the test +/// suite strands a leaf expression above one. This pins that choice. +#[tokio::test] +async fn split_declines_local_limit() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let limit: Arc = Arc::new(LocalLimitExec::new(scan, 2)); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - LocalLimitExec: fetch=2 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - LocalLimitExec: fetch=2 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + " + ); + Ok(()) +} + +/// A scan with more than one file group: a single `OFFSET` already stacks two +/// hosts, so stopping at the first would leave the scan reading the struct. +#[tokio::test] +async fn split_descends_through_limit_and_coalesce() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let coalesce: Arc = Arc::new(CoalescePartitionsExec::new(scan)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CoalescePartitionsExec + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CoalescePartitionsExec + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// `fetch = None`, which plain SQL does not reach: an `OFFSET` with no `LIMIT` +/// is not pushed into the scan, so only a hand-built plan covers it. +#[tokio::test] +async fn split_descends_through_global_limit_without_fetch() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=2, fetch=None + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=2, fetch=None + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// A host carrying a `fetch` of its own has to keep it across the rebuild. The +/// `.slt` plans show a fetch on this node, but `LimitPushdown` puts it there +/// after the split, so they do not cover this. +#[tokio::test] +async fn split_keeps_the_coalesce_fetch() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let coalesce: Arc = + Arc::new(CoalescePartitionsExec::new(scan).with_fetch(Some(4))); + let limit: Arc = + Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CoalescePartitionsExec: fetch=4 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CoalescePartitionsExec: fetch=4 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// Each of the three limits keeps its own `skip` and `fetch` after the rebuild. +#[tokio::test] +async fn split_descends_through_three_hosts() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let inner: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(9))); + let middle: Arc = + Arc::new(GlobalLimitExec::new(inner, 2, Some(6))); + let outer: Arc = + Arc::new(GlobalLimitExec::new(middle, 3, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, outer)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=3, fetch=3 + - GlobalLimitExec: skip=2, fetch=6 + - GlobalLimitExec: skip=1, fetch=9 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=3, fetch=3 + - GlobalLimitExec: skip=2, fetch=6 + - GlobalLimitExec: skip=1, fetch=9 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// `CooperativeExec` and `BufferExec` are not hosts, but as the *bottom* of the +/// chain they delegate the swap to their own input, so the split commits and +/// the scan narrows in one pass. +#[tokio::test] +async fn split_commits_at_a_pass_through_bottom() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + let cooperative: Arc = Arc::new(CooperativeExec::new(scan)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(cooperative, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CooperativeExec + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - CooperativeExec + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + + let (schema, scan) = limit_split_scan()?; + let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(buffer, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - BufferExec: capacity=4 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - BufferExec: capacity=4 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// A `FilterExec` bottom takes the lower projection by holding it over its own +/// input, so after one pass the scan still reads everything and the plan has +/// gained a node. This rule is scheduled twice, and the second run is what +/// pushes the projection into the source. Nothing else states that dependency. +#[tokio::test] +async fn split_below_a_filter_narrows_on_the_second_run() -> Result<()> { + // Three columns so the lower projection narrows; with two it does not, and + // `FilterExec` declines before reaching the branch this test is about. + let schema: SchemaRef = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new( + "s", + DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), + true, + ), + Field::new("k", DataType::Int64, true), + ])); + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::parse("test:///").unwrap(), + Arc::new(ParquetSource::new(Arc::clone(&schema))), + ) + .with_file(PartitionedFile::new("x".to_string(), 100)) + .build(); + let predicate = binary( + col("id", &schema)?, + Operator::Gt, + Arc::new(Literal::new(ScalarValue::Int64(Some(0)))), + &schema, + )?; + let filter: Arc = Arc::new(FilterExec::try_new( + predicate, + DataSourceExec::from_data_source(config), + )?); + let limit: Arc = + Arc::new(GlobalLimitExec::new(filter, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + let first = ProjectionPushdown::new() + .optimize(Arc::clone(&projection), &ConfigOptions::default())?; + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0] + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + " + ); + + assert_snapshot!( + OptimizationTest::new(first, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - ProjectionExec: expr=[id@0 as id, get_field(s@1, value) as __datafusion_leaf_0] + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s, k], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - FilterExec: id@0 > 0 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} + +/// A memory source declines an aliased `get_field`, so the split must not +/// commit: it would add a projection below the limit that nobody absorbs. +#[tokio::test] +async fn split_declines_when_the_child_refuses_the_projection() -> Result<()> { + let schema: SchemaRef = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new( + "s", + DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), + true, + ), + ])); + let batch = RecordBatch::new_empty(Arc::clone(&schema)); + let source = MemorySourceConfig::try_new(&[vec![batch]], Arc::clone(&schema), None)?; + let scan = DataSourceExec::from_data_source(source); + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: partitions=1, partition_sizes=[1] + output: + Ok: + - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: partitions=1, partition_sizes=[1] + " + ); + Ok(()) +} + +/// `file_row_index()` as the leaf, which is what #27494 reports. Unlike +/// `get_field` it cannot be evaluated above the scan at all, so the output +/// shows the source resolving it into its hidden column. +#[tokio::test] +async fn split_descends_through_global_limit_with_a_marker() -> Result<()> { + let schema: SchemaRef = + Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, true)])); + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::parse("test:///").unwrap(), + Arc::new(ParquetSource::new(Arc::clone(&schema))), + ) + .with_file(PartitionedFile::new("x".to_string(), 100)) + .build(); + let marker: Arc = Arc::new(ScalarFunctionExpr::new( + "file_row_index", + datafusion_functions::core::file_row_index(), + vec![], + Arc::new(Field::new("r", DataType::Int64, true)), + Arc::new(ConfigOptions::default()), + )); + let exprs = vec![ + ProjectionExpr { + expr: marker, + alias: "r".to_string(), + }, + ProjectionExpr { + expr: binary( + col("id", &schema)?, + Operator::Plus, + Arc::new(Literal::new(ScalarValue::Int64(Some(1)))), + &schema, + )?, + alias: "w".to_string(), + }, + ]; + let limit: Arc = Arc::new(GlobalLimitExec::new( + DataSourceExec::from_data_source(config), + 1, + Some(3), + )); + let projection: Arc = + Arc::new(ProjectionExec::try_new(exprs, limit)?); + + assert_snapshot!( + OptimizationTest::new(projection, ProjectionPushdown::new(), false), + @r" + OptimizationTest: + input: + - ProjectionExec: expr=[file_row_index() as r, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id], file_type=parquet + output: + Ok: + - ProjectionExec: expr=[__datafusion_leaf_0@1 as r, id@0 + 1 as w] + - GlobalLimitExec: skip=1, fetch=3 + - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], file_type=parquet + " + ); + Ok(()) +} diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index a792b4131d43e..f88521103a150 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -23,8 +23,10 @@ use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable}; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::{conjunction, split_conjunction}; use datafusion_physical_expr_common::physical_expr::{PhysicalExpr, is_volatile}; +use datafusion_physical_plan::coalesce_partitions::CoalescePartitionsExec; use datafusion_physical_plan::joins::NestedLoopJoinExec; use datafusion_physical_plan::joins::utils::{ColumnIndex, JoinFilter}; +use datafusion_physical_plan::limit::GlobalLimitExec; use datafusion_physical_plan::projection::{ ProjectionExec, remove_unnecessary_projections, }; @@ -68,11 +70,12 @@ impl PhysicalOptimizerRule for ProjectionPushdown { .map(|t| t.data)?; // Push what can already descend, then split the projections that are - // stuck above a `RepartitionExec`. The split needs no cleanup pass of - // its own: the outer projection it leaves either keeps every expression - // a plain column, and is then no narrower than the widened child, or it - // narrows and holds a computed one. `RepartitionExec` declines both, it - // is not removable because it renames, and nothing else moved. + // stuck above a node that will not take a whole projection. The split + // needs no cleanup pass of its own: the outer projection it leaves + // either keeps every expression a plain column, and is then no narrower + // than the widened child, or it narrows and holds a computed one. Every + // node `split_host_child` allows declines both, the outer projection is + // not removable because it renames, and nothing else moved. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { @@ -507,6 +510,59 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } +/// Returns the input of `node` if the split may place the leaf projection +/// below it. +/// +/// The split gives `node` an input with different columns, so `node` must not +/// reference its input's columns and must output them unchanged, or the outer +/// projection's column indices would point at the wrong columns. The arms are +/// an allowlist: satisfying that is necessary, not sufficient. +fn split_host_child(node: &Arc) -> Option<&Arc> { + if let Some(repartition) = node.downcast_ref::() { + // Hash and Range partitioning reference columns by index, which would + // have to be remapped against the rewritten child schema. Round robin + // carries no column references, and is what `EnsureRequirements` + // inserts here. + if !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) { + return None; + } + Some(repartition.input()) + } else if let Some(limit) = node.downcast_ref::() { + // A source that supports skip pushdown wraps its scan in this for the + // skip, which leaves the projection holding the leaf above it. + Some(limit.input()) + } else if let Some(coalesce) = node.downcast_ref::() { + // A scan with more than one file group puts this between that limit + // and the source. + Some(coalesce.input()) + } else { + None + } +} + +/// The hosts between a projection and the child the split places the leaf +/// projection on. +struct SplitHostChain<'a> { + /// Outermost first, so the rebuild walks this in reverse. + hosts: Vec<&'a Arc>, + child: &'a Arc, +} + +/// Walks down from `node` for as long as [`split_host_child`] allows, so that +/// stacked hosts are descended in one go rather than one per pass. +fn split_host_chain(node: &Arc) -> Option> { + let mut hosts = vec![]; + let mut current = node; + while let Some(child) = split_host_child(current) { + hosts.push(current); + current = child; + } + (!hosts.is_empty()).then_some(SplitHostChain { + hosts, + child: current, + }) +} + /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. /// @@ -515,21 +571,22 @@ fn leaf_column_name(index: usize) -> String { /// and stops that projection descending past it, so a `MoveTowardsLeafNodes` /// expression sharing it never reaches the source. Splitting leaves the /// computation above the repartition, still parallelised. +/// +/// A source that pushes a skip down strands those leaves the same way: it wraps +/// its scan in a `GlobalLimitExec` for the skip, and no projection at all swaps +/// past that node. With more than one file group a `CoalescePartitionsExec` +/// sits under that limit too, so the split walks a chain of such nodes rather +/// than a single one. fn try_split_leaf_projection( plan: &Arc, ) -> Result>> { let Some(projection) = plan.downcast_ref::() else { return Ok(None); }; - let Some(repartition) = projection.input().downcast_ref::() else { + let Some(SplitHostChain { hosts, child }) = split_host_chain(projection.input()) + else { return Ok(None); }; - // Hash and Range partitioning reference columns by index, which would have - // to be remapped against the rewritten child schema. Round robin carries no - // column references, and is what `EnsureRequirements` inserts here. - if !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) { - return Ok(None); - } let leaves = collect_leaf_exprs(projection.expr())?; if leaves.is_empty() { @@ -540,7 +597,6 @@ fn try_split_leaf_projection( // column used *only* inside an extracted leaf must be dropped, otherwise the // source keeps reading it: for `s['a'] + 1` that would read the whole struct // alongside the extracted field, which is worse than not splitting at all. - let child = repartition.input(); let child_schema = child.schema(); let passthrough_indices = collect_outer_columns(projection.expr(), &leaves)?; let mut lower_exprs = passthrough_indices @@ -561,8 +617,9 @@ fn try_split_leaf_projection( } let lower_projection = ProjectionExec::try_new(lower_exprs, Arc::clone(child))?; - // Only commit the split if the child really absorbs the leaf projection. - // Otherwise this would just add a projection that helps nobody. + // Commit only if the child takes the lower projection. A `Some` does not + // always mean the source absorbed it: `FilterExec` takes it by holding it + // over its own input, so the scan narrows on this rule's second run. let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { return Ok(None); }; @@ -583,18 +640,21 @@ fn try_split_leaf_projection( }) .collect::>>()?; - // The child gained the leaf columns, so the repartition's properties have to - // be recomputed rather than carried over. - let new_repartition = Arc::clone(projection.input()).replace_children( - vec![new_child], - ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), - )?; + // The child gained the leaf columns, so every host's properties have to be + // recomputed rather than carried over. Innermost host first. + let mut new_host = new_child; + for host in hosts.iter().rev() { + new_host = Arc::clone(host).replace_children( + vec![new_host], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } // `try_new` would derive the output schema from the expressions alone and // drop the metadata the planner set, which `schema_check` then rejects. Ok(Some(Arc::new( ProjectionExec::try_new_with_schema_metadata( new_exprs, - new_repartition, + new_host, projection.schema().as_ref(), )?, ))) diff --git a/datafusion/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index 45ccb38a8fbde..36d5e75f83ae2 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -314,6 +314,208 @@ SELECT file_row_index() + 1, column1 FROM parquet_table ORDER BY column1 # `RESET` restores the global default rather than the harness value, which the # harness rejects as leftover configuration. +# A leaf expression must also reach the scan when the source pushes an +# `OFFSET` down. Every query below errors out without that. + +# Every `OFFSET` below sets a skip that differs from the fetch, and the two +# controls set no fetch at all: swapped numbers would show. + +# The marker is BARE here, and alone in its projection. +query I +SELECT r FROM (SELECT file_row_index() AS r FROM parquet_table OFFSET 1 LIMIT 3) +ORDER BY r +---- +1 +2 +3 + +# The marker wrapped in arithmetic. +query I +SELECT r FROM (SELECT file_row_index() + 1 AS r FROM parquet_table OFFSET 1 LIMIT 3) +ORDER BY r +---- +2 +3 +4 + +# A computed sibling in the same projection, which stays above the limit. +query II +SELECT r, w FROM ( + SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY r +---- +1 21 +2 31 +3 41 + +# The sibling marker behaves the same way. Compared against a predicate rather +# than printed, so the expectation does not depend on the absolute file path. +query B +SELECT n FROM ( + SELECT length(input_file_name()) > 0 AS n FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY n +---- +true +true +true + +# Not specific to arithmetic: any enclosing expression has the same effect. +query T +SELECT t FROM ( + SELECT arrow_typeof(file_row_index()) AS t FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY t +---- +Int64 +Int64 +Int64 + +# The plan behind the values above: the marker is rewritten inside the scan and +# the limit keeps both of its numbers, in that order. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: parquet_table projection=[], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as r] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +# `OFFSET 0` is the control: with no skip there is nothing to push down, so +# this shape never depended on the split. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 0 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: parquet_table projection=[], fetch=3 +physical_plan DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as r], limit=3, file_type=parquet + +# `OFFSET` with no `LIMIT` is the other control: the scan absorbs the +# projection before any limit exists, so the split is never consulted. +query TT +EXPLAIN SELECT file_row_index() AS r FROM parquet_table OFFSET 2 +---- +logical_plan +01)Limit: skip=2, fetch=None +02)--Projection: file_row_index() AS r +03)----TableScan: parquet_table projection=[] +physical_plan +01)GlobalLimitExec: skip=2, fetch=None +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as r], file_type=parquet + +# A repartition above the limit must not disturb the split: the outer +# projection keeps a `KeepInPlace` expression, so a `RepartitionExec` is +# inserted beneath it, and the extracted leaf sits below that with the limit +# still between it and the scan. `batch_size` is below the row count again, for +# the reason given above. + +statement ok +SET datafusion.execution.batch_size = 2; + +query II +SELECT r, w FROM ( + SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +) ORDER BY r +---- +1 21 +2 31 +3 41 + +query TT +EXPLAIN SELECT file_row_index() AS r, column1 + 1 AS w FROM parquet_table OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r, CAST(parquet_table.column1 AS Int64) + Int64(1) AS w +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1, parquet_table.column1 +04)------TableScan: parquet_table projection=[column1], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_extracted_1@0 as r, CAST(column1@1 AS Int64) + 1 as w] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----ProjectionExec: expr=[__datafusion_leaf_0@1 as __datafusion_extracted_1, column1@0 as column1] +04)------GlobalLimitExec: skip=1, fetch=3 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/parquet_table/data.parquet]]}, projection=[column1, CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +statement ok +SET datafusion.execution.batch_size = 8192; + +# More than one file group puts a second node between the limit and the scan, +# so the leaf has to descend past two rather than one. + +statement ok +COPY (VALUES (10), (20), (30)) +TO 'test_files/scratch/file_row_index/offset_two_files/a.parquet' +STORED AS PARQUET; + +statement ok +COPY (VALUES (40), (50), (60)) +TO 'test_files/scratch/file_row_index/offset_two_files/b.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE offset_two_files(column1 int) +STORED AS PARQUET +LOCATION 'test_files/scratch/file_row_index/offset_two_files/'; + +query TT +EXPLAIN SELECT file_row_index() AS r FROM offset_two_files OFFSET 1 LIMIT 3 +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS r +02)--Limit: skip=0, fetch=3 +03)----Projection: file_row_index() AS __datafusion_extracted_1 +04)------TableScan: offset_two_files projection=[], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as r] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----CoalescePartitionsExec: fetch=4 +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/offset_two_files/a.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/file_row_index/offset_two_files/b.parquet]]}, projection=[CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], limit=4, file_type=parquet + +# Which rows survive the skip depends on the partition merge order, which is +# not guaranteed, so this counts them instead of listing them. `count(r)` and +# not `count(*)`, which would let `r` be dropped and never evaluated. +query I +SELECT count(r) FROM ( + SELECT file_row_index() AS r FROM offset_two_files OFFSET 1 LIMIT 3 +) +---- +3 + +statement ok +DROP TABLE offset_two_files; + +# Not a parquet-only defect: any listing format strands the leaf the same way, +# and every other query in this file is parquet. `file_row_index()` is itself +# parquet-only, so this uses `input_file_name()`, which errors before the fix. + +statement ok +COPY (VALUES (10), (20), (30), (40), (50)) +TO 'test_files/scratch/file_row_index/offset_json/data.json' +STORED AS JSON; + +statement ok +CREATE EXTERNAL TABLE offset_json(column1 int) +STORED AS JSON +LOCATION 'test_files/scratch/file_row_index/offset_json/'; + +query B +SELECT n FROM ( + SELECT length(input_file_name()) > 0 AS n FROM offset_json OFFSET 1 LIMIT 3 +) ORDER BY n +---- +true +true +true + +statement ok +DROP TABLE offset_json; + statement ok DROP TABLE parquet_table; From 77da6bc31e16fc5243d7957cf63e81f2c22041a0 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Mon, 23 Nov 2026 21:00:50 +0800 Subject: [PATCH 2/6] test: share the parquet scan the split tests build, and fix two comments Review follow-ups on the previous commit; no behaviour changes. `limit_split_scan`, `split_below_a_filter_narrows_on_the_second_run` and `split_descends_through_global_limit_with_a_marker` each built the same single-file parquet scan inline. They now share `parquet_scan`. The rule's comment claimed every node `split_host_child` allows declines the outer projection the split leaves above it. `CoalescePartitionsExec` takes a narrowing projection, and once the leaves are extracted below it that outer projection is narrower than the widened child, so this rule's second run in the physical optimizer pushes it down. The comment now says that instead of claiming no node moves. `file_row_index.slt` said every query below the `OFFSET` heading errors out without the fix. Only the value queries do: the two controls pass either way, and the other `EXPLAIN`s differ in their plan rather than erroring. The next sentence also described both controls as setting no fetch, which only one of them does, and the control's own comment already says so. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 43 +++++++------------ .../src/projection_pushdown.rs | 8 ++-- .../test_files/file_row_index.slt | 6 +-- 3 files changed, 21 insertions(+), 36 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index f12e9434d94ef..7c98d7f640386 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -2041,6 +2041,16 @@ async fn split_declines_hash_repartition() -> Result<()> { Ok(()) } +fn parquet_scan(schema: &SchemaRef) -> Arc { + let config = FileScanConfigBuilder::new( + ObjectStoreUrl::parse("test:///").unwrap(), + Arc::new(ParquetSource::new(Arc::clone(schema))), + ) + .with_file(PartitionedFile::new("x".to_string(), 100)) + .build(); + DataSourceExec::from_data_source(config) +} + fn limit_split_scan() -> Result<(SchemaRef, Arc)> { let schema: SchemaRef = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, true), @@ -2050,13 +2060,7 @@ fn limit_split_scan() -> Result<(SchemaRef, Arc)> { true, ), ])); - let config = FileScanConfigBuilder::new( - ObjectStoreUrl::parse("test:///").unwrap(), - Arc::new(ParquetSource::new(Arc::clone(&schema))), - ) - .with_file(PartitionedFile::new("x".to_string(), 100)) - .build(); - Ok((schema, DataSourceExec::from_data_source(config))) + Ok((Arc::clone(&schema), parquet_scan(&schema))) } fn limit_split_exprs(schema: &SchemaRef) -> Result> { @@ -2367,22 +2371,14 @@ async fn split_below_a_filter_narrows_on_the_second_run() -> Result<()> { ), Field::new("k", DataType::Int64, true), ])); - let config = FileScanConfigBuilder::new( - ObjectStoreUrl::parse("test:///").unwrap(), - Arc::new(ParquetSource::new(Arc::clone(&schema))), - ) - .with_file(PartitionedFile::new("x".to_string(), 100)) - .build(); let predicate = binary( col("id", &schema)?, Operator::Gt, Arc::new(Literal::new(ScalarValue::Int64(Some(0)))), &schema, )?; - let filter: Arc = Arc::new(FilterExec::try_new( - predicate, - DataSourceExec::from_data_source(config), - )?); + let filter: Arc = + Arc::new(FilterExec::try_new(predicate, parquet_scan(&schema))?); let limit: Arc = Arc::new(GlobalLimitExec::new(filter, 1, Some(3))); let projection: Arc = @@ -2474,12 +2470,6 @@ async fn split_declines_when_the_child_refuses_the_projection() -> Result<()> { async fn split_descends_through_global_limit_with_a_marker() -> Result<()> { let schema: SchemaRef = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, true)])); - let config = FileScanConfigBuilder::new( - ObjectStoreUrl::parse("test:///").unwrap(), - Arc::new(ParquetSource::new(Arc::clone(&schema))), - ) - .with_file(PartitionedFile::new("x".to_string(), 100)) - .build(); let marker: Arc = Arc::new(ScalarFunctionExpr::new( "file_row_index", datafusion_functions::core::file_row_index(), @@ -2502,11 +2492,8 @@ async fn split_descends_through_global_limit_with_a_marker() -> Result<()> { alias: "w".to_string(), }, ]; - let limit: Arc = Arc::new(GlobalLimitExec::new( - DataSourceExec::from_data_source(config), - 1, - Some(3), - )); + let limit: Arc = + Arc::new(GlobalLimitExec::new(parquet_scan(&schema), 1, Some(3))); let projection: Arc = Arc::new(ProjectionExec::try_new(exprs, limit)?); diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index f88521103a150..a4d40565506be 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -71,11 +71,9 @@ impl PhysicalOptimizerRule for ProjectionPushdown { // Push what can already descend, then split the projections that are // stuck above a node that will not take a whole projection. The split - // needs no cleanup pass of its own: the outer projection it leaves - // either keeps every expression a plain column, and is then no narrower - // than the widened child, or it narrows and holds a computed one. Every - // node `split_host_child` allows declines both, the outer projection is - // not removable because it renames, and nothing else moved. + // runs no cleanup pass: an outer projection it leaves narrowing on top + // of a `CoalescePartitionsExec` is pushed below it by this rule's second + // run in the physical optimizer. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { diff --git a/datafusion/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index 36d5e75f83ae2..d059a23ad651e 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -315,10 +315,10 @@ SELECT file_row_index() + 1, column1 FROM parquet_table ORDER BY column1 # harness rejects as leftover configuration. # A leaf expression must also reach the scan when the source pushes an -# `OFFSET` down. Every query below errors out without that. +# `OFFSET` down. Every value query below errors out without that. -# Every `OFFSET` below sets a skip that differs from the fetch, and the two -# controls set no fetch at all: swapped numbers would show. +# Every `OFFSET` below sets a skip that differs from the fetch, so swapped +# numbers would show. # The marker is BARE here, and alone in its projection. query I From 96da981da61d9f78ad3bc17ca69e37acfacd20c9 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Mon, 30 Nov 2026 19:01:18 +0800 Subject: [PATCH 3/6] test: keep one unit test per behavior the split guards The eleven unit tests added here all assert plan text through `OptimizationTest`, so none of them can see the failure the issue reports: a marker leaf under a pushed-down `OFFSET` fails at execution, and a plan snapshot never runs the plan. The `.slt` value queries do cover that, so the Rust tests that restate a shape SQL already reaches are gone: - the `GlobalLimitExec` happy path and its marker variant: the eight value queries in `file_row_index.slt` and the `EXPLAIN` beside them - the limit-and-coalesce chain and the three-limit chain: the two-file-group `EXPLAIN` and the `count(r)` under it - the no-leaf decline: twelve existing `.slt` files fail without it - the memory-source decline: `projection_pushdown.slt` covers it with nearly the same comment - the `CooperativeExec` half of the pass-through test: that node is inserted after both of this rule's passes, so it cannot be there What stays is one test per behavior no SQL plan expresses: the two fetch shapes merge, since both say that a chain node keeps its own `skip` and `fetch` across the rebuild, and the two chain-bottom tests are named after the behavior they pin rather than the step the rule takes. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 271 ++---------------- 1 file changed, 18 insertions(+), 253 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 7c98d7f640386..2f50228e332ff 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use std::sync::Arc; -use arrow::array::RecordBatch; use arrow::compute::SortOptions; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use datafusion::datasource::listing::PartitionedFile; @@ -2091,60 +2090,6 @@ fn limit_split_exprs(schema: &SchemaRef) -> Result> { ]) } -#[tokio::test] -async fn split_descends_through_global_limit() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - // `skip` and `fetch` differ so that swapping them would show. - let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); - Ok(()) -} - -/// The no-leaf `EXPLAIN` in the `.slt` cannot pin this, because the plan is the -/// same either way. -#[tokio::test] -async fn split_declines_global_limit_without_leaf() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); - let exprs = vec![limit_split_exprs(&schema)?.swap_remove(1)]; - let projection: Arc = - Arc::new(ProjectionExec::try_new(exprs, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - " - ); - Ok(()) -} - /// `LocalLimitExec` is left out of `split_host_child`: no query in the test /// suite strands a leaf expression above one. This pins that choice. #[tokio::test] @@ -2172,41 +2117,15 @@ async fn split_declines_local_limit() -> Result<()> { Ok(()) } -/// A scan with more than one file group: a single `OFFSET` already stacks two -/// hosts, so stopping at the first would leave the scan reading the struct. -#[tokio::test] -async fn split_descends_through_limit_and_coalesce() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - let coalesce: Arc = Arc::new(CoalescePartitionsExec::new(scan)); - let limit: Arc = - Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CoalescePartitionsExec - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CoalescePartitionsExec - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); - Ok(()) -} - -/// `fetch = None`, which plain SQL does not reach: an `OFFSET` with no `LIMIT` -/// is not pushed into the scan, so only a hand-built plan covers it. +/// Each node in the chain keeps its own `skip` and `fetch` across the rebuild. +/// Losing one returns the wrong rows, with no sign of it in the plan. +/// +/// Neither shape is reachable from SQL: an `OFFSET` with no `LIMIT` is absorbed +/// by the scan before any limit exists, and the fetch on a +/// `CoalescePartitionsExec` is put there by `LimitPushdown`, which runs after +/// this rule's first pass. #[tokio::test] -async fn split_descends_through_global_limit_without_fetch() -> Result<()> { +async fn split_keeps_each_chain_node_fetch() -> Result<()> { let (schema, scan) = limit_split_scan()?; let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); let projection: Arc = @@ -2227,14 +2146,7 @@ async fn split_descends_through_global_limit_without_fetch() -> Result<()> { - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet " ); - Ok(()) -} -/// A host carrying a `fetch` of its own has to keep it across the rebuild. The -/// `.slt` plans show a fetch on this node, but `LimitPushdown` puts it there -/// after the split, so they do not cover this. -#[tokio::test] -async fn split_keeps_the_coalesce_fetch() -> Result<()> { let (schema, scan) = limit_split_scan()?; let coalesce: Arc = Arc::new(CoalescePartitionsExec::new(scan).with_fetch(Some(4))); @@ -2263,70 +2175,12 @@ async fn split_keeps_the_coalesce_fetch() -> Result<()> { Ok(()) } -/// Each of the three limits keeps its own `skip` and `fetch` after the rebuild. +/// A `BufferExec` is not a chain node, but as the *bottom* of the chain it +/// delegates the swap to its own input, so the leaf still reaches the scan in +/// one pass. `HashJoinBuffering` inserts it between this rule's two runs, so no +/// SQL plan has one here. #[tokio::test] -async fn split_descends_through_three_hosts() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - let inner: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(9))); - let middle: Arc = - Arc::new(GlobalLimitExec::new(inner, 2, Some(6))); - let outer: Arc = - Arc::new(GlobalLimitExec::new(middle, 3, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, outer)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=3, fetch=3 - - GlobalLimitExec: skip=2, fetch=6 - - GlobalLimitExec: skip=1, fetch=9 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=3, fetch=3 - - GlobalLimitExec: skip=2, fetch=6 - - GlobalLimitExec: skip=1, fetch=9 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); - Ok(()) -} - -/// `CooperativeExec` and `BufferExec` are not hosts, but as the *bottom* of the -/// chain they delegate the swap to their own input, so the split commits and -/// the scan narrows in one pass. -#[tokio::test] -async fn split_commits_at_a_pass_through_bottom() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - let cooperative: Arc = Arc::new(CooperativeExec::new(scan)); - let limit: Arc = - Arc::new(GlobalLimitExec::new(cooperative, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CooperativeExec - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CooperativeExec - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); - +async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { let (schema, scan) = limit_split_scan()?; let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); let limit: Arc = @@ -2354,12 +2208,12 @@ async fn split_commits_at_a_pass_through_bottom() -> Result<()> { Ok(()) } -/// A `FilterExec` bottom takes the lower projection by holding it over its own -/// input, so after one pass the scan still reads everything and the plan has -/// gained a node. This rule is scheduled twice, and the second run is what -/// pushes the projection into the source. Nothing else states that dependency. +/// A `FilterExec` at the bottom of the chain takes the lower projection by +/// holding it over its own input, so the leaf reaches the scan only on this +/// rule's second run. Plain SQL does not reach this: the logical optimizer +/// extracts the leaf first, leaving none on the filter. #[tokio::test] -async fn split_below_a_filter_narrows_on_the_second_run() -> Result<()> { +async fn leaf_reaches_the_scan_below_a_filter() -> Result<()> { // Three columns so the lower projection narrows; with two it does not, and // `FilterExec` declines before reaching the branch this test is about. let schema: SchemaRef = Arc::new(Schema::new(vec![ @@ -2425,92 +2279,3 @@ async fn split_below_a_filter_narrows_on_the_second_run() -> Result<()> { ); Ok(()) } - -/// A memory source declines an aliased `get_field`, so the split must not -/// commit: it would add a projection below the limit that nobody absorbs. -#[tokio::test] -async fn split_declines_when_the_child_refuses_the_projection() -> Result<()> { - let schema: SchemaRef = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int64, true), - Field::new( - "s", - DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), - true, - ), - ])); - let batch = RecordBatch::new_empty(Arc::clone(&schema)); - let source = MemorySourceConfig::try_new(&[vec![batch]], Arc::clone(&schema), None)?; - let scan = DataSourceExec::from_data_source(source); - let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: partitions=1, partition_sizes=[1] - output: - Ok: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: partitions=1, partition_sizes=[1] - " - ); - Ok(()) -} - -/// `file_row_index()` as the leaf, which is what #27494 reports. Unlike -/// `get_field` it cannot be evaluated above the scan at all, so the output -/// shows the source resolving it into its hidden column. -#[tokio::test] -async fn split_descends_through_global_limit_with_a_marker() -> Result<()> { - let schema: SchemaRef = - Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, true)])); - let marker: Arc = Arc::new(ScalarFunctionExpr::new( - "file_row_index", - datafusion_functions::core::file_row_index(), - vec![], - Arc::new(Field::new("r", DataType::Int64, true)), - Arc::new(ConfigOptions::default()), - )); - let exprs = vec![ - ProjectionExpr { - expr: marker, - alias: "r".to_string(), - }, - ProjectionExpr { - expr: binary( - col("id", &schema)?, - Operator::Plus, - Arc::new(Literal::new(ScalarValue::Int64(Some(1)))), - &schema, - )?, - alias: "w".to_string(), - }, - ]; - let limit: Arc = - Arc::new(GlobalLimitExec::new(parquet_scan(&schema), 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(exprs, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[file_row_index() as r, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as r, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, CAST(__datafusion_file_row_index@1 AS Int64;N) as __datafusion_leaf_0], file_type=parquet - " - ); - Ok(()) -} From cb671ff8bfa25697bbe2c5ee0388bdd8728682a2 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Mon, 30 Nov 2026 19:31:46 +0800 Subject: [PATCH 4/6] test: drop the LocalLimitExec decline for a comment Printing the chain, its child and which of this rule's two passes is running, over all 309 `.slt` files and over twelve hand-written shapes that put an aggregate, a window, a union, a join, a sort, an unnest or a cross join under the limit, never strands a leaf above a `LocalLimitExec`. The node shows up 10 times in the suite and 9 times in those shapes, every time on the first pass and every time with no leaf above it, because `LimitPushdown` folds its fetch into the scan before the second pass. Adding it to the allowlist changes no plan in the suite either. The test therefore pinned a decision nothing can observe, and it was the only one left here that still passed with the fix reverted. What it recorded belongs in `split_host_child`, where a reader wondering why the node is not an arm is already looking. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 29 +------------------ .../src/projection_pushdown.rs | 3 ++ 2 files changed, 4 insertions(+), 28 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 2f50228e332ff..12193bc62d2ae 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -44,7 +44,7 @@ use datafusion_physical_plan::joins::{ HashJoinExec, NestedLoopJoinExec, PartitionMode, SortMergeJoinExec, StreamJoinPartitionMode, SymmetricHashJoinExec, }; -use datafusion_physical_plan::limit::{GlobalLimitExec, LocalLimitExec}; +use datafusion_physical_plan::limit::GlobalLimitExec; use datafusion_physical_plan::projection::{ProjectionExec, ProjectionExpr, update_expr}; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::sorts::sort::SortExec; @@ -2090,33 +2090,6 @@ fn limit_split_exprs(schema: &SchemaRef) -> Result> { ]) } -/// `LocalLimitExec` is left out of `split_host_child`: no query in the test -/// suite strands a leaf expression above one. This pins that choice. -#[tokio::test] -async fn split_declines_local_limit() -> Result<()> { - let (schema, scan) = limit_split_scan()?; - let limit: Arc = Arc::new(LocalLimitExec::new(scan, 2)); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - LocalLimitExec: fetch=2 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - LocalLimitExec: fetch=2 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - " - ); - Ok(()) -} - /// Each node in the chain keeps its own `skip` and `fetch` across the rebuild. /// Losing one returns the wrong rows, with no sign of it in the plan. /// diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index a4d40565506be..764dca3b2fc1b 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -515,6 +515,9 @@ fn leaf_column_name(index: usize) -> String { /// reference its input's columns and must output them unchanged, or the outer /// projection's column indices would point at the wrong columns. The arms are /// an allowlist: satisfying that is necessary, not sufficient. +/// `LocalLimitExec` satisfies it too but is deliberately not an arm: it is only +/// there before `LimitPushdown` folds its fetch into the scan, and no query in +/// the suite leaves a leaf above one by then. fn split_host_child(node: &Arc) -> Option<&Arc> { if let Some(repartition) = node.downcast_ref::() { // Hash and Range partitioning reference columns by index, which would From 30eb8e2d7eeffb71344dbfbcf08eff502d804b26 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Tue, 1 Dec 2026 21:47:07 +0800 Subject: [PATCH 5/6] test: run two of the three split tests instead of only formatting them All three asserted plan text, so renaming a `Display` label reddened them while the failure the issue reports -- the marker erroring above the limit -- was invisible: a `get_field` leaf returns the same rows whether or not it reaches the scan, and the tests never ran the plan. Two of the three shapes can be executed. Build them over a real five-row Parquet file with a `file_row_index()` leaf and assert the rows, first in the test so it is the failure a regression reports. Reverting the rule now fails them with `Execution("file_row_index() is source dependent and cannot be evaluated directly")`, and dropping a host's skip during the rebuild fails them with the wrong rows. The third shape needs `get_field`'s narrowing, which a marker cannot provide, so its doc says it can only pin the plan. Also, in the comments: drop two that restated the function doc and one that restated where `EnsureRequirements` runs, replace "no projection at all swaps past that node" with the missing override it rests on, name both `BufferExec` inserters rather than one, and use the shared `parquet_scan()` helper at the fourth identical site. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 98 ++++++++++++++++--- .../src/projection_pushdown.rs | 23 ++--- 2 files changed, 96 insertions(+), 25 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 12193bc62d2ae..2ea0d7c7d26fd 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -14,7 +14,9 @@ use datafusion::datasource::source::DataSourceExec; use datafusion::prelude::{ParquetReadOptions, SessionContext}; use datafusion_common::config::{ConfigOptions, CsvOptions}; use datafusion_common::metadata::FieldMetadata; -use datafusion_common::{JoinSide, JoinType, NullEquality, Result, ScalarValue}; +use datafusion_common::{ + JoinSide, JoinType, NullEquality, Result, ScalarValue, assert_batches_eq, +}; use datafusion_datasource::TableSchemaBuilder; use datafusion_datasource::file_scan_config::FileScanConfigBuilder; use datafusion_execution::object_store::ObjectStoreUrl; @@ -51,7 +53,7 @@ use datafusion_physical_plan::sorts::sort::SortExec; use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec}; use datafusion_physical_plan::union::UnionExec; -use datafusion_physical_plan::{ExecutionPlan, displayable}; +use datafusion_physical_plan::{ExecutionPlan, collect, displayable}; use insta::assert_snapshot; @@ -1977,16 +1979,10 @@ async fn split_declines_hash_repartition() -> Result<()> { true, ), ])); - let config = FileScanConfigBuilder::new( - ObjectStoreUrl::parse("test:///").unwrap(), - Arc::new(ParquetSource::new(Arc::clone(&schema))), - ) - .with_file(PartitionedFile::new("x".to_string(), 100)) - .build(); // Parquet absorbs a leaf projection, so the split would commit here if the // partitioning check did not stop it first. let hash = Arc::new(RepartitionExec::try_new( - DataSourceExec::from_data_source(config), + parquet_scan(&schema), Partitioning::Hash(vec![col("id", &schema)?], 4), )?); @@ -2090,6 +2086,44 @@ fn limit_split_exprs(schema: &SchemaRef) -> Result> { ]) } +/// A real five-row Parquet file and the scan the planner builds over it, so a +/// hand-built chain above it can be *run*, not only formatted. +async fn five_row_parquet( + dir: &tempfile::TempDir, +) -> Result<(SessionContext, Arc)> { + let path = dir.path().join("leaf_split_rows.parquet"); + let path = path.to_str().expect("temp path is not utf-8"); + let ctx = SessionContext::new(); + ctx.sql(&format!( + "COPY (SELECT column1 AS id, column2 AS s FROM VALUES \ + (1, {{value: 100}}), (2, {{value: 200}}), (3, {{value: 150}}), \ + (4, {{value: 300}}), (5, {{value: 250}})) \ + TO '{path}' STORED AS PARQUET" + )) + .await? + .collect() + .await?; + ctx.register_parquet("t", path, ParquetReadOptions::default()) + .await?; + let scan = ctx.table("t").await?.create_physical_plan().await?; + Ok((ctx, scan)) +} + +/// The marker from #27494: `invoke_with_args` is an `exec_err!`, so it returns +/// rows only if the split put it inside the scan. +fn marker_exprs() -> Vec { + vec![ProjectionExpr { + expr: Arc::new(ScalarFunctionExpr::new( + "file_row_index", + datafusion_functions::core::file_row_index(), + vec![], + Arc::new(Field::new("r", DataType::Int64, true)), + Arc::new(ConfigOptions::default()), + )), + alias: "r".to_string(), + }] +} + /// Each node in the chain keeps its own `skip` and `fetch` across the rebuild. /// Losing one returns the wrong rows, with no sign of it in the plan. /// @@ -2099,6 +2133,25 @@ fn limit_split_exprs(schema: &SchemaRef) -> Result> { /// this rule's first pass. #[tokio::test] async fn split_keeps_each_chain_node_fetch() -> Result<()> { + // Neither snapshot can see the failure the issue reports: they do not run + // the plan, and a `get_field` leaf returns the same rows whether or not it + // reaches the scan. The same chain with the marker leaf does run, and sees + // both halves — without the split the marker errors, and a dropped `skip` + // comes back as the wrong rows. + let dir = tempfile::tempdir()?; + let (ctx, scan) = five_row_parquet(&dir).await?; + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); + let projection: Arc = + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 2 |", "| 3 |", "| 4 |", "+---+" + ], + &collect(optimized, ctx.task_ctx()).await? + ); + let (schema, scan) = limit_split_scan()?; let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); let projection: Arc = @@ -2150,10 +2203,29 @@ async fn split_keeps_each_chain_node_fetch() -> Result<()> { /// A `BufferExec` is not a chain node, but as the *bottom* of the chain it /// delegates the swap to its own input, so the leaf still reaches the scan in -/// one pass. `HashJoinBuffering` inserts it between this rule's two runs, so no -/// SQL plan has one here. +/// one pass. Both of its inserters run after this rule's first pass — +/// `HashJoinBuffering` before the second, `PushdownSort` after it — and no +/// query in the suite leaves a leaf above one. #[tokio::test] async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { + // The snapshot stops at the plan. Running the same chain over a real source + // is what shows the marker reached the scan rather than the limit. + let dir = tempfile::tempdir()?; + let (ctx, scan) = five_row_parquet(&dir).await?; + let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(buffer, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+" + ], + &collect(optimized, ctx.task_ctx()).await? + ); + let (schema, scan) = limit_split_scan()?; let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); let limit: Arc = @@ -2184,7 +2256,9 @@ async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { /// A `FilterExec` at the bottom of the chain takes the lower projection by /// holding it over its own input, so the leaf reaches the scan only on this /// rule's second run. Plain SQL does not reach this: the logical optimizer -/// extracts the leaf first, leaving none on the filter. +/// extracts the leaf first, leaving none on the filter. The shape needs +/// `get_field`'s narrowing, and a `get_field` leaf returns the same rows either +/// way, so unlike the two tests above this one can only pin the plan. #[tokio::test] async fn leaf_reaches_the_scan_below_a_filter() -> Result<()> { // Three columns so the lower projection narrows; with two it does not, and diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index 764dca3b2fc1b..155009f7e38a8 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -71,9 +71,8 @@ impl PhysicalOptimizerRule for ProjectionPushdown { // Push what can already descend, then split the projections that are // stuck above a node that will not take a whole projection. The split - // runs no cleanup pass: an outer projection it leaves narrowing on top - // of a `CoalescePartitionsExec` is pushed below it by this rule's second - // run in the physical optimizer. + // runs no cleanup pass: an outer projection it leaves narrowing is + // pushed below the host on this rule's second run. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { @@ -522,19 +521,16 @@ fn split_host_child(node: &Arc) -> Option<&Arc() { // Hash and Range partitioning reference columns by index, which would // have to be remapped against the rewritten child schema. Round robin - // carries no column references, and is what `EnsureRequirements` - // inserts here. + // carries no column references. if !matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) { return None; } Some(repartition.input()) } else if let Some(limit) = node.downcast_ref::() { - // A source that supports skip pushdown wraps its scan in this for the - // skip, which leaves the projection holding the leaf above it. + // A skip pushed into the source wraps the scan in this. Some(limit.input()) } else if let Some(coalesce) = node.downcast_ref::() { - // A scan with more than one file group puts this between that limit - // and the source. + // Two or more file groups put this under that limit. Some(coalesce.input()) } else { None @@ -574,10 +570,11 @@ fn split_host_chain(node: &Arc) -> Option> /// computation above the repartition, still parallelised. /// /// A source that pushes a skip down strands those leaves the same way: it wraps -/// its scan in a `GlobalLimitExec` for the skip, and no projection at all swaps -/// past that node. With more than one file group a `CoalescePartitionsExec` -/// sits under that limit too, so the split walks a chain of such nodes rather -/// than a single one. +/// its scan in a `GlobalLimitExec` for the skip, which has no +/// `try_swapping_with_projection` override, so no projection descends past it. +/// With more than one file group a `CoalescePartitionsExec` sits under that +/// limit too, so the split walks a chain of such nodes rather than a single +/// one. fn try_split_leaf_projection( plan: &Arc, ) -> Result>> { From eb5d23e2d4b28c7c9c432547df10c3606b9250f6 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Wed, 2 Dec 2026 07:54:00 +0800 Subject: [PATCH 6/6] test: read the rebuilt nodes instead of their rendered plan The two split tests kept a plan snapshot beside their execution assertion: renaming `GlobalLimitExec`'s `skip=` field turns both red with no behavior change. Drop them, and keep the one cell the second snapshot was the only detector for -- the fetch on a `CoalescePartitionsExec` surviving the rebuild -- by reading that fetch back off the rebuilt node, since dropping it costs the coalesce an early stop and leaves every row unchanged. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01RQf3XXpi2VAxHLGeqpsQi1 --- .../physical_optimizer/projection_pushdown.rs | 109 ++++-------------- 1 file changed, 24 insertions(+), 85 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 2ea0d7c7d26fd..160258217ea47 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -2046,18 +2046,6 @@ fn parquet_scan(schema: &SchemaRef) -> Arc { DataSourceExec::from_data_source(config) } -fn limit_split_scan() -> Result<(SchemaRef, Arc)> { - let schema: SchemaRef = Arc::new(Schema::new(vec![ - Field::new("id", DataType::Int64, true), - Field::new( - "s", - DataType::Struct(vec![Field::new("value", DataType::Int64, true)].into()), - true, - ), - ])); - Ok((Arc::clone(&schema), parquet_scan(&schema))) -} - fn limit_split_exprs(schema: &SchemaRef) -> Result> { let leaf: Arc = Arc::new(ScalarFunctionExpr::new( "get_field", @@ -2125,7 +2113,9 @@ fn marker_exprs() -> Vec { } /// Each node in the chain keeps its own `skip` and `fetch` across the rebuild. -/// Losing one returns the wrong rows, with no sign of it in the plan. +/// A lost `skip` comes back as the wrong rows; a lost `fetch` on the +/// `CoalescePartitionsExec` only costs it an early stop, which no row can +/// show, so that one is read back off the rebuilt node instead. /// /// Neither shape is reachable from SQL: an `OFFSET` with no `LIMIT` is absorbed /// by the scan before any limit exists, and the fetch on a @@ -2133,14 +2123,10 @@ fn marker_exprs() -> Vec { /// this rule's first pass. #[tokio::test] async fn split_keeps_each_chain_node_fetch() -> Result<()> { - // Neither snapshot can see the failure the issue reports: they do not run - // the plan, and a `get_field` leaf returns the same rows whether or not it - // reaches the scan. The same chain with the marker leaf does run, and sees - // both halves — without the split the marker errors, and a dropped `skip` - // comes back as the wrong rows. let dir = tempfile::tempdir()?; let (ctx, scan) = five_row_parquet(&dir).await?; - let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); + let limit: Arc = + Arc::new(GlobalLimitExec::new(Arc::clone(&scan), 2, None)); let projection: Arc = Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); let optimized = @@ -2152,52 +2138,32 @@ async fn split_keeps_each_chain_node_fetch() -> Result<()> { &collect(optimized, ctx.task_ctx()).await? ); - let (schema, scan) = limit_split_scan()?; - let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 2, None)); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=2, fetch=None - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=2, fetch=None - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); - - let (schema, scan) = limit_split_scan()?; + // The same leaf two nodes down, so one pass has to walk the whole chain. let coalesce: Arc = Arc::new(CoalescePartitionsExec::new(scan).with_fetch(Some(4))); let limit: Arc = Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + Arc::new(ProjectionExec::try_new(marker_exprs(), limit)?); + let optimized = + ProjectionPushdown::new().optimize(projection, &ConfigOptions::default())?; - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CoalescePartitionsExec: fetch=4 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - CoalescePartitionsExec: fetch=4 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " + assert_batches_eq!( + [ + "+---+", "| r |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+" + ], + &collect(Arc::clone(&optimized), ctx.task_ctx()).await? ); + + // Dropping the coalesce's own fetch costs it an early stop and nothing + // else, so no row above can show it: read it back off the rebuilt node. + let rebuilt_limit = Arc::clone(optimized.children()[0]); + let rebuilt_coalesce = Arc::clone(rebuilt_limit.children()[0]); + let rebuilt_limit = rebuilt_limit + .downcast_ref::() + .expect("the rebuild keeps the node itself, not only its numbers"); + assert_eq!((rebuilt_limit.skip(), rebuilt_limit.fetch()), (1, Some(3))); + assert_eq!(rebuilt_coalesce.fetch(), Some(4)); Ok(()) } @@ -2208,8 +2174,6 @@ async fn split_keeps_each_chain_node_fetch() -> Result<()> { /// query in the suite leaves a leaf above one. #[tokio::test] async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { - // The snapshot stops at the plan. Running the same chain over a real source - // is what shows the marker reached the scan rather than the limit. let dir = tempfile::tempdir()?; let (ctx, scan) = five_row_parquet(&dir).await?; let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); @@ -2225,31 +2189,6 @@ async fn leaf_reaches_the_scan_below_a_pass_through_node() -> Result<()> { ], &collect(optimized, ctx.task_ctx()).await? ); - - let (schema, scan) = limit_split_scan()?; - let buffer: Arc = Arc::new(BufferExec::new(scan, 4)); - let limit: Arc = - Arc::new(GlobalLimitExec::new(buffer, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - assert_snapshot!( - OptimizationTest::new(projection, ProjectionPushdown::new(), false), - @r" - OptimizationTest: - input: - - ProjectionExec: expr=[get_field(s@1, value) as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - BufferExec: capacity=4 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet - output: - Ok: - - ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] - - GlobalLimitExec: skip=1, fetch=3 - - BufferExec: capacity=4 - - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], file_type=parquet - " - ); Ok(()) }