Skip to main content

datafusion_optimizer/
extract_leaf_expressions.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Two-pass optimizer pipeline that pushes cheap expressions (like struct field
6//! access `user['status']`) closer to data sources, enabling early data reduction
7//! and source-level optimizations (e.g., Parquet column pruning). See
8//! [`ExtractLeafExpressions`] (pass 1) and [`PushDownLeafProjections`] (pass 2).
9//!
10//! # Precedence over [`PushDownFilter`]
11//!
12//! [`PushDownLeafProjections`] and [`PushDownFilter`] both move nodes towards
13//! the leaves, and for an adjacent filter and *pure extraction projection* (a
14//! projection whose expressions are only `__datafusion_extracted_N` aliases and
15//! pass-through columns) they want the opposite order:
16//!
17//! ```text
18//! Filter: t.date = '2025-01-03'                                  <-- (A)
19//!   Projection: get_field(t.ids, 'id1') AS __datafusion_extracted_1, t.date   <-- (B)
20//!     TableScan: t
21//! ```
22//!
23//! `PushDownFilter` wants (A) below (B). `PushDownLeafProjections` wants (B)
24//! below (A). Before <https://github.com/apache/datafusion/issues/14540> was
25//! decided the two rules undid each other on every optimizer pass, and the rule
26//! that runs later in the list won.
27//!
28//! **Invariant: pure extraction projections win.** `PushDownFilter` does not
29//! move a filter below a pure extraction projection, so the plan above is the
30//! final plan. `PushDownLeafProjections` keeps moving such a projection through
31//! a filter, which is how the projection reaches the scan.
32//!
33//! The reason is that the extraction projection is the node a source absorbs.
34//! A Parquet scan merges it into the file projection and reads only the struct
35//! leaf. With the opposite precedence the scan reads the whole struct whenever
36//! `datafusion.execution.parquet.pushdown_filters` is `false`, which is the
37//! default. The filter loses nothing by staying one node higher, because
38//! `PushDownFilter` records the predicate in
39//! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan) in the pass
40//! that runs before the extraction projection exists, so row group pruning and
41//! source level filtering still happen.
42//!
43//! # Yields to [`OptimizeProjections`]
44//!
45//! When the extraction projection cannot move below the input of a projection
46//! (for example a `TableScan` or an `Aggregate`), [`PushDownLeafProjections`]
47//! leaves the projection unchanged. Splitting it in place would give a
48//! recovery projection over an extraction projection on the same input, and
49//! `OptimizeProjections` merges those two back into the original projection.
50//! The two rules would then undo each other on every optimizer pass. The split
51//! has no use there: the source absorbs the leaf expressions of the original
52//! projection just as well.
53//!
54//! [`PushDownFilter`]: crate::push_down_filter::PushDownFilter
55//! [`OptimizeProjections`]: crate::optimize_projections::OptimizeProjections
56
57use indexmap::{IndexMap, IndexSet};
58use std::collections::{BTreeSet, HashMap};
59use std::sync::Arc;
60
61use datafusion_common::alias::AliasGenerator;
62use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
63use datafusion_common::{Column, DFSchema, Result, qualified_name};
64use datafusion_expr::logical_plan::LogicalPlan;
65use datafusion_expr::{Expr, ExpressionPlacement, Projection};
66
67use crate::optimizer::ApplyOrder;
68use crate::push_down_filter::replace_cols_by_name;
69use crate::utils::{ColumnReference, has_all_column_refs, schema_columns};
70use crate::{OptimizerConfig, OptimizerRule};
71
72/// Prefix for aliases generated by the extraction optimizer passes.
73///
74/// This prefix is **reserved for internal optimizer use**. User-defined aliases
75/// starting with this prefix may be misidentified as optimizer-generated
76/// extraction aliases, leading to unexpected behavior. Do not use this prefix
77/// in user queries.
78const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted";
79
80/// Returns `true` if any sub-expression in `exprs` has
81/// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement.
82///
83/// This is a lightweight pre-check that short-circuits as soon as one
84/// extractable expression is found, avoiding the expensive allocations
85/// (column HashSets, extractors, expression rewrites) that the full
86/// extraction pipeline requires.
87fn has_extractable_expr(exprs: &[Expr]) -> bool {
88    exprs.iter().any(|expr| {
89        expr.exists(|e| Ok(e.placement() == ExpressionPlacement::MoveTowardsLeafNodes))
90            .unwrap_or(false)
91    })
92}
93
94/// Returns the flat names of `plan`'s output columns whose defining expression
95/// is volatile (e.g. `random()`).
96///
97/// Only a [`LogicalPlan::Projection`] can define such a column: anywhere else
98/// the value has already been materialized by the projection that produced it,
99/// so referencing the column again does not re-evaluate anything.
100fn volatile_output_columns(plan: &LogicalPlan) -> BTreeSet<String> {
101    let LogicalPlan::Projection(projection) = plan else {
102        return BTreeSet::new();
103    };
104    projection
105        .schema
106        .iter()
107        .zip(projection.expr.iter())
108        .filter(|(_, expr)| expr.is_volatile())
109        .map(|((qualifier, field), _)| Column::from((qualifier, field)).flat_name())
110        .collect()
111}
112
113/// Returns `true` if building an extraction projection for `exprs` on top of
114/// `input` would duplicate a volatile computation.
115///
116/// When `input` is already a projection, [`build_extraction_projection_impl`]
117/// *merges* into it: every column reference in an extracted expression is
118/// replaced by that column's defining expression (see
119/// [`build_projection_replace_map`]). Inlining a volatile definition makes the
120/// merged projection evaluate it a second, independent time, so the extracted
121/// value no longer matches the column it was derived from:
122///
123/// ```text
124/// Projection: s, get_field(s, 'a') AS field
125///   Projection: named_struct('a', random()) AS s
126/// ```
127///
128/// would merge into a single projection computing `random()` twice, and
129/// `field` would then differ from `s['a']` on every row. Callers skip the
130/// extraction instead.
131fn would_duplicate_volatile<'a>(
132    exprs: impl IntoIterator<Item = &'a Expr>,
133    input: &LogicalPlan,
134) -> bool {
135    let volatile = volatile_output_columns(input);
136    if volatile.is_empty() {
137        return false;
138    }
139    exprs.into_iter().any(|expr| {
140        expr.column_refs()
141            .iter()
142            .any(|col| volatile.contains(&col.flat_name()))
143    })
144}
145
146/// Extracts `MoveTowardsLeafNodes` sub-expressions from non-projection nodes
147/// into **extraction projections** (pass 1 of 2).
148///
149/// This handles Filter, Sort, Limit, Aggregate, and Join nodes. For Projection
150/// nodes, extraction and pushdown are handled by [`PushDownLeafProjections`].
151///
152/// # Key Concepts
153///
154/// **Extraction projection**: a projection inserted *below* a node that
155/// pre-computes a cheap expression and exposes it under an alias
156/// (`__datafusion_extracted_N`). The parent node then references the alias
157/// instead of the original expression.
158///
159/// **Recovery projection**: a projection inserted *above* a node to restore
160/// the original output schema when extraction changes it.
161/// Schema-preserving nodes (Filter, Sort, Limit) gain extra columns from
162/// the extraction projection that bubble up; the recovery projection selects
163/// only the original columns to hide the extras.
164///
165/// # Example
166///
167/// Given a filter with a struct field access:
168///
169/// ```text
170/// Filter: user['status'] = 'active'
171///   TableScan: t [id, user]
172/// ```
173///
174/// This rule:
175/// 1. Inserts an **extraction projection** below the filter:
176/// 2. Adds a **recovery projection** above to hide the extra column:
177///
178/// ```text
179/// Projection: id, user                                                        <-- recovery projection
180///   Filter: __datafusion_extracted_1 = 'active'
181///     Projection: user['status'] AS __datafusion_extracted_1, id, user         <-- extraction projection
182///       TableScan: t [id, user]
183/// ```
184///
185/// **Important:** The `PushDownFilter` rule is aware of projections created by this rule
186/// and will not push filters through them. It uses `ExpressionPlacement` to detect
187/// `MoveTowardsLeafNodes` expressions and skip filter pushdown past them.
188#[derive(Default, Debug)]
189pub struct ExtractLeafExpressions {}
190
191impl ExtractLeafExpressions {
192    /// Create a new [`ExtractLeafExpressions`]
193    pub fn new() -> Self {
194        Self {}
195    }
196}
197
198impl OptimizerRule for ExtractLeafExpressions {
199    fn name(&self) -> &str {
200        "extract_leaf_expressions"
201    }
202
203    fn rewrite(
204        &self,
205        plan: LogicalPlan,
206        config: &dyn OptimizerConfig,
207    ) -> Result<Transformed<LogicalPlan>> {
208        if !config.options().optimizer.enable_leaf_expression_pushdown {
209            return Ok(Transformed::no(plan));
210        }
211        let alias_generator = config.alias_generator();
212
213        // Advance the alias generator past any user-provided __datafusion_extracted_N
214        // aliases to prevent collisions when generating new extraction aliases.
215        advance_generator_past_existing(&plan, alias_generator)?;
216
217        plan.transform_down_with_subqueries(|plan| {
218            extract_from_plan(plan, alias_generator)
219        })
220    }
221}
222
223/// Scans the plan for pre-existing `__datafusion_extracted_N` aliases and
224/// advances the generator counter past them to avoid collisions with
225/// user-provided aliases.
226///
227/// Subquery plans nested inside expressions are scanned as well: extraction
228/// rewrites with `transform_down_with_subqueries`, so it can generate aliases
229/// *inside* a subquery and would otherwise collide with a user alias there.
230fn advance_generator_past_existing(
231    plan: &LogicalPlan,
232    alias_generator: &AliasGenerator,
233) -> Result<()> {
234    plan.apply_with_subqueries(|plan| {
235        plan.apply_expressions(|expr| {
236            expr.apply(|e| {
237                if let Expr::Alias(alias) = e
238                    && let Some(id) = alias
239                        .name
240                        .strip_prefix(EXTRACTED_EXPR_PREFIX)
241                        .and_then(|s| s.strip_prefix('_'))
242                        .and_then(|s| s.parse().ok())
243                {
244                    alias_generator.update_min_id(id);
245                }
246                Ok(TreeNodeRecursion::Continue)
247            })
248        })
249    })
250    .map(|_| ())
251}
252
253/// Extracts `MoveTowardsLeafNodes` sub-expressions from a plan node.
254///
255/// Works for any number of inputs (0, 1, 2, …N). For multi-input nodes
256/// like Join, each extracted sub-expression is routed to the correct input
257/// by checking which input's schema contains all of the expression's column
258/// references.
259fn extract_from_plan(
260    plan: LogicalPlan,
261    alias_generator: &Arc<AliasGenerator>,
262) -> Result<Transformed<LogicalPlan>> {
263    // Only extract from plan types whose output schema is predictable after
264    // expression rewriting.  Nodes like Window derive column names from
265    // their expressions, so rewriting `get_field` inside a window function
266    // changes the output schema and breaks the recovery projection.
267    if !matches!(
268        &plan,
269        LogicalPlan::Aggregate(_)
270            | LogicalPlan::Filter(_)
271            | LogicalPlan::Sort(_)
272            | LogicalPlan::Limit(_)
273            | LogicalPlan::Join(_)
274    ) {
275        return Ok(Transformed::no(plan));
276    }
277
278    let inputs = plan.inputs();
279    if inputs.is_empty() {
280        return Ok(Transformed::no(plan));
281    }
282
283    // Fast pre-check: skip all allocations if no extractable expressions exist
284    let node_exprs = plan.expressions();
285    if !has_extractable_expr(&node_exprs) {
286        return Ok(Transformed::no(plan));
287    }
288
289    // The extraction projection is merged into an input that is already a
290    // projection, which inlines the referenced columns' definitions. Skip the
291    // extraction when that would duplicate a volatile computation.
292    if inputs
293        .iter()
294        .any(|input| would_duplicate_volatile(node_exprs.iter(), input))
295    {
296        return Ok(Transformed::no(plan));
297    }
298
299    // Save original output schema before any transformation
300    let original_schema = Arc::clone(plan.schema());
301
302    // Build per-input schemas from borrowed inputs (before plan is consumed
303    // by map_expressions). We only need schemas and column sets for routing;
304    // the actual inputs are cloned later only if extraction succeeds.
305    let input_schemas: Vec<Arc<DFSchema>> =
306        inputs.iter().map(|i| Arc::clone(i.schema())).collect();
307
308    // Build per-input extractors
309    let mut extractors: Vec<LeafExpressionExtractor> = input_schemas
310        .iter()
311        .map(|schema| LeafExpressionExtractor::new(schema.as_ref(), alias_generator))
312        .collect();
313
314    // Build per-input column sets for routing expressions to the correct input
315    let input_column_sets: Vec<std::collections::HashSet<ColumnReference>> =
316        input_schemas
317            .iter()
318            .map(|schema| schema_columns(schema.as_ref()))
319            .collect();
320
321    // Transform expressions via map_expressions with routing
322    let transformed = plan.map_expressions(|expr| {
323        routing_extract(expr, &mut extractors, &input_column_sets)
324    })?;
325
326    // If no expressions were rewritten, nothing was extracted
327    if !transformed.transformed {
328        return Ok(transformed);
329    }
330
331    // Clone inputs now that we know extraction succeeded. Wrap in Arc
332    // upfront since build_extraction_projection expects &Arc<LogicalPlan>.
333    let owned_inputs: Vec<Arc<LogicalPlan>> = transformed
334        .data
335        .inputs()
336        .into_iter()
337        .map(|i| Arc::new(i.clone()))
338        .collect();
339
340    // Build per-input extraction projections (None means no extractions for that input)
341    let new_inputs: Vec<LogicalPlan> = owned_inputs
342        .into_iter()
343        .zip(extractors.iter())
344        .map(|(input_arc, extractor)| {
345            match extractor.build_extraction_projection(&input_arc)? {
346                Some(plan) => Ok(plan),
347                // No extractions for this input — recover the LogicalPlan
348                // without cloning (refcount is 1 since build returned None).
349                None => Ok(Arc::unwrap_or_clone(input_arc)),
350            }
351        })
352        .collect::<Result<Vec<_>>>()?;
353
354    // Rebuild the plan keeping its rewritten expressions but replacing
355    // inputs with the new extraction projections.
356    let new_plan = transformed
357        .data
358        .with_new_exprs(transformed.data.expressions(), new_inputs)?;
359
360    // Add recovery projection if the output schema changed
361    let recovered = build_recovery_projection(original_schema.as_ref(), new_plan)?;
362
363    Ok(Transformed::yes(recovered))
364}
365
366/// Given an expression, returns the index of the input whose columns fully
367/// cover the expression's column references.
368/// Returns `None` if the expression references columns from multiple inputs
369/// or if multiple inputs match (ambiguous, e.g. unqualified columns present
370/// in both sides of a join).
371fn find_owning_input(
372    expr: &Expr,
373    input_column_sets: &[std::collections::HashSet<ColumnReference>],
374) -> Option<usize> {
375    let mut found = None;
376    for (idx, cols) in input_column_sets.iter().enumerate() {
377        if has_all_column_refs(expr, cols) {
378            if found.is_some() {
379                // Ambiguous — multiple inputs match
380                return None;
381            }
382            found = Some(idx);
383        }
384    }
385    found
386}
387
388/// Walks an expression tree top-down, extracting `MoveTowardsLeafNodes`
389/// sub-expressions and routing each to the correct per-input extractor.
390fn routing_extract(
391    expr: Expr,
392    extractors: &mut [LeafExpressionExtractor],
393    input_column_sets: &[std::collections::HashSet<ColumnReference>],
394) -> Result<Transformed<Expr>> {
395    expr.transform_down(|e| {
396        // Skip expressions already aliased with extracted expression pattern
397        if let Expr::Alias(alias) = &e
398            && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
399        {
400            return Ok(Transformed {
401                data: e,
402                transformed: false,
403                tnr: TreeNodeRecursion::Jump,
404            });
405        }
406
407        // Don't extract Alias nodes directly — preserve the alias and let
408        // transform_down recurse into the inner expression
409        if matches!(&e, Expr::Alias(_)) {
410            return Ok(Transformed::no(e));
411        }
412
413        match e.placement() {
414            ExpressionPlacement::MoveTowardsLeafNodes => {
415                if let Some(idx) = find_owning_input(&e, input_column_sets) {
416                    let col_ref = extractors[idx].add_extracted(e)?;
417                    Ok(Transformed::yes(col_ref))
418                } else {
419                    // References columns from multiple inputs — cannot extract
420                    Ok(Transformed::no(e))
421                }
422            }
423            ExpressionPlacement::Column => {
424                // Track columns that the parent node references so the
425                // extraction projection includes them as pass-through.
426                // Without this, the extraction projection would only
427                // contain __datafusion_extracted_N aliases, and the parent couldn't
428                // resolve its other column references.
429                if let Expr::Column(col) = &e
430                    && let Some(idx) = find_owning_input(&e, input_column_sets)
431                {
432                    extractors[idx].columns_needed.insert(col.clone());
433                }
434                Ok(Transformed::no(e))
435            }
436            _ => Ok(Transformed::no(e)),
437        }
438    })
439}
440
441/// Rewrites extraction pairs and column references from one qualifier
442/// space to another.
443///
444/// Builds a replacement map by zipping `from_schema` (whose qualifiers
445/// currently appear in `pairs` / `columns`) with `to_schema` (the
446/// qualifiers we want), then applies `replace_cols_by_name`.
447///
448/// Used for SubqueryAlias (alias-space -> input-space) and Union
449/// (union output-space -> per-branch input-space).
450fn remap_pairs_and_columns(
451    pairs: &[(Expr, String)],
452    columns: &IndexSet<Column>,
453    from_schema: &DFSchema,
454    to_schema: &DFSchema,
455) -> Result<ExtractionTarget> {
456    let mut replace_map = HashMap::with_capacity(from_schema.fields().len());
457    for ((from_q, from_f), (to_q, to_f)) in from_schema.iter().zip(to_schema.iter()) {
458        replace_map.insert(
459            qualified_name(from_q, from_f.name()),
460            Expr::Column(Column::new(to_q.cloned(), to_f.name())),
461        );
462    }
463    let remapped_pairs: Vec<(Expr, String)> = pairs
464        .iter()
465        .map(|(expr, alias)| {
466            Ok((
467                replace_cols_by_name(expr.clone(), &replace_map)?,
468                alias.clone(),
469            ))
470        })
471        .collect::<Result<_>>()?;
472    let remapped_columns: IndexSet<Column> = columns
473        .iter()
474        .filter_map(|col| {
475            let rewritten =
476                replace_cols_by_name(Expr::Column(col.clone()), &replace_map).ok()?;
477            if let Expr::Column(c) = rewritten {
478                Some(c)
479            } else {
480                Some(col.clone())
481            }
482        })
483        .collect();
484    Ok(ExtractionTarget {
485        pairs: remapped_pairs,
486        columns: remapped_columns,
487    })
488}
489
490// =============================================================================
491// Helper Types & Functions for Extraction Targeting
492// =============================================================================
493
494/// A bundle of extraction pairs (expression + alias) and standalone columns
495/// that need to be pushed through a plan node.
496struct ExtractionTarget {
497    /// Extracted expressions paired with their generated aliases.
498    pairs: Vec<(Expr, String)>,
499    /// Standalone column references needed by the parent node.
500    columns: IndexSet<Column>,
501}
502
503/// Build a replacement map from a projection: output_column_name -> underlying_expr.
504///
505/// This is used to resolve column references through a renaming projection.
506/// For example, if a projection has `user AS x`, this maps `x` -> `col("user")`.
507fn build_projection_replace_map(projection: &Projection) -> HashMap<String, Expr> {
508    projection
509        .schema
510        .iter()
511        .zip(projection.expr.iter())
512        .map(|((qualifier, field), expr)| {
513            let key = Column::from((qualifier, field)).flat_name();
514            (key, expr.clone().unalias())
515        })
516        .collect()
517}
518
519/// Build a recovery projection to restore the original output schema.
520///
521/// After extraction, a node's output schema may differ from the original:
522///
523/// - **Schema-preserving nodes** (Filter/Sort/Limit): the extraction projection
524///   below adds extra `__datafusion_extracted_N` columns that bubble up through
525///   the node. Recovery selects only the original columns to hide the extras.
526///   ```text
527///   Original schema: [id, user]
528///   After extraction: [__datafusion_extracted_1, id, user]   ← extra column leaked through
529///   Recovery: SELECT id, user FROM ...                       ← hides __datafusion_extracted_1
530///   ```
531///
532/// - **Schema-defining nodes** (Aggregate): same number of columns but names
533///   may differ because extracted aliases replaced the original expressions.
534///   Recovery maps positionally, aliasing where names changed.
535///   ```text
536///   Original: [SUM(user['balance'])]
537///   After:    [SUM(__datafusion_extracted_1)]                ← name changed
538///   Recovery: SUM(__datafusion_extracted_1) AS "SUM(user['balance'])"
539///   ```
540///
541/// - **Schemas identical** → no recovery projection needed.
542fn build_recovery_projection(
543    original_schema: &DFSchema,
544    input: LogicalPlan,
545) -> Result<LogicalPlan> {
546    let new_schema = input.schema();
547    let orig_len = original_schema.fields().len();
548    let new_len = new_schema.fields().len();
549
550    if orig_len == new_len {
551        // Same number of fields — check if schemas are identical
552        let schemas_match = original_schema.iter().zip(new_schema.iter()).all(
553            |((orig_q, orig_f), (new_q, new_f))| {
554                orig_f.name() == new_f.name() && orig_q == new_q
555            },
556        );
557        if schemas_match {
558            return Ok(input);
559        }
560
561        // Schema-defining nodes (Aggregate, Join): names may differ at some
562        // positions because extracted aliases replaced the original expressions.
563        // Map positionally, aliasing where the name changed.
564        //
565        // Invariant: `with_new_exprs` on all supported node types (Aggregate,
566        // Filter, Sort, Limit, Join) preserves column order, so positional
567        // mapping is safe here.
568        debug_assert!(
569            orig_len == new_len,
570            "build_recovery_projection: positional mapping requires same field count, \
571             got original={orig_len} vs new={new_len}"
572        );
573        let mut proj_exprs = Vec::with_capacity(orig_len);
574        for (i, (orig_qualifier, orig_field)) in original_schema.iter().enumerate() {
575            let (new_qualifier, new_field) = new_schema.qualified_field(i);
576            if orig_field.name() == new_field.name() && orig_qualifier == new_qualifier {
577                proj_exprs.push(Expr::from((orig_qualifier, orig_field)));
578            } else {
579                let new_col = Expr::Column(Column::from((new_qualifier, new_field)));
580                proj_exprs.push(
581                    new_col.alias_qualified(orig_qualifier.cloned(), orig_field.name()),
582                );
583            }
584        }
585        let projection = Projection::try_new(proj_exprs, Arc::new(input))?;
586        Ok(LogicalPlan::Projection(projection))
587    } else {
588        // Schema-preserving nodes: new schema has extra extraction columns.
589        // Original columns still exist by name; select them to hide extras.
590        let col_exprs: Vec<Expr> = original_schema.iter().map(Expr::from).collect();
591        let projection = Projection::try_new(col_exprs, Arc::new(input))?;
592        Ok(LogicalPlan::Projection(projection))
593    }
594}
595
596/// Collects `MoveTowardsLeafNodes` sub-expressions found during expression
597/// tree traversal and can build an extraction projection from them.
598///
599/// # Example
600///
601/// Given `Filter: user['status'] = 'active' AND user['name'] IS NOT NULL`:
602/// - `add_extracted(user['status'])` → stores it, returns `col("__datafusion_extracted_1")`
603/// - `add_extracted(user['name'])`   → stores it, returns `col("__datafusion_extracted_2")`
604/// - `build_extraction_projection()` produces:
605///   `Projection: user['status'] AS __datafusion_extracted_1, user['name'] AS __datafusion_extracted_2, <all input columns>`
606struct LeafExpressionExtractor<'a> {
607    /// Extracted expressions: maps expression -> alias
608    extracted: IndexMap<Expr, String>,
609    /// Columns referenced by extracted expressions or the parent node,
610    /// included as pass-through in the extraction projection.
611    columns_needed: IndexSet<Column>,
612    /// Input schema
613    input_schema: &'a DFSchema,
614    /// Alias generator
615    alias_generator: &'a Arc<AliasGenerator>,
616}
617
618impl<'a> LeafExpressionExtractor<'a> {
619    fn new(input_schema: &'a DFSchema, alias_generator: &'a Arc<AliasGenerator>) -> Self {
620        Self {
621            extracted: IndexMap::new(),
622            columns_needed: IndexSet::new(),
623            input_schema,
624            alias_generator,
625        }
626    }
627
628    /// Adds an expression to extracted set, returns column reference.
629    fn add_extracted(&mut self, expr: Expr) -> Result<Expr> {
630        // Deduplication: reuse existing alias if same expression
631        if let Some(alias) = self.extracted.get(&expr) {
632            return Ok(Expr::Column(Column::new_unqualified(alias)));
633        }
634
635        // Track columns referenced by this expression
636        for col in expr.column_refs() {
637            self.columns_needed.insert(col.clone());
638        }
639
640        // Generate unique alias
641        let alias = self.alias_generator.next(EXTRACTED_EXPR_PREFIX);
642        self.extracted.insert(expr, alias.clone());
643
644        Ok(Expr::Column(Column::new_unqualified(&alias)))
645    }
646
647    /// Builds an extraction projection above the given input, or merges into
648    /// it if the input is already a projection. Delegates to
649    /// [`build_extraction_projection_impl`].
650    ///
651    /// Returns `None` if there are no extractions.
652    fn build_extraction_projection(
653        &self,
654        input: &Arc<LogicalPlan>,
655    ) -> Result<Option<LogicalPlan>> {
656        if self.extracted.is_empty() {
657            return Ok(None);
658        }
659        let pairs: Vec<(Expr, String)> = self
660            .extracted
661            .iter()
662            .map(|(e, a)| (e.clone(), a.clone()))
663            .collect();
664        let proj = build_extraction_projection_impl(
665            &pairs,
666            &self.columns_needed,
667            input,
668            self.input_schema,
669        )?;
670        Ok(Some(LogicalPlan::Projection(proj)))
671    }
672}
673
674/// Resolves `col` against `schema` and returns it with the qualifier that
675/// `schema` gives the field. Returns `None` if `schema` does not hold `col`,
676/// or if the name is ambiguous in `schema`.
677///
678/// Two spellings of the same input column (a bare `c` and a qualified `t.c`)
679/// resolve to the same `Column`, so they compare equal. A column pushed into
680/// a projection this way uses the name that the input gives it.
681fn resolve_against(schema: &DFSchema, col: &Column) -> Option<Column> {
682    schema
683        .qualified_field_from_column(col)
684        .ok()
685        .map(Column::from)
686}
687
688/// Build an extraction projection above the target node (shared by both passes).
689///
690/// If the target is an existing projection, merges into it. This requires
691/// resolving column references through the projection's rename mapping:
692/// if the projection has `user AS u`, and an extracted expression references
693/// `u['name']`, we must rewrite it to `user['name']` since the merged
694/// projection reads from the same input as the original.
695///
696/// Deduplicates by resolved expression equality and adds pass-through
697/// columns as needed. Otherwise builds a fresh projection with extracted
698/// expressions + ALL input schema columns.
699fn build_extraction_projection_impl(
700    extracted_exprs: &[(Expr, String)],
701    columns_needed: &IndexSet<Column>,
702    target: &Arc<LogicalPlan>,
703    target_schema: &DFSchema,
704) -> Result<Projection> {
705    if let LogicalPlan::Projection(existing) = target.as_ref() {
706        // Merge into existing projection
707        let mut proj_exprs = existing.expr.clone();
708
709        // Build a map of existing expressions (by Expr equality) to their aliases
710        let existing_extractions: IndexMap<Expr, String> = existing
711            .expr
712            .iter()
713            .filter_map(|e| {
714                if let Expr::Alias(alias) = e
715                    && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
716                {
717                    return Some((*alias.expr.clone(), alias.name.clone()));
718                }
719                None
720            })
721            .collect();
722
723        // Resolve column references through the projection's rename mapping
724        let replace_map = build_projection_replace_map(existing);
725
726        // Add new extracted expressions, resolving column refs through the projection
727        for (expr, alias) in extracted_exprs {
728            let resolved = replace_cols_by_name(expr.clone().alias(alias), &replace_map)?;
729            let resolved_inner = if let Expr::Alias(a) = &resolved {
730                a.expr.as_ref()
731            } else {
732                &resolved
733            };
734            if let Some(existing_alias) = existing_extractions.get(resolved_inner) {
735                // Same expression already extracted under a different alias —
736                // add the expression with the new alias so both names are
737                // available in the output. We can't reference the existing alias
738                // as a column within the same projection, so we duplicate the
739                // computation.
740                if existing_alias != alias {
741                    proj_exprs.push(resolved);
742                }
743            } else {
744                proj_exprs.push(resolved);
745            }
746        }
747
748        // Add any new pass-through columns that aren't already in the projection.
749        // We check against existing.input.schema() (the projection's source) rather
750        // than target_schema (the projection's output) because columns produced
751        // by alias expressions (e.g., CSE's __common_expr_N) exist in the output but
752        // not the input, and cannot be added as pass-through Column references.
753        //
754        // Resolve the pass-through columns of `existing` (including same-name
755        // aliases such as `t.c AS c`) and the columns in `columns_needed`
756        // against the input schema before comparing them. Otherwise a bare `c`
757        // and a qualified `t.c` do not match, and the merged projection holds
758        // both, which `Projection::try_new` rejects as ambiguous.
759        let input_schema = existing.input.schema();
760        let existing_cols: IndexSet<Column> = existing
761            .expr
762            .iter()
763            .filter_map(|e| resolve_against(input_schema, passthrough_column(e)?))
764            .collect();
765
766        // The names the merged projection already produces. The merge keeps
767        // every expression of `existing`, so the parent can still read each of
768        // these names, and a pass-through column that carries one of them makes
769        // the output schema ambiguous.
770        let output_names: std::collections::HashSet<&str> = existing
771            .schema
772            .fields()
773            .iter()
774            .map(|f| f.name().as_str())
775            .collect();
776
777        for col in columns_needed {
778            // The projection produces this name, so the parent reads it from the
779            // projection's own output. Do not resolve the name through the rename
780            // map: a rename such as `t.a AS b` is a computed output, and its
781            // input column `t.a` beside the output field `a` of a second rename
782            // gives an ambiguous schema (issue #25446).
783            if output_names.contains(col.name.as_str()) {
784                continue;
785            }
786            let col_expr = Expr::Column(col.clone());
787            let resolved = replace_cols_by_name(col_expr, &replace_map)?;
788            if let Expr::Column(resolved_col) = &resolved
789                && let Some(input_col) = resolve_against(input_schema, resolved_col)
790                && !existing_cols.contains(&input_col)
791                && !output_names.contains(input_col.name.as_str())
792            {
793                proj_exprs.push(Expr::Column(input_col));
794            }
795            // Skip a column that resolves to a non-column expr: the existing
796            // projection already computes it. Also skip a column that is not in
797            // the input or is ambiguous there: no single spelling is correct.
798        }
799
800        Projection::try_new(proj_exprs, Arc::clone(&existing.input))
801    } else {
802        // Build new projection with extracted expressions + all input columns
803        let mut proj_exprs =
804            Vec::with_capacity(extracted_exprs.len() + target_schema.fields().len());
805        for (expr, alias) in extracted_exprs {
806            proj_exprs.push(expr.clone().alias(alias));
807        }
808        for (qualifier, field) in target_schema.iter() {
809            proj_exprs.push(Expr::from((qualifier, field)));
810        }
811        Projection::try_new(proj_exprs, Arc::clone(target))
812    }
813}
814
815// =============================================================================
816// Pass 2: PushDownLeafProjections
817// =============================================================================
818
819/// Pushes extraction projections down through schema-preserving nodes towards
820/// leaf nodes (pass 2 of 2, after [`ExtractLeafExpressions`]).
821///
822/// Handles two types of projections:
823/// - **Pure extraction projections** (all `__datafusion_extracted` aliases + columns):
824///   pushes through Filter/Sort/Limit, merges into existing projections, or routes
825///   into multi-input node inputs (Join, SubqueryAlias, etc.)
826/// - **Mixed projections** (user projections containing `MoveTowardsLeafNodes`
827///   sub-expressions): splits into a recovery projection + extraction projection,
828///   then pushes the extraction projection down.
829///
830/// # Example: Pushing through a Filter
831///
832/// After pass 1, the extraction projection sits directly below the filter:
833/// ```text
834/// Projection: id, user                                                              <-- recovery
835///   Filter: __datafusion_extracted_1 = 'active'
836///     Projection: user['status'] AS __datafusion_extracted_1, id, user               <-- extraction
837///       TableScan: t [id, user]
838/// ```
839///
840/// Pass 2 pushes the extraction projection through the recovery and filter,
841/// and a subsequent `OptimizeProjections` pass removes the (now-redundant)
842/// recovery projection:
843/// ```text
844/// Filter: __datafusion_extracted_1 = 'active'
845///   Projection: user['status'] AS __datafusion_extracted_1, id, user                 <-- extraction (pushed down)
846///     TableScan: t [id, user]
847/// ```
848#[derive(Default, Debug)]
849pub struct PushDownLeafProjections {}
850
851impl PushDownLeafProjections {
852    pub fn new() -> Self {
853        Self {}
854    }
855}
856
857impl OptimizerRule for PushDownLeafProjections {
858    fn name(&self) -> &str {
859        "push_down_leaf_projections"
860    }
861
862    fn apply_order(&self) -> Option<ApplyOrder> {
863        Some(ApplyOrder::TopDown)
864    }
865
866    fn rewrite(
867        &self,
868        plan: LogicalPlan,
869        config: &dyn OptimizerConfig,
870    ) -> Result<Transformed<LogicalPlan>> {
871        if !config.options().optimizer.enable_leaf_expression_pushdown {
872            return Ok(Transformed::no(plan));
873        }
874        let alias_generator = config.alias_generator();
875        match try_push_input(&plan, alias_generator)? {
876            Some(new_plan) => Ok(Transformed::yes(new_plan)),
877            None => Ok(Transformed::no(plan)),
878        }
879    }
880}
881
882/// Attempts to push a projection's extractable expressions further down.
883///
884/// Returns `Some(new_subtree)` if the projection was pushed down or merged,
885/// `None` if there is nothing to push or the projection sits above a barrier.
886fn try_push_input(
887    input: &LogicalPlan,
888    alias_generator: &Arc<AliasGenerator>,
889) -> Result<Option<LogicalPlan>> {
890    let LogicalPlan::Projection(proj) = input else {
891        return Ok(None);
892    };
893    split_and_push_projection(proj, alias_generator)
894}
895
896/// If this is a passthrough column.  I.e,
897///
898///  - A bare column expression
899///  - A trivial alias rename (i.e, `p.column AS column`)
900fn passthrough_column(expr: &Expr) -> Option<&Column> {
901    match expr {
902        Expr::Column(col) => Some(col),
903        Expr::Alias(alias) => match alias.expr.as_ref() {
904            Expr::Column(col) if col.name == alias.name => Some(col),
905            _ => None,
906        },
907        _ => None,
908    }
909}
910
911/// Returns `true` if merging the extracted `pairs` (and the pass-through
912/// `columns_needed`) into `child` would inline a `KeepInPlace` definition into
913/// more than one reference site — e.g. a struct-returning UDF `f(c)` behind both
914/// `f(c)['a']` and `f(c)['b']`, or behind `f(c)['a']` and a bare `f(c)`.
915///
916/// `CommonSubexprEliminate` hoists such an expression into a shared column so it
917/// runs once; [`build_extraction_projection_impl`] then resolves that column
918/// back to its definition and re-duplicates it. Mirrors the
919/// `optimize_projections` merge guard (#8296): a compute-once expression used
920/// more than once stays in place.
921fn merge_would_duplicate_kept_expr(
922    pairs: &[(Expr, String)],
923    columns_needed: &IndexSet<Column>,
924    child: &Projection,
925) -> bool {
926    // Columns whose `KeepInPlace` definition must stay put; inlining one would
927    // duplicate a compute-once expression. Plain columns, pushable exprs, and
928    // literals are all cheap to duplicate, so only `KeepInPlace` counts.
929    let kept_columns: std::collections::HashSet<String> = child
930        .schema
931        .iter()
932        .zip(child.expr.iter())
933        .filter_map(|((qualifier, field), expr)| {
934            if matches!(expr.placement(), ExpressionPlacement::KeepInPlace) {
935                Some(Column::from((qualifier, field)).flat_name())
936            } else {
937                None
938            }
939        })
940        .collect();
941    if kept_columns.is_empty() {
942        return false;
943    }
944
945    // Count every site that references a kept column. A pair that references the
946    // same kept column twice still inlines one copy, so count each pair at most
947    // once per column.
948    let mut usage: HashMap<String, usize> = HashMap::new();
949    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
950    for (expr, _alias) in pairs {
951        seen.clear();
952        for col in expr.column_refs() {
953            let name = col.flat_name();
954            if kept_columns.contains(&name) && seen.insert(name.clone()) {
955                *usage.entry(name).or_insert(0) += 1;
956            }
957        }
958    }
959    // Pass-through / pre-existing-alias inputs are additional reference sites:
960    // a bare `f(c)` alongside `f(c)['a']` also pins the compute-once column, so
961    // counting only `pairs` under-counted and re-duplicated it (#23655).
962    for col in columns_needed {
963        let name = col.flat_name();
964        if kept_columns.contains(&name) {
965            *usage.entry(name).or_insert(0) += 1;
966        }
967    }
968    usage.values().any(|&count| count > 1)
969}
970
971/// Splits a projection into extractable pieces, pushes them towards leaf
972/// nodes, and adds a recovery projection if needed.
973///
974/// Handles both:
975/// - **Pure extraction projections** (all `__datafusion_extracted` aliases + columns)
976/// - **Mixed projections** (containing `MoveTowardsLeafNodes` sub-expressions)
977///
978/// Returns `Some(new_subtree)` if extractions were pushed down,
979/// `None` if there is nothing to extract or push.
980///
981/// # Example: Mixed Projection
982///
983/// ```text
984/// Input plan:
985///   Projection: user['name'] IS NOT NULL AS has_name, id
986///     Filter: ...
987///       TableScan
988///
989/// Phase 1 (Split):
990///   extraction_pairs: [(user['name'], "__datafusion_extracted_1")]
991///   recovery_exprs:   [__datafusion_extracted_1 IS NOT NULL AS has_name, id]
992///
993/// Phase 2 (Push):
994///   Push extraction projection through Filter toward TableScan
995///
996/// Phase 3 (Recovery):
997///   Projection: __datafusion_extracted_1 IS NOT NULL AS has_name, id       <-- recovery
998///     Filter: ...
999///       Projection: user['name'] AS __datafusion_extracted_1, id           <-- extraction (pushed)
1000///         TableScan
1001/// ```
1002fn split_and_push_projection(
1003    proj: &Projection,
1004    alias_generator: &Arc<AliasGenerator>,
1005) -> Result<Option<LogicalPlan>> {
1006    // Fast pre-check: skip if there are no pre-existing extracted aliases
1007    // and no new extractable expressions.
1008    let has_existing_extracted = proj.expr.iter().any(|e| {
1009        matches!(e, Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX))
1010    });
1011    if !has_existing_extracted && !has_extractable_expr(&proj.expr) {
1012        return Ok(None);
1013    }
1014
1015    let input = &proj.input;
1016    let input_schema = input.schema();
1017
1018    // ── Phase 1: Split ──────────────────────────────────────────────────
1019    // For each projection expression, collect extraction pairs and build
1020    // recovery expressions.
1021    //
1022    // Pre-existing `__datafusion_extracted` aliases are inserted into the
1023    // extractor's `IndexMap` with the **full** `Expr::Alias(…)` as the key,
1024    // so the alias name participates in equality. This prevents collisions
1025    // when CSE rewrites produce the same inner expression under different
1026    // alias names (e.g. `__common_expr_4 AS __datafusion_extracted_1` and
1027    // `__common_expr_4 AS __datafusion_extracted_3`). New extractions from
1028    // `routing_extract` use bare (non-Alias) keys and get normal dedup.
1029    //
1030    // When building the final `extraction_pairs`, the Alias wrapper is
1031    // stripped so consumers see the usual `(inner_expr, alias_name)` tuples.
1032
1033    let mut extractors = vec![LeafExpressionExtractor::new(
1034        input_schema.as_ref(),
1035        alias_generator,
1036    )];
1037    let input_column_sets = vec![schema_columns(input_schema.as_ref())];
1038
1039    let original_schema = proj.schema.as_ref();
1040    let mut recovery_exprs: Vec<Expr> = Vec::with_capacity(proj.expr.len());
1041    let mut has_new_extractions = false;
1042    let mut proj_exprs_captured: usize = 0;
1043
1044    for (expr, (qualifier, field)) in proj.expr.iter().zip(original_schema.iter()) {
1045        if let Some(col) = passthrough_column(expr) {
1046            // Pass-through — the input already produces this column, so
1047            // there is nothing to extract; just track it in the extractor.
1048            extractors[0].columns_needed.insert(col.clone());
1049            recovery_exprs.push(expr.clone());
1050            proj_exprs_captured += 1;
1051        } else if let Expr::Alias(alias) = expr
1052            && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
1053        {
1054            // Insert the full Alias expression as the key so that
1055            // distinct alias names don't collide in the IndexMap.
1056            let alias_name = alias.name.clone();
1057
1058            for col_ref in alias.expr.column_refs() {
1059                extractors[0].columns_needed.insert(col_ref.clone());
1060            }
1061
1062            extractors[0]
1063                .extracted
1064                .insert(expr.clone(), alias_name.clone());
1065            recovery_exprs.push(Expr::Column(Column::new_unqualified(&alias_name)));
1066            proj_exprs_captured += 1;
1067        } else {
1068            // Everything else: run through routing_extract
1069            let transformed =
1070                routing_extract(expr.clone(), &mut extractors, &input_column_sets)?;
1071            if transformed.transformed {
1072                has_new_extractions = true;
1073            }
1074            let transformed_expr = transformed.data;
1075
1076            // Build recovery expression, aliasing back to original name if needed
1077            let original_name = field.name();
1078            let needs_alias = if let Expr::Column(col) = &transformed_expr {
1079                col.name.as_str() != original_name
1080            } else {
1081                let expr_name = transformed_expr.schema_name().to_string();
1082                original_name != &expr_name
1083            };
1084            let recovery_expr = if needs_alias {
1085                transformed_expr
1086                    .clone()
1087                    .alias_qualified(qualifier.cloned(), original_name)
1088            } else {
1089                transformed_expr.clone()
1090            };
1091
1092            recovery_exprs.push(recovery_expr);
1093        }
1094    }
1095
1096    // Build extraction_pairs, stripping the Alias wrapper from pre-existing
1097    // entries (they used the full Alias as the map key to avoid dedup).
1098    let extractor = &extractors[0];
1099    let extraction_pairs: Vec<(Expr, String)> = extractor
1100        .extracted
1101        .iter()
1102        .map(|(e, a)| match e {
1103            Expr::Alias(alias) => (*alias.expr.clone(), a.clone()),
1104            _ => (e.clone(), a.clone()),
1105        })
1106        .collect();
1107    let columns_needed = &extractor.columns_needed;
1108
1109    // If no extractions found, nothing to do
1110    if extraction_pairs.is_empty() {
1111        return Ok(None);
1112    }
1113
1114    // Pushing into an input that is already a projection merges into it and
1115    // inlines the referenced columns' definitions. Leave the projection alone
1116    // when that would duplicate a volatile computation.
1117    if would_duplicate_volatile(
1118        extraction_pairs.iter().map(|(expr, _)| expr),
1119        input.as_ref(),
1120    ) {
1121        return Ok(None);
1122    }
1123
1124    // Merging here would re-inline an expression `CommonSubexprEliminate` hoisted
1125    // to run once, undoing it (issue #23655); leave the projection in place.
1126    if let LogicalPlan::Projection(child) = input.as_ref()
1127        && merge_would_duplicate_kept_expr(&extraction_pairs, columns_needed, child)
1128    {
1129        return Ok(None);
1130    }
1131
1132    // ── Phase 2: Push down ──────────────────────────────────────────────
1133    let proj_input = Arc::clone(&proj.input);
1134    let pushed = push_extraction_pairs(
1135        &extraction_pairs,
1136        columns_needed,
1137        proj,
1138        &proj_input,
1139        alias_generator,
1140        proj_exprs_captured,
1141    )?;
1142
1143    // ── Phase 3: Recovery ───────────────────────────────────────────────
1144    // Determine the base plan: either the pushed result or an in-place extraction.
1145    let base_plan = match pushed {
1146        Some(plan) => plan,
1147        None => {
1148            if !has_new_extractions {
1149                // Only pre-existing __datafusion_extracted aliases and columns, no new
1150                // extractions from routing_extract. The original projection is
1151                // already an extraction projection that couldn't be pushed
1152                // further. Return None. This return also ends the recursion
1153                // of the `try_push_input` call below, which comes back here
1154                // with a pure extraction projection.
1155                return Ok(None);
1156            }
1157            // Build the extraction projection in place, then push it. It is a
1158            // pure extraction projection, which can go through nodes that the
1159            // original projection cannot.
1160            let input_arc = Arc::clone(input);
1161            let extraction = LogicalPlan::Projection(build_extraction_projection_impl(
1162                &extraction_pairs,
1163                columns_needed,
1164                &input_arc,
1165                input_schema.as_ref(),
1166            )?);
1167            match try_push_input(&extraction, alias_generator)? {
1168                Some(pushed) => pushed,
1169                // The extraction projection cannot move below `input`. Leave
1170                // the original projection unchanged: the split would put the
1171                // extraction projection on the same input, and
1172                // `OptimizeProjections` merges the recovery and extraction
1173                // projections back into the original projection. The rules
1174                // would then undo each other in every optimizer pass. The
1175                // source absorbs the leaf expressions of the original
1176                // projection just as well.
1177                None => return Ok(None),
1178            }
1179        }
1180    };
1181
1182    // The recovery projection restores the original projection's output. We need
1183    // it whenever `base_plan` no longer exposes the same set of output column
1184    // names, which happens two ways:
1185    //   * a column is *renamed* — a transformed expression now surfaces as its
1186    //     internal `__datafusion_extracted_*` alias instead of the original name;
1187    //   * a column is *leaked* — pushing the projection down widens `base_plan`
1188    //     with an inner extraction projection's *other* extracted aliases bubbling
1189    //     up through a Filter. A schema-caching parent like SubqueryAlias then
1190    //     keeps a stale schema (see `map_children` in `logical_plan/tree_node.rs`)
1191    //     and the later `optimize_projections` pass fails to resolve columns.
1192    //
1193    // Both are captured by comparing the *set of unqualified field names*. We
1194    // compare by unqualified name rather than the full qualified schema on
1195    // purpose: extracted aliases are globally unique, so name-only comparison is
1196    // unambiguous for them, while it ignores the benign column reordering and the
1197    // `SubqueryAlias` re-qualification (`sub.__datafusion_extracted_1` vs
1198    // `__datafusion_extracted_1`) that a qualified/ordered comparison would
1199    // spuriously treat as drift, stacking redundant recovery projections.
1200    //
1201    // A name comparison alone is not sufficient. A name says nothing about the
1202    // *value* behind it. Take the projection
1203    // `(- t.a) AS a, t.s, get_field(t.s, "b") AS __datafusion_extracted_1`. When
1204    // the extraction goes below it, the pushed plan keeps every name, but it
1205    // exposes the table column `t.a` where the projection computed `- t.a`. If
1206    // the recovery projection goes away, the computed column becomes its own
1207    // input column and the query gives wrong results. See
1208    // <https://github.com/apache/datafusion/issues/25414>.
1209    //
1210    // So the recovery projection also stays when a recovery expression computes
1211    // a value, that is, when it is not a pass-through of a column.
1212    let base_names: BTreeSet<&str> = base_plan
1213        .schema()
1214        .fields()
1215        .iter()
1216        .map(|f| f.name().as_str())
1217        .collect();
1218    let original_names: BTreeSet<&str> = original_schema
1219        .fields()
1220        .iter()
1221        .map(|f| f.name().as_str())
1222        .collect();
1223    let computes_a_value = recovery_exprs
1224        .iter()
1225        .any(|expr| passthrough_column(expr).is_none());
1226    let needs_recovery = base_names != original_names || computes_a_value;
1227
1228    // Wrap with recovery projection if the output schema changed
1229    if needs_recovery {
1230        let recovery = LogicalPlan::Projection(Projection::try_new(
1231            recovery_exprs,
1232            Arc::new(base_plan),
1233        )?);
1234        Ok(Some(recovery))
1235    } else {
1236        Ok(Some(base_plan))
1237    }
1238}
1239
1240/// Returns true if `exprs` are the expressions of a *pure extraction
1241/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)`
1242/// or a bare `Column`, and there is at least one extraction alias.
1243///
1244/// Such projections can safely be pushed further without re-extraction.
1245///
1246/// [`PushDownFilter`](crate::push_down_filter::PushDownFilter) uses the same
1247/// predicate to keep a filter above such a projection. See the module
1248/// documentation for the precedence rule.
1249pub(crate) fn is_pure_extraction_projection(exprs: &[Expr]) -> bool {
1250    let mut has_extraction = false;
1251    for expr in exprs {
1252        match expr {
1253            Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX) => {
1254                has_extraction = true;
1255            }
1256            Expr::Column(_) => {}
1257            _ => return false,
1258        }
1259    }
1260    has_extraction
1261}
1262
1263/// Pushes extraction pairs down through the projection's input node,
1264/// dispatching to the appropriate handler based on the input node type.
1265fn push_extraction_pairs(
1266    pairs: &[(Expr, String)],
1267    columns_needed: &IndexSet<Column>,
1268    proj: &Projection,
1269    proj_input: &Arc<LogicalPlan>,
1270    alias_generator: &Arc<AliasGenerator>,
1271    proj_exprs_captured: usize,
1272) -> Result<Option<LogicalPlan>> {
1273    match proj_input.as_ref() {
1274        // Merge into existing projection, then try to push the result further down.
1275        // Only merge when every expression in the outer projection is fully
1276        // captured as either an extraction pair (Case A: __datafusion_extracted
1277        // alias) or a plain column (Case B). Uncaptured expressions (e.g.
1278        // `col AS __common_expr_1` from CSE, or complex expressions with
1279        // extracted sub-parts) would be lost during the merge.
1280        LogicalPlan::Projection(_) if proj_exprs_captured == proj.expr.len() => {
1281            let target_schema = Arc::clone(proj_input.schema());
1282            let merged = build_extraction_projection_impl(
1283                pairs,
1284                columns_needed,
1285                proj_input,
1286                target_schema.as_ref(),
1287            )?;
1288            let merged_is_pure = is_pure_extraction_projection(&merged.expr);
1289            let merged_plan = LogicalPlan::Projection(merged);
1290
1291            // After merging, try to push the result further down, but ONLY
1292            // if the merged result is still a pure extraction projection
1293            // (all __datafusion_extracted aliases + columns). If the merge inherited
1294            // bare MoveTowardsLeafNodes expressions from the inner projection,
1295            // pushing would re-extract them into new aliases and fail when
1296            // the (None, true) fallback can't find the original aliases.
1297            // This handles: Extraction → Recovery(cols) → Filter → ... → TableScan
1298            // by pushing through the recovery projection AND the filter in one pass.
1299            if merged_is_pure
1300                && let Some(pushed) = try_push_input(&merged_plan, alias_generator)?
1301            {
1302                return Ok(Some(pushed));
1303            }
1304            Ok(Some(merged_plan))
1305        }
1306        // Generic: handles Filter/Sort/Limit (via recursion),
1307        // SubqueryAlias (with qualifier remap in try_push_into_inputs),
1308        // Join, and anything else.
1309        // Safely bails out for nodes that don't pass through extracted
1310        // columns (Aggregate, Window) via the output schema check.
1311        _ => try_push_into_inputs(
1312            pairs,
1313            columns_needed,
1314            proj_input.as_ref(),
1315            alias_generator,
1316        ),
1317    }
1318}
1319
1320/// Routes extraction pairs and columns to the appropriate inputs.
1321///
1322/// - **Union**: broadcasts to every input via [`remap_pairs_and_columns`].
1323/// - **Other nodes**: routes each expression to the one input that owns
1324///   all of its column references (via [`find_owning_input`]).
1325///
1326/// Returns `None` if any expression can't be routed or no input has pairs.
1327fn route_to_inputs(
1328    pairs: &[(Expr, String)],
1329    columns: &IndexSet<Column>,
1330    node: &LogicalPlan,
1331    input_column_sets: &[std::collections::HashSet<ColumnReference>],
1332    input_schemas: &[Arc<DFSchema>],
1333) -> Result<Option<Vec<ExtractionTarget>>> {
1334    let num_inputs = input_schemas.len();
1335    let mut per_input: Vec<ExtractionTarget> = (0..num_inputs)
1336        .map(|_| ExtractionTarget {
1337            pairs: vec![],
1338            columns: IndexSet::new(),
1339        })
1340        .collect();
1341
1342    if matches!(node, LogicalPlan::Union(_)) {
1343        // Union output schema and each input schema have the same fields by
1344        // index but may differ in qualifiers (e.g. output `s` vs input
1345        // `simple_struct.s`). Remap pairs/columns to each input's space.
1346        let union_schema = node.schema();
1347        for (idx, input_schema) in input_schemas.iter().enumerate() {
1348            per_input[idx] =
1349                remap_pairs_and_columns(pairs, columns, union_schema, input_schema)?;
1350        }
1351    } else {
1352        for (expr, alias) in pairs {
1353            match find_owning_input(expr, input_column_sets) {
1354                Some(idx) => per_input[idx].pairs.push((expr.clone(), alias.clone())),
1355                None => return Ok(None), // Cross-input expression — bail out
1356            }
1357        }
1358        for col in columns {
1359            let col_expr = Expr::Column(col.clone());
1360            match find_owning_input(&col_expr, input_column_sets) {
1361                Some(idx) => {
1362                    per_input[idx].columns.insert(col.clone());
1363                }
1364                None => return Ok(None), // Ambiguous column — bail out
1365            }
1366        }
1367    }
1368
1369    // Check at least one input has extractions to push
1370    if per_input.iter().all(|t| t.pairs.is_empty()) {
1371        return Ok(None);
1372    }
1373
1374    Ok(Some(per_input))
1375}
1376
1377/// Pushes extraction expressions into a node's inputs by routing each
1378/// expression to the input that owns all of its column references.
1379///
1380/// Works for any number of inputs (1, 2, …N). For single-input nodes,
1381/// all expressions trivially route to that input. For multi-input nodes
1382/// (Join, etc.), each expression is routed to the side that owns its columns.
1383///
1384/// Returns `Some(new_node)` if all expressions could be routed AND the
1385/// rebuilt node's output schema contains all extracted aliases.
1386/// Returns `None` if any expression references columns from multiple inputs
1387/// or the node doesn't pass through the extracted columns.
1388///
1389/// # Example: Join with expressions from both sides
1390///
1391/// ```text
1392/// Extraction projection above a Join:
1393///   Projection: left.user['name'] AS __datafusion_extracted_1, right.order['total'] AS __datafusion_extracted_2, ...
1394///     Join: left.id = right.user_id
1395///       TableScan: left [id, user]
1396///       TableScan: right [user_id, order]
1397///
1398/// After routing each expression to its owning input:
1399///   Join: left.id = right.user_id
1400///     Projection: user['name'] AS __datafusion_extracted_1, id, user              <-- left-side extraction
1401///       TableScan: left [id, user]
1402///     Projection: order['total'] AS __datafusion_extracted_2, user_id, order      <-- right-side extraction
1403///       TableScan: right [user_id, order]
1404/// ```
1405fn try_push_into_inputs(
1406    pairs: &[(Expr, String)],
1407    columns_needed: &IndexSet<Column>,
1408    node: &LogicalPlan,
1409    alias_generator: &Arc<AliasGenerator>,
1410) -> Result<Option<LogicalPlan>> {
1411    let inputs = node.inputs();
1412    if inputs.is_empty() {
1413        return Ok(None);
1414    }
1415
1416    // Unnest may output a column with the same name but different value/type
1417    // than its input column. Name-based routing cannot distinguish those.
1418    if matches!(node, LogicalPlan::Unnest(_)) {
1419        return Ok(None);
1420    }
1421
1422    // SubqueryAlias remaps qualifiers between input and output.
1423    // Rewrite pairs/columns from alias-space to input-space before routing.
1424    let remapped = if let LogicalPlan::SubqueryAlias(sa) = node {
1425        remap_pairs_and_columns(pairs, columns_needed, &sa.schema, sa.input.schema())?
1426    } else {
1427        ExtractionTarget {
1428            pairs: pairs.to_vec(),
1429            columns: columns_needed.clone(),
1430        }
1431    };
1432    let pairs = &remapped.pairs[..];
1433    let columns_needed = &remapped.columns;
1434
1435    // Build per-input schemas and column sets for routing
1436    let input_schemas: Vec<Arc<DFSchema>> =
1437        inputs.iter().map(|i| Arc::clone(i.schema())).collect();
1438    let input_column_sets: Vec<std::collections::HashSet<ColumnReference>> =
1439        input_schemas.iter().map(|s| schema_columns(s)).collect();
1440
1441    // Route pairs and columns to the appropriate inputs
1442    let Some(per_input) = route_to_inputs(
1443        pairs,
1444        columns_needed,
1445        node,
1446        &input_column_sets,
1447        &input_schemas,
1448    )?
1449    else {
1450        return Ok(None);
1451    };
1452
1453    let num_inputs = inputs.len();
1454
1455    // Build per-input extraction projections and push them as far as possible
1456    // immediately. This is critical because map_children preserves cached schemas,
1457    // so if the TopDown pass later pushes a child further (changing its output
1458    // schema), the parent node's schema becomes stale.
1459    let mut new_inputs: Vec<LogicalPlan> = Vec::with_capacity(num_inputs);
1460    let is_union = matches!(node, LogicalPlan::Union(_));
1461    for (idx, input) in inputs.into_iter().enumerate() {
1462        if per_input[idx].pairs.is_empty() {
1463            new_inputs.push(input.clone());
1464        } else {
1465            // Merging into an input projection inlines the referenced columns'
1466            // definitions; bail out when that would duplicate a volatile
1467            // computation.
1468            if would_duplicate_volatile(
1469                per_input[idx].pairs.iter().map(|(expr, _)| expr),
1470                input,
1471            ) {
1472                return Ok(None);
1473            }
1474            let input_arc = Arc::new(input.clone());
1475            let target_schema = Arc::clone(input.schema());
1476            let proj = build_extraction_projection_impl(
1477                &per_input[idx].pairs,
1478                &per_input[idx].columns,
1479                &input_arc,
1480                target_schema.as_ref(),
1481            )?;
1482            // Verify all requested aliases appear in the projection's output.
1483            // A merge may deduplicate if the same expression already exists
1484            // under a different alias, leaving the requested alias missing.
1485            let proj_schema = proj.schema.as_ref();
1486            for (_expr, alias) in &per_input[idx].pairs {
1487                if !proj_schema.fields().iter().any(|f| f.name() == alias) {
1488                    return Ok(None);
1489                }
1490            }
1491            let proj_plan = LogicalPlan::Projection(proj);
1492            // Try to push the extraction projection further down within
1493            // this input (e.g., through Filter → existing extraction projection).
1494            // This ensures the input's output schema is stable and won't change
1495            // when the TopDown pass later visits children.
1496            let pushed = match try_push_input(&proj_plan, alias_generator)? {
1497                Some(pushed) => pushed,
1498                None => proj_plan,
1499            };
1500            if is_union {
1501                new_inputs.push(align_union_input(pushed, &per_input[idx])?);
1502            } else {
1503                new_inputs.push(pushed);
1504            }
1505        }
1506    }
1507
1508    // Rebuild the node with new inputs
1509    let new_node = node.with_new_exprs(node.expressions(), new_inputs)?;
1510
1511    // Safety check: verify all extracted aliases appear in the rebuilt
1512    // node's output schema. Nodes like Aggregate define their own output
1513    // and won't pass through extracted columns — bail out for those.
1514    let output_schema = new_node.schema();
1515    for (_expr, alias) in pairs {
1516        if !output_schema.fields().iter().any(|f| f.name() == alias) {
1517            return Ok(None);
1518        }
1519    }
1520
1521    Ok(Some(new_node))
1522}
1523
1524/// Projects one input of a `Union` to the extracted aliases, in pair order,
1525/// followed by the needed columns, in column order.
1526///
1527/// `Union` matches its inputs by position, not by name. A merge into an
1528/// existing projection appends the aliases after the existing expressions,
1529/// while a new projection puts them first. Without this, two inputs that take
1530/// different paths disagree on the position of each column, and the union
1531/// reads the alias of one input from an unrelated column of another input.
1532fn align_union_input(
1533    input: LogicalPlan,
1534    target: &ExtractionTarget,
1535) -> Result<LogicalPlan> {
1536    let exprs: Vec<Expr> = target
1537        .pairs
1538        .iter()
1539        .map(|(_, alias)| Expr::Column(Column::new_unqualified(alias)))
1540        .chain(target.columns.iter().map(|col| Expr::Column(col.clone())))
1541        .collect();
1542    // Skip the extra projection when the input already has this exact layout.
1543    let fields = input.schema().fields();
1544    let already_aligned = fields.len() == exprs.len()
1545        && target
1546            .pairs
1547            .iter()
1548            .map(|(_, alias)| alias.as_str())
1549            .chain(target.columns.iter().map(|col| col.name.as_str()))
1550            .zip(fields.iter())
1551            .all(|(name, field)| field.name() == name);
1552    if already_aligned {
1553        return Ok(input);
1554    }
1555    Projection::try_new(exprs, Arc::new(input)).map(LogicalPlan::Projection)
1556}
1557
1558#[cfg(test)]
1559mod tests {
1560
1561    use super::*;
1562    use crate::common_subexpr_eliminate::CommonSubexprEliminate;
1563    use crate::optimize_projections::OptimizeProjections;
1564    use crate::test::udfs::{PlacementTestUDF, get_field_like};
1565    use crate::test::*;
1566    use crate::{Optimizer, OptimizerContext};
1567    use datafusion_expr::expr::ScalarFunction;
1568    use datafusion_expr::{
1569        ScalarUDF, Volatility, col, lit, logical_plan::builder::LogicalPlanBuilder,
1570    };
1571
1572    fn leaf_udf(expr: Expr, name: &str) -> Expr {
1573        Expr::ScalarFunction(ScalarFunction::new_udf(
1574            Arc::new(ScalarUDF::new_from_impl(
1575                PlacementTestUDF::new()
1576                    .with_placement(ExpressionPlacement::MoveTowardsLeafNodes),
1577            )),
1578            vec![expr, lit(name)],
1579        ))
1580    }
1581
1582    /// A stand-in for `random()`: a volatile expression that must be evaluated
1583    /// exactly once per row.
1584    fn volatile_udf(expr: Expr) -> Expr {
1585        Expr::ScalarFunction(ScalarFunction::new_udf(
1586            Arc::new(ScalarUDF::new_from_impl(
1587                PlacementTestUDF::new()
1588                    .with_placement(ExpressionPlacement::KeepInPlace)
1589                    .with_volatility(Volatility::Volatile),
1590            )),
1591            vec![expr],
1592        ))
1593    }
1594
1595    // =========================================================================
1596    // Combined optimization stage formatter
1597    // =========================================================================
1598
1599    /// Runs all 4 optimization stages and returns a single formatted string.
1600    /// Stages that produce the same plan as the previous stage show
1601    /// "(same as <previous>)" to reduce noise.
1602    ///
1603    /// Stages:
1604    /// 1. **Original** - OptimizeProjections only (baseline)
1605    /// 2. **After Extraction** - + ExtractLeafExpressions
1606    /// 3. **After Pushdown** - + PushDownLeafProjections
1607    /// 4. **Optimized** - + final OptimizeProjections
1608    fn format_optimization_stages(plan: &LogicalPlan) -> Result<String> {
1609        let run = |rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>| -> Result<String> {
1610            let ctx = OptimizerContext::new().with_max_passes(1);
1611            let optimizer = Optimizer::with_rules(rules);
1612            let optimized = optimizer.optimize(plan.clone(), &ctx, |_, _| {})?;
1613            Ok(format!("{optimized}"))
1614        };
1615
1616        let original = run(vec![Arc::new(OptimizeProjections::new())])?;
1617
1618        let after_extract = run(vec![
1619            Arc::new(OptimizeProjections::new()),
1620            Arc::new(ExtractLeafExpressions::new()),
1621        ])?;
1622
1623        let after_pushdown = run(vec![
1624            Arc::new(OptimizeProjections::new()),
1625            Arc::new(ExtractLeafExpressions::new()),
1626            Arc::new(PushDownLeafProjections::new()),
1627        ])?;
1628
1629        let optimized = run(vec![
1630            Arc::new(OptimizeProjections::new()),
1631            Arc::new(ExtractLeafExpressions::new()),
1632            Arc::new(PushDownLeafProjections::new()),
1633            Arc::new(OptimizeProjections::new()),
1634        ])?;
1635
1636        let mut out = format!("## Original Plan\n{original}");
1637
1638        out.push_str("\n\n## After Extraction\n");
1639        if after_extract == original {
1640            out.push_str("(same as original)");
1641        } else {
1642            out.push_str(&after_extract);
1643        }
1644
1645        out.push_str("\n\n## After Pushdown\n");
1646        if after_pushdown == after_extract {
1647            out.push_str("(same as after extraction)");
1648        } else {
1649            out.push_str(&after_pushdown);
1650        }
1651
1652        out.push_str("\n\n## Optimized\n");
1653        if optimized == after_pushdown {
1654            out.push_str("(same as after pushdown)");
1655        } else {
1656            out.push_str(&optimized);
1657        }
1658
1659        Ok(out)
1660    }
1661
1662    /// Assert all optimization stages for a plan in a single insta snapshot.
1663    macro_rules! assert_stages {
1664        ($plan:expr, @ $expected:literal $(,)?) => {{
1665            let result = format_optimization_stages(&$plan)?;
1666            insta::assert_snapshot!(result, @ $expected);
1667            Ok::<(), datafusion_common::DataFusionError>(())
1668        }};
1669    }
1670
1671    #[test]
1672    fn test_extract_from_filter() -> Result<()> {
1673        let table_scan = test_table_scan_with_struct()?;
1674        let plan = LogicalPlanBuilder::from(table_scan.clone())
1675            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
1676            .select(vec![
1677                table_scan
1678                    .schema()
1679                    .index_of_column_by_name(None, "id")
1680                    .unwrap(),
1681            ])?
1682            .build()?;
1683
1684        assert_stages!(plan, @r#"
1685        ## Original Plan
1686        Projection: test.id
1687          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
1688            TableScan: test projection=[id, user]
1689
1690        ## After Extraction
1691        Projection: test.id
1692          Projection: test.id, test.user
1693            Filter: __datafusion_extracted_1 = Utf8("active")
1694              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
1695                TableScan: test projection=[id, user]
1696
1697        ## After Pushdown
1698        (same as after extraction)
1699
1700        ## Optimized
1701        Projection: test.id
1702          Filter: __datafusion_extracted_1 = Utf8("active")
1703            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id
1704              TableScan: test projection=[id, user]
1705        "#)
1706    }
1707
1708    #[test]
1709    fn test_no_extraction_for_column() -> Result<()> {
1710        let table_scan = test_table_scan()?;
1711        let plan = LogicalPlanBuilder::from(table_scan)
1712            .filter(col("a").eq(lit(1)))?
1713            .build()?;
1714
1715        assert_stages!(plan, @"
1716        ## Original Plan
1717        Filter: test.a = Int32(1)
1718          TableScan: test projection=[a, b, c]
1719
1720        ## After Extraction
1721        (same as original)
1722
1723        ## After Pushdown
1724        (same as after extraction)
1725
1726        ## Optimized
1727        (same as after pushdown)
1728        ")
1729    }
1730
1731    #[test]
1732    fn test_extract_from_projection() -> Result<()> {
1733        let table_scan = test_table_scan_with_struct()?;
1734        let plan = LogicalPlanBuilder::from(table_scan)
1735            .project(vec![leaf_udf(col("user"), "name")])?
1736            .build()?;
1737
1738        assert_stages!(plan, @r#"
1739        ## Original Plan
1740        Projection: leaf_udf(test.user, Utf8("name"))
1741          TableScan: test projection=[user]
1742
1743        ## After Extraction
1744        (same as original)
1745
1746        ## After Pushdown
1747        (same as after extraction)
1748
1749        ## Optimized
1750        (same as after pushdown)
1751        "#)
1752    }
1753
1754    #[test]
1755    fn test_extract_from_projection_with_subexpression() -> Result<()> {
1756        let table_scan = test_table_scan_with_struct()?;
1757        let plan = LogicalPlanBuilder::from(table_scan)
1758            .project(vec![
1759                leaf_udf(col("user"), "name")
1760                    .is_not_null()
1761                    .alias("has_name"),
1762            ])?
1763            .build()?;
1764
1765        assert_stages!(plan, @r#"
1766        ## Original Plan
1767        Projection: leaf_udf(test.user, Utf8("name")) IS NOT NULL AS has_name
1768          TableScan: test projection=[user]
1769
1770        ## After Extraction
1771        (same as original)
1772
1773        ## After Pushdown
1774        (same as after extraction)
1775
1776        ## Optimized
1777        (same as after pushdown)
1778        "#)
1779    }
1780
1781    #[test]
1782    fn test_projection_no_extraction_for_column() -> Result<()> {
1783        let table_scan = test_table_scan()?;
1784        let plan = LogicalPlanBuilder::from(table_scan)
1785            .project(vec![col("a"), col("b")])?
1786            .build()?;
1787
1788        assert_stages!(plan, @"
1789        ## Original Plan
1790        TableScan: test projection=[a, b]
1791
1792        ## After Extraction
1793        (same as original)
1794
1795        ## After Pushdown
1796        (same as after extraction)
1797
1798        ## Optimized
1799        (same as after pushdown)
1800        ")
1801    }
1802
1803    #[test]
1804    fn test_filter_with_deduplication() -> Result<()> {
1805        let table_scan = test_table_scan_with_struct()?;
1806        let field_access = leaf_udf(col("user"), "name");
1807        // Filter with the same expression used twice
1808        let plan = LogicalPlanBuilder::from(table_scan)
1809            .filter(
1810                field_access
1811                    .clone()
1812                    .is_not_null()
1813                    .and(field_access.is_null()),
1814            )?
1815            .build()?;
1816
1817        assert_stages!(plan, @r#"
1818        ## Original Plan
1819        Filter: leaf_udf(test.user, Utf8("name")) IS NOT NULL AND leaf_udf(test.user, Utf8("name")) IS NULL
1820          TableScan: test projection=[id, user]
1821
1822        ## After Extraction
1823        Projection: test.id, test.user
1824          Filter: __datafusion_extracted_1 IS NOT NULL AND __datafusion_extracted_1 IS NULL
1825            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
1826              TableScan: test projection=[id, user]
1827
1828        ## After Pushdown
1829        (same as after extraction)
1830
1831        ## Optimized
1832        (same as after pushdown)
1833        "#)
1834    }
1835
1836    #[test]
1837    fn test_already_leaf_expression_in_filter() -> Result<()> {
1838        let table_scan = test_table_scan_with_struct()?;
1839        let plan = LogicalPlanBuilder::from(table_scan)
1840            .filter(leaf_udf(col("user"), "name").eq(lit("test")))?
1841            .build()?;
1842
1843        assert_stages!(plan, @r#"
1844        ## Original Plan
1845        Filter: leaf_udf(test.user, Utf8("name")) = Utf8("test")
1846          TableScan: test projection=[id, user]
1847
1848        ## After Extraction
1849        Projection: test.id, test.user
1850          Filter: __datafusion_extracted_1 = Utf8("test")
1851            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
1852              TableScan: test projection=[id, user]
1853
1854        ## After Pushdown
1855        (same as after extraction)
1856
1857        ## Optimized
1858        (same as after pushdown)
1859        "#)
1860    }
1861
1862    #[test]
1863    fn test_extract_from_aggregate_group_by() -> Result<()> {
1864        use datafusion_expr::test::function_stub::count;
1865
1866        let table_scan = test_table_scan_with_struct()?;
1867        let plan = LogicalPlanBuilder::from(table_scan)
1868            .aggregate(vec![leaf_udf(col("user"), "status")], vec![count(lit(1))])?
1869            .build()?;
1870
1871        assert_stages!(plan, @r#"
1872        ## Original Plan
1873        Aggregate: groupBy=[[leaf_udf(test.user, Utf8("status"))]], aggr=[[COUNT(Int32(1))]]
1874          TableScan: test projection=[user]
1875
1876        ## After Extraction
1877        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), COUNT(Int32(1))
1878          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
1879            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user
1880              TableScan: test projection=[user]
1881
1882        ## After Pushdown
1883        (same as after extraction)
1884
1885        ## Optimized
1886        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), COUNT(Int32(1))
1887          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
1888            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1
1889              TableScan: test projection=[user]
1890        "#)
1891    }
1892
1893    #[test]
1894    fn test_extract_from_aggregate_args() -> Result<()> {
1895        use datafusion_expr::test::function_stub::count;
1896
1897        let table_scan = test_table_scan_with_struct()?;
1898        let plan = LogicalPlanBuilder::from(table_scan)
1899            .aggregate(
1900                vec![col("user")],
1901                vec![count(leaf_udf(col("user"), "value"))],
1902            )?
1903            .build()?;
1904
1905        assert_stages!(plan, @r#"
1906        ## Original Plan
1907        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(leaf_udf(test.user, Utf8("value")))]]
1908          TableScan: test projection=[user]
1909
1910        ## After Extraction
1911        Projection: test.user, COUNT(__datafusion_extracted_1) AS COUNT(leaf_udf(test.user,Utf8("value")))
1912          Aggregate: groupBy=[[test.user]], aggr=[[COUNT(__datafusion_extracted_1)]]
1913            Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
1914              TableScan: test projection=[user]
1915
1916        ## After Pushdown
1917        (same as after extraction)
1918
1919        ## Optimized
1920        (same as after pushdown)
1921        "#)
1922    }
1923
1924    #[test]
1925    fn test_projection_with_filter_combined() -> Result<()> {
1926        let table_scan = test_table_scan_with_struct()?;
1927        let plan = LogicalPlanBuilder::from(table_scan)
1928            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
1929            .project(vec![leaf_udf(col("user"), "name")])?
1930            .build()?;
1931
1932        assert_stages!(plan, @r#"
1933        ## Original Plan
1934        Projection: leaf_udf(test.user, Utf8("name"))
1935          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
1936            TableScan: test projection=[user]
1937
1938        ## After Extraction
1939        Projection: leaf_udf(test.user, Utf8("name"))
1940          Projection: test.user
1941            Filter: __datafusion_extracted_1 = Utf8("active")
1942              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user
1943                TableScan: test projection=[user]
1944
1945        ## After Pushdown
1946        Projection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
1947          Projection: test.user, __datafusion_extracted_2
1948            Filter: __datafusion_extracted_1 = Utf8("active")
1949              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
1950                TableScan: test projection=[user]
1951
1952        ## Optimized
1953        Projection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
1954          Filter: __datafusion_extracted_1 = Utf8("active")
1955            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
1956              TableScan: test projection=[user]
1957        "#)
1958    }
1959
1960    #[test]
1961    fn test_projection_preserves_alias() -> Result<()> {
1962        let table_scan = test_table_scan_with_struct()?;
1963        let plan = LogicalPlanBuilder::from(table_scan)
1964            .project(vec![leaf_udf(col("user"), "name").alias("username")])?
1965            .build()?;
1966
1967        assert_stages!(plan, @r#"
1968        ## Original Plan
1969        Projection: leaf_udf(test.user, Utf8("name")) AS username
1970          TableScan: test projection=[user]
1971
1972        ## After Extraction
1973        (same as original)
1974
1975        ## After Pushdown
1976        (same as after extraction)
1977
1978        ## Optimized
1979        (same as after pushdown)
1980        "#)
1981    }
1982
1983    /// Test: Projection with different field than Filter
1984    /// `SELECT id, s['label'] FROM t WHERE s['value'] > 150`
1985    /// Both `s['label']` and `s['value']` should be in a single extraction projection.
1986    #[test]
1987    fn test_projection_different_field_from_filter() -> Result<()> {
1988        let table_scan = test_table_scan_with_struct()?;
1989        let plan = LogicalPlanBuilder::from(table_scan)
1990            .filter(leaf_udf(col("user"), "value").gt(lit(150)))?
1991            .project(vec![col("user"), leaf_udf(col("user"), "label")])?
1992            .build()?;
1993
1994        assert_stages!(plan, @r#"
1995        ## Original Plan
1996        Projection: test.user, leaf_udf(test.user, Utf8("label"))
1997          Filter: leaf_udf(test.user, Utf8("value")) > Int32(150)
1998            TableScan: test projection=[user]
1999
2000        ## After Extraction
2001        Projection: test.user, leaf_udf(test.user, Utf8("label"))
2002          Projection: test.user
2003            Filter: __datafusion_extracted_1 > Int32(150)
2004              Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
2005                TableScan: test projection=[user]
2006
2007        ## After Pushdown
2008        Projection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))
2009          Projection: test.user, __datafusion_extracted_2
2010            Filter: __datafusion_extracted_1 > Int32(150)
2011              Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2
2012                TableScan: test projection=[user]
2013
2014        ## Optimized
2015        Projection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))
2016          Filter: __datafusion_extracted_1 > Int32(150)
2017            Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2
2018              TableScan: test projection=[user]
2019        "#)
2020    }
2021
2022    #[test]
2023    fn test_projection_deduplication() -> Result<()> {
2024        let table_scan = test_table_scan_with_struct()?;
2025        let field = leaf_udf(col("user"), "name");
2026        let plan = LogicalPlanBuilder::from(table_scan)
2027            .project(vec![field.clone(), field.clone().alias("name2")])?
2028            .build()?;
2029
2030        assert_stages!(plan, @r#"
2031        ## Original Plan
2032        Projection: leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("name")) AS name2
2033          TableScan: test projection=[user]
2034
2035        ## After Extraction
2036        (same as original)
2037
2038        ## After Pushdown
2039        (same as after extraction)
2040
2041        ## Optimized
2042        (same as after pushdown)
2043        "#)
2044    }
2045
2046    // =========================================================================
2047    // Additional tests for code coverage
2048    // =========================================================================
2049
2050    /// Extractions push through Sort nodes to reach the TableScan.
2051    #[test]
2052    fn test_extract_through_sort() -> Result<()> {
2053        let table_scan = test_table_scan_with_struct()?;
2054        let plan = LogicalPlanBuilder::from(table_scan)
2055            .sort(vec![col("user").sort(true, true)])?
2056            .project(vec![leaf_udf(col("user"), "name")])?
2057            .build()?;
2058
2059        assert_stages!(plan, @r#"
2060        ## Original Plan
2061        Projection: leaf_udf(test.user, Utf8("name"))
2062          Sort: test.user ASC NULLS FIRST
2063            TableScan: test projection=[user]
2064
2065        ## After Extraction
2066        (same as original)
2067
2068        ## After Pushdown
2069        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
2070          Sort: test.user ASC NULLS FIRST
2071            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
2072              TableScan: test projection=[user]
2073
2074        ## Optimized
2075        (same as after pushdown)
2076        "#)
2077    }
2078
2079    /// Extractions push through Limit nodes to reach the TableScan.
2080    #[test]
2081    fn test_extract_through_limit() -> Result<()> {
2082        let table_scan = test_table_scan_with_struct()?;
2083        let plan = LogicalPlanBuilder::from(table_scan)
2084            .limit(0, Some(10))?
2085            .project(vec![leaf_udf(col("user"), "name")])?
2086            .build()?;
2087
2088        assert_stages!(plan, @r#"
2089        ## Original Plan
2090        Projection: leaf_udf(test.user, Utf8("name"))
2091          Limit: skip=0, fetch=10
2092            TableScan: test projection=[user]
2093
2094        ## After Extraction
2095        (same as original)
2096
2097        ## After Pushdown
2098        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
2099          Limit: skip=0, fetch=10
2100            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
2101              TableScan: test projection=[user]
2102
2103        ## Optimized
2104        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
2105          Limit: skip=0, fetch=10
2106            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
2107              TableScan: test projection=[user]
2108        "#)
2109    }
2110
2111    /// Aliased aggregate functions like count(...).alias("cnt") are handled.
2112    #[test]
2113    fn test_extract_from_aliased_aggregate() -> Result<()> {
2114        use datafusion_expr::test::function_stub::count;
2115
2116        let table_scan = test_table_scan_with_struct()?;
2117        let plan = LogicalPlanBuilder::from(table_scan)
2118            .aggregate(
2119                vec![col("user")],
2120                vec![count(leaf_udf(col("user"), "value")).alias("cnt")],
2121            )?
2122            .build()?;
2123
2124        assert_stages!(plan, @r#"
2125        ## Original Plan
2126        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(leaf_udf(test.user, Utf8("value"))) AS cnt]]
2127          TableScan: test projection=[user]
2128
2129        ## After Extraction
2130        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(__datafusion_extracted_1) AS cnt]]
2131          Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
2132            TableScan: test projection=[user]
2133
2134        ## After Pushdown
2135        (same as after extraction)
2136
2137        ## Optimized
2138        (same as after pushdown)
2139        "#)
2140    }
2141
2142    /// Aggregates with no MoveTowardsLeafNodes expressions return unchanged.
2143    #[test]
2144    fn test_aggregate_no_extraction() -> Result<()> {
2145        use datafusion_expr::test::function_stub::count;
2146
2147        let table_scan = test_table_scan()?;
2148        let plan = LogicalPlanBuilder::from(table_scan)
2149            .aggregate(vec![col("a")], vec![count(col("b"))])?
2150            .build()?;
2151
2152        assert_stages!(plan, @"
2153        ## Original Plan
2154        Aggregate: groupBy=[[test.a]], aggr=[[COUNT(test.b)]]
2155          TableScan: test projection=[a, b]
2156
2157        ## After Extraction
2158        (same as original)
2159
2160        ## After Pushdown
2161        (same as after extraction)
2162
2163        ## Optimized
2164        (same as after pushdown)
2165        ")
2166    }
2167
2168    /// Projections containing extracted expression aliases are skipped (already extracted).
2169    #[test]
2170    fn test_skip_extracted_projection() -> Result<()> {
2171        let table_scan = test_table_scan_with_struct()?;
2172        let plan = LogicalPlanBuilder::from(table_scan)
2173            .project(vec![
2174                leaf_udf(col("user"), "name").alias("__datafusion_extracted_manual"),
2175                col("user"),
2176            ])?
2177            .build()?;
2178
2179        assert_stages!(plan, @r#"
2180        ## Original Plan
2181        Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_manual, test.user
2182          TableScan: test projection=[user]
2183
2184        ## After Extraction
2185        (same as original)
2186
2187        ## After Pushdown
2188        (same as after extraction)
2189
2190        ## Optimized
2191        (same as after pushdown)
2192        "#)
2193    }
2194
2195    /// Multiple extractions merge into a single extracted expression projection.
2196    #[test]
2197    fn test_merge_into_existing_extracted_projection() -> Result<()> {
2198        let table_scan = test_table_scan_with_struct()?;
2199        let plan = LogicalPlanBuilder::from(table_scan)
2200            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
2201            .filter(leaf_udf(col("user"), "name").is_not_null())?
2202            .build()?;
2203
2204        assert_stages!(plan, @r#"
2205        ## Original Plan
2206        Filter: leaf_udf(test.user, Utf8("name")) IS NOT NULL
2207          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
2208            TableScan: test projection=[id, user]
2209
2210        ## After Extraction
2211        Projection: test.id, test.user
2212          Filter: __datafusion_extracted_1 IS NOT NULL
2213            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
2214              Projection: test.id, test.user
2215                Filter: __datafusion_extracted_2 = Utf8("active")
2216                  Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user
2217                    TableScan: test projection=[id, user]
2218
2219        ## After Pushdown
2220        Projection: test.id, test.user
2221          Filter: __datafusion_extracted_1 IS NOT NULL
2222            Projection: test.id, test.user, __datafusion_extracted_1
2223              Filter: __datafusion_extracted_2 = Utf8("active")
2224                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
2225                  TableScan: test projection=[id, user]
2226
2227        ## Optimized
2228        (same as after pushdown)
2229        "#)
2230    }
2231
2232    /// Extractions push through passthrough projections (columns only).
2233    #[test]
2234    fn test_extract_through_passthrough_projection() -> Result<()> {
2235        let table_scan = test_table_scan_with_struct()?;
2236        let plan = LogicalPlanBuilder::from(table_scan)
2237            .project(vec![col("user")])?
2238            .project(vec![leaf_udf(col("user"), "name")])?
2239            .build()?;
2240
2241        assert_stages!(plan, @r#"
2242        ## Original Plan
2243        Projection: leaf_udf(test.user, Utf8("name"))
2244          TableScan: test projection=[user]
2245
2246        ## After Extraction
2247        (same as original)
2248
2249        ## After Pushdown
2250        (same as after extraction)
2251
2252        ## Optimized
2253        (same as after pushdown)
2254        "#)
2255    }
2256
2257    /// Merging an extraction into an input projection inlines the definition of
2258    /// every column the extraction references. When that definition is volatile
2259    /// the inlined copy is an independent evaluation, so the extraction must be
2260    /// skipped and the plan left alone.
2261    #[test]
2262    fn test_no_merge_into_volatile_projection() -> Result<()> {
2263        let table_scan = test_table_scan()?;
2264        let plan = LogicalPlanBuilder::from(table_scan)
2265            .project(vec![volatile_udf(col("a")).alias("v")])?
2266            .project(vec![col("v"), leaf_udf(col("v"), "x")])?
2267            .build()?;
2268
2269        assert_stages!(plan, @r#"
2270        ## Original Plan
2271        Projection: v, leaf_udf(v, Utf8("x"))
2272          Projection: keep_in_place_udf(test.a) AS v
2273            TableScan: test projection=[a]
2274
2275        ## After Extraction
2276        (same as original)
2277
2278        ## After Pushdown
2279        (same as after extraction)
2280
2281        ## Optimized
2282        (same as after pushdown)
2283        "#)
2284    }
2285
2286    /// Same guard for pass 1: extracting out of a `Filter` whose input
2287    /// projection defines the referenced column volatilely would make the
2288    /// predicate test a second, independent evaluation.
2289    #[test]
2290    fn test_no_extraction_from_filter_over_volatile_projection() -> Result<()> {
2291        let table_scan = test_table_scan()?;
2292        let plan = LogicalPlanBuilder::from(table_scan)
2293            .project(vec![volatile_udf(col("a")).alias("v")])?
2294            .filter(leaf_udf(col("v"), "x").eq(lit(1u32)))?
2295            .build()?;
2296
2297        assert_stages!(plan, @r#"
2298        ## Original Plan
2299        Filter: leaf_udf(v, Utf8("x")) = UInt32(1)
2300          Projection: keep_in_place_udf(test.a) AS v
2301            TableScan: test projection=[a]
2302
2303        ## After Extraction
2304        (same as original)
2305
2306        ## After Pushdown
2307        (same as after extraction)
2308
2309        ## Optimized
2310        (same as after pushdown)
2311        "#)
2312    }
2313
2314    /// Projections with aliased columns (nothing to extract) return unchanged.
2315    #[test]
2316    fn test_projection_early_return_no_extraction() -> Result<()> {
2317        let table_scan = test_table_scan()?;
2318        let plan = LogicalPlanBuilder::from(table_scan)
2319            .project(vec![col("a").alias("x"), col("b")])?
2320            .build()?;
2321
2322        assert_stages!(plan, @"
2323        ## Original Plan
2324        Projection: test.a AS x, test.b
2325          TableScan: test projection=[a, b]
2326
2327        ## After Extraction
2328        (same as original)
2329
2330        ## After Pushdown
2331        (same as after extraction)
2332
2333        ## Optimized
2334        (same as after pushdown)
2335        ")
2336    }
2337
2338    /// Projections with arithmetic expressions but no MoveTowardsLeafNodes return unchanged.
2339    #[test]
2340    fn test_projection_with_arithmetic_no_extraction() -> Result<()> {
2341        let table_scan = test_table_scan()?;
2342        let plan = LogicalPlanBuilder::from(table_scan)
2343            .project(vec![(col("a") + col("b")).alias("sum")])?
2344            .build()?;
2345
2346        assert_stages!(plan, @"
2347        ## Original Plan
2348        Projection: test.a + test.b AS sum
2349          TableScan: test projection=[a, b]
2350
2351        ## After Extraction
2352        (same as original)
2353
2354        ## After Pushdown
2355        (same as after extraction)
2356
2357        ## Optimized
2358        (same as after pushdown)
2359        ")
2360    }
2361
2362    /// Aggregate extractions merge into existing extracted projection created by Filter.
2363    #[test]
2364    fn test_aggregate_merge_into_extracted_projection() -> Result<()> {
2365        use datafusion_expr::test::function_stub::count;
2366
2367        let table_scan = test_table_scan_with_struct()?;
2368        let plan = LogicalPlanBuilder::from(table_scan)
2369            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
2370            .aggregate(vec![leaf_udf(col("user"), "name")], vec![count(lit(1))])?
2371            .build()?;
2372
2373        assert_stages!(plan, @r#"
2374        ## Original Plan
2375        Aggregate: groupBy=[[leaf_udf(test.user, Utf8("name"))]], aggr=[[COUNT(Int32(1))]]
2376          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
2377            TableScan: test projection=[user]
2378
2379        ## After Extraction
2380        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
2381          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
2382            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
2383              Projection: test.user
2384                Filter: __datafusion_extracted_2 = Utf8("active")
2385                  Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user
2386                    TableScan: test projection=[user]
2387
2388        ## After Pushdown
2389        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
2390          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
2391            Projection: test.user, __datafusion_extracted_1
2392              Filter: __datafusion_extracted_2 = Utf8("active")
2393                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
2394                  TableScan: test projection=[user]
2395
2396        ## Optimized
2397        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
2398          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
2399            Projection: __datafusion_extracted_1
2400              Filter: __datafusion_extracted_2 = Utf8("active")
2401                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
2402                  TableScan: test projection=[user]
2403        "#)
2404    }
2405
2406    /// Projection containing a MoveTowardsLeafNodes sub-expression above an
2407    /// Aggregate. The Aggregate blocks pushdown, so the extraction cannot move
2408    /// and the original projection is kept unchanged.
2409    #[test]
2410    fn test_projection_with_leaf_expr_above_aggregate() -> Result<()> {
2411        use datafusion_expr::test::function_stub::count;
2412
2413        let table_scan = test_table_scan_with_struct()?;
2414        let plan = LogicalPlanBuilder::from(table_scan)
2415            .aggregate(vec![col("user")], vec![count(lit(1))])?
2416            .project(vec![
2417                leaf_udf(col("user"), "name")
2418                    .is_not_null()
2419                    .alias("has_name"),
2420                col("COUNT(Int32(1))"),
2421            ])?
2422            .build()?;
2423
2424        assert_stages!(plan, @r#"
2425        ## Original Plan
2426        Projection: leaf_udf(test.user, Utf8("name")) IS NOT NULL AS has_name, COUNT(Int32(1))
2427          Aggregate: groupBy=[[test.user]], aggr=[[COUNT(Int32(1))]]
2428            TableScan: test projection=[user]
2429
2430        ## After Extraction
2431        (same as original)
2432
2433        ## After Pushdown
2434        (same as after extraction)
2435
2436        ## Optimized
2437        (same as after pushdown)
2438        "#)
2439    }
2440
2441    /// Merging adds new pass-through columns not in the existing extracted projection.
2442    #[test]
2443    fn test_merge_with_new_columns() -> Result<()> {
2444        let table_scan = test_table_scan()?;
2445        let plan = LogicalPlanBuilder::from(table_scan)
2446            .filter(leaf_udf(col("a"), "x").eq(lit(1)))?
2447            .filter(leaf_udf(col("b"), "y").eq(lit(2)))?
2448            .build()?;
2449
2450        assert_stages!(plan, @r#"
2451        ## Original Plan
2452        Filter: leaf_udf(test.b, Utf8("y")) = Int32(2)
2453          Filter: leaf_udf(test.a, Utf8("x")) = Int32(1)
2454            TableScan: test projection=[a, b, c]
2455
2456        ## After Extraction
2457        Projection: test.a, test.b, test.c
2458          Filter: __datafusion_extracted_1 = Int32(2)
2459            Projection: leaf_udf(test.b, Utf8("y")) AS __datafusion_extracted_1, test.a, test.b, test.c
2460              Projection: test.a, test.b, test.c
2461                Filter: __datafusion_extracted_2 = Int32(1)
2462                  Projection: leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_2, test.a, test.b, test.c
2463                    TableScan: test projection=[a, b, c]
2464
2465        ## After Pushdown
2466        Projection: test.a, test.b, test.c
2467          Filter: __datafusion_extracted_1 = Int32(2)
2468            Projection: test.a, test.b, test.c, __datafusion_extracted_1
2469              Filter: __datafusion_extracted_2 = Int32(1)
2470                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
2471                  TableScan: test projection=[a, b, c]
2472
2473        ## Optimized
2474        (same as after pushdown)
2475        "#)
2476    }
2477
2478    /// A filter can name a column bare (`a`) while the projection below it
2479    /// outputs the qualified `test.a`. The optimizer leaves this shape when it
2480    /// removes the empty input of a `UNION ALL` (for example
2481    /// `... UNION ALL SELECT ... WHERE 1 = 2`). The merge must match the two, and not add a bare `a`
2482    /// beside `test.a`, which is an ambiguous schema.
2483    #[test]
2484    fn test_merge_bare_column_into_qualified_projection() -> Result<()> {
2485        let table_scan = test_table_scan()?;
2486        let projection = LogicalPlanBuilder::from(table_scan)
2487            .project(vec![
2488                col("test.a"),
2489                col("test.b"),
2490                (col("test.c") + lit(1)).alias("d"),
2491            ])?
2492            .build()?;
2493        let predicate =
2494            leaf_udf(Expr::Column(Column::new_unqualified("a")), "x").eq(lit(1));
2495        let plan = LogicalPlan::Filter(datafusion_expr::Filter::try_new(
2496            predicate,
2497            Arc::new(projection),
2498        )?);
2499
2500        assert_stages!(plan, @r#"
2501        ## Original Plan
2502        Filter: leaf_udf(a, Utf8("x")) = Int32(1)
2503          Projection: test.a, test.b, test.c + Int32(1) AS d
2504            TableScan: test projection=[a, b, c]
2505
2506        ## After Extraction
2507        Projection: test.a, test.b, d
2508          Filter: __datafusion_extracted_1 = Int32(1)
2509            Projection: test.a, test.b, test.c + Int32(1) AS d, leaf_udf(a, Utf8("x")) AS __datafusion_extracted_1
2510              TableScan: test projection=[a, b, c]
2511
2512        ## After Pushdown
2513        (same as after extraction)
2514
2515        ## Optimized
2516        (same as after pushdown)
2517        "#)
2518    }
2519
2520    /// When the merge appends a needed column that the projection does not
2521    /// keep, it must append the input's qualified column (`test.b`), not the
2522    /// bare `b` that the caller asked for.
2523    #[test]
2524    fn test_merge_appends_qualified_column_for_bare_request() -> Result<()> {
2525        let projection = LogicalPlanBuilder::from(test_table_scan()?)
2526            .project(vec![col("test.a")])?
2527            .build()?;
2528        let target_schema = Arc::clone(projection.schema());
2529        let columns_needed: IndexSet<Column> =
2530            IndexSet::from([Column::new_unqualified("b")]);
2531
2532        let merged = build_extraction_projection_impl(
2533            &[],
2534            &columns_needed,
2535            &Arc::new(projection),
2536            &target_schema,
2537        )?;
2538
2539        assert_eq!(
2540            merged.expr,
2541            vec![
2542                Expr::Column(Column::new(Some("test"), "a")),
2543                Expr::Column(Column::new(Some("test"), "b")),
2544            ]
2545        );
2546        Ok(())
2547    }
2548
2549    /// A projection can spell a pass-through column as a same-name alias
2550    /// (`test.a AS a`). Merging an extraction into it must treat that alias as
2551    /// the pass-through it is, and not add `test.a` beside the `a` it outputs,
2552    /// which is an ambiguous schema.
2553    #[test]
2554    fn test_merge_into_projection_with_same_name_alias() -> Result<()> {
2555        let table_scan = test_table_scan()?;
2556        let plan = LogicalPlanBuilder::from(table_scan)
2557            .project(vec![
2558                col("test.a").alias("a"),
2559                col("test.b").alias("b"),
2560                col("test.c").alias("c"),
2561            ])?
2562            .filter(leaf_udf(col("a"), "x").eq(lit(1)))?
2563            .build()?;
2564
2565        assert_stages!(plan, @r#"
2566        ## Original Plan
2567        Filter: leaf_udf(a, Utf8("x")) = Int32(1)
2568          Projection: test.a AS a, test.b AS b, test.c AS c
2569            TableScan: test projection=[a, b, c]
2570
2571        ## After Extraction
2572        Projection: a, b, c
2573          Filter: __datafusion_extracted_1 = Int32(1)
2574            Projection: test.a AS a, test.b AS b, test.c AS c, leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_1
2575              TableScan: test projection=[a, b, c]
2576
2577        ## After Pushdown
2578        (same as after extraction)
2579
2580        ## Optimized
2581        (same as after pushdown)
2582        "#)
2583    }
2584
2585    // =========================================================================
2586    // Join extraction tests
2587    // =========================================================================
2588
2589    /// Create a second table scan with struct field for join tests
2590    fn test_table_scan_with_struct_named(name: &str) -> Result<LogicalPlan> {
2591        use arrow::datatypes::Schema;
2592        let schema = Schema::new(test_table_scan_with_struct_fields());
2593        datafusion_expr::logical_plan::table_scan(Some(name), &schema, None)?.build()
2594    }
2595
2596    /// Extraction from equijoin keys (`on` expressions).
2597    #[test]
2598    fn test_extract_from_join_on() -> Result<()> {
2599        use datafusion_expr::JoinType;
2600
2601        let left = test_table_scan_with_struct()?;
2602        let right = test_table_scan_with_struct_named("right")?;
2603
2604        let plan = LogicalPlanBuilder::from(left)
2605            .join_with_expr_keys(
2606                right,
2607                JoinType::Inner,
2608                (
2609                    vec![leaf_udf(col("user"), "id")],
2610                    vec![leaf_udf(col("user"), "id")],
2611                ),
2612                None,
2613            )?
2614            .build()?;
2615
2616        assert_stages!(plan, @r#"
2617        ## Original Plan
2618        Inner Join: leaf_udf(test.user, Utf8("id")) = leaf_udf(right.user, Utf8("id"))
2619          TableScan: test projection=[id, user]
2620          TableScan: right projection=[id, user]
2621
2622        ## After Extraction
2623        Projection: test.id, test.user, right.id, right.user
2624          Inner Join: __datafusion_extracted_1 = __datafusion_extracted_2
2625            Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_1, test.id, test.user
2626              TableScan: test projection=[id, user]
2627            Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_2, right.id, right.user
2628              TableScan: right projection=[id, user]
2629
2630        ## After Pushdown
2631        (same as after extraction)
2632
2633        ## Optimized
2634        (same as after pushdown)
2635        "#)
2636    }
2637
2638    /// Extraction from non-equi join filter.
2639    #[test]
2640    fn test_extract_from_join_filter() -> Result<()> {
2641        use datafusion_expr::JoinType;
2642
2643        let left = test_table_scan_with_struct()?;
2644        let right = test_table_scan_with_struct_named("right")?;
2645
2646        let plan = LogicalPlanBuilder::from(left)
2647            .join_on(
2648                right,
2649                JoinType::Inner,
2650                vec![
2651                    col("test.user").eq(col("right.user")),
2652                    leaf_udf(col("test.user"), "status").eq(lit("active")),
2653                ],
2654            )?
2655            .build()?;
2656
2657        assert_stages!(plan, @r#"
2658        ## Original Plan
2659        Inner Join:  Filter: test.user = right.user AND leaf_udf(test.user, Utf8("status")) = Utf8("active")
2660          TableScan: test projection=[id, user]
2661          TableScan: right projection=[id, user]
2662
2663        ## After Extraction
2664        Projection: test.id, test.user, right.id, right.user
2665          Inner Join:  Filter: test.user = right.user AND __datafusion_extracted_1 = Utf8("active")
2666            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
2667              TableScan: test projection=[id, user]
2668            TableScan: right projection=[id, user]
2669
2670        ## After Pushdown
2671        (same as after extraction)
2672
2673        ## Optimized
2674        (same as after pushdown)
2675        "#)
2676    }
2677
2678    /// Extraction from both left and right sides of a join.
2679    #[test]
2680    fn test_extract_from_join_both_sides() -> Result<()> {
2681        use datafusion_expr::JoinType;
2682
2683        let left = test_table_scan_with_struct()?;
2684        let right = test_table_scan_with_struct_named("right")?;
2685
2686        let plan = LogicalPlanBuilder::from(left)
2687            .join_on(
2688                right,
2689                JoinType::Inner,
2690                vec![
2691                    col("test.user").eq(col("right.user")),
2692                    leaf_udf(col("test.user"), "status").eq(lit("active")),
2693                    leaf_udf(col("right.user"), "role").eq(lit("admin")),
2694                ],
2695            )?
2696            .build()?;
2697
2698        assert_stages!(plan, @r#"
2699        ## Original Plan
2700        Inner Join:  Filter: test.user = right.user AND leaf_udf(test.user, Utf8("status")) = Utf8("active") AND leaf_udf(right.user, Utf8("role")) = Utf8("admin")
2701          TableScan: test projection=[id, user]
2702          TableScan: right projection=[id, user]
2703
2704        ## After Extraction
2705        Projection: test.id, test.user, right.id, right.user
2706          Inner Join:  Filter: test.user = right.user AND __datafusion_extracted_1 = Utf8("active") AND __datafusion_extracted_2 = Utf8("admin")
2707            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
2708              TableScan: test projection=[id, user]
2709            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id, right.user
2710              TableScan: right projection=[id, user]
2711
2712        ## After Pushdown
2713        (same as after extraction)
2714
2715        ## Optimized
2716        (same as after pushdown)
2717        "#)
2718    }
2719
2720    /// Join with no MoveTowardsLeafNodes expressions returns unchanged.
2721    #[test]
2722    fn test_extract_from_join_no_extraction() -> Result<()> {
2723        use datafusion_expr::JoinType;
2724
2725        let left = test_table_scan()?;
2726        let right = test_table_scan_with_name("right")?;
2727
2728        let plan = LogicalPlanBuilder::from(left)
2729            .join(right, JoinType::Inner, (vec!["a"], vec!["a"]), None)?
2730            .build()?;
2731
2732        assert_stages!(plan, @"
2733        ## Original Plan
2734        Inner Join: test.a = right.a
2735          TableScan: test projection=[a, b, c]
2736          TableScan: right projection=[a, b, c]
2737
2738        ## After Extraction
2739        (same as original)
2740
2741        ## After Pushdown
2742        (same as after extraction)
2743
2744        ## Optimized
2745        (same as after pushdown)
2746        ")
2747    }
2748
2749    /// Join followed by filter with extraction.
2750    #[test]
2751    fn test_extract_from_filter_above_join() -> Result<()> {
2752        use datafusion_expr::JoinType;
2753
2754        let left = test_table_scan_with_struct()?;
2755        let right = test_table_scan_with_struct_named("right")?;
2756
2757        let plan = LogicalPlanBuilder::from(left)
2758            .join_with_expr_keys(
2759                right,
2760                JoinType::Inner,
2761                (
2762                    vec![leaf_udf(col("user"), "id")],
2763                    vec![leaf_udf(col("user"), "id")],
2764                ),
2765                None,
2766            )?
2767            .filter(leaf_udf(col("test.user"), "status").eq(lit("active")))?
2768            .build()?;
2769
2770        assert_stages!(plan, @r#"
2771        ## Original Plan
2772        Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
2773          Inner Join: leaf_udf(test.user, Utf8("id")) = leaf_udf(right.user, Utf8("id"))
2774            TableScan: test projection=[id, user]
2775            TableScan: right projection=[id, user]
2776
2777        ## After Extraction
2778        Projection: test.id, test.user, right.id, right.user
2779          Filter: __datafusion_extracted_1 = Utf8("active")
2780            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, right.id, right.user
2781              Projection: test.id, test.user, right.id, right.user
2782                Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3
2783                  Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_2, test.id, test.user
2784                    TableScan: test projection=[id, user]
2785                  Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.user
2786                    TableScan: right projection=[id, user]
2787
2788        ## After Pushdown
2789        Projection: test.id, test.user, right.id, right.user
2790          Filter: __datafusion_extracted_1 = Utf8("active")
2791            Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_1
2792              Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3
2793                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
2794                  TableScan: test projection=[id, user]
2795                Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.user
2796                  TableScan: right projection=[id, user]
2797
2798        ## Optimized
2799        (same as after pushdown)
2800        "#)
2801    }
2802
2803    /// Extraction projection (get_field in SELECT) above a Join pushes into
2804    /// the correct input side.
2805    #[test]
2806    fn test_extract_projection_above_join() -> Result<()> {
2807        use datafusion_expr::JoinType;
2808
2809        let left = test_table_scan_with_struct()?;
2810        let right = test_table_scan_with_struct_named("right")?;
2811
2812        let plan = LogicalPlanBuilder::from(left)
2813            .join(right, JoinType::Inner, (vec!["id"], vec!["id"]), None)?
2814            .project(vec![
2815                leaf_udf(col("test.user"), "status"),
2816                leaf_udf(col("right.user"), "role"),
2817            ])?
2818            .build()?;
2819
2820        assert_stages!(plan, @r#"
2821        ## Original Plan
2822        Projection: leaf_udf(test.user, Utf8("status")), leaf_udf(right.user, Utf8("role"))
2823          Inner Join: test.id = right.id
2824            TableScan: test projection=[id, user]
2825            TableScan: right projection=[id, user]
2826
2827        ## After Extraction
2828        (same as original)
2829
2830        ## After Pushdown
2831        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), __datafusion_extracted_2 AS leaf_udf(right.user,Utf8("role"))
2832          Inner Join: test.id = right.id
2833            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
2834              TableScan: test projection=[id, user]
2835            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id, right.user
2836              TableScan: right projection=[id, user]
2837
2838        ## Optimized
2839        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), __datafusion_extracted_2 AS leaf_udf(right.user,Utf8("role"))
2840          Inner Join: test.id = right.id
2841            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id
2842              TableScan: test projection=[id, user]
2843            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id
2844              TableScan: right projection=[id, user]
2845        "#)
2846    }
2847
2848    /// Join where both sides have same-named columns: a qualified reference
2849    /// to the right side must be routed to the right input, not the left.
2850    #[test]
2851    fn test_extract_from_join_qualified_right_side() -> Result<()> {
2852        use datafusion_expr::JoinType;
2853
2854        let left = test_table_scan_with_struct()?;
2855        let right = test_table_scan_with_struct_named("right")?;
2856
2857        // Filter references right.user explicitly — must route to right side
2858        let plan = LogicalPlanBuilder::from(left)
2859            .join_on(
2860                right,
2861                JoinType::Inner,
2862                vec![
2863                    col("test.id").eq(col("right.id")),
2864                    leaf_udf(col("right.user"), "status").eq(lit("active")),
2865                ],
2866            )?
2867            .build()?;
2868
2869        assert_stages!(plan, @r#"
2870        ## Original Plan
2871        Inner Join:  Filter: test.id = right.id AND leaf_udf(right.user, Utf8("status")) = Utf8("active")
2872          TableScan: test projection=[id, user]
2873          TableScan: right projection=[id, user]
2874
2875        ## After Extraction
2876        Projection: test.id, test.user, right.id, right.user
2877          Inner Join:  Filter: test.id = right.id AND __datafusion_extracted_1 = Utf8("active")
2878            TableScan: test projection=[id, user]
2879            Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user
2880              TableScan: right projection=[id, user]
2881
2882        ## After Pushdown
2883        (same as after extraction)
2884
2885        ## Optimized
2886        (same as after pushdown)
2887        "#)
2888    }
2889
2890    /// When both inputs contain the same unqualified column, an unqualified
2891    /// column reference is ambiguous and `find_owning_input` must return
2892    /// `None` rather than always returning 0 (the left side).
2893    #[test]
2894    fn test_find_owning_input_ambiguous_unqualified_column() {
2895        use std::collections::HashSet;
2896
2897        // Simulate schema_columns output for two sides of a join where both
2898        // have a "user" column — each set contains the qualified and
2899        // unqualified form.
2900        let relation = "test".into();
2901        let left_cols: HashSet<ColumnReference> = [
2902            ColumnReference::new(Some(&relation), "user"),
2903            ColumnReference::new_unqualified("user"),
2904        ]
2905        .into_iter()
2906        .collect();
2907
2908        let relation = "right".into();
2909        let right_cols: HashSet<ColumnReference> = [
2910            ColumnReference::new(Some(&relation), "user"),
2911            ColumnReference::new_unqualified("user"),
2912        ]
2913        .into_iter()
2914        .collect();
2915
2916        let input_column_sets = vec![left_cols, right_cols];
2917
2918        // Unqualified "user" matches both sets — must return None (ambiguous)
2919        let unqualified = Expr::Column(Column::new_unqualified("user"));
2920        assert_eq!(find_owning_input(&unqualified, &input_column_sets), None);
2921
2922        // Qualified "right.user" matches only the right set — must return Some(1)
2923        let qualified_right = Expr::Column(Column::new(Some("right"), "user"));
2924        assert_eq!(
2925            find_owning_input(&qualified_right, &input_column_sets),
2926            Some(1)
2927        );
2928
2929        // Qualified "test.user" matches only the left set — must return Some(0)
2930        let qualified_left = Expr::Column(Column::new(Some("test"), "user"));
2931        assert_eq!(
2932            find_owning_input(&qualified_left, &input_column_sets),
2933            Some(0)
2934        );
2935    }
2936
2937    /// Two leaf_udf expressions from different sides of a Join in a Filter.
2938    /// Each is routed to its respective input side independently.
2939    #[test]
2940    fn test_extract_from_join_cross_input_expression() -> Result<()> {
2941        let left = test_table_scan_with_struct()?;
2942        let right = test_table_scan_with_struct_named("right")?;
2943
2944        let plan = LogicalPlanBuilder::from(left)
2945            .join_on(
2946                right,
2947                datafusion_expr::JoinType::Inner,
2948                vec![col("test.id").eq(col("right.id"))],
2949            )?
2950            .filter(
2951                leaf_udf(col("test.user"), "status")
2952                    .eq(leaf_udf(col("right.user"), "status")),
2953            )?
2954            .build()?;
2955
2956        assert_stages!(plan, @r#"
2957        ## Original Plan
2958        Filter: leaf_udf(test.user, Utf8("status")) = leaf_udf(right.user, Utf8("status"))
2959          Inner Join:  Filter: test.id = right.id
2960            TableScan: test projection=[id, user]
2961            TableScan: right projection=[id, user]
2962
2963        ## After Extraction
2964        Projection: test.id, test.user, right.id, right.user
2965          Filter: __datafusion_extracted_1 = __datafusion_extracted_2
2966            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user, right.id, right.user
2967              Inner Join:  Filter: test.id = right.id
2968                TableScan: test projection=[id, user]
2969                TableScan: right projection=[id, user]
2970
2971        ## After Pushdown
2972        Projection: test.id, test.user, right.id, right.user
2973          Filter: __datafusion_extracted_1 = __datafusion_extracted_2
2974            Inner Join:  Filter: test.id = right.id
2975              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
2976                TableScan: test projection=[id, user]
2977              Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_2, right.id, right.user
2978                TableScan: right projection=[id, user]
2979
2980        ## Optimized
2981        (same as after pushdown)
2982        "#)
2983    }
2984
2985    // =========================================================================
2986    // Column-rename through intermediate node tests
2987    // =========================================================================
2988
2989    /// Projection with leaf expr above Filter above renaming Projection.
2990    #[test]
2991    fn test_extract_through_filter_with_column_rename() -> Result<()> {
2992        let table_scan = test_table_scan_with_struct()?;
2993        let plan = LogicalPlanBuilder::from(table_scan)
2994            .project(vec![col("user").alias("x")])?
2995            .filter(col("x").is_not_null())?
2996            .project(vec![leaf_udf(col("x"), "a")])?
2997            .build()?;
2998
2999        assert_stages!(plan, @r#"
3000        ## Original Plan
3001        Projection: leaf_udf(x, Utf8("a"))
3002          Filter: x IS NOT NULL
3003            Projection: test.user AS x
3004              TableScan: test projection=[user]
3005
3006        ## After Extraction
3007        (same as original)
3008
3009        ## After Pushdown
3010        Projection: __datafusion_extracted_1 AS leaf_udf(x,Utf8("a"))
3011          Filter: x IS NOT NULL
3012            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
3013              TableScan: test projection=[user]
3014
3015        ## Optimized
3016        (same as after pushdown)
3017        "#)
3018    }
3019
3020    /// Same as above but with a partial extraction (leaf + arithmetic).
3021    #[test]
3022    fn test_extract_partial_through_filter_with_column_rename() -> Result<()> {
3023        let table_scan = test_table_scan_with_struct()?;
3024        let plan = LogicalPlanBuilder::from(table_scan)
3025            .project(vec![col("user").alias("x")])?
3026            .filter(col("x").is_not_null())?
3027            .project(vec![leaf_udf(col("x"), "a").is_not_null()])?
3028            .build()?;
3029
3030        assert_stages!(plan, @r#"
3031        ## Original Plan
3032        Projection: leaf_udf(x, Utf8("a")) IS NOT NULL
3033          Filter: x IS NOT NULL
3034            Projection: test.user AS x
3035              TableScan: test projection=[user]
3036
3037        ## After Extraction
3038        (same as original)
3039
3040        ## After Pushdown
3041        Projection: __datafusion_extracted_1 IS NOT NULL AS leaf_udf(x,Utf8("a")) IS NOT NULL
3042          Filter: x IS NOT NULL
3043            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
3044              TableScan: test projection=[user]
3045
3046        ## Optimized
3047        (same as after pushdown)
3048        "#)
3049    }
3050
3051    /// Tests merge_into_extracted_projection path through a renaming projection.
3052    #[test]
3053    fn test_extract_from_filter_above_renaming_projection() -> Result<()> {
3054        let table_scan = test_table_scan_with_struct()?;
3055        let plan = LogicalPlanBuilder::from(table_scan)
3056            .project(vec![col("user").alias("x")])?
3057            .filter(leaf_udf(col("x"), "a").eq(lit("active")))?
3058            .build()?;
3059
3060        assert_stages!(plan, @r#"
3061        ## Original Plan
3062        Filter: leaf_udf(x, Utf8("a")) = Utf8("active")
3063          Projection: test.user AS x
3064            TableScan: test projection=[user]
3065
3066        ## After Extraction
3067        Projection: x
3068          Filter: __datafusion_extracted_1 = Utf8("active")
3069            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
3070              TableScan: test projection=[user]
3071
3072        ## After Pushdown
3073        (same as after extraction)
3074
3075        ## Optimized
3076        (same as after pushdown)
3077        "#)
3078    }
3079
3080    /// A projection that swaps two column names, below a filter and a struct
3081    /// field read. The merge must not resolve the parent's column references
3082    /// through the rename map: the input column `test.user` beside the output
3083    /// field `user` of the other rename gives an ambiguous schema (#25446).
3084    #[test]
3085    fn test_extract_above_projection_that_swaps_column_names() -> Result<()> {
3086        let table_scan = test_table_scan_with_struct()?;
3087        let plan = LogicalPlanBuilder::from(table_scan)
3088            .project(vec![col("user").alias("id"), col("id").alias("user")])?
3089            .filter(col("user").gt(lit(0u32)))?
3090            .project(vec![col("id"), col("user"), leaf_udf(col("id"), "name")])?
3091            .build()?;
3092
3093        assert_stages!(plan, @r#"
3094        ## Original Plan
3095        Projection: id, user, leaf_udf(id, Utf8("name"))
3096          Filter: user > UInt32(0)
3097            Projection: test.user AS id, test.id AS user
3098              TableScan: test projection=[id, user]
3099
3100        ## After Extraction
3101        (same as original)
3102
3103        ## After Pushdown
3104        Projection: id, user, __datafusion_extracted_1 AS leaf_udf(id,Utf8("name"))
3105          Filter: user > UInt32(0)
3106            Projection: test.user AS id, test.id AS user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
3107              TableScan: test projection=[id, user]
3108
3109        ## Optimized
3110        (same as after pushdown)
3111        "#)
3112    }
3113
3114    /// A projection that gives a computed column the name of its own input
3115    /// column. The extraction projection goes below the filter, which puts a
3116    /// column named `id` under the rename, so the two plans have the same set
3117    /// of field names. The recovery projection must stay, or the rename is lost
3118    /// and the query gives wrong results.
3119    #[test]
3120    fn test_extract_above_projection_that_redefines_column_name() -> Result<()> {
3121        let table_scan = test_table_scan_with_struct()?;
3122        let plan = LogicalPlanBuilder::from(table_scan)
3123            .filter(col("id").gt(lit(0u32)))?
3124            .project(vec![(col("id") * lit(10u32)).alias("id"), col("user")])?
3125            .alias("sub")?
3126            .project(vec![col("sub.id"), leaf_udf(col("sub.user"), "name")])?
3127            .build()?;
3128
3129        assert_stages!(plan, @r#"
3130        ## Original Plan
3131        Projection: sub.id, leaf_udf(sub.user, Utf8("name"))
3132          SubqueryAlias: sub
3133            Projection: test.id * UInt32(10) AS id, test.user
3134              Filter: test.id > UInt32(0)
3135                TableScan: test projection=[id, user]
3136
3137        ## After Extraction
3138        (same as original)
3139
3140        ## After Pushdown
3141        Projection: sub.id, __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
3142          SubqueryAlias: sub
3143            Projection: test.id * UInt32(10) AS id, test.user, __datafusion_extracted_1
3144              Filter: test.id > UInt32(0)
3145                Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
3146                  TableScan: test projection=[id, user]
3147
3148        ## Optimized
3149        Projection: sub.id, __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
3150          SubqueryAlias: sub
3151            Projection: test.id * UInt32(10) AS id, __datafusion_extracted_1
3152              Filter: test.id > UInt32(0)
3153                Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id
3154                  TableScan: test projection=[id, user]
3155        "#)
3156    }
3157
3158    // =========================================================================
3159    // SubqueryAlias extraction tests
3160    // =========================================================================
3161
3162    /// Extraction projection pushes through SubqueryAlias.
3163    #[test]
3164    fn test_extract_through_subquery_alias() -> Result<()> {
3165        let table_scan = test_table_scan_with_struct()?;
3166        let plan = LogicalPlanBuilder::from(table_scan)
3167            .alias("sub")?
3168            .project(vec![leaf_udf(col("sub.user"), "name")])?
3169            .build()?;
3170
3171        assert_stages!(plan, @r#"
3172        ## Original Plan
3173        Projection: leaf_udf(sub.user, Utf8("name"))
3174          SubqueryAlias: sub
3175            TableScan: test projection=[user]
3176
3177        ## After Extraction
3178        (same as original)
3179
3180        ## After Pushdown
3181        Projection: __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
3182          SubqueryAlias: sub
3183            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
3184              TableScan: test projection=[user]
3185
3186        ## Optimized
3187        Projection: __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
3188          SubqueryAlias: sub
3189            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
3190              TableScan: test projection=[user]
3191        "#)
3192    }
3193
3194    /// Extraction projection pushes through SubqueryAlias + Filter.
3195    #[test]
3196    fn test_extract_through_subquery_alias_with_filter() -> Result<()> {
3197        let table_scan = test_table_scan_with_struct()?;
3198        let plan = LogicalPlanBuilder::from(table_scan)
3199            .alias("sub")?
3200            .filter(leaf_udf(col("sub.user"), "status").eq(lit("active")))?
3201            .project(vec![leaf_udf(col("sub.user"), "name")])?
3202            .build()?;
3203
3204        assert_stages!(plan, @r#"
3205        ## Original Plan
3206        Projection: leaf_udf(sub.user, Utf8("name"))
3207          Filter: leaf_udf(sub.user, Utf8("status")) = Utf8("active")
3208            SubqueryAlias: sub
3209              TableScan: test projection=[user]
3210
3211        ## After Extraction
3212        Projection: leaf_udf(sub.user, Utf8("name"))
3213          Projection: sub.user
3214            Filter: __datafusion_extracted_1 = Utf8("active")
3215              Projection: leaf_udf(sub.user, Utf8("status")) AS __datafusion_extracted_1, sub.user
3216                SubqueryAlias: sub
3217                  TableScan: test projection=[user]
3218
3219        ## After Pushdown
3220        Projection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))
3221          Projection: sub.user, __datafusion_extracted_2
3222            Filter: __datafusion_extracted_1 = Utf8("active")
3223              SubqueryAlias: sub
3224                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.user
3225                  TableScan: test projection=[user]
3226
3227        ## Optimized
3228        Projection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))
3229          Filter: __datafusion_extracted_1 = Utf8("active")
3230            SubqueryAlias: sub
3231              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
3232                TableScan: test projection=[user]
3233        "#)
3234    }
3235
3236    /// Two layers of SubqueryAlias: extraction pushes through both.
3237    #[test]
3238    fn test_extract_through_nested_subquery_alias() -> Result<()> {
3239        let table_scan = test_table_scan_with_struct()?;
3240        let plan = LogicalPlanBuilder::from(table_scan)
3241            .alias("inner_sub")?
3242            .alias("outer_sub")?
3243            .project(vec![leaf_udf(col("outer_sub.user"), "name")])?
3244            .build()?;
3245
3246        assert_stages!(plan, @r#"
3247        ## Original Plan
3248        Projection: leaf_udf(outer_sub.user, Utf8("name"))
3249          SubqueryAlias: outer_sub
3250            SubqueryAlias: inner_sub
3251              TableScan: test projection=[user]
3252
3253        ## After Extraction
3254        (same as original)
3255
3256        ## After Pushdown
3257        Projection: __datafusion_extracted_1 AS leaf_udf(outer_sub.user,Utf8("name"))
3258          SubqueryAlias: outer_sub
3259            SubqueryAlias: inner_sub
3260              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
3261                TableScan: test projection=[user]
3262
3263        ## Optimized
3264        Projection: __datafusion_extracted_1 AS leaf_udf(outer_sub.user,Utf8("name"))
3265          SubqueryAlias: outer_sub
3266            SubqueryAlias: inner_sub
3267              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
3268                TableScan: test projection=[user]
3269        "#)
3270    }
3271
3272    /// Plain columns through SubqueryAlias -- no extraction needed.
3273    #[test]
3274    fn test_subquery_alias_no_extraction() -> Result<()> {
3275        let table_scan = test_table_scan()?;
3276        let plan = LogicalPlanBuilder::from(table_scan)
3277            .alias("sub")?
3278            .project(vec![col("sub.a"), col("sub.b")])?
3279            .build()?;
3280
3281        assert_stages!(plan, @"
3282        ## Original Plan
3283        SubqueryAlias: sub
3284          TableScan: test projection=[a, b]
3285
3286        ## After Extraction
3287        (same as original)
3288
3289        ## After Pushdown
3290        (same as after extraction)
3291
3292        ## Optimized
3293        (same as after pushdown)
3294        ")
3295    }
3296
3297    /// Two UDFs with the same `name()` but different concrete types should NOT be
3298    /// deduplicated -- they are semantically different expressions that happen to
3299    /// collide on `schema_name()`.
3300    #[test]
3301    fn test_different_udfs_same_schema_name_not_deduplicated() -> Result<()> {
3302        let udf_a = Arc::new(ScalarUDF::new_from_impl(
3303            PlacementTestUDF::new()
3304                .with_placement(ExpressionPlacement::MoveTowardsLeafNodes)
3305                .with_id(1),
3306        ));
3307        let udf_b = Arc::new(ScalarUDF::new_from_impl(
3308            PlacementTestUDF::new()
3309                .with_placement(ExpressionPlacement::MoveTowardsLeafNodes)
3310                .with_id(2),
3311        ));
3312
3313        let expr_a = Expr::ScalarFunction(ScalarFunction::new_udf(
3314            udf_a,
3315            vec![col("user"), lit("field")],
3316        ));
3317        let expr_b = Expr::ScalarFunction(ScalarFunction::new_udf(
3318            udf_b,
3319            vec![col("user"), lit("field")],
3320        ));
3321
3322        // Verify preconditions: same schema_name but different Expr
3323        assert_eq!(
3324            expr_a.schema_name().to_string(),
3325            expr_b.schema_name().to_string(),
3326            "Both expressions should have the same schema_name"
3327        );
3328        assert_ne!(
3329            expr_a, expr_b,
3330            "Expressions should NOT be equal (different UDF instances)"
3331        );
3332
3333        let table_scan = test_table_scan_with_struct()?;
3334        let plan = LogicalPlanBuilder::from(table_scan.clone())
3335            .filter(expr_a.clone().eq(lit("a")).and(expr_b.clone().eq(lit("b"))))?
3336            .select(vec![
3337                table_scan
3338                    .schema()
3339                    .index_of_column_by_name(None, "id")
3340                    .unwrap(),
3341            ])?
3342            .build()?;
3343
3344        assert_stages!(plan, @r#"
3345        ## Original Plan
3346        Projection: test.id
3347          Filter: leaf_udf(test.user, Utf8("field")) = Utf8("a") AND leaf_udf(test.user, Utf8("field")) = Utf8("b")
3348            TableScan: test projection=[id, user]
3349
3350        ## After Extraction
3351        Projection: test.id
3352          Projection: test.id, test.user
3353            Filter: __datafusion_extracted_1 = Utf8("a") AND __datafusion_extracted_2 = Utf8("b")
3354              Projection: leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_2, test.id, test.user
3355                TableScan: test projection=[id, user]
3356
3357        ## After Pushdown
3358        (same as after extraction)
3359
3360        ## Optimized
3361        Projection: test.id
3362          Filter: __datafusion_extracted_1 = Utf8("a") AND __datafusion_extracted_2 = Utf8("b")
3363            Projection: leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_2, test.id
3364              TableScan: test projection=[id, user]
3365        "#)
3366    }
3367
3368    // =========================================================================
3369    // Filter pushdown interaction tests
3370    // =========================================================================
3371
3372    /// Extraction pushdown through a filter that already had its own
3373    /// `leaf_udf` extracted.
3374    #[test]
3375    fn test_extraction_pushdown_through_filter_with_extracted_predicate() -> Result<()> {
3376        let table_scan = test_table_scan_with_struct()?;
3377        let plan = LogicalPlanBuilder::from(table_scan)
3378            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
3379            .project(vec![col("id"), leaf_udf(col("user"), "name")])?
3380            .build()?;
3381
3382        assert_stages!(plan, @r#"
3383        ## Original Plan
3384        Projection: test.id, leaf_udf(test.user, Utf8("name"))
3385          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
3386            TableScan: test projection=[id, user]
3387
3388        ## After Extraction
3389        Projection: test.id, leaf_udf(test.user, Utf8("name"))
3390          Projection: test.id, test.user
3391            Filter: __datafusion_extracted_1 = Utf8("active")
3392              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
3393                TableScan: test projection=[id, user]
3394
3395        ## After Pushdown
3396        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
3397          Projection: test.id, test.user, __datafusion_extracted_2
3398            Filter: __datafusion_extracted_1 = Utf8("active")
3399              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
3400                TableScan: test projection=[id, user]
3401
3402        ## Optimized
3403        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
3404          Filter: __datafusion_extracted_1 = Utf8("active")
3405            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
3406              TableScan: test projection=[id, user]
3407        "#)
3408    }
3409
3410    /// Same expression in filter predicate and projection output.
3411    #[test]
3412    fn test_extraction_pushdown_same_expr_in_filter_and_projection() -> Result<()> {
3413        let table_scan = test_table_scan_with_struct()?;
3414        let field_expr = leaf_udf(col("user"), "status");
3415        let plan = LogicalPlanBuilder::from(table_scan)
3416            .filter(field_expr.clone().gt(lit(5)))?
3417            .project(vec![col("id"), field_expr])?
3418            .build()?;
3419
3420        assert_stages!(plan, @r#"
3421        ## Original Plan
3422        Projection: test.id, leaf_udf(test.user, Utf8("status"))
3423          Filter: leaf_udf(test.user, Utf8("status")) > Int32(5)
3424            TableScan: test projection=[id, user]
3425
3426        ## After Extraction
3427        Projection: test.id, leaf_udf(test.user, Utf8("status"))
3428          Projection: test.id, test.user
3429            Filter: __datafusion_extracted_1 > Int32(5)
3430              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
3431                TableScan: test projection=[id, user]
3432
3433        ## After Pushdown
3434        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))
3435          Projection: test.id, test.user, __datafusion_extracted_2
3436            Filter: __datafusion_extracted_1 > Int32(5)
3437              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
3438                TableScan: test projection=[id, user]
3439
3440        ## Optimized
3441        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))
3442          Filter: __datafusion_extracted_1 > Int32(5)
3443            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2
3444              TableScan: test projection=[id, user]
3445        "#)
3446    }
3447
3448    /// Left join with a `leaf_udf` filter on the right side AND
3449    /// the projection also selects `leaf_udf` from the right side.
3450    #[test]
3451    fn test_left_join_with_filter_and_projection_extraction() -> Result<()> {
3452        use datafusion_expr::JoinType;
3453
3454        let left = test_table_scan_with_struct()?;
3455        let right = test_table_scan_with_struct_named("right")?;
3456
3457        let plan = LogicalPlanBuilder::from(left)
3458            .join_on(
3459                right,
3460                JoinType::Left,
3461                vec![
3462                    col("test.id").eq(col("right.id")),
3463                    leaf_udf(col("right.user"), "status").gt(lit(5)),
3464                ],
3465            )?
3466            .project(vec![
3467                col("test.id"),
3468                leaf_udf(col("test.user"), "name"),
3469                leaf_udf(col("right.user"), "status"),
3470            ])?
3471            .build()?;
3472
3473        assert_stages!(plan, @r#"
3474        ## Original Plan
3475        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(right.user, Utf8("status"))
3476          Left Join:  Filter: test.id = right.id AND leaf_udf(right.user, Utf8("status")) > Int32(5)
3477            TableScan: test projection=[id, user]
3478            TableScan: right projection=[id, user]
3479
3480        ## After Extraction
3481        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(right.user, Utf8("status"))
3482          Projection: test.id, test.user, right.id, right.user
3483            Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
3484              TableScan: test projection=[id, user]
3485              Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user
3486                TableScan: right projection=[id, user]
3487
3488        ## After Pushdown
3489        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))
3490          Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_2, __datafusion_extracted_3
3491            Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
3492              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id, test.user
3493                TableScan: test projection=[id, user]
3494              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
3495                TableScan: right projection=[id, user]
3496
3497        ## Optimized
3498        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))
3499          Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
3500            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id
3501              TableScan: test projection=[id, user]
3502            Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_3
3503              TableScan: right projection=[id, user]
3504        "#)
3505    }
3506
3507    /// Extraction projection pushed through a filter whose predicate
3508    /// references a different extracted expression.
3509    #[test]
3510    fn test_pure_extraction_proj_push_through_filter() -> Result<()> {
3511        let table_scan = test_table_scan_with_struct()?;
3512        let plan = LogicalPlanBuilder::from(table_scan)
3513            .filter(leaf_udf(col("user"), "status").gt(lit(5)))?
3514            .project(vec![
3515                col("id"),
3516                leaf_udf(col("user"), "name"),
3517                leaf_udf(col("user"), "status"),
3518            ])?
3519            .build()?;
3520
3521        assert_stages!(plan, @r#"
3522        ## Original Plan
3523        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("status"))
3524          Filter: leaf_udf(test.user, Utf8("status")) > Int32(5)
3525            TableScan: test projection=[id, user]
3526
3527        ## After Extraction
3528        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("status"))
3529          Projection: test.id, test.user
3530            Filter: __datafusion_extracted_1 > Int32(5)
3531              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
3532                TableScan: test projection=[id, user]
3533
3534        ## After Pushdown
3535        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))
3536          Projection: test.id, test.user, __datafusion_extracted_2, __datafusion_extracted_3
3537            Filter: __datafusion_extracted_1 > Int32(5)
3538              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
3539                TableScan: test projection=[id, user]
3540
3541        ## Optimized
3542        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))
3543          Filter: __datafusion_extracted_1 > Int32(5)
3544            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_3
3545              TableScan: test projection=[id, user]
3546        "#)
3547    }
3548
3549    /// When an extraction projection's __extracted alias references a column
3550    /// (e.g. `user`) that is NOT a standalone expression in the projection,
3551    /// the merge into the inner projection should still succeed.
3552    #[test]
3553    fn test_merge_extraction_into_projection_with_column_ref_inflation() -> Result<()> {
3554        let table_scan = test_table_scan_with_struct()?;
3555
3556        // Inner projection (simulates a trimmed projection)
3557        let inner = LogicalPlanBuilder::from(table_scan)
3558            .project(vec![col("user"), col("id")])?
3559            .build()?;
3560
3561        // Outer projection: __extracted alias + id (but NOT user as standalone).
3562        // The alias references `user` internally, inflating columns_needed.
3563        let plan = LogicalPlanBuilder::from(inner)
3564            .project(vec![
3565                leaf_udf(col("user"), "status")
3566                    .alias(format!("{EXTRACTED_EXPR_PREFIX}_1")),
3567                col("id"),
3568            ])?
3569            .build()?;
3570
3571        // Run only PushDownLeafProjections
3572        let ctx = OptimizerContext::new().with_max_passes(1);
3573        let optimizer =
3574            Optimizer::with_rules(vec![Arc::new(PushDownLeafProjections::new())]);
3575        let result = optimizer.optimize(plan, &ctx, |_, _| {})?;
3576
3577        // With the fix: merge succeeds → extraction merged into inner projection.
3578        // Without the fix: merge rejected → two separate projections remain.
3579        insta::assert_snapshot!(format!("{result}"), @r#"
3580        Projection: __datafusion_extracted_1, test.id
3581          Projection: test.user, test.id, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1
3582            TableScan: test
3583        "#);
3584
3585        Ok(())
3586    }
3587
3588    /// Regression test: the optimizer must not push extractions through
3589    /// `Unnest`.
3590    ///
3591    /// `try_push_into_inputs` routes extracted pairs to inputs by column name.
3592    /// `Unnest` can emit an output column with the same name as its input
3593    /// column but a different value/type (the unnested element), so name-based
3594    /// routing cannot tell the two apart. `try_push_into_inputs` therefore
3595    /// treats `Unnest` as a barrier and bails instead of pushing through it
3596    /// (see the `matches!(node, LogicalPlan::Unnest(_))` guard there).
3597    #[test]
3598    fn test_no_push_through_unnest() -> Result<()> {
3599        use arrow::datatypes::{DataType, Field, Schema};
3600
3601        let schema = Schema::new(vec![
3602            Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
3603            Field::new("other_col", DataType::Int32, true),
3604        ]);
3605        let table_scan =
3606            datafusion_expr::logical_plan::table_scan(Some("t"), &schema, None)?
3607                .build()?;
3608        let plan = LogicalPlanBuilder::from(table_scan)
3609            .unnest_column("list_col")?
3610            .filter(leaf_udf(col("list_col"), "x").eq(lit(1i32)))?
3611            .build()?;
3612
3613        let ctx = OptimizerContext::new().with_max_passes(1);
3614        let optimizer = Optimizer::with_rules(vec![
3615            Arc::new(ExtractLeafExpressions::new()),
3616            Arc::new(PushDownLeafProjections::new()),
3617        ]);
3618        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
3619
3620        insta::assert_snapshot!(format!("{optimized}"), @r#"
3621        Projection: list_col, t.other_col
3622          Filter: __datafusion_extracted_1 = Int32(1)
3623            Projection: leaf_udf(list_col, Utf8("x")) AS __datafusion_extracted_1, list_col, t.other_col
3624              Unnest: lists[t.list_col|depth=1] structs[]
3625                TableScan: t
3626        "#);
3627
3628        Ok(())
3629    }
3630
3631    /// Regression test: a leaf expression used in **both** the filter and the
3632    /// projection, with the **bare base column** also projected, over a
3633    /// `SubqueryAlias` whose projection emits an **extra column the outer query
3634    /// never consumes** (`synth`).
3635    ///
3636    /// This reproduces a production failure where the leaf-pushdown passes drop
3637    /// the bare passthrough column from an intermediate schema, causing the
3638    /// subsequent `optimize_projections` run to fail with:
3639    /// `Schema error: No field named __datafusion_extracted_N`.
3640    ///
3641    /// Equivalent SQL:
3642    /// ```sql
3643    /// CREATE VIEW v AS SELECT user, id, id + 1 AS synth FROM test;
3644    /// SELECT user['status'], user, id FROM v WHERE user['status'] IS NOT NULL;
3645    /// ```
3646    #[test]
3647    fn test_subquery_alias_with_unconsumed_column() -> Result<()> {
3648        let table_scan = test_table_scan_with_struct()?;
3649
3650        // This is the plan shape *after* `push_down_filter` has run: it pushes
3651        // the `leaf_udf(...)` filter down through the `SubqueryAlias` and below
3652        // the view's inner projection. The filter and the outer projection now
3653        // each contain the same leaf expression but are separated by the
3654        // `SubqueryAlias`, so they extract into two *independent* aliases
3655        // (`__datafusion_extracted_1` from the filter, `__datafusion_extracted_2`
3656        // from the projection) instead of deduplicating into one.
3657        //
3658        // The view projects an extra `synth` column the outer query never
3659        // consumes — without it the bug does not manifest.
3660        let inner = LogicalPlanBuilder::from(table_scan)
3661            .filter(leaf_udf(col("user"), "status").is_not_null())?
3662            .project(vec![
3663                col("user"),
3664                col("id"),
3665                (col("id") + lit(1u32)).alias("synth"),
3666            ])?
3667            .alias("v")?
3668            .build()?;
3669
3670        // Outer projection: leaf expr + the bare base column + id.
3671        let plan = LogicalPlanBuilder::from(inner)
3672            .project(vec![
3673                leaf_udf(col("v.user"), "status"),
3674                col("v.user"),
3675                col("v.id"),
3676            ])?
3677            .build()?;
3678
3679        // Run the leaf-pushdown passes followed by `optimize_projections`,
3680        // exactly as the default optimizer schedules them. `optimize_projections`
3681        // is what prunes the unused `synth` column and validates the plan; if the
3682        // leaf passes drop the bare `v.user` passthrough column it fails with
3683        // `Schema error: No field named __datafusion_extracted_N`.
3684        let ctx = OptimizerContext::new();
3685        let optimizer = Optimizer::with_rules(vec![
3686            Arc::new(ExtractLeafExpressions::new()),
3687            Arc::new(PushDownLeafProjections::new()),
3688            Arc::new(OptimizeProjections::new()),
3689        ]);
3690        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
3691
3692        // The bare `test.user` passthrough column is preserved and the view's
3693        // output schema (`user`, `id`, `__datafusion_extracted_2`) is restored
3694        // by a recovery projection, so `optimize_projections` succeeds.
3695        insta::assert_snapshot!(format!("{optimized}"), @r#"
3696        Projection: __datafusion_extracted_2 AS leaf_udf(v.user,Utf8("status")), v.user, v.id
3697          SubqueryAlias: v
3698            Projection: test.user, test.id, __datafusion_extracted_2
3699              Filter: __datafusion_extracted_1 IS NOT NULL
3700                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
3701                  TableScan: test projection=[id, user]
3702        "#);
3703
3704        Ok(())
3705    }
3706
3707    /// Reproduces a schema-ambiguity failure in `PushDownLeafProjections`.
3708    ///
3709    /// ```text
3710    /// Optimizer rule 'push_down_leaf_projections' failed
3711    /// caused by
3712    /// Schema error: Schema contains qualified field name p.__datafusion_extracted_1
3713    /// and unqualified field name __datafusion_extracted_1 which would be ambiguous
3714    /// ```
3715    ///
3716    /// Four ingredients, each necessary:
3717    ///
3718    /// 1. a `SubqueryAlias` over each join input (bare aliased table scans pass),
3719    /// 2. a **left** join (an inner join passes),
3720    /// 3. a leaf expression on *each* side, so extraction pushes into both inputs,
3721    /// 4. an aggregate above the join (a projection passes).
3722    ///
3723    /// With extraction pushed inside both aliases, the left input re-exposes its
3724    /// alias qualified as `p.__datafusion_extracted_1`, while the recovery
3725    /// projection above the join rebuilds the same reference unqualified via
3726    /// `Column::new_unqualified`, so one schema ends up holding both spellings.
3727    ///
3728    /// Equivalent SQL:
3729    /// ```sql
3730    /// CREATE VIEW p AS SELECT user, id FROM test;
3731    /// CREATE VIEW c AS SELECT user, id FROM other;
3732    /// SELECT p.user['a'], count(1)
3733    /// FROM p LEFT JOIN c ON p.id = c.id
3734    /// WHERE c.user['t'] IS NOT NULL
3735    /// GROUP BY 1;
3736    /// ```
3737    #[test]
3738    fn test_leaf_expr_on_both_sides_of_left_join_under_aggregate() -> Result<()> {
3739        use datafusion_expr::JoinType;
3740        use datafusion_expr::test::function_stub::count;
3741
3742        fn view(name: &str, table: LogicalPlan) -> Result<LogicalPlan> {
3743            LogicalPlanBuilder::from(table)
3744                .project(vec![col("user"), col("id")])?
3745                .alias(name)?
3746                .build()
3747        }
3748
3749        let left = view("p", test_table_scan_with_struct()?)?;
3750        let right = view("c", test_table_scan_with_struct_named("right")?)?;
3751
3752        let plan = LogicalPlanBuilder::from(left)
3753            .join(right, JoinType::Left, (vec!["id"], vec!["id"]), None)?
3754            .filter(leaf_udf(col("c.user"), "t").is_not_null())?
3755            .aggregate(vec![leaf_udf(col("p.user"), "a")], vec![count(lit(1))])?
3756            .build()?;
3757
3758        // The full optimizer, not `format_optimization_stages`: the triggering
3759        // shape (`p.__datafusion_extracted_1 AS __datafusion_extracted_1`) only
3760        // appears once projection merging has collapsed the recovery projection
3761        // over the `SubqueryAlias`.
3762        let ctx = OptimizerContext::new();
3763        let optimized = Optimizer::new().optimize(plan, &ctx, |_, _| {})?;
3764        insta::assert_snapshot!(format!("{optimized}"), @r#"
3765        Projection: __datafusion_extracted_1 AS leaf_udf(p.user,Utf8("a")), COUNT(Int32(1))
3766          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
3767            Projection: p.__datafusion_extracted_1 AS __datafusion_extracted_1
3768              Inner Join: p.id = c.id
3769                SubqueryAlias: p
3770                  Projection: test.id, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
3771                    TableScan: test projection=[id, user]
3772                SubqueryAlias: c
3773                  Projection: right.id
3774                    Filter: __datafusion_extracted_2 IS NOT NULL
3775                      Projection: right.id, leaf_udf(right.user, Utf8("t")) AS __datafusion_extracted_2
3776                        TableScan: right projection=[id, user]
3777        "#);
3778        Ok(())
3779    }
3780
3781    /// Pre-existing `__datafusion_extracted_N` aliases must advance the alias
3782    /// generator even when they live inside a subquery plan, since extraction
3783    /// descends into subqueries and would otherwise reuse the same alias.
3784    #[test]
3785    fn test_advance_generator_past_alias_in_subquery() -> Result<()> {
3786        use datafusion_expr::in_subquery;
3787
3788        let subquery = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
3789            .project(vec![
3790                leaf_udf(col("user"), "name").alias("__datafusion_extracted_7"),
3791            ])?
3792            .build()?;
3793        let plan = LogicalPlanBuilder::from(test_table_scan_with_struct_named("outer")?)
3794            .filter(in_subquery(col("id"), Arc::new(subquery)))?
3795            .build()?;
3796
3797        let alias_generator = AliasGenerator::new();
3798        advance_generator_past_existing(&plan, &alias_generator)?;
3799
3800        assert_eq!(
3801            alias_generator.next(EXTRACTED_EXPR_PREFIX),
3802            "__datafusion_extracted_8"
3803        );
3804
3805        Ok(())
3806    }
3807
3808    /// Regression test for issue #23655: `f(c)['a'], f(c)['b']` on a
3809    /// struct-returning UDF must evaluate `f(c)` once, not once per field access.
3810    ///
3811    /// `keep_in_place_udf` / `get_field_like` model `f(c)` and `f(c)[key]` — the
3812    /// crate can't depend on the real `get_field` (see [`get_field_like`]).
3813    /// Without the guard, `PushDownLeafProjections` re-inlines the shared UDF that
3814    /// `CommonSubexprEliminate` hoisted and the passes oscillate to a double
3815    /// evaluation.
3816    #[test]
3817    fn test_struct_returning_udf_evaluated_once() -> Result<()> {
3818        let udf = ScalarUDF::new_from_impl(
3819            PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
3820        );
3821        let f_c = udf.call(vec![col("c")]);
3822        let plan = LogicalPlanBuilder::from(test_table_scan()?)
3823            .project(vec![
3824                get_field_like(f_c.clone(), "a"),
3825                get_field_like(f_c, "b"),
3826            ])?
3827            .build()?;
3828
3829        // The full four-rule interaction, default pass budget so any oscillation
3830        // would surface here as a double evaluation.
3831        let ctx = OptimizerContext::new();
3832        let optimizer = Optimizer::with_rules(vec![
3833            Arc::new(CommonSubexprEliminate::new()),
3834            Arc::new(ExtractLeafExpressions::new()),
3835            Arc::new(PushDownLeafProjections::new()),
3836            Arc::new(OptimizeProjections::new()),
3837        ]);
3838        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
3839
3840        // Every field access reads the UDF back through `__common_expr_1`; none
3841        // wraps a fresh `keep_in_place_udf(...)` call. Asserted explicitly so a
3842        // careless snapshot re-accept can't quietly restore the double evaluation.
3843        let formatted = format!("{optimized}");
3844        assert_eq!(
3845            formatted
3846                .matches("get_field_like(keep_in_place_udf")
3847                .count(),
3848            0,
3849            "struct-returning UDF must not be re-evaluated inside a field access; got:\n{formatted}"
3850        );
3851
3852        insta::assert_snapshot!(formatted, @r#"
3853        Projection: get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("a")), get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("b"))
3854          Projection: keep_in_place_udf(test.c) AS __common_expr_1
3855            TableScan: test projection=[c]
3856        "#);
3857
3858        Ok(())
3859    }
3860
3861    #[test]
3862    fn test_struct_returning_udf_evaluated_once_with_bare_reference() -> Result<()> {
3863        // Regression for the `SELECT f(c)['a'], f(c)` shape: the struct UDF is
3864        // referenced once through a field access and once as a bare value. The
3865        // bare reference is tracked in `columns_needed`, not `extraction_pairs`,
3866        // so a guard that counted only pairs would re-inline `f(c)` and evaluate
3867        // it twice (#23655).
3868        let udf = ScalarUDF::new_from_impl(
3869            PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
3870        );
3871        let f_c = udf.call(vec![col("c")]);
3872        let plan = LogicalPlanBuilder::from(test_table_scan()?)
3873            .project(vec![get_field_like(f_c.clone(), "a"), f_c])?
3874            .build()?;
3875
3876        let ctx = OptimizerContext::new();
3877        let optimizer = Optimizer::with_rules(vec![
3878            Arc::new(CommonSubexprEliminate::new()),
3879            Arc::new(ExtractLeafExpressions::new()),
3880            Arc::new(PushDownLeafProjections::new()),
3881            Arc::new(OptimizeProjections::new()),
3882        ]);
3883        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
3884
3885        // The field access must read the UDF back through `__common_expr_1`, not
3886        // wrap a fresh `keep_in_place_udf(...)` call. Asserted explicitly so a
3887        // careless snapshot re-accept can't quietly restore the double evaluation.
3888        let formatted = format!("{optimized}");
3889        assert_eq!(
3890            formatted
3891                .matches("get_field_like(keep_in_place_udf")
3892                .count(),
3893            0,
3894            "struct-returning UDF must not be re-evaluated inside a field access; got:\n{formatted}"
3895        );
3896
3897        insta::assert_snapshot!(formatted, @r#"
3898        Projection: get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("a")), __common_expr_1 AS keep_in_place_udf(test.c)
3899          Projection: keep_in_place_udf(test.c) AS __common_expr_1
3900            TableScan: test projection=[c]
3901        "#);
3902
3903        Ok(())
3904    }
3905
3906    /// `passthrough_column` tells `split_and_push_projection` which projection
3907    /// expressions the input already produces. A renaming alias (`test.a AS b`)
3908    /// does not qualify: it is a new output column. If the function accepted
3909    /// it, the rename would count as captured, and the recovery projection
3910    /// that restores the name would be dropped.
3911    #[test]
3912    fn test_passthrough_column_rejects_renaming_alias() {
3913        // A bare column is a pass-through.
3914        let bare = Expr::Column(Column::new(Some("test"), "a"));
3915        assert_eq!(
3916            passthrough_column(&bare).map(|c| c.flat_name()),
3917            Some("test.a".to_string())
3918        );
3919
3920        // `test.a AS a` keeps the name, so it is a pass-through.
3921        let trivial_rename = Expr::Column(Column::new(Some("test"), "a")).alias("a");
3922        assert_eq!(
3923            passthrough_column(&trivial_rename).map(|c| c.flat_name()),
3924            Some("test.a".to_string())
3925        );
3926
3927        // `test.a AS b` changes the name, so it is not a pass-through.
3928        let renaming = Expr::Column(Column::new(Some("test"), "a")).alias("b");
3929        assert_eq!(passthrough_column(&renaming), None);
3930
3931        // An alias over anything other than a column is not a pass-through.
3932        let not_a_column = lit(1).alias("a");
3933        assert_eq!(passthrough_column(&not_a_column), None);
3934    }
3935
3936    /// `is_pure_extraction_projection` decides if a merged projection can go
3937    /// down one more level. It must accept only `__datafusion_extracted`
3938    /// aliases and plain columns, and only with at least one extraction. An
3939    /// alias with a different prefix must not count: a second push would
3940    /// re-extract the expression under a new alias that the parent cannot
3941    /// resolve.
3942    #[test]
3943    fn test_is_pure_extraction_projection() -> Result<()> {
3944        let scan = test_table_scan_with_struct()?;
3945
3946        // Columns only: nothing was extracted.
3947        let columns_only = LogicalPlanBuilder::from(scan.clone())
3948            .project(vec![col("id"), col("user")])?
3949            .build()?;
3950        assert!(!is_pure_extraction_projection(&columns_only.expressions()));
3951
3952        // One extraction alias and one pass-through column.
3953        let pure = LogicalPlanBuilder::from(scan.clone())
3954            .project(vec![
3955                leaf_udf(col("user"), "status").alias("__datafusion_extracted_1"),
3956                col("id"),
3957            ])?
3958            .build()?;
3959        assert!(is_pure_extraction_projection(&pure.expressions()));
3960
3961        // The same shape under a `CommonSubexprEliminate` alias is not an
3962        // extraction projection.
3963        let common_expr = LogicalPlanBuilder::from(scan.clone())
3964            .project(vec![
3965                leaf_udf(col("user"), "status").alias("__common_expr_1"),
3966                col("id"),
3967            ])?
3968            .build()?;
3969        assert!(!is_pure_extraction_projection(&common_expr.expressions()));
3970
3971        // A bare expression is never allowed.
3972        let bare_expr = LogicalPlanBuilder::from(scan)
3973            .project(vec![leaf_udf(col("user"), "status"), col("id")])?
3974            .build()?;
3975        assert!(!is_pure_extraction_projection(&bare_expr.expressions()));
3976
3977        Ok(())
3978    }
3979
3980    /// A non-volatile `KeepInPlace` expression: the kind that
3981    /// `CommonSubexprEliminate` hoists into a column so it runs one time.
3982    fn keep_in_place_udf(expr: Expr) -> Expr {
3983        Expr::ScalarFunction(ScalarFunction::new_udf(
3984            Arc::new(ScalarUDF::new_from_impl(
3985                PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
3986            )),
3987            vec![expr],
3988        ))
3989    }
3990
3991    /// `merge_would_duplicate_kept_expr` must block a merge only when it would
3992    /// inline one `KeepInPlace` definition into more than one reference site.
3993    /// It must count reference sites for `KeepInPlace` columns alone: a plain
3994    /// column is cheap to duplicate, and a merge that touches only plain
3995    /// columns must still go ahead.
3996    #[test]
3997    fn test_merge_would_duplicate_kept_expr_counts_only_kept_columns() -> Result<()> {
3998        let scan = test_table_scan_with_struct()?;
3999        // `k` holds a `KeepInPlace` definition. `id` is a plain column.
4000        let child = Projection::try_new(
4001            vec![keep_in_place_udf(col("user")).alias("k"), col("id")],
4002            Arc::new(scan),
4003        )?;
4004        let no_columns = IndexSet::new();
4005
4006        // One reference site: the merge inlines one copy, so it is free.
4007        let one_site = vec![(
4008            get_field_like(col("k"), "a"),
4009            "__datafusion_extracted_1".to_string(),
4010        )];
4011        assert!(!merge_would_duplicate_kept_expr(
4012            &one_site,
4013            &no_columns,
4014            &child
4015        ));
4016
4017        // Two reference sites: the merge would evaluate `k` two times.
4018        let two_sites = vec![
4019            (
4020                get_field_like(col("k"), "a"),
4021                "__datafusion_extracted_1".to_string(),
4022            ),
4023            (
4024                get_field_like(col("k"), "b"),
4025                "__datafusion_extracted_2".to_string(),
4026            ),
4027        ];
4028        assert!(merge_would_duplicate_kept_expr(
4029            &two_sites,
4030            &no_columns,
4031            &child
4032        ));
4033
4034        // A pass-through reference to `k` is a second site too (#23655).
4035        let kept_column: IndexSet<Column> =
4036            std::iter::once(Column::new_unqualified("k")).collect();
4037        assert!(merge_would_duplicate_kept_expr(
4038            &one_site,
4039            &kept_column,
4040            &child
4041        ));
4042
4043        // Two sites that reference the plain column `id` are cheap to
4044        // duplicate, so the merge must still go ahead.
4045        let plain_column_sites = vec![
4046            (
4047                get_field_like(col("id"), "a"),
4048                "__datafusion_extracted_1".to_string(),
4049            ),
4050            (
4051                get_field_like(col("id"), "b"),
4052                "__datafusion_extracted_2".to_string(),
4053            ),
4054        ];
4055        assert!(!merge_would_duplicate_kept_expr(
4056            &plain_column_sites,
4057            &no_columns,
4058            &child
4059        ));
4060        Ok(())
4061    }
4062
4063    /// Regression test for <https://github.com/apache/datafusion/issues/25414>.
4064    ///
4065    /// `(- test.id) AS id` computes a new value under the same name as its input
4066    /// column `test.id`. Pushing the extraction below that projection makes
4067    /// `test.id` visible again under the name `id`. The recovery projection must
4068    /// stay, or the computed column is silently replaced by the table column.
4069    ///
4070    /// The two leaf rules run alone here, in their production order.
4071    /// `optimize_projections` merges the two projections into one and hides the
4072    /// shape, and it only runs after both leaf rules.
4073    #[test]
4074    fn test_recovery_kept_for_same_name_computed_column() -> Result<()> {
4075        let table_scan = test_table_scan_with_struct()?;
4076        let plan = LogicalPlanBuilder::from(table_scan)
4077            .filter(col("id").gt(lit(0u32)))?
4078            .project(vec![
4079                Expr::Negative(Box::new(col("id"))).alias("id"),
4080                col("user"),
4081            ])?
4082            .project(vec![col("id"), leaf_udf(col("user"), "name")])?
4083            .build()?;
4084
4085        let ctx = OptimizerContext::new().with_max_passes(1);
4086        let optimizer = Optimizer::with_rules(vec![
4087            Arc::new(ExtractLeafExpressions::new()),
4088            Arc::new(PushDownLeafProjections::new()),
4089        ]);
4090        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;
4091
4092        insta::assert_snapshot!(format!("{optimized}"), @r#"
4093        Projection: id, __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
4094          Projection: (- test.id) AS id, test.user, __datafusion_extracted_1
4095            Filter: test.id > UInt32(0)
4096              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
4097                TableScan: test
4098        "#);
4099        Ok(())
4100    }
4101}