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

dongjoon-hyun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new fea3ac7a6651 [SPARK-61232][SQL] UnionExec whole-stage codegen fails 
when a child output repeats an ExprId
fea3ac7a6651 is described below

commit fea3ac7a665125f078ef33cc63a13e92ac6608b4
Author: Xiduo You <[email protected]>
AuthorDate: Mon Nov 9 22:56:10 2026 -0800

    [SPARK-61232][SQL] UnionExec whole-stage codegen fails when a child output 
repeats an ExprId
    
    ### What changes were proposed in this pull request?
    
    `UnionExec.doConsume` projected each child column through an `Alias` over 
the child's
    `Attribute` and bound it with `BindReferences`, which resolves an `ExprId` 
to its first
    occurrence in the child's output. A child output that repeats an `ExprId` 
(a union that
    concatenates a `SELECT p, p, w` branch) therefore read the first position 
for both, so the
    second union output column took the first column's value, and the generated 
row declared
    that input variable twice, which Janino rejects with "Redefinition of local 
variable".
    
    Read the child row positionally instead: one `BoundReference` per union 
output column at
    its own position. That is what `doExecute` does, since it concatenates 
child rows as they
    are. `perChildProjections`, its `Alias` wrapper and the `BindReferences` 
call are removed.
    
    ### Why are the changes needed?
    
    The union's whole-stage codegen path has to keep each output column at its 
own position,
    not at the first occurrence of its `ExprId`: otherwise the wrong column is 
read and the
    shared input variable's declaration is emitted twice, which fails the stage.
    
    The union whole-stage codegen was added in 4.2.0 (SPARK-56482); it is off 
by default on the
    4.2 line and on by default from 4.3. The repeated-`ExprId` shape also needs 
the two
    analyzer confs below disabled, so the default analyzer path never reaches 
it:
    
    - `spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved=false`
    - `spark.sql.enforceTypeCoercionBeforeUnionDeduplication.enabled=false`
    
    The analyzer otherwise removes a repeated output column with 
`DeduplicateUnionChildOutput`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, a bug fix. Unions that do not repeat an `ExprId` in a child's output 
are unaffected:
    binding by position and binding by `ExprId` pick the same position when the 
`ExprId` is
    unique. Only the union's whole-stage codegen path changes; `doExecute` was 
already
    positional.
    
    ### How was this patch tested?
    
    Added a `SPARK-61232` case to `UnionCodegenSuite`. It builds the 
repeated-`ExprId` shape,
    asserts that a fused union's `InputAdapter` child still repeats an `ExprId` 
and that the
    outer union fuses over its query stages, and compares the fused result with 
the interpreted
    one. Before the fix it fails with the Janino redefinition; after it, 
`UnionCodegenSuite`,
    `UnionCodegenAnsiSuite` and `UnionCodegenAqeSuite` pass 177/177.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Yes, with Claude Code.
    
    Assisted-by: deepseek-flash
    
    
    Closes #60236 from ulysses-you/union-duplicate-expr-codegen.
    
    Authored-by: Xiduo You <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
    
    
    skip-checks: true
---
 .../sql/execution/basicPhysicalOperators.scala     | 31 ++++--------
 .../spark/sql/execution/UnionCodegenSuite.scala    | 56 ++++++++++++++++++++++
 .../sql/execution/benchmark/UnionBenchmark.scala   |  6 +--
 3 files changed, 69 insertions(+), 24 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
index 3c94cab249b5..010b351b2d95 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala
@@ -1377,22 +1377,6 @@ case class UnionExec(children: Seq[SparkPlan]) extends 
SparkPlan with CodegenSup
     if (isPlainUnion(raw)) super.outputPartitioning else raw
   }
 
-  // Per-child projection from the child's output to the union's output. The 
wrapped
-  // child is always the source `Attribute` (deterministic by construction); 
the Alias
-  // only remaps the exprId/name/metadata. `WidenSetOperationTypes` aligns 
top-level
-  // dataTypes, but nested nullability differences bypass it; those cases are 
caught
-  // by the `type-mismatch` gate below, which is the single source of truth 
for the
-  // `src.dataType == tgt.dataType` invariant `doConsume` relies on.
-  @transient private lazy val perChildProjections: 
IndexedSeq[Seq[NamedExpression]] =
-    children.toIndexedSeq.map { child =>
-      child.output.zip(output).map { case (src, tgt) =>
-        Alias(src, tgt.name)(
-          exprId = tgt.exprId,
-          qualifier = tgt.qualifier,
-          explicitMetadata = Some(tgt.metadata))
-      }
-    }
-
   // The confs the gate reads, taken from the record rather than live for the 
reason the plain-union
   // decision is stamped: `conf` is live, so the gate, `metrics` and the copy 
`insertInputAdapter`
   // puts inside the codegen shell would otherwise be free to read different 
values. When a child is
@@ -1501,7 +1485,7 @@ case class UnionExec(children: Seq[SparkPlan]) extends 
SparkPlan with CodegenSup
   // Per-emission codegen state, set in `doProduce` and read in `doConsume`.
   // `numOutputRowsTerm` is registered once per stage so the metric appears in
   // `references[]` exactly once instead of once per child; 
`currentEmittingChild`
-  // tells `doConsume` which child's projection to bind.
+  // tells `doConsume` which child's output it reads by position.
   //
   // A single `UnionExec` instance can have its codegen driven by more than one
   // thread at the same time: a reused exchange/subquery stage is generated
@@ -1596,12 +1580,17 @@ case class UnionExec(children: Seq[SparkPlan]) extends 
SparkPlan with CodegenSup
       ctx: CodegenContext, input: Seq[ExprCode], row: ExprCode): String = {
     val i = currentEmittingChild.get
     require(i >= 0, "UnionExec.doConsume invoked outside doProduce emission 
window")
-    // Route BoundReference reads through `currentVars` (the incoming row is
-    // delivered as variables under WSCG, not via ctx.INPUT_ROW).
-    val bound = BindReferences.bindReferences(perChildProjections(i), 
children(i).output)
+    // Read the incoming row (delivered as `currentVars` under WSCG) by 
position. Binding by
+    // `ExprId` would resolve a child output that repeats an `ExprId` (e.g. 
`SELECT a, a`) to
+    // the first occurrence, so the second union output column would take the 
first column's
+    // value and its declaration would be emitted twice. `doExecute` is 
positional too, since
+    // it concatenates child rows as they are.
     ctx.currentVars = input
     ctx.INPUT_ROW = null
-    val projectedExprCodes = bound.map(_.genCode(ctx))
+    val childOutput = children(i).output
+    val projectedExprCodes = childOutput.zipWithIndex.map { case (attr, pos) =>
+      BoundReference(pos, attr.dataType, attr.nullable).genCode(ctx)
+    }
 
     s"""
        |${numOutputRowsTerm.get}.add(1L);
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
index 4636a3ae0955..43797cca0692 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/UnionCodegenSuite.scala
@@ -358,6 +358,62 @@ class UnionCodegenSuite extends SharedSparkSession with 
AdaptiveSparkPlanHelper
       s"Expected the union of both array rows, got $collectedArrays")
   }
 
+  test("SPARK-61232: UnionExec whole-stage codegen fails when a child output 
repeats an ExprId") {
+    // `SELECT p, p, w` leaves two output positions with one ExprId, and `r` 
is a union, so for
+    // `p2`'s rows its second position holds `r` while its first holds `q`. A 
union child reading
+    // its output by ExprId would take the first position for both: the second 
union output
+    // column would hold the first column's value, and the generated row would 
declare that
+    // value's variable twice, which Janino rejects.
+    //
+    // The analyzer normally replaces a repeated output column with a fresh 
ExprId
+    // (`DeduplicateUnionChildOutput`); these confs keep it so the physical 
union sees it.
+    withSQLConf(
+      SQLConf.UNION_IS_RESOLVED_WHEN_DUPLICATES_PER_CHILD_RESOLVED.key -> 
"false",
+      SQLConf.ENFORCE_TYPE_COERCION_BEFORE_UNION_DEDUPLICATION.key -> "false",
+      SQLConf.ANALYZER_DUAL_RUN_LEGACY_AND_SINGLE_PASS_RESOLVER.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "5",
+      SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+      SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true") {
+      def build(): DataFrame = {
+        val p1 = spark.range(1000)
+          .selectExpr("id p", "id w").select(col("p"), col("p"), col("w"))
+        val p2 = spark.range(1000, 11000).selectExpr("id q", "id % 1000 r", 
"id w2")
+        // `u` does not line up with `r`'s partitioning, so the union is plain 
and fuses
+        // through its query stages.
+        val x = spark.range(1000)
+          .selectExpr("id x", "id c", "id u").repartition(col("u"))
+        val r = p1.union(p2).repartition(p1.col("p"))
+        x.union(r)
+      }
+      val fused = build()
+      val answer = fused.collect().toSeq
+      // The bug needs the union that fuses over query stages to read a child 
whose output
+      // repeats an ExprId. The analyzer can drop that shape, so assert it 
survived rather than
+      // letting the test go vacuous. The check is on the InputAdapter child: 
the inner union
+      // below `r` repeats an ExprId too, but it has no InputAdapter child, so 
it cannot satisfy
+      // the guard on its own.
+      val fusedUnionExecs = fusedUnions(fused)
+      assert(
+        fusedUnionExecs.exists(_.children.exists { c =>
+          c.isInstanceOf[InputAdapter] &&
+            c.output.map(_.exprId).distinct.size < c.output.size
+        }),
+        s"expected the fused union's staged child to repeat an ExprId:\n" +
+          fused.queryExecution.executedPlan)
+      // Without AQE the nested union below `r` keeps this union out of 
codegen; AQE turns the
+      // children into query stages, and that is the shape the fused union 
consumes.
+      
assert(fusedUnionExecs.exists(_.children.exists(_.isInstanceOf[InputAdapter])),
+        s"expected the outer union to fuse over its query stages:\n" +
+          fused.queryExecution.executedPlan)
+      assert(answer.length == 12000)
+      // The fused path must agree with the interpreted one, which 
concatenates child rows as
+      // they are and so keeps each union output column at its own position.
+      withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false") {
+        checkAnswer(build(), answer)
+      }
+    }
+  }
+
   // 
---------------------------------------------------------------------------
   // Correctness: N children, empty partitions, mixed partition counts
   // 
---------------------------------------------------------------------------
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/UnionBenchmark.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/UnionBenchmark.scala
index ea9dac094d43..78adc1dc35fc 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/UnionBenchmark.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/UnionBenchmark.scala
@@ -60,9 +60,9 @@ object UnionBenchmark extends SqlBasedBenchmark {
     dfs.reduce((a, b) => a.union(b)).filter(col("id") > 0)
   }
 
-  // Type widening: alternate int and long children so UnionExec needs to
-  // insert `Cast` nodes in `perChildProjections`, adding per-row work in
-  // each helper method.
+  // Type widening: alternate int and long children. `WidenSetOperationTypes` 
adds a
+  // `Project(Cast)` above each int child only; the long children and the 
union add no
+  // conversion, so only every other helper method does the per-row cast.
   private def buildWideningQuery(n: Int): DataFrame = {
     val dfs = (0 until n).map { i =>
       val df = spark.range(i * 10000L, i * 10000L + 10000L).toDF("id")


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

Reply via email to