diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs index 3ed0880feb432..b6613366a230e 100644 --- a/datafusion/optimizer/src/extract_leaf_expressions.rs +++ b/datafusion/optimizer/src/extract_leaf_expressions.rs @@ -61,6 +61,7 @@ use std::sync::Arc; use datafusion_common::alias::AliasGenerator; use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_common::{Column, DFSchema, Result, qualified_name}; +use datafusion_expr::expr::Alias; use datafusion_expr::logical_plan::LogicalPlan; use datafusion_expr::{Expr, ExpressionPlacement, Projection}; @@ -71,12 +72,45 @@ use crate::{OptimizerConfig, OptimizerRule}; /// Prefix for aliases generated by the extraction optimizer passes. /// -/// This prefix is **reserved for internal optimizer use**. User-defined aliases -/// starting with this prefix may be misidentified as optimizer-generated -/// extraction aliases, leading to unexpected behavior. Do not use this prefix -/// in user queries. +/// Aliases starting with this prefix are classified as extraction aliases when +/// their inner expression is eligible for leaf pushdown +/// ([`ExpressionPlacement::should_push_to_leaves`]). Canonical positive decimal +/// suffixes (`1..usize::MAX`, without leading zeros) are parsed solely to seed +/// [`AliasGenerator`]; user aliases with this prefix that wrap pushable +/// expressions may still be treated as extraction aliases. const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted"; +/// Recognizes canonical positive decimal IDs (`1..usize::MAX` without leading +/// zeros) for seeding [`AliasGenerator`] in [`advance_generator_past_existing`]. +/// +/// Extraction alias classification uses [`is_extracted_alias`] instead so +/// generated `usize::MAX` (and wrapped `0`) aliases are accepted while +/// non-pushable user aliases with canonical names are rejected. +fn extracted_expr_id(name: &str) -> Option { + let suffix = name + .strip_prefix(EXTRACTED_EXPR_PREFIX)? + .strip_prefix('_')?; + // Integer parsing alone also accepts leading zeros and a leading '+'. + if suffix.starts_with('0') || !suffix.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let id = suffix.parse::().ok()?; + // update_min_id adds one, so the maximum value has no usable successor. + (id < usize::MAX).then_some(id) +} + +/// Returns `true` if `alias` carries the extraction prefix and wraps an +/// expression eligible for leaf pushdown (`MoveTowardsLeafNodes` or `Column`). +/// +/// Checking expression placement prevents user-defined aliases with canonical +/// names (such as `10 / id AS __datafusion_extracted_1`) from being hoisted +/// below filters, while accepting optimizer-generated aliases regardless of +/// counter wraparound at `usize::MAX`. +fn is_extracted_alias(alias: &Alias) -> bool { + alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && alias.expr.placement().should_push_to_leaves() +} + /// Returns `true` if any sub-expression in `exprs` has /// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement. /// @@ -210,44 +244,76 @@ impl OptimizerRule for ExtractLeafExpressions { } let alias_generator = config.alias_generator(); - // Advance the alias generator past any user-provided __datafusion_extracted_N - // aliases to prevent collisions when generating new extraction aliases. - advance_generator_past_existing(&plan, alias_generator)?; + // Collect all existing `__datafusion_extracted*` names and advance the + // generator past canonical IDs to avoid collisions when allocating new + // extraction aliases. + let mut reserved_names = advance_generator_past_existing(&plan, alias_generator)?; plan.transform_down_with_subqueries(|plan| { - extract_from_plan(plan, alias_generator) + extract_from_plan(plan, alias_generator, &mut reserved_names) }) } } -/// Scans the plan for pre-existing `__datafusion_extracted_N` aliases and -/// advances the generator counter past them to avoid collisions with -/// user-provided aliases. -/// -/// Subquery plans nested inside expressions are scanned as well: extraction -/// rewrites with `transform_down_with_subqueries`, so it can generate aliases -/// *inside* a subquery and would otherwise collide with a user alias there. -fn advance_generator_past_existing( +/// Collects all `__datafusion_extracted*` field and alias names present in +/// `plan` and any nested subqueries. +fn collect_extracted_names( plan: &LogicalPlan, - alias_generator: &AliasGenerator, -) -> Result<()> { - plan.apply_with_subqueries(|plan| { - plan.apply_expressions(|expr| { +) -> Result> { + let mut names = std::collections::HashSet::new(); + plan.apply_with_subqueries(|node| { + for field in node.schema().fields() { + if field.name().starts_with(EXTRACTED_EXPR_PREFIX) { + names.insert(field.name().clone()); + } + } + node.apply_expressions(|expr| { expr.apply(|e| { if let Expr::Alias(alias) = e - && let Some(id) = alias - .name - .strip_prefix(EXTRACTED_EXPR_PREFIX) - .and_then(|s| s.strip_prefix('_')) - .and_then(|s| s.parse().ok()) + && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) { - alias_generator.update_min_id(id); + names.insert(alias.name.clone()); } Ok(TreeNodeRecursion::Continue) }) }) - }) - .map(|_| ()) + })?; + Ok(names) +} + +/// Scans the plan for pre-existing `__datafusion_extracted*` names, advances +/// the generator counter past canonical IDs, and returns the full reserved set. +/// +/// Subquery plans nested inside expressions are scanned as well: extraction +/// rewrites with `transform_down_with_subqueries`, so it can generate aliases +/// *inside* a subquery and would otherwise collide with a user alias there. +fn advance_generator_past_existing( + plan: &LogicalPlan, + alias_generator: &AliasGenerator, +) -> Result> { + let reserved_names = collect_extracted_names(plan)?; + for name in &reserved_names { + if let Some(id) = extracted_expr_id(name) { + alias_generator.update_min_id(id); + } + } + Ok(reserved_names) +} + +/// Allocates the next extraction alias not present in `reserved_names` and +/// records it in `reserved_names`. Returns `None` if no free name is found +/// within a bounded probe so callers can skip extraction instead of colliding. +fn next_available_alias( + alias_generator: &AliasGenerator, + reserved_names: &mut std::collections::HashSet, +) -> Option { + for _ in 0..=reserved_names.len() { + let candidate = alias_generator.next(EXTRACTED_EXPR_PREFIX); + if reserved_names.insert(candidate.clone()) { + return Some(candidate); + } + } + None } /// Extracts `MoveTowardsLeafNodes` sub-expressions from a plan node. @@ -259,6 +325,7 @@ fn advance_generator_past_existing( fn extract_from_plan( plan: LogicalPlan, alias_generator: &Arc, + reserved_names: &mut std::collections::HashSet, ) -> Result> { // Only extract from plan types whose output schema is predictable after // expression rewriting. Nodes like Window derive column names from @@ -320,7 +387,7 @@ fn extract_from_plan( // Transform expressions via map_expressions with routing let transformed = plan.map_expressions(|expr| { - routing_extract(expr, &mut extractors, &input_column_sets) + routing_extract(expr, &mut extractors, &input_column_sets, reserved_names) })?; // If no expressions were rewritten, nothing was extracted @@ -391,11 +458,12 @@ fn routing_extract( expr: Expr, extractors: &mut [LeafExpressionExtractor], input_column_sets: &[std::collections::HashSet], + reserved_names: &mut std::collections::HashSet, ) -> Result> { expr.transform_down(|e| { - // Skip expressions already aliased with extracted expression pattern + // Skip expressions already aliased as extraction expressions. if let Expr::Alias(alias) = &e - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) { return Ok(Transformed { data: e, @@ -412,11 +480,13 @@ fn routing_extract( match e.placement() { ExpressionPlacement::MoveTowardsLeafNodes => { - if let Some(idx) = find_owning_input(&e, input_column_sets) { - let col_ref = extractors[idx].add_extracted(e)?; + if let Some(idx) = find_owning_input(&e, input_column_sets) + && let Some(col_ref) = + extractors[idx].add_extracted(e.clone(), reserved_names) + { Ok(Transformed::yes(col_ref)) } else { - // References columns from multiple inputs — cannot extract + // References columns from multiple inputs or no alias available Ok(Transformed::no(e)) } } @@ -625,23 +695,30 @@ impl<'a> LeafExpressionExtractor<'a> { } } - /// Adds an expression to extracted set, returns column reference. - fn add_extracted(&mut self, expr: Expr) -> Result { + /// Adds an expression to extracted set, returning a column reference or + /// `None` if no non-colliding alias is available. + fn add_extracted( + &mut self, + expr: Expr, + reserved_names: &mut std::collections::HashSet, + ) -> Option { // Deduplication: reuse existing alias if same expression if let Some(alias) = self.extracted.get(&expr) { - return Ok(Expr::Column(Column::new_unqualified(alias))); + return Some(Expr::Column(Column::new_unqualified(alias))); } + // Generate a unique alias before mutating `columns_needed` so skipped + // extractions leave extractor state unchanged. + let alias = next_available_alias(self.alias_generator, reserved_names)?; + // Track columns referenced by this expression for col in expr.column_refs() { self.columns_needed.insert(col.clone()); } - // Generate unique alias - let alias = self.alias_generator.next(EXTRACTED_EXPR_PREFIX); self.extracted.insert(expr, alias.clone()); - Ok(Expr::Column(Column::new_unqualified(&alias))) + Some(Expr::Column(Column::new_unqualified(&alias))) } /// Builds an extraction projection above the given input, or merges into @@ -712,7 +789,7 @@ fn build_extraction_projection_impl( .iter() .filter_map(|e| { if let Expr::Alias(alias) = e - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) { return Some((*alias.expr.clone(), alias.name.clone())); } @@ -871,8 +948,12 @@ impl OptimizerRule for PushDownLeafProjections { if !config.options().optimizer.enable_leaf_expression_pushdown { return Ok(Transformed::no(plan)); } + if !matches!(&plan, LogicalPlan::Projection(_)) { + return Ok(Transformed::no(plan)); + } let alias_generator = config.alias_generator(); - match try_push_input(&plan, alias_generator)? { + let mut reserved_names = advance_generator_past_existing(&plan, alias_generator)?; + match try_push_input(&plan, alias_generator, &mut reserved_names)? { Some(new_plan) => Ok(Transformed::yes(new_plan)), None => Ok(Transformed::no(plan)), } @@ -886,11 +967,12 @@ impl OptimizerRule for PushDownLeafProjections { fn try_push_input( input: &LogicalPlan, alias_generator: &Arc, + reserved_names: &mut std::collections::HashSet, ) -> Result> { let LogicalPlan::Projection(proj) = input else { return Ok(None); }; - split_and_push_projection(proj, alias_generator) + split_and_push_projection(proj, alias_generator, reserved_names) } /// If this is a passthrough column. I.e, @@ -1002,18 +1084,30 @@ fn merge_would_duplicate_kept_expr( fn split_and_push_projection( proj: &Projection, alias_generator: &Arc, + reserved_names: &mut std::collections::HashSet, ) -> Result> { // Fast pre-check: skip if there are no pre-existing extracted aliases // and no new extractable expressions. - let has_existing_extracted = proj.expr.iter().any(|e| { - matches!(e, Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX)) - }); + let has_existing_extracted = proj + .expr + .iter() + .any(|e| matches!(e, Expr::Alias(alias) if is_extracted_alias(alias))); if !has_existing_extracted && !has_extractable_expr(&proj.expr) { return Ok(None); } let input = &proj.input; let input_schema = input.schema(); + // Collect `__datafusion_extracted*` names present anywhere in `proj.input`'s + // subtree. Carrying an alias down under a name that already exists below + // `proj` (e.g. a user column in a table, join side, or UNION branch) can + // collide; re-extracting it under a fresh plan-wide reserved name avoids + // collisions in one place without blocking ordinary pushdowns. + let subtree_extracted_names = if has_existing_extracted { + collect_extracted_names(input.as_ref())? + } else { + std::collections::HashSet::new() + }; // ── Phase 1: Split ────────────────────────────────────────────────── // For each projection expression, collect extraction pairs and build @@ -1049,7 +1143,8 @@ fn split_and_push_projection( recovery_exprs.push(expr.clone()); proj_exprs_captured += 1; } else if let Expr::Alias(alias) = expr - && alias.name.starts_with(EXTRACTED_EXPR_PREFIX) + && is_extracted_alias(alias) + && !subtree_extracted_names.contains(&alias.name) { // Insert the full Alias expression as the key so that // distinct alias names don't collide in the IndexMap. @@ -1065,9 +1160,20 @@ fn split_and_push_projection( recovery_exprs.push(Expr::Column(Column::new_unqualified(&alias_name))); proj_exprs_captured += 1; } else { - // Everything else: run through routing_extract - let transformed = - routing_extract(expr.clone(), &mut extractors, &input_column_sets)?; + // Everything else (including pre-existing extraction aliases whose + // name already exists in `proj.input`'s subtree): unwrap colliding + // extraction aliases so `routing_extract` allocates a fresh + // plan-wide unique name and recovery restores the original name. + let target_expr = match expr { + Expr::Alias(alias) if is_extracted_alias(alias) => (*alias.expr).clone(), + _ => expr.clone(), + }; + let transformed = routing_extract( + target_expr, + &mut extractors, + &input_column_sets, + reserved_names, + )?; if transformed.transformed { has_new_extractions = true; } @@ -1137,6 +1243,7 @@ fn split_and_push_projection( proj, &proj_input, alias_generator, + reserved_names, proj_exprs_captured, )?; @@ -1164,7 +1271,7 @@ fn split_and_push_projection( &input_arc, input_schema.as_ref(), )?); - match try_push_input(&extraction, alias_generator)? { + match try_push_input(&extraction, alias_generator, reserved_names)? { Some(pushed) => pushed, // The extraction projection cannot move below `input`. Leave // the original projection unchanged: the split would put the @@ -1238,8 +1345,15 @@ fn split_and_push_projection( } /// Returns true if `exprs` are the expressions of a *pure extraction -/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)` -/// or a bare `Column`, and there is at least one extraction alias. +/// projection*: every expression is either an extraction alias (matching +/// [`EXTRACTED_EXPR_PREFIX`] with a pushdown-eligible inner expression via +/// [`ExpressionPlacement::should_push_to_leaves`]) or a bare `Column`, and +/// there is at least one extraction alias. +/// +/// Numeric suffix validation is reserved for generator seeding in +/// [`advance_generator_past_existing`]; classification relies on prefix and +/// expression placement so generated `usize::MAX` (and wrapped `0`) aliases +/// are accepted while non-pushable user aliases are rejected. /// /// Such projections can safely be pushed further without re-extraction. /// @@ -1250,7 +1364,7 @@ pub(crate) fn is_pure_extraction_projection(exprs: &[Expr]) -> bool { let mut has_extraction = false; for expr in exprs { match expr { - Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX) => { + Expr::Alias(alias) if is_extracted_alias(alias) => { has_extraction = true; } Expr::Column(_) => {} @@ -1268,6 +1382,7 @@ fn push_extraction_pairs( proj: &Projection, proj_input: &Arc, alias_generator: &Arc, + reserved_names: &mut std::collections::HashSet, proj_exprs_captured: usize, ) -> Result> { match proj_input.as_ref() { @@ -1297,7 +1412,8 @@ fn push_extraction_pairs( // This handles: Extraction → Recovery(cols) → Filter → ... → TableScan // by pushing through the recovery projection AND the filter in one pass. if merged_is_pure - && let Some(pushed) = try_push_input(&merged_plan, alias_generator)? + && let Some(pushed) = + try_push_input(&merged_plan, alias_generator, reserved_names)? { return Ok(Some(pushed)); } @@ -1313,6 +1429,7 @@ fn push_extraction_pairs( columns_needed, proj_input.as_ref(), alias_generator, + reserved_names, ), } } @@ -1407,6 +1524,7 @@ fn try_push_into_inputs( columns_needed: &IndexSet, node: &LogicalPlan, alias_generator: &Arc, + reserved_names: &mut std::collections::HashSet, ) -> Result> { let inputs = node.inputs(); if inputs.is_empty() { @@ -1493,10 +1611,11 @@ fn try_push_into_inputs( // this input (e.g., through Filter → existing extraction projection). // This ensures the input's output schema is stable and won't change // when the TopDown pass later visits children. - let pushed = match try_push_input(&proj_plan, alias_generator)? { - Some(pushed) => pushed, - None => proj_plan, - }; + let pushed = + match try_push_input(&proj_plan, alias_generator, reserved_names)? { + Some(pushed) => pushed, + None => proj_plan, + }; if is_union { new_inputs.push(align_union_input(pushed, &per_input[idx])?); } else { @@ -3778,6 +3897,202 @@ mod tests { Ok(()) } + #[test] + fn test_extracted_expr_id_boundaries() { + for id in [1, 42, usize::MAX - 1] { + let name = format!("{EXTRACTED_EXPR_PREFIX}_{id}"); + assert_eq!(extracted_expr_id(&name), Some(id), "{name}"); + } + + assert_eq!(extracted_expr_id(EXTRACTED_EXPR_PREFIX), None); + let invalid_suffixes = + ["", "0", "01", "0001", "+1", "-1", "1x", " 1", "1 ", "1"] + .map(str::to_owned); + for suffix in invalid_suffixes + .into_iter() + .chain([usize::MAX.to_string(), format!("{}0", usize::MAX)]) + { + let name = format!("{EXTRACTED_EXPR_PREFIX}_{suffix}"); + assert_eq!(extracted_expr_id(&name), None, "{name}"); + } + } + + #[test] + fn test_advance_generator_ignores_invalid_extraction_ids() -> Result<()> { + let exprs = [ + "0".to_owned(), + "01".to_owned(), + usize::MAX.to_string(), + format!("{}0", usize::MAX), + ] + .into_iter() + .map(|suffix| lit(1).alias(format!("{EXTRACTED_EXPR_PREFIX}_{suffix}"))) + .collect::>(); + let plan = LogicalPlanBuilder::from(test_table_scan_with_struct()?) + .project(exprs)? + .build()?; + let alias_generator = AliasGenerator::new(); + advance_generator_past_existing(&plan, &alias_generator)?; + assert_eq!( + alias_generator.next(EXTRACTED_EXPR_PREFIX), + "__datafusion_extracted_1" + ); + Ok(()) + } + + fn inexact_table_scan_with_struct() -> Result { + #[derive(Debug)] + struct InexactStructTable(arrow::datatypes::SchemaRef); + + impl datafusion_expr::TableSource for InexactStructTable { + fn schema(&self) -> arrow::datatypes::SchemaRef { + Arc::clone(&self.0) + } + fn table_type(&self) -> datafusion_expr::TableType { + datafusion_expr::TableType::Base + } + fn supports_filters_pushdown( + &self, + filters: &[&Expr], + ) -> Result> { + Ok(vec![ + datafusion_expr::TableProviderFilterPushDown::Inexact; + filters.len() + ]) + } + } + + let schema = Arc::new(arrow::datatypes::Schema::new( + test_table_scan_with_struct_fields(), + )); + LogicalPlanBuilder::scan("test", Arc::new(InexactStructTable(schema)), None)? + .build() + } + + #[test] + fn test_canonical_user_alias_not_pushed_below_filter() -> Result<()> { + let table_scan = inexact_table_scan_with_struct()?; + let guarded_div = datafusion_expr::binary_expr( + lit(10u32), + datafusion_expr::Operator::Divide, + col("id"), + ) + .alias(format!("{EXTRACTED_EXPR_PREFIX}_1")); + let plan = LogicalPlanBuilder::from(table_scan) + .filter( + col("id") + .gt(lit(0u32)) + .and(leaf_udf(col("user"), "status").eq(lit("active"))), + )? + .project(vec![guarded_div])? + .build()?; + + let ctx = OptimizerContext::new(); + let optimizer = Optimizer::with_rules(vec![ + Arc::new(crate::push_down_filter::PushDownFilter::new()), + Arc::new(ExtractLeafExpressions::new()), + Arc::new(PushDownLeafProjections::new()), + Arc::new(OptimizeProjections::new()), + ]); + let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?; + insta::assert_snapshot!(format!("{optimized}"), @r#" + Projection: UInt32(10) / test.id AS __datafusion_extracted_1 + Filter: test.id > UInt32(0) AND __datafusion_extracted_2 = Utf8("active") + Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id + TableScan: test projection=[id, user], partial_filters=[test.id > UInt32(0), leaf_udf(test.user, Utf8("status")) = Utf8("active")] + "#); + Ok(()) + } + + #[test] + fn test_existing_max_and_zero_aliases_avoid_schema_ambiguity() -> Result<()> { + let table_scan = inexact_table_scan_with_struct()?; + let max_minus_one = format!("{EXTRACTED_EXPR_PREFIX}_{}", usize::MAX - 1); + let max_alias = format!("{EXTRACTED_EXPR_PREFIX}_{}", usize::MAX); + let zero_alias = format!("{EXTRACTED_EXPR_PREFIX}_0"); + let plan = LogicalPlanBuilder::from(table_scan) + .filter(leaf_udf(col("user"), "status").eq(lit("active")))? + .filter(leaf_udf(col("user"), "role").eq(lit("admin")))? + .project(vec![ + col("id"), + leaf_udf(col("user"), "name").alias(&max_minus_one), + lit(1u32).alias(&max_alias), + lit(2u32).alias(&zero_alias), + ])? + .build()?; + + let ctx = OptimizerContext::new(); + let optimizer = Optimizer::with_rules(vec![ + Arc::new(crate::push_down_filter::PushDownFilter::new()), + Arc::new(ExtractLeafExpressions::new()), + Arc::new(PushDownLeafProjections::new()), + Arc::new(OptimizeProjections::new()), + ]); + let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?; + let formatted = format!("{optimized}"); + assert!( + formatted.contains("__datafusion_extracted_1 = Utf8(\"active\")") + && formatted.contains("__datafusion_extracted_2 = Utf8(\"admin\")"), + "expected wraparound allocation to skip existing _MAX and _0 aliases:\n{formatted}" + ); + Ok(()) + } + + #[test] + fn test_standalone_pushdown_skips_existing_extracted_aliases() -> Result<()> { + let table_scan = test_table_scan_with_struct()?; + let plan = LogicalPlanBuilder::from(table_scan) + .filter(col("id").gt(lit(0u32)))? + .project(vec![ + (leaf_udf(col("user"), "status").eq(lit("active"))).alias("is_active"), + lit(1u32).alias("__datafusion_extracted_1"), + ])? + .build()?; + + let ctx = OptimizerContext::new(); + let optimizer = + Optimizer::with_rules(vec![Arc::new(PushDownLeafProjections::new())]); + let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?; + let formatted = format!("{optimized}"); + assert!( + formatted.contains("AS __datafusion_extracted_2"), + "expected standalone PushDownLeafProjections to skip __datafusion_extracted_1:\n{formatted}" + ); + Ok(()) + } + + #[test] + fn test_left_semi_join_leaf_pushdown_preserved() -> Result<()> { + let left = test_table_scan_with_struct_named("l")?; + let right = test_table_scan_with_struct_named("r")?; + let plan = LogicalPlanBuilder::from(left) + .join( + right, + datafusion_expr::JoinType::LeftSemi, + (vec!["l.id"], vec!["r.id"]), + None, + )? + .project(vec![ + leaf_udf(col("l.user"), "name").alias("user_name"), + col("l.id"), + ])? + .build()?; + + 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, |_, _| {})?; + let formatted = format!("{optimized}"); + assert!( + formatted.contains("Projection: leaf_udf(l.user, Utf8(\"name\")) AS __datafusion_extracted_1, l.id"), + "expected leaf expression to push below LeftSemi join:\n{formatted}" + ); + Ok(()) + } + /// Pre-existing `__datafusion_extracted_N` aliases must advance the alias /// generator even when they live inside a subquery plan, since extraction /// descends into subqueries and would otherwise reuse the same alias. @@ -3969,11 +4284,59 @@ mod tests { assert!(!is_pure_extraction_projection(&common_expr.expressions())); // A bare expression is never allowed. - let bare_expr = LogicalPlanBuilder::from(scan) + let bare_expr = LogicalPlanBuilder::from(scan.clone()) .project(vec![leaf_udf(col("user"), "status"), col("id")])? .build()?; assert!(!is_pure_extraction_projection(&bare_expr.expressions())); + // Generated boundary IDs (usize::MAX and wrapped 0) remain valid when + // wrapping a pushdown-eligible expression. + let max_id_expr = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + leaf_udf(col("user"), "status") + .alias(format!("{EXTRACTED_EXPR_PREFIX}_{}", usize::MAX)), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&max_id_expr.expressions())); + + let zero_id_expr = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + leaf_udf(col("user"), "status") + .alias(format!("{EXTRACTED_EXPR_PREFIX}_0")), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&zero_id_expr.expressions())); + + // Column-backed extraction aliases (e.g. after CSE or SubqueryAlias) + // are pushdown-eligible too. + let column_alias = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + col("user").alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(is_pure_extraction_projection(&column_alias.expressions())); + + // Canonical user aliases wrapping KeepInPlace or Literal expressions + // must not be classified as extraction aliases. + let non_pushable = LogicalPlanBuilder::from(scan.clone()) + .project(vec![ + (col("id") + lit(1u32)).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(!is_pure_extraction_projection(&non_pushable.expressions())); + + let literal_alias = LogicalPlanBuilder::from(scan) + .project(vec![ + lit(1u32).alias(format!("{EXTRACTED_EXPR_PREFIX}_1")), + col("id"), + ])? + .build()?; + assert!(!is_pure_extraction_projection(&literal_alias.expressions())); + Ok(()) } diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..4050458759f36 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -1949,6 +1949,171 @@ ORDER BY simple_struct.id; # (https://github.com/apache/datafusion/issues/20430) # ========================================================================= +# A prefix alone does not make an alias an extraction. In particular, moving +# this division below the filter would evaluate it on the zero row as well. +statement ok +CREATE TABLE extracted_alias_names AS +SELECT * FROM (VALUES (0), (1)) AS v(id); + +query I +SELECT 10 / id AS __datafusion_extracted_manual +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_1x +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS "__datafusion_extracted_+1" +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_0 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_01 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names WHERE id > 0; +---- +10 + +statement ok +DROP TABLE extracted_alias_names; + +# Combine id > 0 with a struct-field extraction predicate where both rows match +# s['a'] = 1: leaf extraction pushes get_field(s, 'a') below the filter while +# keeping guarded division above it for both canonical and manual aliases. +statement ok +COPY ( + SELECT column1 AS id, column2 AS s + FROM VALUES (0, {a: 1}), (1, {a: 1}) +) TO 'test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE extracted_alias_names_struct +STORED AS PARQUET +LOCATION 'test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet'; + +query TT +EXPLAIN SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +logical_plan +01)Projection: Int64(10) / extracted_alias_names_struct.id AS __datafusion_extracted_1 +02)--Filter: extracted_alias_names_struct.id > Int64(0) AND __datafusion_extracted_2 = Int64(1) +03)----Projection: get_field(extracted_alias_names_struct.s, Utf8("a")) AS __datafusion_extracted_2, extracted_alias_names_struct.id +04)------TableScan: extracted_alias_names_struct projection=[id, s], partial_filters=[extracted_alias_names_struct.id > Int64(0), get_field(extracted_alias_names_struct.s, Utf8("a")) = Int64(1)] +physical_plan +01)ProjectionExec: expr=[10 / id@0 as __datafusion_extracted_1] +02)--FilterExec: id@1 > 0 AND __datafusion_extracted_2@0 = 1, projection=[id@1] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/extracted_alias_names_struct.parquet]]}, projection=[get_field(s@1, a) as __datafusion_extracted_2, id], file_type=parquet, predicate=id@0 > 0 AND get_field(s@1, a) = 1, pruning_predicate=id_null_count@1 != row_count@2 AND id_max@0 > 0, required_guarantees=[] + +query I +SELECT 10 / id AS __datafusion_extracted_1 +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +10 + +query I +SELECT 10 / id AS __datafusion_extracted_manual +FROM extracted_alias_names_struct +WHERE id > 0 AND s['a'] = 1; +---- +10 + +statement ok +DROP TABLE extracted_alias_names_struct; + +# The filter reads the input column while the projection gives the extracted +# struct field the same name. +statement ok +CREATE TABLE review_alias_collision AS +SELECT column1 AS __datafusion_extracted_manual, column2 AS s +FROM VALUES (0, {a: 1}), (1, {a: 2}); + +query I +SELECT s['a'] AS __datafusion_extracted_manual +FROM review_alias_collision AS t +WHERE t.__datafusion_extracted_manual > 0; +---- +2 + +query I +SELECT result.__datafusion_extracted_manual +FROM ( + SELECT s['a'] AS __datafusion_extracted_manual + FROM review_alias_collision AS t + WHERE t.__datafusion_extracted_manual > 0 +) AS result; +---- +2 + +statement ok +DROP TABLE review_alias_collision; + +# Nested UNION ALL where an extraction alias collides with a column name +# present only in the second branch. +statement ok +CREATE TABLE review_union_left AS +SELECT column1 AS x, column2 AS __datafusion_extracted_1, column3 AS s +FROM VALUES (1, 10, {a: 100}); + +statement ok +CREATE TABLE review_union_right AS +SELECT column1 AS __datafusion_extracted_1, column2 AS __datafusion_extracted_2, column3 AS s +FROM VALUES (2, 20, {a: 200}); + +query II rowsort +SELECT s['a'] AS __datafusion_extracted_1, x +FROM ( + SELECT x, s FROM review_union_left + UNION ALL + SELECT __datafusion_extracted_1, s FROM review_union_right +); +---- +100 1 +200 2 + +query II rowsort +SELECT s['a'] AS __datafusion_extracted_1, __datafusion_extracted_1 AS orig +FROM ( + SELECT __datafusion_extracted_1, s FROM review_union_left + UNION ALL + SELECT __datafusion_extracted_2, s FROM review_union_right +); +---- +100 10 +200 20 + +statement ok +DROP TABLE review_union_left; + +statement ok +DROP TABLE review_union_right; + statement ok COPY ( select {f1: 1, f2: 2} as s ) TO 'test_files/scratch/projection_pushdown/test.parquet'