This is an automated email from the ASF dual-hosted git repository.
ulysses-you pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new a7fbe0a94a2a [SPARK-61211][SQL] Avoid wrong union output partitioning
from child attributes that do not map to the union output
a7fbe0a94a2a is described below
commit a7fbe0a94a2a8359b584e1d07b3fe93accd300b5
Author: Xiduo You <[email protected]>
AuthorDate: Wed Nov 11 15:57:18 2026 +0800
[SPARK-61211][SQL] Avoid wrong union output partitioning from child
attributes that do not map to the union output
### What changes were proposed in this pull request?
`UnionExec.prepareOutputPartitioning` maps each child's
`outputPartitioning` onto the union's output so that the children's layouts can
be compared. This PR stops that mapping from producing a layout the child's
rows do not have:
- A member of the child's partitioning that references an attribute the
child does not output is dropped. Left unmapped, it could equal another child's
real output attribute.
- A child with no member left reports `UnknownPartitioning`, which leaves
the whole union unknown. Survivors keep their shape, so a single
`KeyedPartitioning` still merges.
- A partitioning that references no attribute, such as `SinglePartition`,
passes through.
Repeated `ExprId`s are handled by SPARK-61356.
Fixes [SPARK-61211](https://issues.apache.org/jira/browse/SPARK-61211).
### Why are the changes needed?
An unmapped attribute could equal another child's real output attribute, so
the union advertised a layout its rows do not have. `EnsureRequirements` then
omitted a necessary exchange and returned wrong results without an error. With
default configs:
```scala
val kv = spark.range(1000).as[Long].groupByKey(x => (x % 10, x % 7))
val c = kv.keys.toDF().repartition($"_1").cache()
c.count()
c.select("_1").union(c.select("_2")).groupBy("_1").count().count()
// 10 expected, 38 before this PR (AQE on and off)
```
A column-pruned `InMemoryTableScanExec` reports the cached plan's
partitioning over a column it does not output. SPARK-61326 checks
`relation.output`, not the scan's own pruned output, so this remains.
`MapGroupsExec` and `SerializeFromObjectExec` do the same with the grouping key.
### Does this PR introduce _any_ user-facing change?
Yes, a correctness fix for queries that have returned wrong results since
`spark.sql.unionOutputPartitioning` was added in 4.1.0. A union over such
children now gets the exchange it needs. Members that still describe the child
pass through, so a column-pruned cached shuffled join keeps its exchange-free
plan.
### How was this patch tested?
New tests in `DataFrameSetOperationsSuite`, all failing before this PR:
- Column-pruned cached scans, and a grouped Dataset's keys with
`mapGroups`, with AQE on and off.
- A column-pruned cached shuffled join keeps its exchange-free plan.
- Plan-level cases over `HashPartitioning`, `KeyedPartitioning` and
`PartitioningCollection`.
Existing suites pass, including `UnionCodegen*Suite`,
`KeyGroupedPartitioningSuite`, `EnsureRequirementsSuite`, `PlannerSuite`,
`DatasetSuite`, `CachedTableSuite`, `InMemoryColumnarQuerySuite`,
`AdaptiveQueryExecSuite` and all `*PlanStabilitySuite` (TPC-DS plans unchanged).
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Closes #60271 from ulysses-you/worktree-union-duplicate-partitioning.
Authored-by: Xiduo You <[email protected]>
Signed-off-by: Xiduo You <[email protected]>
(cherry picked from commit 3ee9dcfe3c2807516a4657a3bcbe3d041fcb5613)
Signed-off-by: Xiduo You <[email protected]>
skip-checks: true
---
.../sql/execution/basicPhysicalOperators.scala | 47 ++++++---
.../spark/sql/DataFrameSetOperationsSuite.scala | 115 ++++++++++++++++++++-
2 files changed, 147 insertions(+), 15 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 55f425dddfbf..da4a4678b1aa 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
@@ -1110,7 +1110,9 @@ case class UnionExec(children: Seq[SparkPlan]) extends
SparkPlan with CodegenSup
/**
* Returns the output partitionings of the children, with the attributes
converted to this
- * union's output attributes at the same position.
+ * union's output attributes at the same position. A member that does not
map is dropped, and a
+ * child with no member left reports `UnknownPartitioning`. A partitioning
that references no
+ * attribute, such as `SinglePartition`, passes through.
*/
private def prepareOutputPartitioning(): Seq[Partitioning] = {
// Map every child's partitioning attributes to this union's output
attributes, so all
@@ -1122,18 +1124,39 @@ case class UnionExec(children: Seq[SparkPlan]) extends
SparkPlan with CodegenSup
// a partitioning built inside a view or subquery carries that relation's
qualifier.
// `AttributeMap` is keyed by `ExprId`, so remapping every child
(including the first)
// normalizes all of those.
+ //
+ // A member that references an attribute the child does not output, such
as the key a
+ // `MapGroups` or a column-pruned cached scan passes through, is dropped:
left unmapped, it
+ // could equal another child's real output attribute. A child with no
member left reports
+ // unknown, which leaves the whole union unknown. A child that repeats an
`ExprId` does not
+ // reach here (see `rawPartitioning`).
val unionOutput = output
- val attributesMap = children.map(_.output).map { childAttrs =>
- AttributeMap(childAttrs.zip(unionOutput))
- }
- children.map(_.outputPartitioning).zip(attributesMap).map { case (p,
attributeMap) =>
- p match {
- case e: Expression =>
- e.transform {
- case a: Attribute if attributeMap.contains(a) =>
- attributeMap(a)
- }.asInstanceOf[Partitioning]
- case _ => p
+ children.map { child =>
+ child.outputPartitioning match {
+ case p: Expression =>
+ val attributeMap = AttributeMap(child.output.zip(unionOutput))
+ def remap(member: Partitioning): Partitioning = member match {
+ case e: Expression =>
+ e.transform {
+ case a: Attribute if attributeMap.contains(a) =>
+ attributeMap(a)
+ }.asInstanceOf[Partitioning]
+ case _ => member
+ }
+ // The common case: keep the partitioning as it is, which also keeps
its shape, so a
+ // single `KeyedPartitioning` stays one. Otherwise each member is
checked on its own.
+ if (p.references.subsetOf(child.outputSet)) {
+ remap(p)
+ } else {
+ PartitioningCollection.flatten(p).filter {
+ case e: Expression => e.references.subsetOf(child.outputSet)
+ case _ => true
+ } match {
+ case Seq() => UnknownPartitioning(p.numPartitions)
+ case survivors => PartitioningCollection(survivors.map(remap))
+ }
+ }
+ case p => p
}
}
}
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 6c630175176c..5e9cbf8bbae0 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
@@ -20,15 +20,19 @@ package org.apache.spark.sql
import java.sql.{Date, Timestamp}
import java.util.Locale
-import org.apache.spark.sql.catalyst.expressions.AttributeReference
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference, Expression}
import org.apache.spark.sql.catalyst.optimizer.RemoveNoopUnion
import org.apache.spark.sql.catalyst.plans.logical.Union
-import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning,
KeyedPartitioning, PartitioningCollection, UnknownPartitioning}
+import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning,
KeyedPartitioning, Partitioning, PartitioningCollection, UnknownPartitioning}
import org.apache.spark.sql.connector.catalog.InMemoryCatalog
-import org.apache.spark.sql.execution.{SparkPlan, UnionExec}
+import org.apache.spark.sql.execution.{LeafExecNode, SparkPlan, UnionExec}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
import org.apache.spark.sql.execution.exchange.{ReusedExchangeExec,
ShuffleExchangeExec}
+import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.{ExamplePoint, ExamplePointUDT,
SharedSparkSession, SQLTestData}
@@ -2119,6 +2123,95 @@ class DataFrameSetOperationsSuite extends
SharedSparkSession with AdaptiveSparkP
}
}
+ test("SPARK-61211: union partitioning - an attribute the child does not
output") {
+ import UnionPartitioningFixture._
+
+ withSQLConf(SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true") {
+ val Seq(k, v, w) = Seq("k", "v", "w").map(attr)
+ // The second child reports the first child's `k` but outputs only `v`
(and `w`).
+ val reported = Seq(
+ union(Seq(k) -> hash(k), Seq(v) -> hash(k)),
+ union(Seq(k) -> keyed(k), Seq(v) -> keyed(k)),
+ // The lone keyed survivor stays in a collection, so the union does
not merge it.
+ union(
+ Seq(k) -> keyed(k),
+ Seq(v) -> PartitioningCollection(Seq(HashPartitioning(Seq(k), 2),
keyed(v)))))
+ assert(reported.forall(_.isInstanceOf[UnknownPartitioning]),
reported.mkString("\n"))
+ // Only the member on `k` is dropped; the one on `w` still describes the
child.
+ assert(union(
+ Seq(k, w) -> PartitioningCollection(Seq(hash(k), hash(w))),
+ Seq(v, w) -> PartitioningCollection(Seq(hash(k), hash(w)))) == hash(w))
+ }
+ }
+
+ test("SPARK-61211: union of a grouped Dataset's keys and mapGroups") {
+ // `MapGroupsExec` and `SerializeFromObjectExec` pass the grouping key's
partitioning through
+ // while outputting only the mapped value, so the second child reports
`hash(key)` over rows
+ // whose value is `key + 1`.
+ Seq(true, false).foreach { aqe =>
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+ // Coalescing the few rows into one partition would hide the wrong
partitioning.
+ SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+ SQLConf.SHUFFLE_PARTITIONS.key -> "5",
+ SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true") {
+ val kv = spark.range(100).as[Long].groupByKey(_ % 10)
+ val u = kv.keys.toDF().union(kv.mapGroups((k, _) => k + 1).toDF())
+ val df = u.withColumn("rn",
+
row_number().over(Window.partitionBy(u.columns(0)).orderBy(u.columns(0))))
+ // The values 0 to 10, each once.
+ assert(df.collect().count(_.getInt(1) == 1) == 11, s"aqe=$aqe")
+ }
+ }
+ }
+
+ test("SPARK-61211: union of column-pruned cached scans") {
+ // A column-pruned `InMemoryTableScanExec` reports the cached plan's
partitioning, so the scan
+ // of `_2` reports `hash(_1)` over a column it does not output.
+ val kv = spark.range(1000).as[Long].groupByKey(x => (x % 10, x % 7))
+ val cached = kv.keys.toDF().repartition($"_1").cache()
+ try {
+ cached.count()
+ Seq(true, false).foreach { aqe =>
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+ SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true") {
+ val df =
cached.select("_1").union(cached.select("_2")).groupBy("_1").count()
+ checkAnswer(df,
+ (0L until 7L).map(Row(_, 17L)) ++ (7L until 10L).map(Row(_, 7L)))
+ }
+ }
+ } finally {
+ cached.unpersist()
+ }
+ }
+
+ test("SPARK-61211: union keeps the partitioning a column-pruned cached join
still reports") {
+ withSQLConf(
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.UNION_OUTPUT_PARTITIONING.key -> "true") {
+ val joined = spark.range(1000).selectExpr("id k", "id v")
+ .join(spark.range(1000).selectExpr("id k2"), $"k" === $"k2").cache()
+ try {
+ joined.count()
+ Seq(true, false).foreach { aqe =>
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString) {
+ // Each scan reports the cached plan's keys, one of which (`k2`)
it does not output.
+ // The member on `k` still describes it, so the aggregate needs no
exchange.
+ val df = joined.select("k", "v")
+ .union(joined.where($"v" > 0).select("k", "v"))
+ .groupBy("k").count()
+ checkAnswer(df, Row(0L, 1L) +: (1L until 1000L).map(Row(_, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.isEmpty,
plan)
+ }
+ }
+ } finally {
+ joined.unpersist()
+ }
+ }
+ }
+
test("SPARK-51262: exceptAll after dropDuplicates with subset should not
throw") {
// Data where dropDuplicates(subset) produces deterministic results - to
avoid test flakiness.
val df1 = spark.createDataFrame(Seq(
@@ -2173,3 +2266,19 @@ case class Struct2a(C2: Int, c1: Int)
case class Struct3(c3: Int)
case class Struct3a(C3: Int)
case class Struct4(c3: Int, c5: Int)
+
+private object UnionPartitioningFixture {
+ def attr(name: String): AttributeReference = AttributeReference(name,
LongType)()
+ def hash(e: Expression): HashPartitioning = HashPartitioning(Seq(e), 5)
+ def keyed(e: Expression): KeyedPartitioning =
+ KeyedPartitioning(Seq(e), Seq(InternalRow(0L), InternalRow(1L)))
+ def union(children: (Seq[Attribute], Partitioning)*): Partitioning =
+ UnionExec(children.map { case (o, p) => UnionChildStub(o, p)
}).outputPartitioning
+}
+
+private case class UnionChildStub(
+ override val output: Seq[Attribute],
+ override val outputPartitioning: Partitioning) extends LeafExecNode {
+ override protected def doExecute(): RDD[InternalRow] =
+ throw SparkUnsupportedOperationException()
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]