Apache DataFusion SQL Query Engine
Fix leaf expression reconciliation (#22971)
Peter Ld5f03d9f9396
diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rsindex 185f9d045f..c90f1567fa 100644--- a/datafusion/optimizer/src/extract_leaf_expressions.rs+++ b/datafusion/optimizer/src/extract_leaf_expressions.rs@@ -21,7 +21,7 @@//! [`ExtractLeafExpressions`] (pass 1) and [`PushDownLeafProjections`] (pass 2).use indexmap::{IndexMap, IndexSet};-use std::collections::HashMap;+use std::collections::{BTreeSet, HashMap};use std::sync::Arc;use datafusion_common::alias::AliasGenerator;@@ -827,12 +827,8 @@ fn split_and_push_projection(let original_schema = proj.schema.as_ref();let mut recovery_exprs: Vec<Expr> = Vec::with_capacity(proj.expr.len());- let mut needs_recovery = false;let mut has_new_extractions = false;let mut proj_exprs_captured: usize = 0;- // Track standalone column expressions (Case B) to detect column refs- // from extracted aliases (Case A) that aren't also standalone expressions.- let mut standalone_columns: IndexSet<Column> = IndexSet::new();for (expr, (qualifier, field)) in proj.expr.iter().zip(original_schema.iter()) {if let Expr::Alias(alias) = expr@@ -854,7 +850,6 @@ fn split_and_push_projection(} else if let Expr::Column(col) = expr {// Plain column pass-through — track it in the extractorextractors[0].columns_needed.insert(col.clone());- standalone_columns.insert(col.clone());recovery_exprs.push(expr.clone());proj_exprs_captured += 1;} else {@@ -875,7 +870,6 @@ fn split_and_push_projection(original_name != &expr_name};let recovery_expr = if needs_alias {- needs_recovery = true;transformed_expr.clone().alias_qualified(qualifier.cloned(), original_name)@@ -883,14 +877,6 @@ fn split_and_push_projection(transformed_expr.clone()};- // If the expression was transformed (i.e., has extracted sub-parts),- // it differs from what the pushed projection outputs → needs recovery.- // Also, any non-column, non-__datafusion_extracted expression needs recovery- // because the pushed extraction projection won't output it directly.- if transformed.transformed || !matches!(expr, Expr::Column(_)) {- needs_recovery = true;- }-recovery_exprs.push(recovery_expr);}}@@ -913,17 +899,6 @@ fn split_and_push_projection(return Ok(None);}- // If columns_needed has entries that aren't standalone projection columns- // (i.e., they came from column refs inside extracted aliases), a merge- // into an inner projection will widen the schema with those extra columns,- // requiring a recovery projection to restore the original schema.- if columns_needed- .iter()- .any(|c| !standalone_columns.contains(c))- {- needs_recovery = true;- }-// ── Phase 2: Push down ──────────────────────────────────────────────let proj_input = Arc::clone(&proj.input);let pushed = push_extraction_pairs(@@ -959,6 +934,37 @@ fn split_and_push_projection(}};+ // The recovery projection restores the original projection's output. We need+ // it whenever `base_plan` no longer exposes the same set of output column+ // names, which happens two ways:+ // * a column is *renamed* — a transformed expression now surfaces as its+ // internal `__datafusion_extracted_*` alias instead of the original name;+ // * a column is *leaked* — pushing the projection down widens `base_plan`+ // with an inner extraction projection's *other* extracted aliases bubbling+ // up through a Filter. A schema-caching parent like SubqueryAlias then+ // keeps a stale schema (see `map_children` in `logical_plan/tree_node.rs`)+ // and the later `optimize_projections` pass fails to resolve columns.+ //+ // Both are captured by comparing the *set of unqualified field names*. We+ // compare by unqualified name rather than the full qualified schema on+ // purpose: extracted aliases are globally unique, so name-only comparison is+ // unambiguous for them, while it ignores the benign column reordering and the+ // `SubqueryAlias` re-qualification (`sub.__datafusion_extracted_1` vs+ // `__datafusion_extracted_1`) that a qualified/ordered comparison would+ // spuriously treat as drift, stacking redundant recovery projections.+ let base_names: BTreeSet<&str> = base_plan+ .schema()+ .fields()+ .iter()+ .map(|f| f.name().as_str())+ .collect();+ let original_names: BTreeSet<&str> = original_schema+ .fields()+ .iter()+ .map(|f| f.name().as_str())+ .collect();+ let needs_recovery = base_names != original_names;+// Wrap with recovery projection if the output schema changedif needs_recovery {let recovery = LogicalPlan::Projection(Projection::try_new(@@ -1618,9 +1624,10 @@ mod tests {## After PushdownProjection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))- Filter: __datafusion_extracted_1 = Utf8("active")- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2- TableScan: test projection=[user]+ Projection: test.user, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 = Utf8("active")+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2+ TableScan: test projection=[user]## OptimizedProjection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))@@ -1681,13 +1688,17 @@ mod tests {TableScan: test projection=[user]## After Pushdown+ Projection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))+ Projection: test.user, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 > Int32(150)+ Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2+ TableScan: test projection=[user]++ ## OptimizedProjection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))Filter: __datafusion_extracted_1 > Int32(150)Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2TableScan: test projection=[user]-- ## Optimized- (same as after pushdown)"#)}@@ -1892,19 +1903,15 @@ mod tests {TableScan: test projection=[id, user]## After Pushdown- Projection: test.id, test.user- Filter: __datafusion_extracted_1 IS NOT NULL- Filter: __datafusion_extracted_2 = Utf8("active")- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1- TableScan: test projection=[id, user]-- ## OptimizedProjection: test.id, test.userFilter: __datafusion_extracted_1 IS NOT NULLProjection: test.id, test.user, __datafusion_extracted_1Filter: __datafusion_extracted_2 = Utf8("active")Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1TableScan: test projection=[id, user]++ ## Optimized+ (same as after pushdown)"#)}@@ -2013,9 +2020,10 @@ mod tests {## After PushdownProjection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]- Filter: __datafusion_extracted_2 = Utf8("active")- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1- TableScan: test projection=[user]+ Projection: test.user, __datafusion_extracted_1+ Filter: __datafusion_extracted_2 = Utf8("active")+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1+ TableScan: test projection=[user]## OptimizedProjection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))@@ -2092,19 +2100,15 @@ mod tests {TableScan: test projection=[a, b, c]## After Pushdown- Projection: test.a, test.b, test.c- Filter: __datafusion_extracted_1 = Int32(2)- Filter: __datafusion_extracted_2 = Int32(1)- Projection: leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_2, test.a, test.b, test.c, leaf_udf(test.b, Utf8("y")) AS __datafusion_extracted_1- TableScan: test projection=[a, b, c]-- ## OptimizedProjection: test.a, test.b, test.cFilter: __datafusion_extracted_1 = Int32(2)Projection: test.a, test.b, test.c, __datafusion_extracted_1Filter: __datafusion_extracted_2 = Int32(1)Projection: leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_2, test.a, test.b, test.c, leaf_udf(test.b, Utf8("y")) AS __datafusion_extracted_1TableScan: test projection=[a, b, c]++ ## Optimized+ (same as after pushdown)"#)}@@ -2314,21 +2318,15 @@ mod tests {## After PushdownProjection: test.id, test.user, right.id, right.userFilter: __datafusion_extracted_1 = Utf8("active")- Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3- Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1- TableScan: test projection=[id, user]- Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.user- TableScan: right projection=[id, user]-- ## Optimized- Projection: test.id, test.user, right.id, right.user- Filter: __datafusion_extracted_1 = Utf8("active")- Projection: test.id, test.user, __datafusion_extracted_1, right.id, right.user+ Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_1Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1TableScan: test projection=[id, user]Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.userTableScan: right projection=[id, user]++ ## Optimized+ (same as after pushdown)"#)}@@ -2681,10 +2679,11 @@ mod tests {## After PushdownProjection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))- Filter: __datafusion_extracted_1 = Utf8("active")- SubqueryAlias: sub- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.user- TableScan: test projection=[user]+ Projection: sub.user, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 = Utf8("active")+ SubqueryAlias: sub+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.user+ TableScan: test projection=[user]## OptimizedProjection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))@@ -2856,9 +2855,10 @@ mod tests {## After PushdownProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))- Filter: __datafusion_extracted_1 = Utf8("active")- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2- TableScan: test projection=[id, user]+ Projection: test.id, test.user, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 = Utf8("active")+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2+ TableScan: test projection=[id, user]## OptimizedProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))@@ -2893,9 +2893,10 @@ mod tests {## After PushdownProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))- Filter: __datafusion_extracted_1 > Int32(5)- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2- TableScan: test projection=[id, user]+ Projection: test.id, test.user, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 > Int32(5)+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2+ TableScan: test projection=[id, user]## OptimizedProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))@@ -2947,11 +2948,12 @@ mod tests {## After PushdownProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))- Left Join: Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)- Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id, test.user- TableScan: test projection=[id, user]- Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_3- TableScan: right projection=[id, user]+ Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_2, __datafusion_extracted_3+ Left Join: Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)+ Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id, test.user+ TableScan: test projection=[id, user]+ Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_3+ TableScan: right projection=[id, user]## OptimizedProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))@@ -2992,9 +2994,10 @@ mod tests {## After PushdownProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))- Filter: __datafusion_extracted_1 > Int32(5)- Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_3- TableScan: test projection=[id, user]+ Projection: test.id, test.user, __datafusion_extracted_2, __datafusion_extracted_3+ Filter: __datafusion_extracted_1 > Int32(5)+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_3+ TableScan: test projection=[id, user]## OptimizedProjection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))@@ -3086,4 +3089,80 @@ mod tests {Ok(())}++ /// Regression test: a leaf expression used in **both** the filter and the+ /// projection, with the **bare base column** also projected, over a+ /// `SubqueryAlias` whose projection emits an **extra column the outer query+ /// never consumes** (`synth`).+ ///+ /// This reproduces a production failure where the leaf-pushdown passes drop+ /// the bare passthrough column from an intermediate schema, causing the+ /// subsequent `optimize_projections` run to fail with:+ /// `Schema error: No field named __datafusion_extracted_N`.+ ///+ /// Equivalent SQL:+ /// ```sql+ /// CREATE VIEW v AS SELECT user, id, id + 1 AS synth FROM test;+ /// SELECT user['status'], user, id FROM v WHERE user['status'] IS NOT NULL;+ /// ```+ #[test]+ fn test_subquery_alias_with_unconsumed_column() -> Result<()> {+ let table_scan = test_table_scan_with_struct()?;++ // This is the plan shape *after* `push_down_filter` has run: it pushes+ // the `leaf_udf(...)` filter down through the `SubqueryAlias` and below+ // the view's inner projection. The filter and the outer projection now+ // each contain the same leaf expression but are separated by the+ // `SubqueryAlias`, so they extract into two *independent* aliases+ // (`__datafusion_extracted_1` from the filter, `__datafusion_extracted_2`+ // from the projection) instead of deduplicating into one.+ //+ // The view projects an extra `synth` column the outer query never+ // consumes — without it the bug does not manifest.+ let inner = LogicalPlanBuilder::from(table_scan)+ .filter(leaf_udf(col("user"), "status").is_not_null())?+ .project(vec![+ col("user"),+ col("id"),+ (col("id") + lit(1u32)).alias("synth"),+ ])?+ .alias("v")?+ .build()?;++ // Outer projection: leaf expr + the bare base column + id.+ let plan = LogicalPlanBuilder::from(inner)+ .project(vec![+ leaf_udf(col("v.user"), "status"),+ col("v.user"),+ col("v.id"),+ ])?+ .build()?;++ // Run the leaf-pushdown passes followed by `optimize_projections`,+ // exactly as the default optimizer schedules them. `optimize_projections`+ // is what prunes the unused `synth` column and validates the plan; if the+ // leaf passes drop the bare `v.user` passthrough column it fails with+ // `Schema error: No field named __datafusion_extracted_N`.+ let ctx = OptimizerContext::new();+ let optimizer = Optimizer::with_rules(vec![+ Arc::new(ExtractLeafExpressions::new()),+ Arc::new(PushDownLeafProjections::new()),+ Arc::new(OptimizeProjections::new()),+ ]);+ let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;++ // The bare `test.user` passthrough column is preserved and the view's+ // output schema (`user`, `id`, `__datafusion_extracted_2`) is restored+ // by a recovery projection, so `optimize_projections` succeeds.+ insta::assert_snapshot!(format!("{optimized}"), @r#"+ Projection: __datafusion_extracted_2 AS leaf_udf(v.user,Utf8("status")), v.user, v.id+ SubqueryAlias: v+ Projection: test.user, test.id, __datafusion_extracted_2+ Filter: __datafusion_extracted_1 IS NOT NULL+ Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2+ TableScan: test projection=[id, user]+ "#);++ Ok(())+ }}diff --git a/datafusion/sqllogictest/test_files/struct.slt b/datafusion/sqllogictest/test_files/struct.sltindex 982e2c6f4a..a0e47a8691 100644--- a/datafusion/sqllogictest/test_files/struct.slt+++ b/datafusion/sqllogictest/test_files/struct.slt@@ -1714,3 +1714,22 @@ RESET datafusion.sql_parser.dialect;statement okdrop table t_agg_window;++# extract_leaf_expressions regression+statement ok+create table leaf_base as select named_struct('status', 'active') as s, 1 as id;++statement ok+create view leaf_view as select s, id, id + 1 as synth from leaf_base;++query T?I+select s['status'], s, id from leaf_view where s['status'] is not null;+----+active {status: active} 1++statement ok+drop view leaf_view;++statement ok+drop table leaf_base;+