From c9d24317c97bd245ef2836b60174ee7a61fd8765 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:38:05 -0600 Subject: [PATCH 1/6] refactor: move the TableScan arm of PushDownFilter into a function A follow-up commit pushes predicates into a scan from a second place. A function lets both places use the same code. The function takes the predicate and the TableScan instead of a Filter, so the type states that the input is a scan. It rebuilds the unchanged filter from the two when it pushes nothing down. Apart from that and indentation, the body is the TableScan arm unchanged. The caller passes predicates_changed || reorder_changed as changed. Co-Authored-By: Claude Opus 5.5 --- datafusion/optimizer/src/push_down_filter.rs | 216 ++++++++++--------- 1 file changed, 118 insertions(+), 98 deletions(-) diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 892941d66d6b8..07512a5b89d34 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -45,7 +45,7 @@ use datafusion_common::{ }; use datafusion_expr::expr::WindowFunction; use datafusion_expr::expr_rewriter::replace_col; -use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan}; +use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan, TableScan}; use datafusion_expr::utils::{ conjunction, expr_to_columns, split_conjunction, split_conjunction_owned, }; @@ -1313,103 +1313,11 @@ impl OptimizerRule for PushDownFilter { result.map_data(|plan| Ok(with_filters(keep_predicates, plan))) } - LogicalPlan::TableScan(scan) => { - let filter_predicates = split_conjunction(&filter.predicate); - // Filters containing scalar subqueries cannot be pushed to - // providers because the subquery result is not available - // until execution time. - let (subquery_filters, pushdown_candidates): (Vec<&Expr>, Vec<&Expr>) = - filter_predicates - .into_iter() - .partition(|pred| pred.contains_scalar_subquery()); - - let (volatile_filters, non_volatile_filters): (Vec<&Expr>, Vec<&Expr>) = - pushdown_candidates - .into_iter() - .partition(|pred| pred.is_volatile()); - - // Check which non-volatile filters are supported by source - let supported_filters = scan - .source - .supports_filters_pushdown(non_volatile_filters.as_slice())?; - assert_eq_or_internal_err!( - non_volatile_filters.len(), - supported_filters.len(), - "Vec returned length: {} from supports_filters_pushdown is not the same size as the filters passed, which length is: {}", - supported_filters.len(), - non_volatile_filters.len() - ); - - if supported_filters - .iter() - .all(|res| res == &TableProviderFilterPushDown::Unsupported) - { - filter.input = Arc::new(LogicalPlan::TableScan(scan)); - return Ok(Transformed::new( - LogicalPlan::Filter(filter), - predicates_changed || reorder_changed, - TreeNodeRecursion::Continue, - )); - } - - // Compose scan filters from non-volatile filters of `Exact` or `Inexact` pushdown type - let zip = non_volatile_filters.iter().zip(supported_filters.iter()); - - let new_scan_filters = zip - .clone() - .filter(|(_, res)| *res != &TableProviderFilterPushDown::Unsupported) - .map(|(&pred, _)| pred); - - // Add new scan filters - let new_scan_filters: Vec = scan - .filters - .iter() - .chain(new_scan_filters) - .unique() - .cloned() - .collect(); - - if supported_filters - .iter() - .all(|res| res == &TableProviderFilterPushDown::Inexact) - && scan.filters == new_scan_filters - { - filter.input = Arc::new(LogicalPlan::TableScan(scan)); - return Ok(Transformed::new( - LogicalPlan::Filter(filter), - predicates_changed || reorder_changed, - TreeNodeRecursion::Continue, - )); - } - let scan = match scan.try_with_filters(new_scan_filters) { - Ok(scan) => scan, - // The fetch and skip guard above returns before this point - // today. This arm keeps the plan correct if that guard moves. - Err(scan) => { - filter.input = Arc::new(LogicalPlan::TableScan(scan)); - return Ok(Transformed::new( - LogicalPlan::Filter(filter), - predicates_changed || reorder_changed, - TreeNodeRecursion::Continue, - )); - } - }; - - // Compose predicates to be of `Unsupported` or `Inexact` pushdown type, - // and also include volatile and subquery-containing filters - let new_predicate: Vec = zip - .filter(|(_, res)| *res != &TableProviderFilterPushDown::Exact) - .map(|(&pred, _)| pred) - .chain(volatile_filters) - .chain(subquery_filters) - .cloned() - .collect(); - - Ok(Transformed::yes(with_filters( - new_predicate, - LogicalPlan::TableScan(scan), - ))) - } + LogicalPlan::TableScan(scan) => push_down_into_table_scan( + filter.predicate, + scan, + predicates_changed || reorder_changed, + ), LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => { // The output is the output of the continuation, so the filter // moves onto the continuation. The body is shared by every scan @@ -1607,6 +1515,118 @@ fn rewrite_projection( Ok((projection, keep_predicates)) } +/// Pushes the conjuncts of `predicate` into `scan`, as far as the source of the +/// scan accepts them, and keeps the rest in a filter above the scan. `changed` +/// tells whether the caller already changed the predicate, so that a result +/// without a pushdown still reports the change. +fn push_down_into_table_scan( + predicate: Expr, + scan: TableScan, + changed: bool, +) -> Result> { + let filter_predicates = split_conjunction(&predicate); + // Filters containing scalar subqueries cannot be pushed to + // providers because the subquery result is not available + // until execution time. + let (subquery_filters, pushdown_candidates): (Vec<&Expr>, Vec<&Expr>) = + filter_predicates + .into_iter() + .partition(|pred| pred.contains_scalar_subquery()); + + let (volatile_filters, non_volatile_filters): (Vec<&Expr>, Vec<&Expr>) = + pushdown_candidates + .into_iter() + .partition(|pred| pred.is_volatile()); + + // Check which non-volatile filters are supported by source + let supported_filters = scan + .source + .supports_filters_pushdown(non_volatile_filters.as_slice())?; + assert_eq_or_internal_err!( + non_volatile_filters.len(), + supported_filters.len(), + "Vec returned length: {} from supports_filters_pushdown is not the same size as the filters passed, which length is: {}", + supported_filters.len(), + non_volatile_filters.len() + ); + + if supported_filters + .iter() + .all(|res| res == &TableProviderFilterPushDown::Unsupported) + { + return Ok(Transformed::new( + LogicalPlan::Filter(Filter::new( + predicate, + Arc::new(LogicalPlan::TableScan(scan)), + )), + changed, + TreeNodeRecursion::Continue, + )); + } + + // Compose scan filters from non-volatile filters of `Exact` or `Inexact` pushdown type + let zip = non_volatile_filters.iter().zip(supported_filters.iter()); + + let new_scan_filters = zip + .clone() + .filter(|(_, res)| *res != &TableProviderFilterPushDown::Unsupported) + .map(|(&pred, _)| pred); + + // Add new scan filters + let new_scan_filters: Vec = scan + .filters + .iter() + .chain(new_scan_filters) + .unique() + .cloned() + .collect(); + + if supported_filters + .iter() + .all(|res| res == &TableProviderFilterPushDown::Inexact) + && scan.filters == new_scan_filters + { + return Ok(Transformed::new( + LogicalPlan::Filter(Filter::new( + predicate, + Arc::new(LogicalPlan::TableScan(scan)), + )), + changed, + TreeNodeRecursion::Continue, + )); + } + let scan = match scan.try_with_filters(new_scan_filters) { + Ok(scan) => scan, + // The fetch and skip guard above returns before this point + // today. This arm keeps the plan correct if that guard moves. + Err(scan) => { + return Ok(Transformed::new( + LogicalPlan::Filter(Filter::new( + predicate, + Arc::new(LogicalPlan::TableScan(scan)), + )), + changed, + TreeNodeRecursion::Continue, + )); + } + }; + + // Compose predicates to be of `Unsupported` or `Inexact` pushdown type, + // and also include volatile and subquery-containing filters + let new_predicate: Vec = zip + .filter(|(_, res)| *res != &TableProviderFilterPushDown::Exact) + .map(|(&pred, _)| pred) + .chain(volatile_filters) + .chain(subquery_filters) + .cloned() + .collect(); + + Ok(Transformed::yes(with_filters( + new_predicate, + LogicalPlan::TableScan(scan), + ))) +} + /// Creates a new LogicalPlan::Filter node. /// /// Deprecated: use [`Filter::try_new`] directly. From f65a32f6f4ac87c8273674a29e626930a314496a Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:38:08 -0600 Subject: [PATCH 2/6] fix: report no change for a scan filter that is already pushed down A filter over a scan with Inexact and Unsupported predicates reported a change on every rewrite. The rule rebuilt the same plan, so the optimizer never saw a fixed point for that plan. The rewrite now reports no change when no predicate is Exact and the scan already records every accepted predicate. The new test source answers Exact, Inexact or Unsupported per predicate. Co-Authored-By: Claude Opus 5.5 --- datafusion/optimizer/src/push_down_filter.rs | 79 +++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 07512a5b89d34..0334c6b378566 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1581,9 +1581,11 @@ fn push_down_into_table_scan( .cloned() .collect(); + // Nothing changes when no predicate leaves the filter and the scan already + // records every accepted predicate. if supported_filters .iter() - .all(|res| res == &TableProviderFilterPushDown::Inexact) + .all(|res| res != &TableProviderFilterPushDown::Exact) && scan.filters == new_scan_filters { return Ok(Transformed::new( @@ -3561,6 +3563,81 @@ mod tests { ) } + /// Answers per predicate by the literal it compares with: `1` is exact, + /// `2` is inexact, and any other value is unsupported. + #[derive(Debug)] + struct PerPredicatePushDownProvider; + + impl TableSource for PerPredicatePushDownProvider { + fn schema(&self) -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + ])) + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> Result> { + Ok(filters + .iter() + .map(|f| match f { + Expr::BinaryExpr(BinaryExpr { right, .. }) + if **right == lit(1i64) => + { + TableProviderFilterPushDown::Exact + } + Expr::BinaryExpr(BinaryExpr { right, .. }) + if **right == lit(2i64) => + { + TableProviderFilterPushDown::Inexact + } + _ => TableProviderFilterPushDown::Unsupported, + }) + .collect()) + } + } + + /// A second rewrite of a filter over a scan that records an inexact + /// predicate and rejects another one changes nothing. + #[test] + fn direct_scan_pushdown_with_inexact_and_unsupported_is_a_fixed_point() -> Result<()> + { + let plan = || -> Result { + let source = PerPredicatePushDownProvider; + LogicalPlanBuilder::from(LogicalPlan::TableScan(TableScan { + table_name: "test".into(), + filters: vec![], + projected_schema: Arc::new(DFSchema::try_from(source.schema())?), + projection: None, + source: Arc::new(source), + fetch: None, + skip: None, + statistics_requests: Box::default(), + })) + .filter(col("a").gt(lit(2i64)).and(col("b").is_not_null()))? + .build() + }; + assert_optimized_plan_equal!(plan()?, @" + Filter: a > Int64(2) AND b IS NOT NULL + TableScan: test, partial_filters=[a > Int64(2)] + ")?; + + let rule = PushDownFilter::new(); + let config = OptimizerContext::new(); + let once = rule.rewrite(plan()?, &config)?; + assert!(once.transformed); + let twice = rule.rewrite(once.data.clone(), &config)?; + assert!(!twice.transformed); + assert_eq!(twice.data, once.data); + Ok(()) + } + #[test] fn filter_with_table_provider_inexact() -> Result<()> { let plan = From d9cab9bfebead743afb81707f6424dd6163bd9e8 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:38:12 -0600 Subject: [PATCH 3/6] fix: push filters above a pure extraction projection into the scan below it Since https://github.com/apache/datafusion/pull/25455, PushDownFilter does not move a filter below a pure extraction projection. The predicate reached the scan only if the filter was there before the extraction projection existed. A filter that reaches the projection later, for example on an optimized plan that is optimized again, never reached the scan. Partition pruning was then lost. The filter stays above the projection. PushDownFilter offers the scan below each predicate that reads only pass-through columns, through push_down_into_table_scan. The scan records the predicates its source accepts, and an Exact predicate leaves the filter. TableScan::try_with_filters keeps a predicate out of a scan with a fetch or a skip. Co-Authored-By: Claude Opus 5.5 --- .../optimizer/src/extract_leaf_expressions.rs | 10 +- datafusion/optimizer/src/push_down_filter.rs | 275 ++++++++++++++++-- .../library-user-guide/query-optimizer.md | 2 +- 3 files changed, 258 insertions(+), 29 deletions(-) diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs index 3ed0880feb432..ec3948584d043 100644 --- a/datafusion/optimizer/src/extract_leaf_expressions.rs +++ b/datafusion/optimizer/src/extract_leaf_expressions.rs @@ -34,11 +34,11 @@ //! A Parquet scan merges it into the file projection and reads only the struct //! leaf. With the opposite precedence the scan reads the whole struct whenever //! `datafusion.execution.parquet.pushdown_filters` is `false`, which is the -//! default. The filter loses nothing by staying one node higher, because -//! `PushDownFilter` records the predicate in -//! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan) in the pass -//! that runs before the extraction projection exists, so row group pruning and -//! source level filtering still happen. +//! default. The filter loses nothing by staying one node higher, because its +//! predicates still reach +//! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan), so row +//! group pruning and source level filtering still happen. See the module +//! documentation of [`PushDownFilter`] for how. //! //! # Yields to [`OptimizeProjections`] //! diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 0334c6b378566..b98353ac7e50c 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -19,10 +19,18 @@ //! //! The reason is that the extraction projection is the node a source absorbs. //! A Parquet scan merges it into the file projection and reads only the struct -//! leaf, which is what the rule exists for. Keeping the filter one node higher -//! costs nothing at the scan, because `PushDownFilter` records the predicate in +//! leaf, which is what the rule exists for. +//! +//! The filter node stays above the projection, but its predicates still reach +//! the source. Usually `PushDownFilter` records them in //! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan) in the pass -//! that runs before the extraction projection exists. +//! that runs before the extraction projection exists. A filter can also reach +//! the projection later, for example when a rewrite puts a filter on an +//! optimized plan and optimizes it again. For that case, when the projection is +//! directly above a scan, `PushDownFilter` offers the scan each predicate that +//! reads only pass-through columns. The scan records the predicates that its +//! source accepts, and a predicate that the source applies exactly leaves the +//! filter. //! //! [`PushDownLeafProjections`]: crate::extract_leaf_expressions::PushDownLeafProjections @@ -1453,17 +1461,19 @@ fn rewrite_projection( // the pass limit stops them, and the surviving plan is decided by rule // order alone. `PushDownFilter` yields here, because the extraction // projection is the node the source absorbs: leaving it at the bottom keeps - // Parquet struct field pruning, and a filter kept one node higher still - // reaches the scan through `TableScan::filters`, which the pass that - // created the extraction projection has already set. + // Parquet struct field pruning. // // See the module documentation of `extract_leaf_expressions` for the // full statement of the invariant. + // + // The filter node stays above, but a predicate that reads only + // pass-through columns is still offered to a scan directly below. The + // filter can reach this position after the pass that created the + // extraction projection, for example when a rewrite puts a filter on an + // optimized subtree and optimizes the result again. Without this step the + // source would never see the predicate. if is_pure_extraction_projection(&projection.expr) { - return Ok(( - Transformed::no(LogicalPlan::Projection(projection)), - predicates, - )); + return push_down_through_extraction_projection_into_scan(predicates, projection); } // Partition projection expressions into non-pushable vs pushable. @@ -1599,8 +1609,10 @@ fn push_down_into_table_scan( } let scan = match scan.try_with_filters(new_scan_filters) { Ok(scan) => scan, - // The fetch and skip guard above returns before this point - // today. This arm keeps the plan correct if that guard moves. + // The scan has a fetch or a skip, which apply after its filters. The + // direct path stops at the general guard in `PushDownFilter::rewrite` + // before this point, but the pure extraction projection path reaches + // the scan without that guard. Err(scan) => { return Ok(Transformed::new( LogicalPlan::Filter(Filter::new( @@ -1629,6 +1641,82 @@ fn push_down_into_table_scan( ))) } +/// Offers the predicates that read only pass-through columns of a pure +/// extraction projection to the scan directly below it. +/// +/// The projection and the filter keep their order, so `PushDownLeafProjections` +/// has nothing to undo. The scan records each predicate its source accepts. A +/// predicate the source applies exactly is removed from the returned +/// predicates, which the caller keeps above the projection. A second call adds +/// no scan filter that is already present, so the plan is a fixed point. +fn push_down_through_extraction_projection_into_scan( + predicates: Vec, + mut projection: Projection, +) -> Result<(Transformed, Vec)> { + let LogicalPlan::TableScan(scan) = projection.input.as_ref() else { + return Ok(( + Transformed::no(LogicalPlan::Projection(projection)), + predicates, + )); + }; + + // A pass-through column has the same name above and below the projection, + // so a predicate that reads only such columns needs no rewrite. + let pass_through: HashSet<&Column> = projection + .expr + .iter() + .filter_map(Expr::try_as_col) + .collect(); + let reads_only_pass_through = |predicate: &Expr| { + predicate + .column_refs() + .iter() + .all(|column| pass_through.contains(column)) + }; + + let Some(scan_predicate) = conjunction( + predicates + .iter() + .filter(|predicate| reads_only_pass_through(predicate)) + .cloned(), + ) else { + return Ok(( + Transformed::no(LogicalPlan::Projection(projection)), + predicates, + )); + }; + let pushed = push_down_into_table_scan(scan_predicate, scan.clone(), false)?; + if !pushed.transformed { + return Ok(( + Transformed::no(LogicalPlan::Projection(projection)), + predicates, + )); + } + + // The predicates the scan does not apply exactly come back in a filter + // above it. They stay above the projection. + let (scan, residual) = match pushed.data { + LogicalPlan::Filter(residual) => ( + Arc::unwrap_or_clone(residual.input), + split_conjunction_owned(residual.predicate), + ), + scan => (scan, vec![]), + }; + // Keep the predicates in their original order, which `reorder_predicates` + // chose by cost. + let keep_predicates = predicates + .into_iter() + .filter(|predicate| { + !reads_only_pass_through(predicate) || residual.contains(predicate) + }) + .collect(); + projection.input = Arc::new(scan); + Ok(( + Transformed::yes(LogicalPlan::Projection(projection)), + keep_predicates, + )) +} + /// Creates a new LogicalPlan::Filter node. /// /// Deprecated: use [`Filter::try_new`] directly. @@ -4932,15 +5020,17 @@ mod tests { ) } - /// A filter is not moved below a pure extraction projection, even when its - /// predicate only references pass-through columns. + /// A predicate above a pure extraction projection that reads only + /// pass-through columns reaches the scan, and the projection stays next to + /// the scan. /// - /// `PushDownLeafProjections` moves such a projection back below the filter, - /// so pushing here would make the two rules undo each other on every - /// optimizer pass. See - /// and the module documentation. + /// The filter node itself does not move below the projection, because + /// `PushDownLeafProjections` would move the projection back below it on + /// every optimizer pass. See + /// and the module + /// documentation. #[test] - fn filter_not_pushed_through_pure_extraction_projection() -> Result<()> { + fn filter_above_pure_extraction_projection_reaches_the_scan() -> Result<()> { let table_scan = test_table_scan()?; // The shape `ExtractLeafExpressions` produces: one extraction alias @@ -4953,8 +5043,9 @@ mod tests { ])? .build()?; - // `b` is a plain pass-through column, so without the precedence rule - // this predicate would reach the scan as a `full_filters` entry. + // The filter does not move below the projection, but `b` is a + // pass-through column, so the predicate reaches the scan. The source + // applies it exactly, so no filter node is left. let plan = LogicalPlanBuilder::from(proj) .filter(col("b").gt(lit(5i64)))? .build()?; @@ -4962,13 +5053,151 @@ mod tests { assert_optimized_plan_equal!( plan, @r" - Filter: test.b > Int64(5) - Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b, test.c + Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b, test.c + TableScan: test, full_filters=[test.b > Int64(5)] + " + ) + } + + /// A filter above a pure extraction projection over a source that applies + /// predicates inexactly. + fn filter_above_extraction_projection_over_inexact_source() -> Result { + let proj = table_scan_with_pushdown_provider_builder( + TableProviderFilterPushDown::Inexact, + vec![], + None, + )? + .project(vec![ + leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"), + col("b"), + ])? + .build()?; + LogicalPlanBuilder::from(proj) + .filter( + col("b") + .gt(lit(5i64)) + .and(col("__datafusion_extracted_1").eq(lit(1i64))), + )? + .build() + } + + #[test] + fn inexact_predicate_above_pure_extraction_projection_reaches_the_scan() -> Result<()> + { + // The scan records the pass-through predicate. Both predicates stay in + // the filter above the projection: one because the source applies it + // inexactly, the other because it reads an extracted alias. They keep + // their order. + assert_optimized_plan_equal!( + filter_above_extraction_projection_over_inexact_source()?, + @r" + Filter: b > Int64(5) AND __datafusion_extracted_1 = Int64(1) + Projection: leaf_udf(a) AS __datafusion_extracted_1, b + TableScan: test, partial_filters=[b > Int64(5)] + " + ) + } + + #[test] + fn pushdown_into_scan_below_extraction_projection_is_a_fixed_point() -> Result<()> { + let rule = PushDownFilter::new(); + let config = OptimizerContext::new(); + let once = rule.rewrite( + filter_above_extraction_projection_over_inexact_source()?, + &config, + )?; + assert!(once.transformed); + let twice = rule.rewrite(once.data.clone(), &config)?; + assert!(!twice.transformed); + assert_eq!(twice.data, once.data); + Ok(()) + } + + #[test] + fn unsupported_predicate_stays_above_pure_extraction_projection() -> Result<()> { + let proj = table_scan_with_pushdown_provider_builder( + TableProviderFilterPushDown::Unsupported, + vec![], + None, + )? + .project(vec![ + leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"), + col("b"), + ])? + .build()?; + let plan = LogicalPlanBuilder::from(proj) + .filter(col("b").gt(lit(5i64)))? + .build()?; + + assert_optimized_plan_equal!( + plan, + @r" + Filter: b > Int64(5) + Projection: leaf_udf(a) AS __datafusion_extracted_1, b TableScan: test " ) } + /// The fetch of a scan applies after its filters, so a predicate above a + /// pure extraction projection must not reach a scan with a fetch. + #[test] + fn predicate_above_pure_extraction_projection_skips_scan_with_fetch() -> Result<()> { + let LogicalPlan::TableScan(scan) = test_table_scan()? else { + unreachable!() + }; + let scan_with_fetch = LogicalPlan::TableScan(TableScan { + fetch: Some(10), + ..scan + }); + let proj = LogicalPlanBuilder::from(scan_with_fetch) + .project(vec![ + leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"), + col("b"), + ])? + .build()?; + let plan = LogicalPlanBuilder::from(proj) + .filter(col("b").gt(lit(5i64)))? + .build()?; + + assert_optimized_plan_equal!( + plan, + @r" + Filter: test.b > Int64(5) + Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b + TableScan: test, fetch=10 + " + ) + } + + /// The skip of a scan applies after its filters, so a predicate above a + /// pure extraction projection must not reach a scan with a skip. + #[test] + fn predicate_above_pure_extraction_projection_skips_scan_with_skip() -> Result<()> { + let LogicalPlan::TableScan(scan) = test_table_scan()? else { + unreachable!() + }; + let scan_with_skip = LogicalPlan::TableScan(TableScan { + skip: Some(1), + ..scan + }); + let proj = LogicalPlanBuilder::from(scan_with_skip) + .project(vec![ + leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"), + col("b"), + ])? + .build()?; + let plan = LogicalPlanBuilder::from(proj) + .filter(col("b").gt(lit(5i64)))? + .build()?; + + assert_optimized_plan_equal!(plan, @" + Filter: test.b > Int64(5) + Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b + TableScan: test, skip=1 + ") + } + /// Runs the default optimizer and returns, for each pass, the names of the /// rules that changed the plan in that pass. fn rules_that_changed_plan_per_pass(plan: LogicalPlan) -> Result>> { diff --git a/docs/source/library-user-guide/query-optimizer.md b/docs/source/library-user-guide/query-optimizer.md index b939333c5f222..1a0fa9ef64b9d 100644 --- a/docs/source/library-user-guide/query-optimizer.md +++ b/docs/source/library-user-guide/query-optimizer.md @@ -164,7 +164,7 @@ Do not let two rules compete. Give one rule precedence, make the competing rule There are two such decisions today: -- `PushDownFilter` yields to a _pure extraction projection_. A pure extraction projection is a projection whose expressions are only `__datafusion_extracted_N` aliases and pass-through columns. `ExtractLeafExpressions` creates it, and `PushDownLeafProjections` moves it towards the leaves. `PushDownFilter` does not move a filter below such a projection, so the projection stays next to the scan. A Parquet scan then merges the projection into the file projection and reads only the struct leaf. The filter loses nothing, because `PushDownFilter` records the predicate in `TableScan::filters` in the pass that runs before the extraction projection exists. See [issue #14540](https://github.com/apache/datafusion/issues/14540). +- `PushDownFilter` yields to a _pure extraction projection_. A pure extraction projection is a projection whose expressions are only `__datafusion_extracted_N` aliases and pass-through columns. `ExtractLeafExpressions` creates it, and `PushDownLeafProjections` moves it towards the leaves. `PushDownFilter` does not move a filter below such a projection, so the projection stays next to the scan. A Parquet scan then merges the projection into the file projection and reads only the struct leaf. The filter loses nothing, because its predicates still reach `TableScan::filters`. Usually `PushDownFilter` records them in the pass that runs before the extraction projection exists. A filter that reaches the projection later, for example when a rewrite puts a filter on an optimized plan and optimizes it again, does not move, but `PushDownFilter` offers its pass-through predicates to the scan directly below the projection. See [issue #14540](https://github.com/apache/datafusion/issues/14540). - `PushDownLeafProjections` yields to `OptimizeProjections`. When the extraction projection cannot move below the input of a projection, for example a `TableScan` or an `Aggregate`, `PushDownLeafProjections` leaves the projection unchanged. A split in place would give a recovery projection over an extraction projection on the same input, which `OptimizeProjections` merges back. The source absorbs the leaf expressions of the original projection just as well. See [PR #26085](https://github.com/apache/datafusion/pull/26085). ### Expression Naming From 87b11f61b9c4fdeb638c02b0db4fc7d9558d4836 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:38:16 -0600 Subject: [PATCH 4/6] test: cover mixed pushdown support above a pure extraction projection A source can answer Exact, Inexact and Unsupported for different predicates of one filter. The test checks that only the exact predicate leaves the filter, that the scan records the accepted predicates, that the residual predicates keep their order, and that a second rewrite changes nothing. Co-Authored-By: Claude Opus 5.5 --- datafusion/optimizer/src/push_down_filter.rs | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index b98353ac7e50c..25661bf112538 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -5098,6 +5098,63 @@ mod tests { ) } + fn filter_above_extraction_projection_over_mixed_source() -> Result { + let source = PerPredicatePushDownProvider; + let scan = LogicalPlan::TableScan(TableScan { + table_name: "test".into(), + filters: vec![], + projected_schema: Arc::new(DFSchema::try_from(source.schema())?), + projection: None, + source: Arc::new(source), + fetch: None, + skip: None, + statistics_requests: Box::default(), + }); + let proj = LogicalPlanBuilder::from(scan) + .project(vec![ + leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"), + col("a"), + col("b"), + ])? + .build()?; + LogicalPlanBuilder::from(proj) + .filter( + col("b") + .is_not_null() + .and(col("__datafusion_extracted_1").eq(lit(1i64))) + .and(col("a").gt(lit(2i64))) + .and(col("b").eq(lit(1i64))), + )? + .build() + } + + #[test] + fn mixed_acceptance_above_pure_extraction_projection() -> Result<()> { + // `b = 1` is exact and leaves the filter. `a > 2` is inexact, so the + // scan records it and the filter keeps it. `b IS NOT NULL` is + // unsupported and stays in the filter only. The predicate on the + // extracted alias is never offered to the scan. The residual + // predicates keep their order. + let plan = filter_above_extraction_projection_over_mixed_source()?; + assert_optimized_plan_equal!(plan, @" + Filter: b IS NOT NULL AND __datafusion_extracted_1 = Int64(1) AND a > Int64(2) + Projection: leaf_udf(a) AS __datafusion_extracted_1, a, b + TableScan: test, full_filters=[b = Int64(1)], partial_filters=[a > Int64(2)] + ")?; + + let rule = PushDownFilter::new(); + let config = OptimizerContext::new(); + let once = rule.rewrite( + filter_above_extraction_projection_over_mixed_source()?, + &config, + )?; + assert!(once.transformed); + let twice = rule.rewrite(once.data.clone(), &config)?; + assert!(!twice.transformed); + assert_eq!(twice.data, once.data); + Ok(()) + } + #[test] fn pushdown_into_scan_below_extraction_projection_is_a_fixed_point() -> Result<()> { let rule = PushDownFilter::new(); From c95b3cdc017a60f673e105cfa4295abf746bc6ec Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:38:16 -0600 Subject: [PATCH 5/6] test: prune partitions for a filter put on an optimized plan The optimizer unit tests use a stub source. This end-to-end test uses a partitioned Parquet table, a real get_field extraction projection and a dictionary partition literal. It checks the optimized plan, that the scan reads only the matching partition file, and the returned rows. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/tests/sql/path_partition.rs | 72 +++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/datafusion/core/tests/sql/path_partition.rs b/datafusion/core/tests/sql/path_partition.rs index bee1b14e8ab04..03ed7fda5e4ac 100644 --- a/datafusion/core/tests/sql/path_partition.rs +++ b/datafusion/core/tests/sql/path_partition.rs @@ -816,3 +816,75 @@ impl ObjectStore for MirroringObjectStore { unimplemented!() } } + +/// A filter on a partition column that is put on an optimized plan must still +/// prune partitions after a second optimization, even when the optimized plan +/// has a pure extraction projection directly above the scan. +#[tokio::test] +async fn partition_filter_on_optimized_plan_prunes_files() -> Result<()> { + use datafusion::dataframe::DataFrame; + use datafusion::physical_plan::{collect, displayable}; + use datafusion_common::assert_batches_eq; + use datafusion_expr::{LogicalPlanBuilder, col, lit}; + + let tmp_dir = tempfile::TempDir::new()?; + let location = format!("{}/", tmp_dir.path().display()); + let ctx = SessionContext::new(); + ctx.sql(&format!( + "COPY (SELECT * FROM (VALUES \ + ('2025-01-01', named_struct('a', 1, 'b', 'x')), \ + ('2025-01-02', named_struct('a', 2, 'b', 'y')), \ + ('2025-01-03', named_struct('a', 3, 'b', 'z'))) AS t(day, s)) \ + TO '{location}' STORED AS PARQUET PARTITIONED BY (day)" + )) + .await? + .collect() + .await?; + ctx.sql(&format!( + "CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION '{location}' \ + PARTITIONED BY (day)" + )) + .await?; + + // The filter on a struct field keeps a pure extraction projection in the + // optimized plan. + let optimized = ctx + .sql("SELECT s['a'] AS a, day FROM t WHERE s['b'] <> 'q'") + .await? + .into_optimized_plan()?; + let filtered = LogicalPlanBuilder::from(optimized) + .filter(col("day").eq(lit("2025-01-03")))? + .build()?; + let df = DataFrame::new(ctx.state(), filtered); + + let logical = df.clone().into_optimized_plan()?; + assert_snapshot!(logical.display_indent(), @r#" + Projection: __datafusion_extracted_2 AS a, t.day + Filter: __datafusion_extracted_1 != Utf8("q") + Projection: get_field(t.s, Utf8("b")) AS __datafusion_extracted_1, t.day, get_field(t.s, Utf8("a")) AS __datafusion_extracted_2 + TableScan: t projection=[s, day], full_filters=[t.day = Dictionary(UInt16, Utf8("2025-01-03"))], partial_filters=[get_field(t.s, Utf8("b")) != Utf8("q")] + "#); + + let physical = df.create_physical_plan().await?; + let physical_text = displayable(physical.as_ref()).indent(false).to_string(); + assert!( + physical_text.contains("file_groups={1 group: [[") + && physical_text.contains("day=2025-01-03") + && !physical_text.contains("day=2025-01-01") + && !physical_text.contains("day=2025-01-02"), + "the scan must read only the matching partition:\n{physical_text}" + ); + + let batches = collect(physical, ctx.task_ctx()).await?; + assert_batches_eq!( + [ + "+---+------------+", + "| a | day |", + "+---+------------+", + "| 3 | 2025-01-03 |", + "+---+------------+", + ], + &batches + ); + Ok(()) +} From 28df619f59c69a0b27c30a4dececb8963c510a81 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:07:29 -0600 Subject: [PATCH 6/6] refactor: negotiate scan pushdown by position after the bounds check A provider that returns an error from supports_filters_pushdown could stop optimization of a scan with a fetch or skip, which never accepts a filter. The helper now rejects such scans and empty candidate lists before asking the provider. It borrows the scan, takes indexed predicates, and returns the positions of the exact predicates, so both callers keep the residual predicates in their original order without building a temporary Filter. Co-Authored-By: Claude Opus 5.5 --- datafusion/optimizer/src/push_down_filter.rs | 217 ++++++++----------- 1 file changed, 85 insertions(+), 132 deletions(-) diff --git a/datafusion/optimizer/src/push_down_filter.rs b/datafusion/optimizer/src/push_down_filter.rs index 25661bf112538..de1ebbfeb086e 100644 --- a/datafusion/optimizer/src/push_down_filter.rs +++ b/datafusion/optimizer/src/push_down_filter.rs @@ -1321,11 +1321,20 @@ impl OptimizerRule for PushDownFilter { result.map_data(|plan| Ok(with_filters(keep_predicates, plan))) } - LogicalPlan::TableScan(scan) => push_down_into_table_scan( - filter.predicate, - scan, - predicates_changed || reorder_changed, - ), + LogicalPlan::TableScan(scan) => { + let predicates = split_conjunction_owned(filter.predicate); + match push_down_into_table_scan(&scan, predicates.iter().enumerate())? { + Some((scan, exact)) => Ok(Transformed::yes(with_filters( + without_exact(predicates, &exact), + LogicalPlan::TableScan(scan), + ))), + None => Ok(Transformed::new( + with_filters(predicates, LogicalPlan::TableScan(scan)), + predicates_changed || reorder_changed, + TreeNodeRecursion::Continue, + )), + } + } LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => { // The output is the output of the continuation, so the filter // moves onto the continuation. The body is shared by every scan @@ -1525,120 +1534,83 @@ fn rewrite_projection( Ok((projection, keep_predicates)) } -/// Pushes the conjuncts of `predicate` into `scan`, as far as the source of the -/// scan accepts them, and keeps the rest in a filter above the scan. `changed` -/// tells whether the caller already changed the predicate, so that a result -/// without a pushdown still reports the change. -fn push_down_into_table_scan( - predicate: Expr, - scan: TableScan, - changed: bool, -) -> Result> { - let filter_predicates = split_conjunction(&predicate); - // Filters containing scalar subqueries cannot be pushed to - // providers because the subquery result is not available - // until execution time. - let (subquery_filters, pushdown_candidates): (Vec<&Expr>, Vec<&Expr>) = - filter_predicates - .into_iter() - .partition(|pred| pred.contains_scalar_subquery()); - - let (volatile_filters, non_volatile_filters): (Vec<&Expr>, Vec<&Expr>) = - pushdown_candidates - .into_iter() - .partition(|pred| pred.is_volatile()); - - // Check which non-volatile filters are supported by source - let supported_filters = scan - .source - .supports_filters_pushdown(non_volatile_filters.as_slice())?; +/// Offers the indexed `candidates` to the source of `scan`. +/// +/// Returns the scan with every accepted predicate recorded, and the positions +/// of the predicates the source applies exactly. Returns `None` when nothing +/// changes: the scan has a fetch or a positive skip (both apply after the scan +/// filters), no candidate is eligible, or no predicate is applied exactly and +/// the scan already records every accepted predicate. The source is not asked +/// in the first two cases. +fn push_down_into_table_scan<'a>( + scan: &TableScan, + candidates: impl IntoIterator, +) -> Result)>> { + if scan.fetch.is_some() || scan.skip.is_some_and(|n| n > 0) { + return Ok(None); + } + + // The result of a scalar subquery is not available until execution, and a + // volatile predicate must run once per row of the filter. + let (positions, predicates): (Vec, Vec<&Expr>) = candidates + .into_iter() + .filter(|(_, p)| !p.contains_scalar_subquery() && !p.is_volatile()) + .unzip(); + if predicates.is_empty() { + return Ok(None); + } + + let supported = scan.source.supports_filters_pushdown(&predicates)?; assert_eq_or_internal_err!( - non_volatile_filters.len(), - supported_filters.len(), + predicates.len(), + supported.len(), "Vec returned length: {} from supports_filters_pushdown is not the same size as the filters passed, which length is: {}", - supported_filters.len(), - non_volatile_filters.len() + supported.len(), + predicates.len() ); - if supported_filters - .iter() - .all(|res| res == &TableProviderFilterPushDown::Unsupported) + let mut exact = HashSet::new(); + let mut accepted = vec![]; + for ((position, predicate), support) in + positions.into_iter().zip(predicates).zip(supported) { - return Ok(Transformed::new( - LogicalPlan::Filter(Filter::new( - predicate, - Arc::new(LogicalPlan::TableScan(scan)), - )), - changed, - TreeNodeRecursion::Continue, - )); + match support { + TableProviderFilterPushDown::Exact => { + exact.insert(position); + accepted.push(predicate); + } + TableProviderFilterPushDown::Inexact => accepted.push(predicate), + TableProviderFilterPushDown::Unsupported => {} + } } - // Compose scan filters from non-volatile filters of `Exact` or `Inexact` pushdown type - let zip = non_volatile_filters.iter().zip(supported_filters.iter()); - - let new_scan_filters = zip - .clone() - .filter(|(_, res)| *res != &TableProviderFilterPushDown::Unsupported) - .map(|(&pred, _)| pred); - - // Add new scan filters let new_scan_filters: Vec = scan .filters .iter() - .chain(new_scan_filters) + .chain(accepted) .unique() .cloned() .collect(); - - // Nothing changes when no predicate leaves the filter and the scan already - // records every accepted predicate. - if supported_filters - .iter() - .all(|res| res != &TableProviderFilterPushDown::Exact) - && scan.filters == new_scan_filters - { - return Ok(Transformed::new( - LogicalPlan::Filter(Filter::new( - predicate, - Arc::new(LogicalPlan::TableScan(scan)), - )), - changed, - TreeNodeRecursion::Continue, - )); + if exact.is_empty() && scan.filters == new_scan_filters { + return Ok(None); } - let scan = match scan.try_with_filters(new_scan_filters) { - Ok(scan) => scan, - // The scan has a fetch or a skip, which apply after its filters. The - // direct path stops at the general guard in `PushDownFilter::rewrite` - // before this point, but the pure extraction projection path reaches - // the scan without that guard. - Err(scan) => { - return Ok(Transformed::new( - LogicalPlan::Filter(Filter::new( - predicate, - Arc::new(LogicalPlan::TableScan(scan)), - )), - changed, - TreeNodeRecursion::Continue, - )); - } - }; - // Compose predicates to be of `Unsupported` or `Inexact` pushdown type, - // and also include volatile and subquery-containing filters - let new_predicate: Vec = zip - .filter(|(_, res)| *res != &TableProviderFilterPushDown::Exact) - .map(|(&pred, _)| pred) - .chain(volatile_filters) - .chain(subquery_filters) - .cloned() - .collect(); + // The bounds check above makes this succeed. It stays as a backstop. + Ok(scan + .clone() + .try_with_filters(new_scan_filters) + .ok() + .map(|scan| (scan, exact))) +} - Ok(Transformed::yes(with_filters( - new_predicate, - LogicalPlan::TableScan(scan), - ))) +/// Returns the predicates whose position is not in `exact`, in their order. +fn without_exact(predicates: Vec, exact: &HashSet) -> Vec { + predicates + .into_iter() + .enumerate() + .filter(|(i, _)| !exact.contains(i)) + .map(|(_, p)| p) + .collect() } /// Offers the predicates that read only pass-through columns of a pure @@ -1674,43 +1646,24 @@ fn push_down_through_extraction_projection_into_scan( .all(|column| pass_through.contains(column)) }; - let Some(scan_predicate) = conjunction( + let Some((scan, exact)) = push_down_into_table_scan( + scan, predicates .iter() - .filter(|predicate| reads_only_pass_through(predicate)) - .cloned(), - ) else { + .enumerate() + .filter(|(_, predicate)| reads_only_pass_through(predicate)), + )? + else { return Ok(( Transformed::no(LogicalPlan::Projection(projection)), predicates, )); }; - let pushed = push_down_into_table_scan(scan_predicate, scan.clone(), false)?; - if !pushed.transformed { - return Ok(( - Transformed::no(LogicalPlan::Projection(projection)), - predicates, - )); - } - // The predicates the scan does not apply exactly come back in a filter - // above it. They stay above the projection. - let (scan, residual) = match pushed.data { - LogicalPlan::Filter(residual) => ( - Arc::unwrap_or_clone(residual.input), - split_conjunction_owned(residual.predicate), - ), - scan => (scan, vec![]), - }; - // Keep the predicates in their original order, which `reorder_predicates` - // chose by cost. - let keep_predicates = predicates - .into_iter() - .filter(|predicate| { - !reads_only_pass_through(predicate) || residual.contains(predicate) - }) - .collect(); - projection.input = Arc::new(scan); + // The predicates the scan does not apply exactly stay above the + // projection, in the order that `reorder_predicates` chose by cost. + let keep_predicates = without_exact(predicates, &exact); + projection.input = Arc::new(LogicalPlan::TableScan(scan)); Ok(( Transformed::yes(LogicalPlan::Projection(projection)), keep_predicates,