diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index c0936eb929b37..bb3a76cd73bd5 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,429 @@ 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(()) +} diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index 364ec8d75aab5..a5e6428e533f8 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -22,8 +22,10 @@ use datafusion_expr::ExpressionPlacement; use datafusion_physical_expr::expressions::{Column, LambdaExpr, LambdaVariable}; use datafusion_physical_expr::projection::ProjectionExpr; 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, }; @@ -66,12 +68,6 @@ 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. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { @@ -490,29 +486,64 @@ 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: meeting 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::() { + Some(limit.input()) + } else { + // A scan with more than one file group puts this between the limit + // and the source. + Some(node.downcast_ref::()?.input()) + } +} + +struct SplitHostChain<'a> { + /// Outermost first, so the rebuild walks this in reverse. + hosts: Vec<&'a Arc>, + child: &'a Arc, +} + +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. -/// -/// `benefits_from_input_partitioning` is true as soon as any expression is -/// `KeepInPlace`, which both inserts a `RepartitionExec` below the projection -/// 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. +/// Without the split the leaves stay above the source: no projection swaps past +/// a `GlobalLimitExec`, and none with a computed expression swaps past a +/// `RepartitionExec`. 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() { @@ -523,7 +554,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 @@ -544,8 +574,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); }; @@ -566,18 +597,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..834271ce2d40f 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -314,6 +314,172 @@ 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 + +# 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; diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 52dbb7875a183..a113d809b8185 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2872,6 +2872,197 @@ SET datafusion.execution.batch_size = 8192; statement ok SET datafusion.execution.target_partitions = 4; +# With an `OFFSET` the source pushes down, a leaf expression must still reach +# the scan. Without that the scan reads the whole struct again. + +# Every `OFFSET` below sets a skip that differs from the fetch: with the two +# numbers equal, nothing here would notice them being swapped. + +query I +SELECT v FROM (SELECT s['value'] AS v FROM leaf_split OFFSET 1 LIMIT 3) ORDER BY v; +---- +150 +200 +300 + +query II +SELECT v, w FROM ( + SELECT s['value'] AS v, id + 1 AS w FROM leaf_split OFFSET 1 LIMIT 3 +) ORDER BY v; +---- +150 4 +200 3 +300 5 + +# A bare `get_field` alone in its projection. +query TT +EXPLAIN SELECT s['value'] AS v FROM leaf_split OFFSET 1 LIMIT 3; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v +02)--Limit: skip=0, fetch=3 +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1 +04)------TableScan: leaf_split projection=[s], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as v] +02)--GlobalLimitExec: skip=1, fetch=3 +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_leaf_0], limit=4, file_type=parquet + +# With a computed sibling, which stays above the limit: only the leaf descends. +query TT +EXPLAIN SELECT s['value'] AS v, id + 1 AS w FROM leaf_split OFFSET 1 LIMIT 3; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v, leaf_split.id + Int64(1) AS w +02)--Limit: skip=0, fetch=3 +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split.id +04)------TableScan: leaf_split projection=[id, s], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], limit=4, file_type=parquet + +# A leaf nested inside a `KeepInPlace` expression: `upper` stays above the +# limit and the scan still reads only the two fields. +query TT +EXPLAIN SELECT s['value'] AS v, upper(s['label']) AS l FROM leaf_split OFFSET 1 LIMIT 3; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v, upper(__datafusion_extracted_2) AS l +02)--Limit: skip=0, fetch=3 +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, get_field(leaf_split.s, Utf8("label")) AS __datafusion_extracted_2 +04)------TableScan: leaf_split projection=[s], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as v, upper(__datafusion_leaf_1@1) as l] +02)--GlobalLimitExec: skip=1, fetch=3 +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_leaf_0, get_field(s@1, label) as __datafusion_leaf_1], limit=4, file_type=parquet + +# No leaf expression: a control, not a guard. The plan is the same either way, +# so `split_declines_global_limit_without_leaf` pins the early bail-out. +query TT +EXPLAIN SELECT id + 1 AS w FROM leaf_split OFFSET 1 LIMIT 3; +---- +logical_plan +01)Projection: leaf_split.id + Int64(1) AS w +02)--Limit: skip=0, fetch=3 +03)----TableScan: leaf_split projection=[id], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[id@0 + 1 as w] +02)--GlobalLimitExec: skip=1, fetch=3 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[id], limit=4, file_type=parquet + +# A marker inside a lambda body, under an `OFFSET`. The lambda queries further +# up have no limit and the limit queries above have no lambda, so nothing +# covered both; this errors before the fix. It stays here rather than in the +# lambda section above, which runs with a `batch_size` that inserts a repartition. +statement ok +SET datafusion.sql_parser.dialect = databricks; + +query ?IT +SELECT a, v, l FROM ( + SELECT array_transform(arr, x -> x + file_row_index()) AS a, + s['value'] AS v, s['label'] AS l + FROM leaf_split OFFSET 1 LIMIT 3 +) ORDER BY v; +---- +[8] 150 gamma +[5, 6] 200 beta +[10, 11, 12] 300 delta + +statement ok +SET datafusion.sql_parser.dialect = generic; + +# More than one file group puts a second node between the limit and the scan, +# so the leaf has to descend past two. + +statement ok +COPY ( + SELECT column1 AS id, column2 AS s FROM VALUES + (1, {value: 100, label: 'alpha'}), (2, {value: 200, label: 'beta'}) +) TO 'test_files/scratch/projection_pushdown/leaf_split_two/a.parquet' +STORED AS PARQUET; + +statement ok +COPY ( + SELECT column1 AS id, column2 AS s FROM VALUES + (3, {value: 150, label: 'gamma'}), (4, {value: 300, label: 'delta'}) +) TO 'test_files/scratch/projection_pushdown/leaf_split_two/b.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE leaf_split_two STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/leaf_split_two/'; + +query TT +EXPLAIN SELECT s['value'] AS v FROM leaf_split_two OFFSET 1 LIMIT 2; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v +02)--Limit: skip=0, fetch=2 +03)----Projection: get_field(leaf_split_two.s, Utf8("value")) AS __datafusion_extracted_1 +04)------TableScan: leaf_split_two projection=[s], fetch=2, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@0 as v] +02)--GlobalLimitExec: skip=1, fetch=2 +03)----CoalescePartitionsExec: fetch=3 +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split_two/a.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split_two/b.parquet]]}, projection=[get_field(s@1, value) as __datafusion_leaf_0], limit=3, file_type=parquet + +query TT +EXPLAIN SELECT s['value'] AS v, id + 1 AS w FROM leaf_split_two OFFSET 1 LIMIT 2; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v, leaf_split_two.id + Int64(1) AS w +02)--Limit: skip=0, fetch=2 +03)----Projection: get_field(leaf_split_two.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split_two.id +04)------TableScan: leaf_split_two projection=[id, s], fetch=2, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] +02)--GlobalLimitExec: skip=1, fetch=2 +03)----CoalescePartitionsExec: fetch=3 +04)------DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split_two/a.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split_two/b.parquet]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], limit=3, file_type=parquet + +# Which rows survive the skip depends on the order the partitions are merged +# in, which is not guaranteed, so this counts them instead of listing them. +query I +SELECT count(v) FROM ( + SELECT s['value'] AS v FROM leaf_split_two OFFSET 1 LIMIT 2 +); +---- +2 + +statement ok +DROP TABLE leaf_split_two; + +# A table bigger than `batch_size` also gets a `RepartitionExec`, which lands +# above the limit. The split then acts on the leaf projection under it. +statement ok +SET datafusion.execution.batch_size = 2; + +query TT +EXPLAIN SELECT s['value'] AS v, id + 1 AS w FROM leaf_split OFFSET 1 LIMIT 3; +---- +logical_plan +01)Projection: __datafusion_extracted_1 AS v, leaf_split.id + Int64(1) AS w +02)--Limit: skip=0, fetch=3 +03)----Projection: get_field(leaf_split.s, Utf8("value")) AS __datafusion_extracted_1, leaf_split.id +04)------TableScan: leaf_split projection=[id, s], fetch=3, skip=1 +physical_plan +01)ProjectionExec: expr=[__datafusion_extracted_1@0 as v, id@1 + 1 as w] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 +03)----ProjectionExec: expr=[__datafusion_leaf_0@1 as __datafusion_extracted_1, id@0 as id] +04)------GlobalLimitExec: skip=1, fetch=3 +05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/leaf_split.parquet]]}, projection=[id, get_field(s@1, value) as __datafusion_leaf_0], limit=4, file_type=parquet + +query II +SELECT v, w FROM (SELECT s['value'] AS v, id + 1 AS w FROM leaf_split OFFSET 1 LIMIT 3) ORDER BY v; +---- +150 4 +200 3 +300 5 + +statement ok +SET datafusion.execution.batch_size = 8192; + statement ok DROP TABLE leaf_split;