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

peter-toth pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new 44871c8fda5a [SPARK-60460][4.1][SQL] Fix nested SPJ leaving a one-side 
shuffle at the old partition count
44871c8fda5a is described below

commit 44871c8fda5aa3ed6bc0ec3b8694d3af5976a5e7
Author: Ammar Chalifah <[email protected]>
AuthorDate: Mon Nov 9 17:00:59 2026 +0100

    [SPARK-60460][4.1][SQL] Fix nested SPJ leaving a one-side shuffle at the 
old partition count
    
    ### What changes were proposed in this pull request?
    
    On `branch-4.1`, an outer storage-partitioned join pushes its merged 
partition values into the scans under an inner join. When that inner join 
shuffled one side (`spark.sql.sources.v2.bucketing.shuffle.enabled=true`), the 
exchange kept the partition count it was planned with. The partitioned scan 
beside it grew to the merged keys, so the two children of the inner join no 
longer had the same number of partitions.
    
    Stopping the push at the exchange, which 
[SPARK-60232](https://issues.apache.org/jira/browse/SPARK-60232) / 
[SPARK-60552](https://issues.apache.org/jira/browse/SPARK-60552) do, does not 
fix this: the exchange still has the old partition count. This PR refuses that 
outer SPJ and lets the join shuffle, instead of rewriting the exchange. All 
changes are in `EnsureRequirements`.
    
    * `nestedShufflesFollowPush`: before the merged values are pushed, every 
key-grouped shuffle the push would reach must already have those values, in 
that order, and no reducer is pushed. The push stops at a shuffle, so it is 
sound only when it changes nothing there. The walk stops at the same place, 
including a `ShuffleQueryStageExec` or a `ReusedExchangeExec`. A reducer would 
regroup the scan on the reduced values while the exchange still routes on the 
raw ones, and `ReducibleFunctio [...]
    * `positionsRegroupBesideShuffle`: the positions-only path has the same 
hazard when the positions narrow the layout a nested one-side shuffle routes 
on. That child is shuffled onto the best spec. Positions that are absent, or 
that select every expression of that shuffle, leave the child as it is. The 
comparison is against the shuffle's own expressions. The matching member's 
expressions are already projected onto the positions, so a prefix such as 
`store` of `(store, dept)` looks like  [...]
    
    Targets `branch-4.1` only. `master` and `branch-4.2+` regroup above the 
inner join with `GroupPartitionsExec` 
([SPARK-55535](https://issues.apache.org/jira/browse/SPARK-55535)) and are 
unaffected. Found while reviewing #59599.
    
    ### Why are the changes needed?
    
    [SPARK-60460](https://issues.apache.org/jira/browse/SPARK-60460). On 4.0 
and 4.1, with `spark.sql.sources.v2.bucketing.shuffle.enabled=true`:
    
    ```sql
    -- pa and pc PARTITIONED BY (id), pd not partitioned
    -- pa: 1, 2, 3    pd: 1, 2, 3    pc: 1, 2, 3, 4, 5
    SELECT /*+ MERGE(pa, pd, pc) */ pa.id, pd.id, pc.id
    FROM pa JOIN pd ON pa.id = pd.id
    JOIN pc ON pa.id = pc.id
    ```
    
    The inner join shuffles `pd` onto `pa`'s three keys. The outer join merges 
in `pc`'s five keys and pushes them into `pa`'s scan. `pd`'s exchange stays at 
three partitions.
    
    * AQE off: `IllegalArgumentException: Can't zip RDDs with unequal numbers 
of partitions: List(5, 3)`
    * AQE on: `requirement failed: PartitioningCollection requires all of its 
partitionings have the same numPartitions`
    
    The same push is wrong in the other shapes from the ticket, with no single 
error:
    
    * Reordered values. An inner shuffle on `(store, dept)` projected onto 
`dept` keeps appearance order `[20], [10]`. The outer join sorts the scan to 
`[10], [20]`. The query returns no rows instead of 2.
    * Narrowed positions. An inner shuffle on `(store, dept)` under an outer 
join on `dept` or `store` leaves the exchange at three partitions. With two 
outer keys, planning fails with `PartitioningCollection`. With a third outer 
key, both sides stay at three partitions and the join silently drops a row, 
`[2, 10, b2, c10]`.
    * Partition filtering. `pa` holds 1, 2, 3 and `pc` holds 2, 3, 4, and the 
outer join is a `RIGHT JOIN` with 
`spark.sql.sources.v2.bucketing.partition.filter.enabled=true`. `pa`'s scan is 
filtered to `pc`'s keys while `pd`'s exchange keeps `[1], [2], [3]`. The result 
is `[null, null, 2], [null, null, 3], [null, null, 4]` instead of `[2, 2, 2], 
[3, 3, 3], [null, null, 4]`.
    * A pushed reducer. `l12` is `bucket(12, id)`, `l4` is `bucket(4, id)`, and 
the unpartitioned side is shuffled onto 12 buckets. The outer join reduces the 
scan to 4. AQE off zips `List(4, 12)`. AQE on fails with 
`PartitioningCollection`.
    * An empty filtered merge. `pc` holds only 7, so the merged values are 
empty. AQE on fails with `PartitioningCollection`. AQE off zips `List(0, 3)`. 
Rewriting the exchange onto that empty list would give it zero partitions, and 
`KeyGroupedPartitioner` divides by zero.
    
    `branch-4.2` and `master` return the three rows of the first query with one 
shuffle, via `GroupPartitionsExec`. On `branch-4.1` the outer join shuffles 
instead, and only where the push would have changed the nested shuffle. The 
first query then has two shuffles. A narrowed join can shuffle the partitioned 
outer side as well: with `sc` holding only dept 10, the plan has three 
shuffles, for `sb`, the nested join, and `sc`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for SPJ on `branch-4.1` (4.1.x) with 
`spark.sql.sources.v2.bucketing.shuffle.enabled=true`:
    
    * The query above, which failed during planning or at runtime, now returns 
the three matching rows. `pd`'s shuffle stays at 3 partitions, and the inner 
join's output is shuffled onto `pc`'s 5.
    * The reordered join, which returned no rows, now returns both.
    * The partition-filter `RIGHT JOIN`, which returned three null-padded rows, 
now returns `[2, 2, 2], [3, 3, 3], [null, null, 4]`.
    * The narrowed-key joins, which failed at planning or dropped `[2, 10, b2, 
c10]`, now return every matching row.
    * The bucket reducer join, which failed at planning or execution, now 
returns all 24 rows.
    * The empty filtered merge returns no rows. It no longer fails, and it does 
not divide by zero.
    * A partitioned table joined to two unpartitioned tables on its partition 
key stays at two shuffles, one per unpartitioned side.
    
    No change on `master` or `branch-4.2+`.
    
    ### How was this patch tested?
    
    Added seven tests to `KeyGroupedPartitioningSuite`, all named after 
SPARK-60460. Each runs with AQE on and off, and shuffle assertions read 
`executedPlan` after `checkAnswer`. None is ignored.
    
    * Merged values differ: the query above. Asserts the three rows and 
shuffles of 3 and 5 partitions. The same join with the nested join on the right 
asserts the same three rows. Also the empty filtered merge, which asserts an 
empty result. On `branch-4.1` the first two fail with the zip error (AQE off) 
or `PartitioningCollection` (AQE on), and the empty merge with `List(0, 3)` or 
`PartitioningCollection`.
    * Reordered values: the `(store, dept)` join projected onto `dept`. Asserts 
both rows. On `branch-4.1` it returns no rows, with no error.
    * Partition filtering: the `RIGHT JOIN` above. Asserts `[2, 2, 2], [3, 3, 
3], [null, null, 4]`. On `branch-4.1` it returns `[null, null, 2], [null, null, 
3], [null, null, 4]`.
    * Reducer: `bucket(12, id)` joined through an unpartitioned table to 
`bucket(4, id)`, ids 0 to 23. Asserts the 24 rows and two shuffles. On 
`branch-4.1` it fails at planning or execution.
    * Narrowed positions: the outer join on `dept` with `sc` holding 10 and 20 
only, the same tables with the outer join on `store`, the ticket's 
`da`/`db`/`de` query, and the three-pair join whose outer table also holds dept 
30. The dept-30 join is also run with the nested join on the right. All assert 
the matching rows. On `branch-4.1` the first three fail at planning with 
`PartitioningCollection`. Both dept-30 joins return the other rows and drop 
`[2, 10, b2, c10]`.
    * Key that does not narrow: `pa` partitioned by `id`, `pd` and `pe` not 
partitioned, each holding 1, 2, 3, with and without 
`allowJoinKeysSubsetOfPartitionKeys`. Asserts the three rows and two shuffles. 
`branch-4.1` plans the same two.
    * Push that changes nothing: `pc` holds 1 and 2, so the merged keys are the 
ones `pd`'s shuffle already has. Asserts the two rows and one shuffle. `pc`'s 
scan is padded. `branch-4.1` plans the same one shuffle. Refusing every such 
push would add a second.
    
    `KeyGroupedPartitioningSuite` and `EnsureRequirementsSuite` pass: 163 
tests, 0 failures.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Yes: Grok 4.7
    
    Closes #60058 from ammarchalifah/SPARK-60460-nested-one-side-shuffle.
    
    Authored-by: Ammar Chalifah <[email protected]>
    Signed-off-by: Peter Toth <[email protected]>
---
 .../execution/exchange/EnsureRequirements.scala    |  96 ++++++-
 .../connector/KeyGroupedPartitioningSuite.scala    | 292 +++++++++++++++++++++
 2 files changed, 379 insertions(+), 9 deletions(-)

diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala
index b73c8824a9ae..b10c467e47da 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala
@@ -230,7 +230,11 @@ case class EnsureRequirements(
             !childrenIndexes.contains(idx) =>
           child
         case ((child, dist), idx) =>
-          if (bestMemberOpt.isDefined && matchedIndexes.contains(idx)) {
+          // A nested one-side shuffle keeps its own layout. Join key 
positions that narrow it
+          // would regroup the scan beside it and leave the shuffle behind, so 
this child is
+          // shuffled onto the best spec instead.
+          if (bestMemberOpt.isDefined && matchedIndexes.contains(idx) &&
+              !positionsRegroupBesideShuffle(child, specs(idx), 
bestMemberOpt.get)) {
             // The positions come from this child's own matching member, since 
they index into its
             // own partition expressions -- the chosen best member only says 
which member of it the
             // two sides agreed on.
@@ -700,14 +704,27 @@ case class EnsureRequirements(
         }
 
         // Now we need to push-down the common partition information to the 
scan in each child.
-        newLeft = populateSpjParams(
-          left, commonPartitionValues = Some(mergedPartValues),
-          joinKeyPositions = leftSpec.joinKeyPositions, reducers = 
leftReducers,
-          applyPartialClustering = applyPartialClustering, replicatePartitions 
= replicateLeftSide)
-        newRight = populateSpjParams(
-          right, commonPartitionValues = Some(mergedPartValues),
-          joinKeyPositions = rightSpec.joinKeyPositions, reducers = 
rightReducers,
-          applyPartialClustering = applyPartialClustering, replicatePartitions 
= replicateRightSide)
+        // A one-side shuffle under either child was planned at its own 
values. The push is
+        // sound only when every such shuffle already has these values, in 
this order, and no
+        // reducer. Otherwise the outer join shuffles.
+        if (nestedShufflesFollowPush(left, mergedPartValues, leftReducers) &&
+            nestedShufflesFollowPush(right, mergedPartValues, rightReducers)) {
+          newLeft = populateSpjParams(
+            left, commonPartitionValues = Some(mergedPartValues),
+            joinKeyPositions = leftSpec.joinKeyPositions, reducers = 
leftReducers,
+            applyPartialClustering = applyPartialClustering,
+            replicatePartitions = replicateLeftSide)
+          newRight = populateSpjParams(
+            right, commonPartitionValues = Some(mergedPartValues),
+            joinKeyPositions = rightSpec.joinKeyPositions, reducers = 
rightReducers,
+            applyPartialClustering = applyPartialClustering,
+            replicatePartitions = replicateRightSide)
+        } else {
+          // "Pushing common partition values" was logged above, before this 
check.
+          logInfo("Not pushing common partition values: a one-side shuffle 
below this join " +
+            "was planned on other values")
+          isCompatible = false
+        }
       }
     }
 
@@ -902,6 +919,67 @@ case class EnsureRequirements(
     case other => other.children.exists(hasReducedScanOutsideJoin)
   }
 
+  /** Partition rows a push expands to, one per output partition. */
+  private def pushedPartitionRows(values: Seq[(InternalRow, Int)]): 
Seq[InternalRow] =
+    values.flatMap { case (row, n) => Seq.fill(n)(row) }
+
+  private def samePartitionValues(
+      partitioning: KeyGroupedPartitioning,
+      rows: Seq[InternalRow]): Boolean =
+    partitioning.partitionValues.length == rows.length &&
+      partitioning.partitionValues.zip(rows).forall { case (left, right) =>
+        left.numFields == partitioning.expressions.length &&
+          left.numFields == right.numFields &&
+          InternalRowComparableWrapper(left, partitioning.expressions) ==
+            InternalRowComparableWrapper(right, partitioning.expressions)
+      }
+
+  /**
+   * Whether every key-grouped shuffle [[populateSpjParams]] would reach below 
`plan` already has
+   * `values`. The push stops at such a shuffle, which was planned at its own 
values, so the push
+   * is sound only when it changes nothing there: the same values in the same 
order, and no
+   * reducer. The walk stops where the push stops.
+   */
+  private def nestedShufflesFollowPush(
+      plan: SparkPlan,
+      values: Seq[(InternalRow, Int)],
+      reducers: Option[Seq[Option[Reducer[_, _]]]]): Boolean = plan match {
+    case _: BroadcastExchangeLike => true
+    case s @ (_: ShuffleExchangeLike | _: ShuffleQueryStageExec | _: 
ReusedExchangeExec) =>
+      s.outputPartitioning match {
+        case k: KeyGroupedPartitioning =>
+          reducers.forall(_.forall(_.isEmpty)) &&
+            samePartitionValues(k, pushedPartitionRows(values))
+        case _ => false
+      }
+    case other => other.children.forall(nestedShufflesFollowPush(_, values, 
reducers))
+  }
+
+  /**
+   * Whether pushing the join key positions of the member of `spec` that 
matches `bestMember`
+   * would regroup a scan beside a one-side shuffle below `plan`. The shuffle 
keeps its own
+   * layout, so only positions that select all of its partition expressions 
keep the two aligned.
+   * The walk stops where the push stops.
+   */
+  private def positionsRegroupBesideShuffle(
+      plan: SparkPlan,
+      spec: ShuffleSpec,
+      bestMember: ShuffleSpec): Boolean = {
+    def regroups(p: SparkPlan, positions: Seq[Int]): Boolean = p match {
+      case _: BroadcastExchangeLike => false
+      case s @ (_: ShuffleExchangeLike | _: ShuffleQueryStageExec | _: 
ReusedExchangeExec) =>
+        s.outputPartitioning match {
+          case k: KeyGroupedPartitioning => positions != k.expressions.indices
+          case _ => false
+        }
+      case other => other.children.exists(regroups(_, positions))
+    }
+    flattenSpec(spec).find(bestMember.isCompatibleWith) match {
+      case Some(KeyGroupedShuffleSpec(_, _, Some(positions))) => 
regroups(plan, positions)
+      case _ => false
+    }
+  }
+
   /**
    * Push SPJ parameters down to every scan below `plan`, composing join-key 
positions with any
    * already pushed by an inner join instead of replacing them.
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
index 74a6c2a7ca90..4d0288cb3375 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala
@@ -4289,6 +4289,298 @@ class KeyGroupedPartitioningSuite extends 
DistributionAndOrderingSuiteBase {
     }
   }
 
+  test("SPARK-60460: nested SPJ shuffles when merged values differ from a 
one-side shuffle") {
+    val idCol = Array(Column.create("id", IntegerType))
+    createTable("pa", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pa VALUES (1), (2), (3)")
+    createTable("pd", idCol, Array.empty)
+    sql("INSERT INTO testcat.ns.pd VALUES (1), (2), (3)")
+    createTable("pc", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pc VALUES (1), (2), (3), (4), (5)")
+    // No key in common, so the filtered merge is empty. Retargeting the 
exchange onto it would
+    // give the shuffle zero partitions.
+    createTable("px", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.px VALUES (7)")
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(pa, pd, pc) */ pa.id, pd.id, pc.id
+            |FROM testcat.ns.pa JOIN testcat.ns.pd ON pa.id = pd.id
+            |JOIN testcat.ns.pc ON pa.id = pc.id
+            |""".stripMargin)
+        checkAnswer(df, Seq(Row(1, 1, 1), Row(2, 2, 2), Row(3, 3, 3)))
+        // pd's shuffle stays at pa's 3 keys. The inner join's output is 
shuffled onto pc's 5.
+        val shuffles = collectAllShuffles(df.queryExecution.executedPlan)
+        assert(shuffles.map(_.outputPartitioning.numPartitions).sorted == 
Seq(3, 5),
+          s"expected shuffles of 3 and 5 partitions, 
got:\n${df.queryExecution.executedPlan}")
+
+        // The nested join on the right reaches the same check on that child.
+        val swapped = sql(
+          """
+            |SELECT /*+ MERGE(pa, pd, pc) */ pc.id, pa.id, pd.id
+            |FROM testcat.ns.pc JOIN (testcat.ns.pa JOIN testcat.ns.pd ON 
pa.id = pd.id)
+            |ON pc.id = pa.id
+            |""".stripMargin)
+        checkAnswer(swapped, Seq(Row(1, 1, 1), Row(2, 2, 2), Row(3, 3, 3)))
+      }
+
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTITION_FILTER_ENABLED.key -> "true") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(pa, pd, px) */ pa.id, pd.id, px.id
+            |FROM testcat.ns.pa JOIN testcat.ns.pd ON pa.id = pd.id
+            |JOIN testcat.ns.px ON pa.id = px.id
+            |""".stripMargin)
+        checkAnswer(df, Seq.empty)
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ shuffles when a one-side shuffle's values are 
reordered") {
+    val cols = Array(Column.create("store", IntegerType), 
Column.create("dept", IntegerType))
+    createTable("sa", cols, Array(identity("store"), identity("dept")))
+    createTable("sb", cols, Array.empty)
+    createTable("sc", cols, Array(identity("dept")))
+    // Projected onto dept, sa's keys appear as 20 then 10. The outer join 
sorts them to 10, 20.
+    sql("INSERT INTO testcat.ns.sa VALUES (1, 20), (2, 10)")
+    sql("INSERT INTO testcat.ns.sb VALUES (0, 10), (0, 20)")
+    sql("INSERT INTO testcat.ns.sc VALUES (0, 10), (0, 20)")
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> 
"true",
+        SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key -> "false") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(sa, sb, sc) */ sa.store, sa.dept, sb.dept, 
sc.dept
+            |FROM testcat.ns.sa JOIN testcat.ns.sb ON sa.dept = sb.dept
+            |JOIN testcat.ns.sc ON sa.dept = sc.dept
+            |""".stripMargin)
+        checkAnswer(df, Seq(Row(1, 20, 20, 20), Row(2, 10, 10, 10)))
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ shuffles when partition filtering changes a 
one-side shuffle") {
+    val idCol = Array(Column.create("id", IntegerType))
+    createTable("pa", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pa VALUES (1), (2), (3)")
+    createTable("pd", idCol, Array.empty)
+    sql("INSERT INTO testcat.ns.pd VALUES (1), (2), (3)")
+    createTable("pc", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pc VALUES (2), (3), (4)")
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PARTITION_FILTER_ENABLED.key -> "true") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(pa, pd, pc) */ pa.id, pd.id, pc.id
+            |FROM testcat.ns.pa JOIN testcat.ns.pd ON pa.id = pd.id
+            |RIGHT JOIN testcat.ns.pc ON pa.id = pc.id
+            |""".stripMargin)
+        checkAnswer(df, Seq(Row(2, 2, 2), Row(3, 3, 3), Row(null, null, 4)))
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ shuffles when a reducer would change a 
one-side shuffle") {
+    val idCol = Array(Column.create("id", LongType))
+    createTable("l12", idCol, Array(bucket(12, "id")))
+    createTable("l4", idCol, Array(bucket(4, "id")))
+    createTable("ld", idCol, Array.empty)
+    Seq("l12", "l4", "ld").foreach(t => sql(s"INSERT INTO testcat.ns.$t SELECT 
id FROM range(24)"))
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(l12, ld, l4) */ l12.id, ld.id, l4.id
+            |FROM testcat.ns.l12 JOIN testcat.ns.ld ON l12.id = ld.id
+            |JOIN testcat.ns.l4 ON l12.id = l4.id
+            |""".stripMargin)
+        checkAnswer(df, (0L until 24L).map(i => Row(i, i, i)))
+        val shuffles = collectAllShuffles(df.queryExecution.executedPlan)
+        assert(shuffles.size == 2,
+          s"expected ld's shuffle and one more, 
got:\n${df.queryExecution.executedPlan}")
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ shuffles when join key positions narrow a 
one-side shuffle") {
+    val cols = Array(
+      Column.create("store", IntegerType),
+      Column.create("dept", IntegerType),
+      Column.create("data", StringType))
+    createTable("sa", cols, Array(identity("store"), identity("dept")))
+    createTable("sb", cols, Array.empty)
+    createTable("sc", cols, Array(identity("dept")))
+    // Three (store, dept) pairs and two depts. Pushing dept leaves sb's 
exchange at 3 partitions.
+    sql("INSERT INTO testcat.ns.sa VALUES (1, 10, 'a1'), (2, 10, 'a2'), (1, 
20, 'a3')")
+    sql("INSERT INTO testcat.ns.sb VALUES (1, 10, 'b1'), (2, 10, 'b2'), (1, 
20, 'b3')")
+    sql("INSERT INTO testcat.ns.sc VALUES (0, 10, 'c10'), (0, 20, 'c20')")
+
+    val pairCols = Array(Column.create("store", IntegerType), 
Column.create("dept", IntegerType))
+    createTable("da", pairCols, Array(identity("store"), identity("dept")))
+    createTable("db", pairCols, Array.empty)
+    createTable("de", Array(Column.create("k", IntegerType), 
Column.create("dept", IntegerType)),
+      Array(identity("k"), identity("dept")))
+    sql("INSERT INTO testcat.ns.da VALUES (1, 20), (3, 20), (2, 10)")
+    sql("INSERT INTO testcat.ns.db VALUES (1, 20), (3, 20), (2, 10)")
+    sql("INSERT INTO testcat.ns.de VALUES (1, 20), (2, 10)")
+
+    createTable("ea", cols, Array(identity("store"), identity("dept")))
+    createTable("eb", cols, Array.empty)
+    createTable("ec", cols, Array(identity("store")))
+    sql("INSERT INTO testcat.ns.ea VALUES (1, 10, 'a1'), (2, 10, 'a2'), (1, 
20, 'a3')")
+    sql("INSERT INTO testcat.ns.eb VALUES (1, 10, 'b1'), (2, 10, 'b2'), (1, 
20, 'b3')")
+    sql("INSERT INTO testcat.ns.ec VALUES (1, 0, 'c1'), (2, 0, 'c2')")
+
+    // An extra dept keeps both sides at 3 partitions. Without the guard, the 
push drops
+    // (2, 10, b2, c10).
+    createTable("fa", cols, Array(identity("store"), identity("dept")))
+    createTable("fb", cols, Array.empty)
+    createTable("fc", cols, Array(identity("dept")))
+    sql("INSERT INTO testcat.ns.fa VALUES (1, 10, 'a1'), (2, 10, 'a2'), (1, 
20, 'a3')")
+    sql("INSERT INTO testcat.ns.fb VALUES (1, 10, 'b1'), (2, 10, 'b2'), (1, 
20, 'b3')")
+    sql("INSERT INTO testcat.ns.fc VALUES (0, 10, 'c10'), (0, 20, 'c20'), (0, 
30, 'c30')")
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> 
"true",
+        SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key -> "false") {
+        checkAnswer(
+          sql(
+            """
+              |SELECT /*+ MERGE(sa, sb, sc) */ sa.store, sa.dept, sb.data, 
sc.data
+              |FROM testcat.ns.sa JOIN testcat.ns.sb
+              |ON sa.store = sb.store AND sa.dept = sb.dept
+              |JOIN testcat.ns.sc ON sa.dept = sc.dept
+              |""".stripMargin),
+          Seq(Row(1, 10, "b1", "c10"), Row(2, 10, "b2", "c10"), Row(1, 20, 
"b3", "c20")))
+        checkAnswer(
+          sql(
+            """
+              |SELECT /*+ MERGE(da, db, de) */ da.store, da.dept, db.store, 
de.k
+              |FROM testcat.ns.da JOIN testcat.ns.db
+              |ON da.store = db.store AND da.dept = db.dept
+              |JOIN testcat.ns.de ON da.dept = de.dept
+              |""".stripMargin),
+          Seq(Row(1, 20, 1, 1), Row(3, 20, 3, 1), Row(2, 10, 2, 2)))
+        checkAnswer(
+          sql(
+            """
+              |SELECT /*+ MERGE(ea, eb, ec) */ ea.store, ea.dept, eb.data, 
ec.data
+              |FROM testcat.ns.ea JOIN testcat.ns.eb
+              |ON ea.store = eb.store AND ea.dept = eb.dept
+              |JOIN testcat.ns.ec ON ea.store = ec.store
+              |""".stripMargin),
+          Seq(Row(1, 10, "b1", "c1"), Row(2, 10, "b2", "c2"), Row(1, 20, "b3", 
"c1")))
+        checkAnswer(
+          sql(
+            """
+              |SELECT /*+ MERGE(fa, fb, fc) */ fa.store, fa.dept, fb.data, 
fc.data
+              |FROM testcat.ns.fa JOIN testcat.ns.fb
+              |ON fa.store = fb.store AND fa.dept = fb.dept
+              |JOIN testcat.ns.fc ON fa.dept = fc.dept
+              |""".stripMargin),
+          Seq(Row(1, 10, "b1", "c10"), Row(2, 10, "b2", "c10"), Row(1, 20, 
"b3", "c20")))
+        // The nested join on the right. Without the guard, the push drops (2, 
10, b2, c10).
+        checkAnswer(
+          sql(
+            """
+              |SELECT /*+ MERGE(fa, fb, fc) */ fa.store, fa.dept, fb.data, 
fc.data
+              |FROM testcat.ns.fc JOIN
+              |(testcat.ns.fa JOIN testcat.ns.fb ON fa.store = fb.store AND 
fa.dept = fb.dept)
+              |ON fa.dept = fc.dept
+              |""".stripMargin),
+          Seq(Row(1, 10, "b1", "c10"), Row(2, 10, "b2", "c10"), Row(1, 20, 
"b3", "c20")))
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ keeps a one-side shuffle the outer key does 
not narrow") {
+    val idCol = Array(Column.create("id", IntegerType))
+    createTable("pa", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pa VALUES (1), (2), (3)")
+    createTable("pd", idCol, Array.empty)
+    sql("INSERT INTO testcat.ns.pd VALUES (1), (2), (3)")
+    createTable("pe", idCol, Array.empty)
+    sql("INSERT INTO testcat.ns.pe VALUES (1), (2), (3)")
+
+    Seq(true, false).foreach { subset =>
+      Seq(true, false).foreach { aqe =>
+        withSQLConf(
+          SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+          SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+          SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+          SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS.key -> 
subset.toString,
+          SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key -> "false") {
+          val df = sql(
+            """
+              |SELECT /*+ MERGE(pa, pd, pe) */ pa.id, pd.id, pe.id
+              |FROM testcat.ns.pa JOIN testcat.ns.pd ON pa.id = pd.id
+              |JOIN testcat.ns.pe ON pa.id = pe.id
+              |""".stripMargin)
+          checkAnswer(df, Seq(Row(1, 1, 1), Row(2, 2, 2), Row(3, 3, 3)))
+          val shuffles = collectAllShuffles(df.queryExecution.executedPlan)
+          assert(shuffles.size == 2,
+            s"pd and pe should each shuffle once, 
got:\n${df.queryExecution.executedPlan}")
+        }
+      }
+    }
+  }
+
+  test("SPARK-60460: nested SPJ pushes past a one-side shuffle that has the 
merged values") {
+    val idCol = Array(Column.create("id", IntegerType))
+    createTable("pa", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pa VALUES (1), (2), (3)")
+    createTable("pd", idCol, Array.empty)
+    sql("INSERT INTO testcat.ns.pd VALUES (1), (2), (3)")
+    createTable("pc", idCol, Array(identity("id")))
+    sql("INSERT INTO testcat.ns.pc VALUES (1), (2)")
+
+    Seq(true, false).foreach { aqe =>
+      withSQLConf(
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+        val df = sql(
+          """
+            |SELECT /*+ MERGE(pa, pd, pc) */ pa.id, pd.id, pc.id
+            |FROM testcat.ns.pa JOIN testcat.ns.pd ON pa.id = pd.id
+            |JOIN testcat.ns.pc ON pa.id = pc.id
+            |""".stripMargin)
+        checkAnswer(df, Seq(Row(1, 1, 1), Row(2, 2, 2)))
+        // pd's shuffle already has the merged keys: pc's scan is padded, 
nothing else shuffles.
+        assert(collectAllShuffles(df.queryExecution.executedPlan).size == 1,
+          s"only pd should shuffle, got:\n${df.queryExecution.executedPlan}")
+      }
+    }
+  }
+
   test("SPARK-48012: one-side shuffle with partition transforms") {
     val items_partitions = Array(bucket(2, "id"), identity("arrive_time"))
     val items_partitions2 = Array(identity("arrive_time"), bucket(2, "id"))


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

Reply via email to