From 941778cc08bdbebd5331ac64d7bb0867f9be2716 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Thu, 12 Nov 2026 23:20:08 +0800 Subject: [PATCH 1/5] fix: split a leaf projection stranded above a limit by a pushed-down OFFSET A source that supports skip pushdown wraps its scan in a `GlobalLimitExec` for the skip, and when the scan has more than one file group `EnsureRequirements` adds a `CoalescePartitionsExec` under that. Either way the nodes land between the scan and the leaf projection the logical rules placed on it. Neither lets that projection swap back down, so `LimitPushdown` leaves two projections adjacent and the next `ProjectionPushdown` merges them, hoisting the leaf expression back above the limit: `file_row_index()` then errors at execution and `get_field` reads the whole struct. `try_split_leaf_projection` already handles the same shape above a `RepartitionExec`. Generalise its host from one hardcoded node to a chain: `split_host_child` accepts a round-robin `RepartitionExec`, a `GlobalLimitExec` or a `CoalescePartitionsExec`, and `split_host_chain` walks as many as are stacked. A single `OFFSET` on a multi-file table already stacks two, so stopping at the first would leave that shape broken. Each arm evaluates no expression of its own, has one child, and passes its child's schema through. That last property is what lets the outer expressions keep their column indices across several hosts, and it holds by construction rather than by luck: none of the three `compute_properties` takes a schema, and each clones its input's equivalence properties, so a host's schema is its child's. A fourth arm that projects would have to re-establish that, and nothing here will catch it; the doc comment says so. Splitting rather than swapping the whole projection past the limit is what keeps the cost right: only the leaf half descends, so the rows the limit skips pay for a field access the source was going to make anyway and never for the outer expressions. Part of #27131 Co-Authored-By: Claude Opus 5 --- .../src/projection_pushdown.rs | 150 ++++++++++++++---- 1 file changed, 123 insertions(+), 27 deletions(-) diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index 364ec8d75aab5..afb05197df3cb 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, }; @@ -67,11 +69,16 @@ 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 chain of the nodes `split_host_child` accepts. The + // split needs no cleanup pass of its own: the outer projection it + // leaves renames the columns it took from the split, so it is not + // removable, and no host lets that projection swap past it. + // `RepartitionExec` and `CoalescePartitionsExec` decline a projection + // that does not narrow; `GlobalLimitExec` declines every projection, + // through the default at `ExecutionPlan::try_swapping_with_projection`. + // A chain bottom that only holds the lower projection instead of + // absorbing it is tidied by this rule's second scheduled run, not by a + // pass added here. 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 +497,113 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } +/// Returns the child of `node` if a projection may be split beneath it. +/// +/// Every arm evaluates no expression of its own and has exactly one child, so +/// widening that child with the leaf columns cannot change what it does. Each +/// also hands its child's schema straight through, which is what lets the +/// outer expressions keep their column indices when the split descends past +/// several of these in a row. +/// +/// That last property holds by construction rather than by luck: none of the +/// three `compute_properties` takes a schema, and each clones its input's +/// equivalence properties, so a host's schema *is* its child's. There is no +/// guard here for it. A fourth arm that projects would need one, because +/// `rewrite_outer_expr` remaps the outer column indices and rebases lambda +/// parameters against the width of the chain's bottom schema, and a host that +/// changed the width would leave both against the wrong one. +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::() { + // `LocalLimitExec` qualifies structurally — no expressions of its own, + // one child, and `replace_children` keeps its fetch — and the planner + // builds one under a `GlobalLimitExec` when the input has more than one + // partition (`physical_planner.rs`, the `Limit` branch). + // The corpus does enter this function at a `LocalLimitExec`, but only + // with no leaf to move, never with one stranded above it, so it is left + // out. `CooperativeExec` and `BufferExec` meet the same three + // conditions, and so did `CoalesceBatchesExec` before it was deprecated + // in 52.0.0: these arms are an allowlist, not whatever those conditions + // admit. `split_declines_local_limit` pins it. + Some(limit.input()) + } else { + // A scan with more than one file group puts this between the limit and + // the source. Its own `try_swapping_with_projection` takes a projection + // only if it narrows, which a leaf projection need not do; the split is + // still worth it here, because what descends is exactly what the source + // prunes to. + Some(node.downcast_ref::()?.input()) + } +} + +/// The hosts a split descends past, and the node that has to absorb the leaf +/// projection. +struct SplitHostChain<'a> { + /// Outermost first, so the rebuild walks this in reverse. + hosts: Vec<&'a Arc>, + /// The first node that is not a host. + child: &'a Arc, +} + +/// Walks the chain of hosts beneath a projection. +/// +/// `None` when the projection sits on no host at all. A single `OFFSET` on a +/// multi-file table already stacks two of them, a `GlobalLimitExec` over a +/// `CoalescePartitionsExec`, so stopping at the first one would leave the leaf +/// expression stranded exactly where it is today. +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; + } + // A termination guard, not an optimization. With it removed this rule is + // handed the same plan over and over: a projection holding a leaf whose + // child is another projection, so the chain is empty. The `counted_volatile` + // queries in `projection_pushdown.slt` are that shape, a volatile inner + // projection being what stops `remove_unnecessary_projections` from merging + // the pair first; that file then runs until the harness gives up while every + // Rust test stays green. Why the rewrite fails to converge is not pinned + // down further. + (!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. +/// Two nodes strand a `MoveTowardsLeafNodes` expression above the source this +/// way, and neither lets the whole projection past: +/// +/// * `benefits_from_input_partitioning` is true as soon as any expression is +/// `KeepInPlace`, which inserts a `RepartitionExec` below the projection. +/// Splitting leaves the computation above it, still parallelised. +/// * a table source that pushes `OFFSET` down wraps its scan in a +/// `GlobalLimitExec`, which lands between the scan and the projection the +/// logical leaf rules placed on it. Splitting sends only the leaves below +/// the limit, so the rows it skips pay for a field access the source was +/// going to make anyway and not for the outer expressions. 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 +614,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 +634,11 @@ 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` here does + // not always mean the source absorbed it: `FilterExec` and + // `SortPreservingMergeExec` take it by holding it over their own input, so + // the scan narrows on this rule's second scheduled run rather than now. + // `DataSourceExec` and `CoalesceBatchesExec` narrow it immediately. let Some(new_child) = child.try_swapping_with_projection(&lower_projection)? else { return Ok(None); }; @@ -566,18 +659,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(), )?, ))) From 5ae56c058d6c0becbaf9c03c354f3ecbd1ba0f09 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Thu, 12 Nov 2026 23:20:08 +0800 Subject: [PATCH 2/5] test: pin the OFFSET shapes that strand a leaf expression above the limit Every `OFFSET` in the new sections sets a skip that differs from the fetch, never `OFFSET n LIMIT n`: the split rebuilds the limit, and with the two numbers equal every assertion would hold just as well if they were swapped. `file_row_index.slt` gets five value queries for the marker UDFs, all of which error before the fix, an `EXPLAIN` for the rewritten plan, and two controls that never depended on it: `OFFSET 0`, and `OFFSET` with no `LIMIT`, where the skip is not pushed into the scan at all. It also gets a json table: `ListingTable::supports_skip_pushdown` is unconditional and the `GlobalLimitExec` wrap only looks at `skip`, so the defect is not specific to parquet, and every other query in the file is. `file_row_index()` itself is parquet-only, so that section uses `input_file_name()`. `projection_pushdown.slt` gets two value queries and four `EXPLAIN`s covering a bare leaf, a leaf beside a computed sibling, a leaf nested inside `upper(...)`, and the no-leaf case. The value queries pass before the fix on purpose: they pin the rows, which is the one thing a plan assertion cannot show. A dropped or swapped `skip` turns the plan text red as well, so they are not the only cover for it. The no-leaf `EXPLAIN` is labelled a control rather than a guard, because the scan prunes to `[id]` whether or not the rule bails out early; the unit test is what pins the bail-out. A further value query puts the marker inside a lambda body under an `OFFSET`: the lambda queries above it have no limit and the limit queries have no lambda, so nothing covered both, and it is also what pins the parameter rebase. Both files get a section with two file groups, which is the shape that stacks a `CoalescePartitionsExec` under the limit. Those count the surviving rows instead of listing them, because which rows survive the skip depends on the order the partitions are merged in, and `count(r)` rather than `count(*)`, so `optimize_projections` cannot drop the marker and leave nothing to evaluate. Neither new section contains a `RepartitionExec`, so both exercise this path rather than the one #27152 fixed. Ten unit tests hand-build the tree, because plain SQL does not reach these shapes: the split committing with both of the limit's numbers intact, the chain descending past two hosts and past three with a distinct pair of numbers on each, a `CoalescePartitionsExec` host keeping its own `fetch`, a `fetch` of `None`, a projection with no leaf expression left alone, `LocalLimitExec` kept out of the host set, a source that refuses the lower projection, the three nodes that meet the host conditions but are left out of the allowlist appearing instead as the chain bottom, and a `FilterExec` bottom, which takes the lower projection without absorbing it so the scan narrows only on this rule's second scheduled run. Part of #27131 Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 354 ++++++++++++++++++ .../test_files/file_row_index.slt | 185 +++++++++ .../test_files/projection_pushdown.slt | 179 +++++++++ 3 files changed, 718 insertions(+) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index c0936eb929b37..7096a628a9beb 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; @@ -2035,3 +2038,354 @@ async fn split_declines_hash_repartition() -> Result<()> { ); Ok(()) } + +/// Schema and parquet scan the `GlobalLimitExec` tests below share: a plain +/// column beside a struct whose `value` field the leaf expression reads. +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))) +} + +/// `[get_field(s, 'value') as v, id + 1 as w]`: one leaf expression beside one +/// that has to stay in place. +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(), + }, + ]) +} + +fn optimized_plan_text(plan: Arc) -> Result { + let optimized = + ProjectionPushdown::new().optimize(plan, &ConfigOptions::default())?; + Ok(displayable(optimized.as_ref()) + .indent(true) + .to_string() + .trim() + .to_string()) +} + +#[tokio::test] +async fn split_descends_through_global_limit() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + // What a source that pushes `OFFSET` down builds: the skip becomes a + // `GlobalLimitExec` around the scan, below the leaf projection. + // `skip` and `fetch` differ on purpose: the split rebuilds the limit, and + // with them equal this snapshot would hold just as well if it swapped them. + let limit: Arc = Arc::new(GlobalLimitExec::new(scan, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + // The leaf reaches the scan, which now reads the one field instead of the + // whole struct. `id + 1` stays above the limit, so the rows the limit skips + // do not pay for it, and both of the limit's numbers survive the rebuild. + assert_snapshot!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +#[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)?); + + // Nothing to move: with no leaf the lower projection would hold only + // columns. Dropping this bail-out moves no work onto the skipped rows and + // does narrow the scan to `[id]` here, but in SQL the other projection + // rules have already narrowed it, so the split would rebuild the tree for + // nothing. This test is what pins the bail-out: the no-leaf `EXPLAIN` in + // the `.slt` cannot, because the plan is the same either way. + assert_snapshot!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +#[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)?); + + // `LocalLimitExec` is not a host. No shape in the test corpus strands a + // leaf expression above one, because without a skip the source absorbs the + // projection before any limit is inserted -- that is what the corpus + // shows, not a proof that nothing can, which is why this test exists. + assert_snapshot!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +#[tokio::test] +async fn split_descends_through_limit_and_coalesce() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + // A scan with more than one file group: `EnsureRequirements` puts a + // `CoalescePartitionsExec` under the limit, so the leaf has to descend past + // two hosts. Stopping at the first leaves the scan reading the struct. + 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!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +#[tokio::test] +async fn split_descends_through_global_limit_without_fetch() -> Result<()> { + let (schema, scan) = limit_split_scan()?; + // `fetch` is `None` for a skip with no fetch above it. Plain SQL does not + // reach the rule this way, because an `OFFSET` with no `LIMIT` is not + // pushed into the scan, so only a hand-built plan covers it. + 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!( + optimized_plan_text(projection)?, + @r" 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 `CoalescePartitionsExec` host carries a `fetch` of its own, and +/// `replace_children` is what keeps it across the rebuild. The `.slt` plans +/// show a fetch on this node, but `LimitPushdown` runs between this rule's two +/// scheduled passes and puts it there after the split, so they do not cover +/// the rebuild. Dropping the copy leaves every suite green without 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!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +/// Three hosts, each with its own pair of numbers. The corpus reaches a chain +/// this deep -- a `RepartitionExec` over a `GlobalLimitExec` over a +/// `CoalescePartitionsExec` occurs, with a `LocalLimitExec` beneath -- but +/// never with a leaf to move, so no `.slt` plan covers the rebuild at depth +/// three. Six numbers have to come back in the right places, not two. +#[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!( + optimized_plan_text(projection)?, + @r" 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(()) +} + +/// The nodes that meet the host conditions but are deliberately left out of +/// the allowlist, in the other role they can play: the bottom of the chain. +/// Each delegates `try_swapping_with_projection` to its own input, so the split +/// commits and the scan narrows in one pass. Every other test here bottoms out +/// at a `DataSourceExec` or at a source that refuses. `CoalesceBatchesExec` +/// behaves the same way but is deprecated in 52.0.0 and nothing constructs it +/// any more, so it is not pinned here. +#[tokio::test] +async fn split_commits_at_a_pass_through_bottom() -> Result<()> { + for bottom in ["CooperativeExec", "BufferExec: capacity=4"] { + let (schema, scan) = limit_split_scan()?; + let wrapped: Arc = if bottom.starts_with("Cooperative") { + Arc::new(CooperativeExec::new(scan)) + } else { + Arc::new(BufferExec::new(scan, 4)) + }; + let limit: Arc = + Arc::new(GlobalLimitExec::new(wrapped, 1, Some(3))); + let projection: Arc = + Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); + + let text = optimized_plan_text(projection)?; + assert!(text.contains(bottom), "{bottom} missing from:\n{text}"); + assert!( + text.contains( + "projection=[id, get_field(s@1, value) as __datafusion_leaf_0]" + ), + "the scan did not absorb the leaf below {bottom}:\n{text}" + ); + } + Ok(()) +} + +/// A chain bottom that takes the lower projection without absorbing it. +/// `FilterExec` accepts a projection that narrows 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 config = ConfigOptions::default(); + let first = ProjectionPushdown::new().optimize(projection, &config)?; + assert_snapshot!( + displayable(first.as_ref()).indent(true).to_string().trim(), + @r" 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 + " + ); + + let second = ProjectionPushdown::new().optimize(first, &config)?; + assert_snapshot!( + displayable(second.as_ref()).indent(true).to_string().trim(), + @r" 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(()) +} + +#[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, + ), + ])); + // 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. + 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!( + optimized_plan_text(projection)?, + @r" 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/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index 45ccb38a8fbde..ca498dd499b6f 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -314,6 +314,191 @@ 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. The skip makes the source wrap its scan in a `GlobalLimitExec`, and a +# scan with more than one file group gets a `CoalescePartitionsExec` under that, +# so the leaf projection the logical rules placed on the scan ends up stranded +# one or two nodes above it. See `try_split_leaf_projection` in +# `datafusion/physical-optimizer/src/projection_pushdown.rs`. + +# Nothing below needs a repartition, so `batch_size` stays at the default set +# just above. This is a different path from the split further up: raising +# `batch_size`, lowering `target_partitions` or shrinking the table does not +# hide it. + +# Every `OFFSET` below sets a skip that differs from the fetch, and the two +# controls set no fetch at all -- never `OFFSET n LIMIT n`: the split rebuilds +# the limit, and with the two numbers equal every assertion below would hold +# just as well if they were swapped. + +# The marker is BARE here, and alone in its projection. Stranded above the +# limit it reaches execution unrewritten and the query errors out. +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. No skip means no limit for the source to push +# down, so nothing is ever inserted below the projection and 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 skip is not pushed into +# the `TableScan` at all, so the scan absorbs the projection before any limit +# exists and 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 `CoalescePartitionsExec` between the limit +# and the scan, so the leaf has to descend past two nodes rather than one. +# Stopping at the first one leaves this shape broken. + +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 order the partitions are merged +# in, which is not guaranteed, so this counts them instead of listing them. +# `count(r)` rather than `count(*)`: the latter lets `optimize_projections` +# drop `r`, and then the marker is never evaluated and the query cannot fail. +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. `ListingTable::supports_skip_pushdown` is +# unconditional and the `GlobalLimitExec` wrap only looks at `skip` +# (`catalog-listing/src/table.rs`), so any listing format strands the leaf the +# same way. Every other query in this file is parquet. `file_row_index()` +# itself is parquet-only, so this uses the marker that is not: +# `input_file_name()`, which errors here 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..f81cb9b3624fe 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2872,6 +2872,185 @@ SET datafusion.execution.batch_size = 8192; statement ok SET datafusion.execution.target_partitions = 4; +# An `OFFSET` the source pushes down puts a `GlobalLimitExec` between the scan +# and the leaf projection, and a second node under it when the scan has more +# than one file group, which strands `get_field` above them and reads the whole +# struct again. See `try_split_leaf_projection` in +# `datafusion/physical-optimizer/src/projection_pushdown.rs`. + +# Every `OFFSET` below sets a skip that differs from the fetch -- `OFFSET 1 +# LIMIT 3` for the single-file queries, `OFFSET 1 LIMIT 2` for the multi-file +# ones -- never `OFFSET n LIMIT n`: the split rebuilds the limit, and with the +# two numbers equal nothing here would notice them being swapped. + +# Values first: these pin the rows, which no plan assertion shows. They are not +# the only cover for a misplaced `skip`, which reddens the plans below as well, +# and they are no cover at all for a dropped `fetch`, which nothing in this file +# notices. The unit tests carry that one. +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, so the rows the limit skips do not pay for it, 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 in the projection. This is a control, not a guard: the +# scan prunes to `[id]` either way, so the plan is the same whether or not the +# rule bails out early. What pins the bail-out is +# `split_declines_global_limit_without_leaf` in +# `datafusion/core/tests/physical_optimizer/projection_pushdown.rs`. +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 cover the body without a limit, and the queries just above cover the limit +# without a lambda; nothing covered both, and this errors before the fix. It is +# also what pins `rebase_lambda_variable`: the parameter index is rebased +# against the chain's bottom schema, which the split has just widened. +# The lambda section above runs with `batch_size = 2`, which inserts a +# repartition; this one has to stay here, where `batch_size` is high enough that +# the only node between the projection and the scan is the limit. +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: a `CoalescePartitionsExec` sits between the limit +# and the scan, so the leaf has to descend past two nodes. Stopping at the +# first one leaves the scan reading the whole struct. + +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; + statement ok DROP TABLE leaf_split; From 7ff2ba1d092fca4cac64608c0757c9490fcc758c Mon Sep 17 00:00:00 2001 From: Cheng-Yi Shih <48374270+cool9850311@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:09:57 +0800 Subject: [PATCH 3/5] Apply batched suggestions from code review Co-authored-by: Jay Zhan --- .../physical_optimizer/projection_pushdown.rs | 3 +- .../src/projection_pushdown.rs | 14 ++++----- .../test_files/projection_pushdown.slt | 30 +++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 7096a628a9beb..22d24ba4a83ab 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -2115,7 +2115,8 @@ async fn split_descends_through_global_limit() -> Result<()> { // do not pay for it, and both of the limit's numbers survive the rebuild. assert_snapshot!( optimized_plan_text(projection)?, - @r" ProjectionExec: expr=[__datafusion_leaf_0@1 as v, id@0 + 1 as w] + @r" + 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 " diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index afb05197df3cb..340467f852e4b 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -566,14 +566,12 @@ fn split_host_chain(node: &Arc) -> Option> hosts.push(current); current = child; } - // A termination guard, not an optimization. With it removed this rule is - // handed the same plan over and over: a projection holding a leaf whose - // child is another projection, so the chain is empty. The `counted_volatile` - // queries in `projection_pushdown.slt` are that shape, a volatile inner - // projection being what stops `remove_unnecessary_projections` from merging - // the pair first; that file then runs until the harness gives up while every - // Rust test stays green. Why the rewrite fails to converge is not pinned - // down further. + // A termination guard, not an optimization. With no host, `current` is the + // projection's own input. When that is a `ProjectionExec` the two cannot + // collapse into (the `counted_volatile` queries in `projection_pushdown.slt`), + // `ProjectionExec::try_swapping_with_projection` returns the lower + // projection stacked on top of it, so the split commits, and + // `transform_down` then visits that lower projection and splits it again. (!hosts.is_empty()).then_some(SplitHostChain { hosts, child: current, diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index f81cb9b3624fe..d991eb6e0b3d5 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -3051,6 +3051,36 @@ SELECT count(v) FROM ( 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; From 8d77edfe246f3d9daf16a00b49603d951a39ed12 Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Sun, 15 Nov 2026 10:41:20 +0800 Subject: [PATCH 4/5] refactor: show input and output plans in the split tests, cut the comments down Addresses the review on the tests and on the comments. Tests: the ten split tests asserted only the optimized plan, through a local `optimized_plan_text` helper. They now use `OptimizationTest`, which this test directory already has (`pushdown_sort.rs` uses it) and which renders the input plan and the output side by side, so a reader sees what the rule changed without opening the test body. It also compares the plan's schema before and after whenever the rule's `schema_check` is true, which `ProjectionPushdown` sets, so each of the ten now carries a schema assertion as well. Two tests needed restructuring to fit: the pass-through-bottom case was a loop over two node types, which inline snapshots cannot be, and is now two sequential assertions; the filter case takes one snapshot per scheduled run of the rule. The same change removes the inline snapshot formatting that the earlier review round asked about. Comments: the first pass measured the surroundings but did not treat the measurement as a ceiling. The second pass asks of every block whether it can be removed rather than whether it can be shortened, keeping one only if a reader would otherwise misread what the code does, or would make a change that breaks something no test catches. What went from the rule: the narration of `optimize()`'s two passes, which the two lines say already; the `split_host_child` and `split_host_chain` doc comments, since the schema pass-through is enforced by `schema_check` and the multi-host chain is stated by `split_descends_through_limit_and_coalesce`; the allowlist note, which `split_declines_local_limit` now carries alone; the `SplitHostChain` type and `child` field docs; the termination guard's note, which claimed non-termination the suite does not demonstrate; and the paragraph on what strands a leaf expression, which is context for the pull request rather than for the function. What stayed is the five facts not inferable from the code: why only round-robin partitioning qualifies, why `CoalescePartitionsExec` is in the chain, that `hosts` runs outermost first, that a `Some` from `try_swapping_with_projection` does not mean the source absorbed the projection, and why the hosts' properties are recomputed. In the tests and the `.slt` files the helper docs and the sentences restating a neighbouring query went; the ones that keep a test from looking redundant, or that explain a deliberately weak assertion, stayed. The termination guard's comment was also the one the review asked to reword. Measuring it first showed the claim was wrong: removing the guard does not hang the suite, it changes one test's output, so the comment went rather than being reworded. Rule: 78 comment lines down to 12, hunk density 64.5% to 21.8%, whole-file 11.9% to 9.4% against a 10.4% baseline, and the longest block this branch adds down from 15 lines to 4 (the file's own maximum is 7). Tests 17.7% to 6.0%, projection_pushdown.slt 18.1% to 10.4%, file_row_index.slt 22.6% to 14.4%. cargo fmt --check clean, clippy clean on datafusion-physical-optimizer --all-targets and on the core_integration test target, 41 projection pushdown tests and 51 physical-optimizer unit tests passing, both touched .slt files green, and the full sqllogictest suite green before the comment pass. Co-Authored-By: Claude Opus 5 --- .../physical_optimizer/projection_pushdown.rs | 336 +++++++++++------- .../src/projection_pushdown.rs | 78 +--- .../test_files/file_row_index.slt | 51 +-- .../test_files/projection_pushdown.slt | 48 +-- 4 files changed, 243 insertions(+), 270 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index 22d24ba4a83ab..e84ba71de7e7d 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -55,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 @@ -2039,8 +2041,6 @@ async fn split_declines_hash_repartition() -> Result<()> { Ok(()) } -/// Schema and parquet scan the `GlobalLimitExec` tests below share: a plain -/// column beside a struct whose `value` field the leaf expression reads. fn limit_split_scan() -> Result<(SchemaRef, Arc)> { let schema: SchemaRef = Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, true), @@ -2059,8 +2059,6 @@ fn limit_split_scan() -> Result<(SchemaRef, Arc)> { Ok((schema, DataSourceExec::from_data_source(config))) } -/// `[get_field(s, 'value') as v, id + 1 as w]`: one leaf expression beside one -/// that has to stay in place. fn limit_split_exprs(schema: &SchemaRef) -> Result> { let leaf: Arc = Arc::new(ScalarFunctionExpr::new( "get_field", @@ -2089,41 +2087,34 @@ fn limit_split_exprs(schema: &SchemaRef) -> Result> { ]) } -fn optimized_plan_text(plan: Arc) -> Result { - let optimized = - ProjectionPushdown::new().optimize(plan, &ConfigOptions::default())?; - Ok(displayable(optimized.as_ref()) - .indent(true) - .to_string() - .trim() - .to_string()) -} - #[tokio::test] async fn split_descends_through_global_limit() -> Result<()> { let (schema, scan) = limit_split_scan()?; - // What a source that pushes `OFFSET` down builds: the skip becomes a - // `GlobalLimitExec` around the scan, below the leaf projection. - // `skip` and `fetch` differ on purpose: the split rebuilds the limit, and - // with them equal this snapshot would hold just as well if it swapped them. + // `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)?); - // The leaf reaches the scan, which now reads the one field instead of the - // whole struct. `id + 1` stays above the limit, so the rows the limit skips - // do not pay for it, and both of the limit's numbers survive the rebuild. assert_snapshot!( - optimized_plan_text(projection)?, + OptimizationTest::new(projection, ProjectionPushdown::new(), false), @r" - 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 + 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()?; @@ -2132,22 +2123,27 @@ async fn split_declines_global_limit_without_leaf() -> Result<()> { let projection: Arc = Arc::new(ProjectionExec::try_new(exprs, limit)?); - // Nothing to move: with no leaf the lower projection would hold only - // columns. Dropping this bail-out moves no work onto the skipped rows and - // does narrow the scan to `[id]` here, but in SQL the other projection - // rules have already narrowed it, so the split would rebuild the tree for - // nothing. This test is what pins the bail-out: the no-leaf `EXPLAIN` in - // the `.slt` cannot, because the plan is the same either way. assert_snapshot!( - optimized_plan_text(projection)?, - @r" ProjectionExec: expr=[id@0 + 1 as w] - GlobalLimitExec: skip=1, fetch=3 - DataSourceExec: file_groups={1 group: [[x]]}, projection=[id, s], file_type=parquet + 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 kept out of the host set. The corpus never strands a +/// leaf above one, but that is what the corpus shows, not a proof that nothing +/// can, so this pins the exclusion. #[tokio::test] async fn split_declines_local_limit() -> Result<()> { let (schema, scan) = limit_split_scan()?; @@ -2155,26 +2151,29 @@ async fn split_declines_local_limit() -> Result<()> { let projection: Arc = Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - // `LocalLimitExec` is not a host. No shape in the test corpus strands a - // leaf expression above one, because without a skip the source absorbs the - // projection before any limit is inserted -- that is what the corpus - // shows, not a proof that nothing can, which is why this test exists. assert_snapshot!( - optimized_plan_text(projection)?, - @r" 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 + 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()?; - // A scan with more than one file group: `EnsureRequirements` puts a - // `CoalescePartitionsExec` under the limit, so the leaf has to descend past - // two hosts. Stopping at the first leaves the scan reading the struct. let coalesce: Arc = Arc::new(CoalescePartitionsExec::new(scan)); let limit: Arc = Arc::new(GlobalLimitExec::new(coalesce, 1, Some(3))); @@ -2182,41 +2181,55 @@ async fn split_descends_through_limit_and_coalesce() -> Result<()> { Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); assert_snapshot!( - optimized_plan_text(projection)?, - @r" 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 + 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()?; - // `fetch` is `None` for a skip with no fetch above it. Plain SQL does not - // reach the rule this way, because an `OFFSET` with no `LIMIT` is not - // pushed into the scan, so only a hand-built plan covers it. 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!( - optimized_plan_text(projection)?, - @r" 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 + 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 `CoalescePartitionsExec` host carries a `fetch` of its own, and -/// `replace_children` is what keeps it across the rebuild. The `.slt` plans -/// show a fetch on this node, but `LimitPushdown` runs between this rule's two -/// scheduled passes and puts it there after the split, so they do not cover -/// the rebuild. Dropping the copy leaves every suite green without this. +/// 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()?; @@ -2228,21 +2241,27 @@ async fn split_keeps_the_coalesce_fetch() -> Result<()> { Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); assert_snapshot!( - optimized_plan_text(projection)?, - @r" 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 + 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(()) } -/// Three hosts, each with its own pair of numbers. The corpus reaches a chain -/// this deep -- a `RepartitionExec` over a `GlobalLimitExec` over a -/// `CoalescePartitionsExec` occurs, with a `LocalLimitExec` beneath -- but -/// never with a leaf to move, so no `.slt` plan covers the rebuild at depth -/// three. Six numbers have to come back in the right places, not two. +/// Six numbers have to come back in the right places, not two. The corpus +/// reaches a chain this deep but never with a leaf to move. #[tokio::test] async fn split_descends_through_three_hosts() -> Result<()> { let (schema, scan) = limit_split_scan()?; @@ -2255,52 +2274,85 @@ async fn split_descends_through_three_hosts() -> Result<()> { Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, outer)?); assert_snapshot!( - optimized_plan_text(projection)?, - @r" 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 + 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(()) } -/// The nodes that meet the host conditions but are deliberately left out of -/// the allowlist, in the other role they can play: the bottom of the chain. -/// Each delegates `try_swapping_with_projection` to its own input, so the split -/// commits and the scan narrows in one pass. Every other test here bottoms out -/// at a `DataSourceExec` or at a source that refuses. `CoalesceBatchesExec` -/// behaves the same way but is deprecated in 52.0.0 and nothing constructs it -/// any more, so it is not pinned here. +/// `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<()> { - for bottom in ["CooperativeExec", "BufferExec: capacity=4"] { - let (schema, scan) = limit_split_scan()?; - let wrapped: Arc = if bottom.starts_with("Cooperative") { - Arc::new(CooperativeExec::new(scan)) - } else { - Arc::new(BufferExec::new(scan, 4)) - }; - let limit: Arc = - Arc::new(GlobalLimitExec::new(wrapped, 1, Some(3))); - let projection: Arc = - Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - - let text = optimized_plan_text(projection)?; - assert!(text.contains(bottom), "{bottom} missing from:\n{text}"); - assert!( - text.contains( - "projection=[id, get_field(s@1, value) as __datafusion_leaf_0]" - ), - "the scan did not absorb the leaf below {bottom}:\n{text}" - ); - } + 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 chain bottom that takes the lower projection without absorbing it. -/// `FilterExec` accepts a projection that narrows by holding it over its own +/// 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. @@ -2338,30 +2390,50 @@ async fn split_below_a_filter_narrows_on_the_second_run() -> Result<()> { let projection: Arc = Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); - let config = ConfigOptions::default(); - let first = ProjectionPushdown::new().optimize(projection, &config)?; + let first = ProjectionPushdown::new() + .optimize(Arc::clone(&projection), &ConfigOptions::default())?; assert_snapshot!( - displayable(first.as_ref()).indent(true).to_string().trim(), - @r" 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 + 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 " ); - let second = ProjectionPushdown::new().optimize(first, &config)?; assert_snapshot!( - displayable(second.as_ref()).indent(true).to_string().trim(), - @r" 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 + 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![ @@ -2372,8 +2444,6 @@ async fn split_declines_when_the_child_refuses_the_projection() -> Result<()> { true, ), ])); - // 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. 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); @@ -2382,10 +2452,18 @@ async fn split_declines_when_the_child_refuses_the_projection() -> Result<()> { Arc::new(ProjectionExec::try_new(limit_split_exprs(&schema)?, limit)?); assert_snapshot!( - optimized_plan_text(projection)?, - @r" 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] + 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 340467f852e4b..e4e8f178464dc 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -68,17 +68,6 @@ impl PhysicalOptimizerRule for ProjectionPushdown { }) .map(|t| t.data)?; - // Push what can already descend, then split the projections that are - // stuck above a chain of the nodes `split_host_child` accepts. The - // split needs no cleanup pass of its own: the outer projection it - // leaves renames the columns it took from the split, so it is not - // removable, and no host lets that projection swap past it. - // `RepartitionExec` and `CoalescePartitionsExec` decline a projection - // that does not narrow; `GlobalLimitExec` declines every projection, - // through the default at `ExecutionPlan::try_swapping_with_projection`. - // A chain bottom that only holds the lower projection instead of - // absorbing it is tidied by this rule's second scheduled run, not by a - // pass added here. Nothing else moved. let plan = plan.transform_down(remove_unnecessary_projections).data()?; plan.transform_down(|plan| { Ok(match try_split_leaf_projection(&plan)? { @@ -497,21 +486,6 @@ fn leaf_column_name(index: usize) -> String { format!("{LEAF_COLUMN_PREFIX}_{index}") } -/// Returns the child of `node` if a projection may be split beneath it. -/// -/// Every arm evaluates no expression of its own and has exactly one child, so -/// widening that child with the leaf columns cannot change what it does. Each -/// also hands its child's schema straight through, which is what lets the -/// outer expressions keep their column indices when the split descends past -/// several of these in a row. -/// -/// That last property holds by construction rather than by luck: none of the -/// three `compute_properties` takes a schema, and each clones its input's -/// equivalence properties, so a host's schema *is* its child's. There is no -/// guard here for it. A fourth arm that projects would need one, because -/// `rewrite_outer_expr` remaps the outer column indices and rebases lambda -/// parameters against the width of the chain's bottom schema, and a host that -/// changed the width would leave both against the wrong one. 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 @@ -523,42 +497,20 @@ fn split_host_child(node: &Arc) -> Option<&Arc() { - // `LocalLimitExec` qualifies structurally — no expressions of its own, - // one child, and `replace_children` keeps its fetch — and the planner - // builds one under a `GlobalLimitExec` when the input has more than one - // partition (`physical_planner.rs`, the `Limit` branch). - // The corpus does enter this function at a `LocalLimitExec`, but only - // with no leaf to move, never with one stranded above it, so it is left - // out. `CooperativeExec` and `BufferExec` meet the same three - // conditions, and so did `CoalesceBatchesExec` before it was deprecated - // in 52.0.0: these arms are an allowlist, not whatever those conditions - // admit. `split_declines_local_limit` pins it. Some(limit.input()) } else { - // A scan with more than one file group puts this between the limit and - // the source. Its own `try_swapping_with_projection` takes a projection - // only if it narrows, which a leaf projection need not do; the split is - // still worth it here, because what descends is exactly what the source - // prunes to. + // A scan with more than one file group puts this between the limit + // and the source. Some(node.downcast_ref::()?.input()) } } -/// The hosts a split descends past, and the node that has to absorb the leaf -/// projection. struct SplitHostChain<'a> { /// Outermost first, so the rebuild walks this in reverse. hosts: Vec<&'a Arc>, - /// The first node that is not a host. child: &'a Arc, } -/// Walks the chain of hosts beneath a projection. -/// -/// `None` when the projection sits on no host at all. A single `OFFSET` on a -/// multi-file table already stacks two of them, a `GlobalLimitExec` over a -/// `CoalescePartitionsExec`, so stopping at the first one would leave the leaf -/// expression stranded exactly where it is today. fn split_host_chain(node: &Arc) -> Option> { let mut hosts = vec![]; let mut current = node; @@ -566,12 +518,6 @@ fn split_host_chain(node: &Arc) -> Option> hosts.push(current); current = child; } - // A termination guard, not an optimization. With no host, `current` is the - // projection's own input. When that is a `ProjectionExec` the two cannot - // collapse into (the `counted_volatile` queries in `projection_pushdown.slt`), - // `ProjectionExec::try_swapping_with_projection` returns the lower - // projection stacked on top of it, so the split commits, and - // `transform_down` then visits that lower projection and splits it again. (!hosts.is_empty()).then_some(SplitHostChain { hosts, child: current, @@ -580,18 +526,6 @@ fn split_host_chain(node: &Arc) -> Option> /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. -/// -/// Two nodes strand a `MoveTowardsLeafNodes` expression above the source this -/// way, and neither lets the whole projection past: -/// -/// * `benefits_from_input_partitioning` is true as soon as any expression is -/// `KeepInPlace`, which inserts a `RepartitionExec` below the projection. -/// Splitting leaves the computation above it, still parallelised. -/// * a table source that pushes `OFFSET` down wraps its scan in a -/// `GlobalLimitExec`, which lands between the scan and the projection the -/// logical leaf rules placed on it. Splitting sends only the leaves below -/// the limit, so the rows it skips pay for a field access the source was -/// going to make anyway and not for the outer expressions. fn try_split_leaf_projection( plan: &Arc, ) -> Result>> { @@ -632,11 +566,9 @@ fn try_split_leaf_projection( } let lower_projection = ProjectionExec::try_new(lower_exprs, Arc::clone(child))?; - // Commit only if the child takes the lower projection. A `Some` here does - // not always mean the source absorbed it: `FilterExec` and - // `SortPreservingMergeExec` take it by holding it over their own input, so - // the scan narrows on this rule's second scheduled run rather than now. - // `DataSourceExec` and `CoalesceBatchesExec` narrow it immediately. + // 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); }; diff --git a/datafusion/sqllogictest/test_files/file_row_index.slt b/datafusion/sqllogictest/test_files/file_row_index.slt index ca498dd499b6f..834271ce2d40f 100644 --- a/datafusion/sqllogictest/test_files/file_row_index.slt +++ b/datafusion/sqllogictest/test_files/file_row_index.slt @@ -314,25 +314,13 @@ 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. The skip makes the source wrap its scan in a `GlobalLimitExec`, and a -# scan with more than one file group gets a `CoalescePartitionsExec` under that, -# so the leaf projection the logical rules placed on the scan ends up stranded -# one or two nodes above it. See `try_split_leaf_projection` in -# `datafusion/physical-optimizer/src/projection_pushdown.rs`. - -# Nothing below needs a repartition, so `batch_size` stays at the default set -# just above. This is a different path from the split further up: raising -# `batch_size`, lowering `target_partitions` or shrinking the table does not -# hide it. +# 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 -- never `OFFSET n LIMIT n`: the split rebuilds -# the limit, and with the two numbers equal every assertion below would hold -# just as well if they were swapped. +# controls set no fetch at all: swapped numbers would show. -# The marker is BARE here, and alone in its projection. Stranded above the -# limit it reaches execution unrewritten and the query errors out. +# 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 @@ -396,9 +384,8 @@ physical_plan 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. No skip means no limit for the source to push -# down, so nothing is ever inserted below the projection and this shape never -# depended on the split. +# `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 ---- @@ -409,9 +396,8 @@ logical_plan 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 skip is not pushed into -# the `TableScan` at all, so the scan absorbs the projection before any limit -# exists and the split is never consulted. +# `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 ---- @@ -423,9 +409,8 @@ 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 `CoalescePartitionsExec` between the limit -# and the scan, so the leaf has to descend past two nodes rather than one. -# Stopping at the first one leaves this shape broken. +# 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)) @@ -456,10 +441,9 @@ physical_plan 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 order the partitions are merged -# in, which is not guaranteed, so this counts them instead of listing them. -# `count(r)` rather than `count(*)`: the latter lets `optimize_projections` -# drop `r`, and then the marker is never evaluated and the query cannot fail. +# 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 @@ -470,12 +454,9 @@ SELECT count(r) FROM ( statement ok DROP TABLE offset_two_files; -# Not a parquet-only defect. `ListingTable::supports_skip_pushdown` is -# unconditional and the `GlobalLimitExec` wrap only looks at `skip` -# (`catalog-listing/src/table.rs`), so any listing format strands the leaf the -# same way. Every other query in this file is parquet. `file_row_index()` -# itself is parquet-only, so this uses the marker that is not: -# `input_file_name()`, which errors here before the fix. +# 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)) diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index d991eb6e0b3d5..a113d809b8185 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -2872,21 +2872,12 @@ SET datafusion.execution.batch_size = 8192; statement ok SET datafusion.execution.target_partitions = 4; -# An `OFFSET` the source pushes down puts a `GlobalLimitExec` between the scan -# and the leaf projection, and a second node under it when the scan has more -# than one file group, which strands `get_field` above them and reads the whole -# struct again. See `try_split_leaf_projection` in -# `datafusion/physical-optimizer/src/projection_pushdown.rs`. - -# Every `OFFSET` below sets a skip that differs from the fetch -- `OFFSET 1 -# LIMIT 3` for the single-file queries, `OFFSET 1 LIMIT 2` for the multi-file -# ones -- never `OFFSET n LIMIT n`: the split rebuilds the limit, and with the -# two numbers equal nothing here would notice them being swapped. - -# Values first: these pin the rows, which no plan assertion shows. They are not -# the only cover for a misplaced `skip`, which reddens the plans below as well, -# and they are no cover at all for a dropped `fetch`, which nothing in this file -# notices. The unit tests carry that one. +# 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; ---- @@ -2931,9 +2922,8 @@ physical_plan 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, so the rows the limit skips do not pay for it, and the scan still -# reads only the two fields. +# 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; ---- @@ -2947,11 +2937,8 @@ physical_plan 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 in the projection. This is a control, not a guard: the -# scan prunes to `[id]` either way, so the plan is the same whether or not the -# rule bails out early. What pins the bail-out is -# `split_declines_global_limit_without_leaf` in -# `datafusion/core/tests/physical_optimizer/projection_pushdown.rs`. +# 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; ---- @@ -2965,13 +2952,9 @@ physical_plan 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 cover the body without a limit, and the queries just above cover the limit -# without a lambda; nothing covered both, and this errors before the fix. It is -# also what pins `rebase_lambda_variable`: the parameter index is rebased -# against the chain's bottom schema, which the split has just widened. -# The lambda section above runs with `batch_size = 2`, which inserts a -# repartition; this one has to stay here, where `batch_size` is high enough that -# the only node between the projection and the scan is the limit. +# 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; @@ -2989,9 +2972,8 @@ SELECT a, v, l FROM ( statement ok SET datafusion.sql_parser.dialect = generic; -# More than one file group: a `CoalescePartitionsExec` sits between the limit -# and the scan, so the leaf has to descend past two nodes. Stopping at the -# first one leaves the scan reading the whole struct. +# 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 ( From 55e47b3ce819749801298aeee2cb1c8b8a31dc1e Mon Sep 17 00:00:00 2001 From: Harry Shih Date: Mon, 16 Nov 2026 21:02:02 +0800 Subject: [PATCH 5/5] docs: restore the split's reason and define what a split host must satisfy Round 2 of review feedback, all four comment-only: - `split_host_child` had no doc after the previous cut, so nothing said what a node has to satisfy to be listed. A `SortExec` arm would compile and no test would catch it, because the arms are an allowlist and an unlisted node is never reached. The doc also states that satisfying the condition is necessary rather than sufficient: `LocalLimitExec`, `CooperativeExec` and `BufferExec` all satisfy it and are deliberately left out. - `try_split_leaf_projection` lost the reason the split exists at all, which main documented before this PR. Restored in one sentence that covers both the repartition and the limit case. - the two test doc comments said "corpus", which is not defined anywhere, and one of them claimed a chain depth the test corpus was never measured for. Co-Authored-By: Claude Opus 5 --- .../core/tests/physical_optimizer/projection_pushdown.rs | 8 +++----- datafusion/physical-optimizer/src/projection_pushdown.rs | 8 ++++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs index e84ba71de7e7d..bb3a76cd73bd5 100644 --- a/datafusion/core/tests/physical_optimizer/projection_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/projection_pushdown.rs @@ -2141,9 +2141,8 @@ async fn split_declines_global_limit_without_leaf() -> Result<()> { Ok(()) } -/// `LocalLimitExec` is kept out of the host set. The corpus never strands a -/// leaf above one, but that is what the corpus shows, not a proof that nothing -/// can, so this pins the exclusion. +/// `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()?; @@ -2260,8 +2259,7 @@ async fn split_keeps_the_coalesce_fetch() -> Result<()> { Ok(()) } -/// Six numbers have to come back in the right places, not two. The corpus -/// reaches a chain this deep but never with a leaf to move. +/// 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()?; diff --git a/datafusion/physical-optimizer/src/projection_pushdown.rs b/datafusion/physical-optimizer/src/projection_pushdown.rs index e4e8f178464dc..a5e6428e533f8 100644 --- a/datafusion/physical-optimizer/src/projection_pushdown.rs +++ b/datafusion/physical-optimizer/src/projection_pushdown.rs @@ -486,6 +486,11 @@ 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 @@ -526,6 +531,9 @@ fn split_host_chain(node: &Arc) -> Option> /// Splits a `ProjectionExec` that mixes leaf expressions with ones that must /// stay in place, moving the leaves into a projection the source absorbs. +/// 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>> {