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 dff942e0dd8e [SPARK-61356][SQL] Fix wrong results by `UnionExec`
output partitioning when a child output repeats an ExprId
dff942e0dd8e is described below
commit dff942e0dd8e9b5fe4cb292d99a39953d8b3520f
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Tue Nov 10 10:33:34 2026 -0800
[SPARK-61356][SQL] Fix wrong results by `UnionExec` output partitioning
when a child output repeats an ExprId
### What changes were proposed in this pull request?
This PR fixes a correctness issue in `UnionExec.outputPartitioning`.
`UnionExec` now reports no partitioning when the output of one of its children
repeats an `ExprId`, instead of passing its children's partitioning through.
### Why are the changes needed?
This is a correctness issue. Since SPARK-52921 (4.1.0), `UnionExec` passes
its children's partitioning through by replacing each child's attributes with
the union's output attributes at the same position. That replacement is keyed
by `ExprId`, while an attribute is read from the first position that carries
its `ExprId` (`AttributeSeq.indexOf`). When a child output repeats an `ExprId`,
the two disagree, and the union reports a hash partitioning on a column the
rows were not hashed by. [...]
There are three cases.
1. A later child repeats an `ExprId`, e.g. `[p, p, w]` hashed by `p`. Its
shuffle hashes the first position, but the map keeps the last one, so the union
reports the partitioning on its second output column.
2. The first child repeats an `ExprId`, so the union's own output does. A
later child hashed by its second column is reported as hashed by `p`, which a
parent reads from the first position.
3. Every child reports a `KeyedPartitioning`. Since SPARK-57881 (4.3.0),
the union merges them through the same replacement, so a later child keyed by
its second column is merged as keyed by the first one.
The positions that share an `ExprId` hold different values when a union
sits below, so the mapping cannot be repaired by choosing one of them.
The analyzer normally replaces a repeated output column of a union child
with a fresh `ExprId` (`DeduplicateUnionChildOutput`), so this requires
`spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved=false` and
`spark.sql.enforceTypeCoercionBeforeUnionDeduplication.enabled=false`.
```scala
spark.conf.set("spark.sql.analyzer.unionIsResolvedWhenDuplicatesPerChildResolved",
"false")
spark.conf.set("spark.sql.enforceTypeCoercionBeforeUnionDeduplication.enabled",
"false")
spark.conf.set("spark.sql.adaptive.enabled", "false")
spark.conf.set("spark.sql.shuffle.partitions", "5")
val c0 = spark.range(100).selectExpr("id p", "id w").select($"p", $"p",
$"w")
val c1 = spark.range(1000).selectExpr("id % 10 q", "id r", "id
w2").repartition($"r")
val df =
c0.repartition(c0.col("p")).union(c1).groupBy(c0.col("p")).agg(sum($"w"))
// Issue: It should return 100 rows, but returns 140 rows with duplicate
groups.
df.count()
```
### Does this PR introduce _any_ user-facing change?
Yes. A query over a union whose child output repeats an `ExprId` no longer
skips a required shuffle because of a partitioning its rows do not have, so it
returns correct results. This only happens when the two analyzer configurations
above are disabled. The released versions since 4.1.0 are affected.
### How was this patch tested?
Pass the CIs with the newly added test case in
`DataFrameSetOperationsSuite`. It covers the three cases and fails without this
fix.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Fable 5.2
Closes #60290 from dongjoon-hyun/SPARK-61356.
Authored-by: Dongjoon Hyun <[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
skip-checks: true
---
.../sql/execution/basicPhysicalOperators.scala | 17 ++++++
.../spark/sql/DataFrameSetOperationsSuite.scala | 60 ++++++++++++++++++++++
2 files changed, 77 insertions(+)
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 eea4bf963cb6..ddb4438d884f 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
@@ -1168,6 +1168,13 @@ case class UnionExec(children: Seq[SparkPlan]) extends
SparkPlan with CodegenSup
}
}
+ // Whether the output of a child repeats an `ExprId`. Fixed for the given
children, so it is
+ // derived once rather than on every read of the partitioning.
+ @transient private lazy val childOutputRepeatsExprId: Boolean =
children.exists { child =>
+ val exprIds = child.output.map(_.exprId)
+ exprIds.distinct.size < exprIds.size
+ }
+
/**
* The SPARK-52921 candidate partitioning derived from the children, which
`outputPartitioning`
* reports when the decision says this union is not a plain concatenation.
That decision comes out
@@ -1177,6 +1184,16 @@ case class UnionExec(children: Seq[SparkPlan]) extends
SparkPlan with CodegenSup
* reports unknown.
*/
private def rawPartitioning: Partitioning = {
+ // An attribute is read from the first position that carries its `ExprId`
(see
+ // `AttributeSeq.indexOf`), so the positions of an output that repeats one
cannot be told
+ // apart by attribute, and they hold different values when a union sits
below. A child's
+ // partitioning then has no reliable counterpart among this union's output
attributes, whether
+ // the repeat is in that child's output or, through the first child, in
this union's own.
+ // The analyzer normally leaves no such child
(`DeduplicateUnionChildOutput`).
+ if (childOutputRepeatsExprId) {
+ return super.outputPartitioning
+ }
+
// Children's partitionings with attributes remapped to this union's
output attributes.
val partitionings = prepareOutputPartitioning()
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSetOperationsSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSetOperationsSuite.scala
index 4cce6129dc5a..6c630175176c 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSetOperationsSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameSetOperationsSuite.scala
@@ -1743,6 +1743,66 @@ class DataFrameSetOperationsSuite extends
SharedSparkSession with AdaptiveSparkP
}
}
+ test("SPARK-61356: union outputPartitioning when a child output repeats an
ExprId") {
+ // `SELECT p, p, w` leaves two output positions with one ExprId. 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.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.SHUFFLE_PARTITIONS.key -> "5",
+ "spark.sql.catalog.testcat" -> classOf[InMemoryCatalog].getName) {
+ def repeated: DataFrame = spark.range(10).selectExpr("id p", "id
w").select($"p", $"p", $"w")
+
+ // A later child repeats the ExprId. `r` is a union, so for `p2`'s rows
its second position
+ // holds `r` while its first holds `q`, and its shuffle hashes the first
one. Reading that
+ // partitioning as one on `c`, the second position, would let the
aggregate skip its exchange
+ // and split a group over partitions.
+ val p1 = repeated
+ val p2 = spark.range(10, 110).selectExpr("id q", "id % 10 r", "id w2")
+ val r = p1.union(p2).repartition(p1.col("p"))
+ val x = spark.range(10).selectExpr("id x", "id c", "id
u").repartition($"c")
+ // All three columns are referenced, so `ColumnPruning` adds no
`Project` below the union.
+ val laterChild = x.union(r).groupBy($"c").agg(sum($"x"), sum($"u"))
+
+ // The first child repeats the ExprId, so this union's own output does.
Its second child is
+ // hashed by `r`, the second position, while `p` is read from the first
one.
+ val c0 = repeated
+ val c1 = spark.range(100).selectExpr("id % 10 q", "id r", "id
w2").repartition($"r")
+ val firstChild =
c0.repartition(c0.col("p")).union(c1).groupBy(c0.col("p")).agg(sum($"w"))
+
+ // Keyed legs are merged rather than passed through. The first leg
repeats its key column,
+ // and the later leg is keyed by `r`, the second position.
+ sql("CREATE TABLE testcat.ns.k1 (id bigint, data string) PARTITIONED BY
(id)")
+ sql("INSERT INTO testcat.ns.k1 VALUES (1, 'a1'), (2, 'a2')")
+ sql("CREATE TABLE testcat.ns.k2 (q bigint, r bigint, w string)
PARTITIONED BY (r)")
+ sql("INSERT INTO testcat.ns.k2 VALUES (1, 5, 'b'), (1, 6, 'c'), (2, 5,
'd')")
+ val k1 = spark.table("testcat.ns.k1")
+ val keyed = k1.select($"id", $"id",
$"data").union(spark.table("testcat.ns.k2"))
+ .groupBy(k1.col("id")).agg(count($"data"))
+
+ Seq(
+ laterChild -> (0 until 10).map(k => Row(k, 12 * k + 550, 12 * k +
550)),
+ firstChild -> (0 until 10).map(k => Row(k, 11 * k + 450)),
+ keyed -> Seq(Row(1, 3), Row(2, 2))
+ ).foreach { case (df, expected) =>
+ val unionExec = df.queryExecution.executedPlan.collect { case u:
UnionExec => u }.head
+ val partitionings = unionExec.children.map(_.outputPartitioning)
+ // The analyzer can drop this shape, so assert it survived rather than
letting the test
+ // go vacuous: children partitioned the same way, one of them
repeating an ExprId.
+ assert((partitionings.forall(_.isInstanceOf[HashPartitioning]) ||
+ partitionings.forall(_.isInstanceOf[KeyedPartitioning])) &&
+ unionExec.children.exists(c => c.output.map(_.exprId).distinct.size
< c.output.size),
+ s"expected hash- or key-partitioned children, one repeating an
ExprId:\n$unionExec")
+ assert(unionExec.outputPartitioning.isInstanceOf[UnknownPartitioning],
+ s"expected no pass-through but got ${unionExec.outputPartitioning}")
+ checkAnswer(df, expected)
+ }
+ }
+ }
+
test("SPARK-52921: union partitioning - range partitioning") {
val df1 = Seq((1, 2, 4), (1, 3, 5), (2, 2, 3), (2, 4, 5)).toDF("a", "b",
"c")
val df2 = Seq((4, 1, 5), (2, 4, 6), (1, 4, 2), (3, 5, 1)).toDF("d", "e",
"f")
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]