This is an automated email from the ASF dual-hosted git repository.
dongjoon-hyun pushed a commit to branch branch-4.3
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.3 by this push:
new cb373baac232 [SPARK-61211][4.3][SQL] Avoid wrong union output
partitioning from child attributes that do not map to the union output
cb373baac232 is described below
commit cb373baac232761c7589900d2a1da714cdb8e9a0
Author: Xiduo You <[email protected]>
AuthorDate: Wed Nov 11 08:27:07 2026 -0800
[SPARK-61211][4.3][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?
Backport of #60271 to `branch-4.3`.
`UnionExec.prepareOutputPartitioning` maps each child's partitioning onto
the union's output so that the children's layouts can be compared. A member of
a child's partitioning that references an attribute the child does not output
is now dropped, and a child with no member left reports `UnknownPartitioning`,
which leaves the whole union unknown. This branch maps the other children onto
the first child's attributes, so the filter is applied to every child before
that mapping.
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; that fix (SPARK-61326) is not on
this branch. `MapGroupsExec` and `SerializeFromObjectExec` do the same with the
grouping key. The repeated-`ExprId` case is a separate issue (SPARK-61356) and
is not part of this backport.
### 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, and members that still describe the
child pass through.
### How was this patch tested?
Four new tests in `DataFrameSetOperationsSuite`: a plan-level case, a
grouped Dataset's keys with `mapGroups`, column-pruned cached scans, and a
column-pruned cached shuffled join that keeps its exchange-free plan, with AQE
on and off where it applies. All four fail before the fix except the
cached-join one, which master also had to fix at a different layer.
Related suites pass on this branch (814 tests):
`DataFrameSetOperationsSuite`, `UnionCodegenSuite`,
`KeyGroupedPartitioningSuite`, `EnsureRequirementsSuite`, `PlannerSuite`,
`DatasetSuite`, `CachedTableSuite` and `InMemoryColumnarQuerySuite`, plus
scalastyle.
### 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 #60329 from ulysses-you/spark-61211-4.3.
Authored-by: Xiduo You <[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
---
.../sql/execution/basicPhysicalOperators.scala | 18 +++-
.../spark/sql/DataFrameSetOperationsSuite.scala | 110 ++++++++++++++++++++-
2 files changed, 125 insertions(+), 3 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 46d960db59a7..f5026e5da2c2 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
@@ -904,7 +904,23 @@ case class UnionExec(children: Seq[SparkPlan]) extends
SparkPlan with CodegenSup
AttributeMap(otherAttrs.zip(firstAttrs))
}
- val partitionings = children.map(_.outputPartitioning)
+ val partitionings = children.map { child =>
+ // 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.
+ child.outputPartitioning match {
+ case p: Expression if !p.references.subsetOf(child.outputSet) =>
+ PartitioningCollection.flatten(p).filter {
+ case e: Expression => e.references.subsetOf(child.outputSet)
+ case _ => true
+ } match {
+ case Seq() => UnknownPartitioning(p.numPartitions)
+ case survivors =>
PartitioningCollection.fromPartitionings(survivors)
+ }
+ case p => p
+ }
+ }
val firstPartitioning = partitionings.head
val otherPartitionings = partitionings.tail
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 b9958e352175..e7343b7c7d20 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,14 +20,19 @@ package org.apache.spark.sql
import java.sql.{Date, Timestamp}
import java.util.Locale
+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}
@@ -1905,6 +1910,91 @@ 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 `hash(k)` over rows whose only columns are
`v` and `w`.
+ assert(union(Seq(k) -> hash(k), Seq(v) ->
hash(k)).isInstanceOf[UnknownPartitioning])
+ assert(union(Seq(k) -> keyed(k), Seq(v) ->
keyed(k)).isInstanceOf[UnknownPartitioning])
+ // 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))
+ // A partitioning that describes its child passes through.
+ assert(union(Seq(k) -> hash(k), Seq(k) -> hash(k)) == hash(k))
+ }
+ }
+
+ 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(
@@ -1959,3 +2049,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]