This is an automated email from the ASF dual-hosted git repository.
dongjoon-hyun pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new cc963511a023 [SPARK-61232][4.2][SQL] UnionExec whole-stage codegen
fails when a child output repeats an ExprId
cc963511a023 is described below
commit cc963511a0231f8c916a0790e3d242e3b3a3da06
Author: Xiduo You <[email protected]>
AuthorDate: Tue Nov 10 11:19:58 2026 -0800
[SPARK-61232][4.2][SQL] UnionExec whole-stage codegen fails when a child
output repeats an ExprId
### What changes were proposed in this pull request?
Backport of #60236 to `branch-4.2`.
Applies unchanged: no conflicts, and the cherry-pick's patch-id matches the
master commit (`cherry picked from commit fea3ac7a665`).
### Why are the changes needed?
`UnionExec.doConsume` projected each child column through an `Alias` 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 columns, and the generated row declared that input variable
twice, which Janino rejects with "Redefinition of local variable".
The fix reads the child row positionally, with one `BoundReference` per
union output column, which is what `doExecute` already does.
The repeated-`ExprId` shape needs
`spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved=false` and
`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. On `branch-4.2` the union whole-stage codegen is behind
`spark.sql.codegen.wholeStage.union.enabled` (default false), so only setups
that enable it are affected. Unions whose child outputs do not repeat an
`ExprId` are unaffected: binding by position and binding by `ExprId` pick the
same position when the `ExprId` is unique.
### How was this patch tested?
`UnionCodegenSuite`, `UnionCodegenAnsiSuite` and `UnionCodegenAqeSuite`
pass 177/177 on `branch-4.2`, including the new `SPARK-61232` case, which runs
in all three suites.
### Was this patch authored or co-authored using generative AI tooling?
Yes. Generated-by: Claude Code.
Closes #60289 from ulysses-you/union-dup-expr-codegen-4.2.
Authored-by: Xiduo You <[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
---
.../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 275d1c1fb710..a565dc3c17b3 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
@@ -1071,22 +1071,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
@@ -1195,7 +1179,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
@@ -1290,12 +1274,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 62e90eda523c..faf07e4c716e 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 QueryTest with
SharedSparkSession with AdaptiveS
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]