kosiew commented on code in PR #26281:
URL: https://github.com/apache/datafusion/pull/26281#discussion_r4706646255


##########
datafusion/optimizer/src/push_down_filter.rs:
##########
@@ -1314,101 +1322,18 @@ 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<Expr> = 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),
+                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)),

Review Comment:
   Please negotiate using borrowed conjuncts and split the owned predicate only 
on `Some`. Rebuilding on `None` can change conjunction association without 
reporting a transformation; add a right-associated regression asserting plan 
equality and `!transformed`.



##########
datafusion/optimizer/src/push_down_filter.rs:
##########
@@ -1607,6 +1534,142 @@ fn rewrite_projection(
     Ok((projection, keep_predicates))
 }
 
+/// 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<Item = (usize, &'a Expr)>,
+) -> Result<Option<(TableScan, HashSet<usize>)>> {
+    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<usize>, 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!(
+        predicates.len(),
+        supported.len(),
+        "Vec returned length: {} from supports_filters_pushdown is not the 
same size as the filters passed, which length is: {}",
+        supported.len(),
+        predicates.len()
+    );
+
+    let mut exact = HashSet::new();
+    let mut accepted = vec![];
+    for ((position, predicate), support) in
+        positions.into_iter().zip(predicates).zip(supported)
+    {
+        match support {
+            TableProviderFilterPushDown::Exact => {
+                exact.insert(position);
+                accepted.push(predicate);
+            }
+            TableProviderFilterPushDown::Inexact => accepted.push(predicate),
+            TableProviderFilterPushDown::Unsupported => {}
+        }
+    }
+
+    let new_scan_filters: Vec<Expr> = scan

Review Comment:
   Suggest returning `Ok(None)` when `accepted.is_empty()`. This avoids 
unnecessary hashing and cloning, and prevents deduplicating existing scan 
filters when the provider accepts nothing.



##########
datafusion/optimizer/src/push_down_filter.rs:
##########
@@ -4856,22 +4996,218 @@ 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()?;
 
         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<LogicalPlan> {
+        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)]
+        "
+        )
+    }
+
+    fn filter_above_extraction_projection_over_mixed_source() -> 
Result<LogicalPlan> {
+        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();
+        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<()> {

Review Comment:
   Consider using a source that advertises skip pushdown support so the 
regression also covers the supported planning path, rather than only a manually 
constructed bounded scan.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to