You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/09/03 03:51:28 UTC

(datafusion) 01/01: fix: do not duplicate volatile expressions when extracting leaf expressions (#24720)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-24720-17115f368dbdf0f21428c0991c3f8ec11f96c090
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit 27e81e9a45317afeacd7d7dc2b77f10637ecd5d5
Author: Jaideep Pyne <ja...@gmail.com>
AuthorDate: Thu Sep 3 03:50:58 2026 +0000

    fix: do not duplicate volatile expressions when extracting leaf expressions (#24720)
    
    ## Which issue does this PR close?
    
    - Closes #24678.
    
    ## Rationale for this change
    
    A column alias denotes one value per row, and `WHERE p` may only return
    rows for which `p` held for that row. Today the leaf-expression
    extraction passes break both:
    
    ```sql
    SELECT s, s['a'] AS field
    FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 3));
    ```
    
    | `s['a']` | `field` |
    |---|---|
    | 0.5159112071865757 | 0.4514238291986653 |
    | 0.0029104680074608646 | 0.28979983332288195 |
    | 0.48542729227457915 | 0.04499392663566881 |
    
    `field` is defined as `s['a']` but differs from it on every row, because
    the plan is
    
    ```
    Projection: named_struct(Utf8("a"), random()) AS s, random() AS field
    ```
    
    The `Filter` form is worse — it returns rows that fail their own
    predicate:
    
    ```sql
    SELECT bool_and(s['a'] > 0.5)
    FROM (SELECT s FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 1000))
          WHERE s['a'] > 0.5);
    -- false; the predicate tested a different draw than the one in the returned `s`
    ```
    
    Setting `datafusion.optimizer.enable_leaf_expression_pushdown = false`
    returns the correct answer in both cases, so the rewrite alone changes
    the meaning of the query.
    
    **Root cause.** `build_extraction_projection_impl` merges an extraction
    into the input projection by resolving column references through
    `build_projection_replace_map`, i.e. by inlining each referenced
    column's *defining* expression. Inlining a volatile definition produces
    a second, independent evaluation. There was no volatility check in the
    file.
    
    This is the same invariant
    `FileScanConfig::try_swapping_with_projection` already enforces for the
    physical projection-pushdown path via `would_duplicate_costly_exprs`
    (#23220) — the logical extraction path was missing it.
    
    ## What changes are included in this PR?
    
    - `volatile_output_columns()` — a projection's output columns whose
    definition is volatile.
    - `would_duplicate_volatile()` — true when an extraction references one
    of them.
    - The guard is applied at the three places that can merge into an input
    projection: `extract_from_plan` (pass 1:
    Filter/Sort/Limit/Aggregate/Join), `split_and_push_projection` (pass 2),
    and `try_push_into_inputs` (multi-input/Union routing). Each already had
    a "leave the plan alone" return path.
    
    The guard is targeted rather than blanket: for `ORDER BY s['a']` the
    extraction still happens, stacked above the volatile projection instead
    of merged into it, so the optimization is kept and the result is
    correct.
    
    ### Relationship to #23691
    
    @fornwall wondered on the issue whether #23691 already covers this. I
    checked out that branch and ran both shapes against it: `SELECT s,
    s['a']` is incidentally fixed there, but `WHERE s['a'] > 0.5` still
    duplicates `random()` and still returns rows failing the predicate.
    #23691 guards `KeepInPlace` *compute cost* in
    `split_and_push_projection` only; volatility is a separate concern (one
    duplication is already wrong, regardless of cost or placement) and pass
    1 is a different code path. The two changes look independent to me and I
    believe they compose, but I'd appreciate a second opinion on that from
    whoever reviews #23691.
    
    ## Are these changes tested?
    
    Yes.
    
    - `datafusion/sqllogictest/test_files/projection_pushdown.slt` — a new
    section beside the existing #23220 volatile section: two `EXPLAIN`s
    pinning `random()` to a single occurrence, and two deterministic
    `bool_and(...)` correctness queries. All four fail on `main` and pass
    here.
    - Two rule-level snapshot tests in `extract_leaf_expressions.rs`
    covering the pass-2 projection merge and the pass-1 `Filter` extraction,
    using a new test-only `PlacementTestUDF::with_volatility()`.
    
    `cargo test -p datafusion-optimizer` (796), `cargo test -p datafusion
    --lib --tests` (2049) and the full 504-file sqllogictest suite all pass;
    `cargo fmt --all` and `cargo clippy --all-targets --all-features -- -D
    warnings` are clean.
    
    ## Are there any user-facing changes?
    
    Queries that were silently returning wrong results now return correct
    ones. No API change. In the affected shapes the extraction is skipped,
    which can cost a small amount of column pruning — only when the
    referenced column is defined by a volatile expression.
    
    ---
    
    <sub>Per the ASF generative-tooling policy and DataFusion's AI-assisted
    contribution guidance: this patch was prepared with AI assistance. The
    core idea is the one described above — the merge path inlines a
    referenced column's defining expression, which duplicates a volatile
    definition — and the open question about how this composes with #23691
    is flagged deliberately rather than glossed over.</sub>
---
 .../optimizer/src/extract_leaf_expressions.rs      | 156 ++++++++++++++++++++-
 datafusion/optimizer/src/test/udfs.rs              |  11 +-
 .../test_files/projection_pushdown.slt             |  77 ++++++++++
 3 files changed, 240 insertions(+), 4 deletions(-)

diff --git a/datafusion/optimizer/src/extract_leaf_expressions.rs b/datafusion/optimizer/src/extract_leaf_expressions.rs
index 107758cf6b..dfaf93bc1e 100644
--- a/datafusion/optimizer/src/extract_leaf_expressions.rs
+++ b/datafusion/optimizer/src/extract_leaf_expressions.rs
@@ -57,6 +57,58 @@ fn has_extractable_expr(exprs: &[Expr]) -> bool {
     })
 }
 
+/// Returns the flat names of `plan`'s output columns whose defining expression
+/// is volatile (e.g. `random()`).
+///
+/// Only a [`LogicalPlan::Projection`] can define such a column: anywhere else
+/// the value has already been materialized by the projection that produced it,
+/// so referencing the column again does not re-evaluate anything.
+fn volatile_output_columns(plan: &LogicalPlan) -> BTreeSet<String> {
+    let LogicalPlan::Projection(projection) = plan else {
+        return BTreeSet::new();
+    };
+    projection
+        .schema
+        .iter()
+        .zip(projection.expr.iter())
+        .filter(|(_, expr)| expr.is_volatile())
+        .map(|((qualifier, field), _)| Column::from((qualifier, field)).flat_name())
+        .collect()
+}
+
+/// Returns `true` if building an extraction projection for `exprs` on top of
+/// `input` would duplicate a volatile computation.
+///
+/// When `input` is already a projection, [`build_extraction_projection_impl`]
+/// *merges* into it: every column reference in an extracted expression is
+/// replaced by that column's defining expression (see
+/// [`build_projection_replace_map`]). Inlining a volatile definition makes the
+/// merged projection evaluate it a second, independent time, so the extracted
+/// value no longer matches the column it was derived from:
+///
+/// ```text
+/// Projection: s, get_field(s, 'a') AS field
+///   Projection: named_struct('a', random()) AS s
+/// ```
+///
+/// would merge into a single projection computing `random()` twice, and
+/// `field` would then differ from `s['a']` on every row. Callers skip the
+/// extraction instead.
+fn would_duplicate_volatile<'a>(
+    exprs: impl IntoIterator<Item = &'a Expr>,
+    input: &LogicalPlan,
+) -> bool {
+    let volatile = volatile_output_columns(input);
+    if volatile.is_empty() {
+        return false;
+    }
+    exprs.into_iter().any(|expr| {
+        expr.column_refs()
+            .iter()
+            .any(|col| volatile.contains(&col.flat_name()))
+    })
+}
+
 /// Extracts `MoveTowardsLeafNodes` sub-expressions from non-projection nodes
 /// into **extraction projections** (pass 1 of 2).
 ///
@@ -195,7 +247,18 @@ fn extract_from_plan(
     }
 
     // Fast pre-check: skip all allocations if no extractable expressions exist
-    if !has_extractable_expr(&plan.expressions()) {
+    let node_exprs = plan.expressions();
+    if !has_extractable_expr(&node_exprs) {
+        return Ok(Transformed::no(plan));
+    }
+
+    // The extraction projection is merged into an input that is already a
+    // projection, which inlines the referenced columns' definitions. Skip the
+    // extraction when that would duplicate a volatile computation.
+    if inputs
+        .iter()
+        .any(|input| would_duplicate_volatile(node_exprs.iter(), input))
+    {
         return Ok(Transformed::no(plan));
     }
 
@@ -917,6 +980,16 @@ fn split_and_push_projection(
         return Ok(None);
     }
 
+    // Pushing into an input that is already a projection merges into it and
+    // inlines the referenced columns' definitions. Leave the projection alone
+    // when that would duplicate a volatile computation.
+    if would_duplicate_volatile(
+        extraction_pairs.iter().map(|(expr, _)| expr),
+        input.as_ref(),
+    ) {
+        return Ok(None);
+    }
+
     // ── Phase 2: Push down ──────────────────────────────────────────────
     let proj_input = Arc::clone(&proj.input);
     let pushed = push_extraction_pairs(
@@ -1215,6 +1288,15 @@ fn try_push_into_inputs(
         if per_input[idx].pairs.is_empty() {
             new_inputs.push(input.clone());
         } else {
+            // Merging into an input projection inlines the referenced columns'
+            // definitions; bail out when that would duplicate a volatile
+            // computation.
+            if would_duplicate_volatile(
+                per_input[idx].pairs.iter().map(|(expr, _)| expr),
+                input,
+            ) {
+                return Ok(None);
+            }
             let input_arc = Arc::new(input.clone());
             let target_schema = Arc::clone(input.schema());
             let proj = build_extraction_projection_impl(
@@ -1270,7 +1352,7 @@ mod tests {
     use crate::{Optimizer, OptimizerContext};
     use datafusion_expr::expr::ScalarFunction;
     use datafusion_expr::{
-        ScalarUDF, col, lit, logical_plan::builder::LogicalPlanBuilder,
+        ScalarUDF, Volatility, col, lit, logical_plan::builder::LogicalPlanBuilder,
     };
 
     fn leaf_udf(expr: Expr, name: &str) -> Expr {
@@ -1283,6 +1365,19 @@ mod tests {
         ))
     }
 
+    /// A stand-in for `random()`: a volatile expression that must be evaluated
+    /// exactly once per row.
+    fn volatile_udf(expr: Expr) -> Expr {
+        Expr::ScalarFunction(ScalarFunction::new_udf(
+            Arc::new(ScalarUDF::new_from_impl(
+                PlacementTestUDF::new()
+                    .with_placement(ExpressionPlacement::KeepInPlace)
+                    .with_volatility(Volatility::Volatile),
+            )),
+            vec![expr],
+        ))
+    }
+
     // =========================================================================
     // Combined optimization stage formatter
     // =========================================================================
@@ -1960,6 +2055,63 @@ mod tests {
         "#)
     }
 
+    /// Merging an extraction into an input projection inlines the definition of
+    /// every column the extraction references. When that definition is volatile
+    /// the inlined copy is an independent evaluation, so the extraction must be
+    /// skipped and the plan left alone.
+    #[test]
+    fn test_no_merge_into_volatile_projection() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .project(vec![volatile_udf(col("a")).alias("v")])?
+            .project(vec![col("v"), leaf_udf(col("v"), "x")])?
+            .build()?;
+
+        assert_stages!(plan, @r#"
+        ## Original Plan
+        Projection: v, leaf_udf(v, Utf8("x"))
+          Projection: keep_in_place_udf(test.a) AS v
+            TableScan: test projection=[a]
+
+        ## After Extraction
+        (same as original)
+
+        ## After Pushdown
+        (same as after extraction)
+
+        ## Optimized
+        (same as after pushdown)
+        "#)
+    }
+
+    /// Same guard for pass 1: extracting out of a `Filter` whose input
+    /// projection defines the referenced column volatilely would make the
+    /// predicate test a second, independent evaluation.
+    #[test]
+    fn test_no_extraction_from_filter_over_volatile_projection() -> Result<()> {
+        let table_scan = test_table_scan()?;
+        let plan = LogicalPlanBuilder::from(table_scan)
+            .project(vec![volatile_udf(col("a")).alias("v")])?
+            .filter(leaf_udf(col("v"), "x").eq(lit(1u32)))?
+            .build()?;
+
+        assert_stages!(plan, @r#"
+        ## Original Plan
+        Filter: leaf_udf(v, Utf8("x")) = UInt32(1)
+          Projection: keep_in_place_udf(test.a) AS v
+            TableScan: test projection=[a]
+
+        ## After Extraction
+        (same as original)
+
+        ## After Pushdown
+        (same as after extraction)
+
+        ## Optimized
+        (same as after pushdown)
+        "#)
+    }
+
     /// Projections with aliased columns (nothing to extract) return unchanged.
     #[test]
     fn test_projection_early_return_no_extraction() -> Result<()> {
diff --git a/datafusion/optimizer/src/test/udfs.rs b/datafusion/optimizer/src/test/udfs.rs
index ba71b6a04a..72b1a63f67 100644
--- a/datafusion/optimizer/src/test/udfs.rs
+++ b/datafusion/optimizer/src/test/udfs.rs
@@ -19,7 +19,7 @@ use arrow::datatypes::DataType;
 use datafusion_common::Result;
 use datafusion_expr::{
     ColumnarValue, Expr, ExpressionPlacement, ScalarFunctionArgs, ScalarUDF,
-    ScalarUDFImpl, Signature, TypeSignature,
+    ScalarUDFImpl, Signature, TypeSignature, Volatility,
 };
 
 /// A configurable test UDF for optimizer tests.
@@ -44,7 +44,7 @@ impl PlacementTestUDF {
             // The actual types don't matter since this UDF is not intended for execution.
             signature: Signature::new(
                 TypeSignature::OneOf(vec![TypeSignature::Any(1), TypeSignature::Any(2)]),
-                datafusion_expr::Volatility::Immutable,
+                Volatility::Immutable,
             ),
             placement: ExpressionPlacement::MoveTowardsLeafNodes,
             id: 0,
@@ -64,6 +64,13 @@ impl PlacementTestUDF {
         self.id = id;
         self
     }
+
+    /// Set the volatility of the UDF, so that rules which must not duplicate a
+    /// volatile computation (e.g. `random()`) can be exercised.
+    pub fn with_volatility(mut self, volatility: Volatility) -> Self {
+        self.signature.volatility = volatility;
+        self
+    }
 }
 
 impl ScalarUDFImpl for PlacementTestUDF {
diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt
index 3c7b6f4cb1..1f9176f713 100644
--- a/datafusion/sqllogictest/test_files/projection_pushdown.slt
+++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt
@@ -2144,6 +2144,83 @@ true
 true
 true
 
+#####################
+# Section: leaf expression extraction does not duplicate volatile expressions
+#
+# Regression test for #24678. `extract_leaf_expressions` / `push_down_leaf_projections`
+# build an extraction projection by *merging* into the input projection, which
+# inlines the definition of every column the extracted expression references.
+# When that definition is volatile the inlined copy is an independent
+# evaluation, so `random()` is drawn twice and the extracted value no longer
+# matches the struct it was derived from.
+#
+# Before the fix the plan below read
+#   Projection: named_struct(Utf8("a"), random()) AS s, random() AS field
+# and `field` differed from `s['a']` on every row. This is the same invariant
+# `FileScanConfig::try_swapping_with_projection` already enforces for the
+# physical pushdown path (#23220).
+#####################
+
+statement ok
+set datafusion.explain.logical_plan_only = true;
+
+# `random()` must appear once; `field` reads the struct materialized below it.
+query TT
+EXPLAIN SELECT s, s['a'] AS field
+FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 3));
+----
+logical_plan
+01)Projection: s, get_field(s, Utf8("a")) AS field
+02)--Projection: named_struct(Utf8("a"), random()) AS s
+03)----TableScan: generate_series() projection=[]
+
+# Same for an extraction out of a Filter: the predicate must test the struct
+# that is returned, not a second draw.
+query TT
+EXPLAIN SELECT s
+FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 3))
+WHERE s['a'] > 0.5;
+----
+logical_plan
+01)Filter: get_field(s, Utf8("a")) > Float64(0.5)
+02)--Projection: named_struct(Utf8("a"), random()) AS s
+03)----TableScan: generate_series() projection=[]
+
+statement ok
+set datafusion.explain.logical_plan_only = false;
+
+# Every row's `field` is the `a` field of that row's own struct.
+query B
+SELECT bool_and(field = s['a'])
+FROM (
+  SELECT s, s['a'] AS field
+  FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 1000))
+);
+----
+true
+
+# Same invariant when the extraction is routed into one side of a join.
+query B
+SELECT bool_and(field = s['a'])
+FROM (
+  SELECT l.s, l.s['a'] AS field
+  FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 1000)) AS l
+  INNER JOIN (SELECT 1 AS k) AS r ON true
+);
+----
+true
+
+# Every surviving row satisfies the predicate it was filtered on.
+query B
+SELECT bool_and(s['a'] > 0.5)
+FROM (
+  SELECT s
+  FROM (SELECT named_struct('a', random()) AS s FROM generate_series(1, 1000))
+  WHERE s['a'] > 0.5
+);
+----
+true
+
 #####################
 # Section: expensive expressions are not re-inlined by projection pushdown
 #


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org