This is an automated email from the ASF dual-hosted git repository.
wangyum 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 8754d79029fb [SPARK-60382][SQL] CoalesceBucketsInJoin should see only
the streamed side of a broadcast join
8754d79029fb is described below
commit 8754d79029fb8d04017cc5b4318130279e651185
Author: Yuming Wang <[email protected]>
AuthorDate: Tue Nov 10 15:09:24 2026 +0800
[SPARK-60382][SQL] CoalesceBucketsInJoin should see only the streamed side
of a broadcast join
### What changes were proposed in this pull request?
`CoalesceBucketsInJoin` could read the bucket count of a broadcast join's
build side and stamp the streamed side's bucketed scan with it, when
`spark.sql.bucketing.coalesceBucketsInJoin.enabled` is true and a sort-merge or
shuffled-hash join's child is a broadcast hash join or broadcast nested-loop
join. The same stamping could also corrupt an unrelated bucketed join nested
inside a broadcast build side, on either build side.
This PR makes `ExtractJoinWithBuckets` find each join input's bucketed scan
by walking only the child that actually exposes its partitioning to the parent
join: through `FilterExec` and `ProjectExec`, and into the streamed child of a
broadcast hash or nested-loop join. The extractor now returns that scan
together with its bucket count, and the rewrite updates only that one scan, so
a bucketed build scan -- whether it is the direct build side or a bucketed join
nested further inside on [...]
### Why are the changes needed?
This is a correctness bug. `getBucketSpec` used `collectFirst`, whose
pre-order walk visits the left child first. With a `BuildLeft` broadcast join,
the left child is the broadcast build side, so a bucketed build scan's count
was reported as the join input's bucket count, and
`updateNumCoalescedBucketsInScan` then stamped every bucketed scan in that
subtree, including the streamed scan whose partitioning the parent join
actually uses. The same `transformUp` over the whole subtree coul [...]
The coalesced scan groups bucket files by their original bucket id modulo
the coalesced count while advertising `HashPartitioning` of that count. When
the streamed table's bucket count is not divisible by the coalesced count (e.g.
100 coalesced to 8), `hash(key) % 100 % 8` and `hash(key) % 8` land in
different partitions for some keys. The other side of the sort-merge join is a
real table of the coalesced bucket count, `EnsureRequirements` inserts no
shuffle, and the join silently dro [...]
```sql
SET spark.sql.adaptive.enabled = false;
SET spark.sql.autoBroadcastJoinThreshold = -1;
SET spark.sql.bucketing.coalesceBucketsInJoin.enabled = true;
SET spark.sql.optimizer.excludedRules =
org.apache.spark.sql.catalyst.optimizer.ReorderJoin;
CREATE TABLE dim16 (i INT, k INT) USING parquet CLUSTERED BY (i) INTO 16
BUCKETS;
CREATE TABLE fact100 (i INT, k INT, v STRING) USING parquet CLUSTERED BY
(i) INTO 100 BUCKETS;
CREATE TABLE other8 (i INT, v STRING) USING parquet CLUSTERED BY (i) INTO 8
BUCKETS;
INSERT INTO dim16 VALUES (0, 1);
CREATE OR REPLACE TEMP VIEW picked AS
SELECT CAST(id AS INT) AS i FROM range(0, 4000)
WHERE pmod(pmod(hash(CAST(id AS INT)), 100), 8) <> pmod(hash(CAST(id AS
INT)), 8)
ORDER BY id LIMIT 1;
INSERT INTO fact100 SELECT i, 1, 'fact' FROM picked;
INSERT INTO other8 SELECT i, 'other' FROM picked;
SELECT /*+ BROADCAST(dim16), MERGE(fact100, other8) */ fact100.i,
fact100.v, other8.v
FROM dim16 JOIN fact100 ON dim16.k = fact100.k JOIN other8 ON fact100.i =
other8.i;
-- returns 0 rows before this PR; 1 row after
```
This reproduces the same way with `spark.sql.adaptive.enabled` at its
default (true); the rule runs in `queryStagePreparationRules` before the
broadcast side materializes into a query stage, so the wrong 0-shuffle plan is
chosen in the initial plan and AQE keeps it unless a re-optimized plan looks
cheaper.
The bug also blocked a valid coalescing: with a 16-bucket streamed scan
hidden behind a 100-bucket build scan, the old code saw 100 first and declined
the whole pair instead of coalescing 16 to 8.
Note `spark.sql.bucketing.coalesceBucketsInJoin.enabled` defaults to false,
so default plans are not affected.
### Does this PR introduce _any_ user-facing change?
Yes, a bug fix: with bucket coalescing in join enabled, queries whose
sort-merge or shuffled-hash join reads through a broadcast join -- or has a
bucketed join nested inside a broadcast build side -- no longer drop or
null-pad rows that should match, and one additional valid coalescing case
(streamed 16 buckets coalesced to 8 behind a 100-bucket build scan) now avoids
a shuffle. Because the ratio and divisibility checks now use the streamed
scan's bucket count instead of whichever sca [...]
### How was this patch tested?
Existing and new tests in `CoalesceBucketsInJoinSuite`:
- `SPARK-60382: broadcast join coalescing uses the streamed side bucket
count` builds the physical plans directly and checks that a 100-bucket streamed
scan against an 8-bucket other side is left untouched, and that the divisible
16-to-8 case only rewrites the streamed scan, for both broadcast hash and
broadcast nested-loop joins.
- `SPARK-60382: a bucketed join inside a broadcast build side keeps its own
bucket count` covers a bucketed sort-merge join nested inside a `BuildRight`
broadcast build side, checking that it is judged on its own instead of being
stamped by the outer join's coalescing decision.
- `SPARK-60382: broadcast hash join bucket coalescing keeps the sort-merge
match` runs the end-to-end SQL above, with `spark.sql.adaptive.enabled` looped
over `true` and `false`, and asserts the matching row is returned while the
100-bucket scan is not stamped with 8.
- All existing tests in the suite still pass: `build/sbt 'sql/testOnly
org.apache.spark.sql.execution.bucketing.CoalesceBucketsInJoinSuite'`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Cursor (GLM 5.3)
Made with [Cursor](https://cursor.com)
Closes #59636 from wangyum/SPARK-60382.
Authored-by: Yuming Wang <[email protected]>
Signed-off-by: Yuming Wang <[email protected]>
skip-checks: true
---
.../bucketing/CoalesceBucketsInJoin.scala | 97 +++++++-----
.../bucketing/CoalesceBucketsInJoinSuite.scala | 175 ++++++++++++++++++++-
2 files changed, 224 insertions(+), 48 deletions(-)
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoin.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoin.scala
index d1464b4ac4ee..d3299393d314 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoin.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoin.scala
@@ -21,7 +21,7 @@ import scala.annotation.tailrec
import org.apache.spark.sql.catalyst.catalog.BucketSpec
import org.apache.spark.sql.catalyst.expressions.Expression
-import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight,
BuildSide}
import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning,
Partitioning, PartitioningCollection}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.{FileSourceScanExec, FilterExec,
ProjectExec, SparkPlan}
@@ -40,27 +40,33 @@ import
org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNes
object CoalesceBucketsInJoin extends Rule[SparkPlan] {
private def updateNumCoalescedBucketsInScan(
plan: SparkPlan,
+ targetScan: FileSourceScanExec,
numCoalescedBuckets: Int): SparkPlan = {
+ // Only the scan whose partitioning reaches this join. A broadcast build
+ // scan in the same subtree keeps its own bucket count. This relies on the
+ // scan instance not being shared across subtrees.
plan transformUp {
- case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty =>
+ case f: FileSourceScanExec if f eq targetScan =>
f.copy(optionalNumCoalescedBuckets = Some(numCoalescedBuckets))
}
}
private def updateNumCoalescedBuckets(
join: ShuffledJoin,
+ leftScan: FileSourceScanExec,
+ rightScan: FileSourceScanExec,
numLeftBuckets: Int,
numCoalescedBuckets: Int): ShuffledJoin = {
if (numCoalescedBuckets != numLeftBuckets) {
val leftCoalescedChild =
- updateNumCoalescedBucketsInScan(join.left, numCoalescedBuckets)
+ updateNumCoalescedBucketsInScan(join.left, leftScan,
numCoalescedBuckets)
join match {
case j: SortMergeJoinExec => j.copy(left = leftCoalescedChild)
case j: ShuffledHashJoinExec => j.copy(left = leftCoalescedChild)
}
} else {
val rightCoalescedChild =
- updateNumCoalescedBucketsInScan(join.right, numCoalescedBuckets)
+ updateNumCoalescedBucketsInScan(join.right, rightScan,
numCoalescedBuckets)
join match {
case j: SortMergeJoinExec => j.copy(right = rightCoalescedChild)
case j: ShuffledHashJoinExec => j.copy(right = rightCoalescedChild)
@@ -85,18 +91,18 @@ object CoalesceBucketsInJoin extends Rule[SparkPlan] {
}
plan transform {
- case ExtractJoinWithBuckets(join, numLeftBuckets, numRightBuckets)
+ case ExtractJoinWithBuckets(join, leftScan, rightScan, numLeftBuckets,
numRightBuckets)
if math.max(numLeftBuckets, numRightBuckets) /
math.min(numLeftBuckets, numRightBuckets) <=
conf.coalesceBucketsInJoinMaxBucketRatio =>
val numCoalescedBuckets = math.min(numLeftBuckets, numRightBuckets)
join match {
case j: SortMergeJoinExec =>
- updateNumCoalescedBuckets(j, numLeftBuckets, numCoalescedBuckets)
+ updateNumCoalescedBuckets(j, leftScan, rightScan, numLeftBuckets,
numCoalescedBuckets)
case j: ShuffledHashJoinExec
// Only coalesce the buckets for shuffled hash join stream side,
// to avoid OOM for build side.
if isCoalesceSHJStreamSide(j, numLeftBuckets, numCoalescedBuckets)
=>
- updateNumCoalescedBuckets(j, numLeftBuckets, numCoalescedBuckets)
+ updateNumCoalescedBuckets(j, leftScan, rightScan, numLeftBuckets,
numCoalescedBuckets)
case other => other
}
case other => other
@@ -105,32 +111,42 @@ object CoalesceBucketsInJoin extends Rule[SparkPlan] {
}
/**
- * An extractor that extracts `SortMergeJoinExec` and `ShuffledHashJoin`,
- * where both sides of the join have the bucketed tables,
- * are consisted of only the scan operation,
- * and numbers of buckets are not equal but divisible.
+ * An extractor that extracts `SortMergeJoinExec` and `ShuffledHashJoin` whose
sides each
+ * reach a bucketed scan through filters, projects, and the streamed child of
a broadcast
+ * join, and whose numbers of buckets are not equal but divisible. It returns
the join, the
+ * bucketed scan of each side, which is the only scan the caller may coalesce,
and the two
+ * numbers of buckets.
*/
object ExtractJoinWithBuckets {
- @tailrec
- private def hasScanOperation(plan: SparkPlan): Boolean = plan match {
- case f: FilterExec => hasScanOperation(f.child)
- case p: ProjectExec => hasScanOperation(p.child)
- case j: BroadcastHashJoinExec =>
- if (j.buildSide == BuildLeft) hasScanOperation(j.right) else
hasScanOperation(j.left)
- case j: BroadcastNestedLoopJoinExec =>
- if (j.buildSide == BuildLeft) hasScanOperation(j.right) else
hasScanOperation(j.left)
- case f: FileSourceScanExec => f.relation.bucketSpec.nonEmpty
- case _ => false
+ private def streamedSide(
+ buildSide: BuildSide, left: SparkPlan, right: SparkPlan): SparkPlan = {
+ if (buildSide == BuildLeft) right else left
}
- private def getBucketSpec(plan: SparkPlan): Option[BucketSpec] = {
- plan.collectFirst {
- case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty &&
- f.optionalNumCoalescedBuckets.isEmpty =>
- f.relation.bucketSpec.get
+ /**
+ * The bucketed scan whose partitioning can reach the parent join through
this side, by
+ * walking through filters, projects, and the streamed child of a broadcast
join. The
+ * caller still checks that this scan's partitioning satisfies the parent
join's keys via
+ * `satisfiesOutputPartitioning`.
+ */
+ @tailrec
+ private def findBucketedScan(plan: SparkPlan): Option[FileSourceScanExec] = {
+ plan match {
+ case f: FilterExec => findBucketedScan(f.child)
+ case p: ProjectExec => findBucketedScan(p.child)
+ case j: BroadcastHashJoinExec =>
+ findBucketedScan(streamedSide(j.buildSide, j.left, j.right))
+ case j: BroadcastNestedLoopJoinExec =>
+ findBucketedScan(streamedSide(j.buildSide, j.left, j.right))
+ case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty => Some(f)
+ case _ => None
}
}
+ private def getBucketSpec(scan: FileSourceScanExec): Option[BucketSpec] = {
+ if (scan.optionalNumCoalescedBuckets.isEmpty) scan.relation.bucketSpec
else None
+ }
+
/**
* The join keys should match with expressions for output partitioning. Note
that
* the ordering does not matter because it will be handled in
`EnsureRequirements`.
@@ -147,13 +163,6 @@ object ExtractJoinWithBuckets {
}
}
- private def isApplicable(j: ShuffledJoin): Boolean = {
- hasScanOperation(j.left) &&
- hasScanOperation(j.right) &&
- satisfiesOutputPartitioning(j.leftKeys, j.left.outputPartitioning) &&
- satisfiesOutputPartitioning(j.rightKeys, j.right.outputPartitioning)
- }
-
private def isDivisible(numBuckets1: Int, numBuckets2: Int): Boolean = {
val (small, large) = (math.min(numBuckets1, numBuckets2),
math.max(numBuckets1, numBuckets2))
// A bucket can be coalesced only if the bigger number of buckets is
divisible by the smaller
@@ -161,17 +170,19 @@ object ExtractJoinWithBuckets {
numBuckets1 != numBuckets2 && large % small == 0
}
- def unapply(plan: SparkPlan): Option[(ShuffledJoin, Int, Int)] = {
+ def unapply(
+ plan: SparkPlan): Option[(ShuffledJoin, FileSourceScanExec,
FileSourceScanExec, Int, Int)] = {
plan match {
- case j: ShuffledJoin if isApplicable(j) =>
- val leftBucket = getBucketSpec(j.left)
- val rightBucket = getBucketSpec(j.right)
- if (leftBucket.isDefined && rightBucket.isDefined &&
- isDivisible(leftBucket.get.numBuckets,
rightBucket.get.numBuckets)) {
- Some(j, leftBucket.get.numBuckets, rightBucket.get.numBuckets)
- } else {
- None
- }
+ case j: ShuffledJoin =>
+ for {
+ leftScan <- findBucketedScan(j.left)
+ rightScan <- findBucketedScan(j.right)
+ if satisfiesOutputPartitioning(j.leftKeys,
j.left.outputPartitioning) &&
+ satisfiesOutputPartitioning(j.rightKeys,
j.right.outputPartitioning)
+ leftBucket <- getBucketSpec(leftScan)
+ rightBucket <- getBucketSpec(rightScan)
+ if isDivisible(leftBucket.numBuckets, rightBucket.numBuckets)
+ } yield (j, leftScan, rightScan, leftBucket.numBuckets,
rightBucket.numBuckets)
case _ => None
}
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoinSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoinSuite.scala
index f8d395bead67..b7e1ba6b4612 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoinSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoinSuite.scala
@@ -17,20 +17,23 @@
package org.apache.spark.sql.execution.bucketing
+import org.apache.spark.sql.{QueryTest, Row}
import org.apache.spark.sql.catalyst.catalog.BucketSpec
import org.apache.spark.sql.catalyst.expressions.{Attribute,
AttributeReference}
import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight,
BuildSide}
import org.apache.spark.sql.catalyst.plans.Inner
import org.apache.spark.sql.catalyst.types.DataTypeUtils
import org.apache.spark.sql.execution.{BinaryExecNode, FileSourceScanExec,
SparkPlan}
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.datasources.{HadoopFsRelation,
InMemoryFileIndex, PartitionSpec}
import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
-import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
ShuffledHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, ShuffledHashJoinExec, SortMergeJoinExec}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types.IntegerType
-class CoalesceBucketsInJoinSuite extends SharedSparkSession {
+class CoalesceBucketsInJoinSuite extends QueryTest with SharedSparkSession
+ with AdaptiveSparkPlanHelper {
private val SORT_MERGE_JOIN = "sortMergeJoin"
private val SHUFFLED_HASH_JOIN = "shuffledHashJoin"
private val BROADCAST_HASH_JOIN = "broadcastHashJoin"
@@ -38,12 +41,20 @@ class CoalesceBucketsInJoinSuite extends SharedSparkSession
{
case class RelationSetting(
cols: Seq[Attribute],
numBuckets: Int,
- expectedCoalescedNumBuckets: Option[Int])
+ expectedCoalescedNumBuckets: Option[Int],
+ bucketCols: Seq[Attribute])
object RelationSetting {
+ def apply(
+ cols: Seq[Attribute],
+ numBuckets: Int,
+ expectedCoalescedNumBuckets: Option[Int]): RelationSetting = {
+ RelationSetting(cols, numBuckets, expectedCoalescedNumBuckets, cols)
+ }
+
def apply(numBuckets: Int, expectedCoalescedNumBuckets: Option[Int]):
RelationSetting = {
val cols = Seq(AttributeReference("i", IntegerType)())
- RelationSetting(cols, numBuckets, expectedCoalescedNumBuckets)
+ RelationSetting(cols, numBuckets, expectedCoalescedNumBuckets, cols)
}
}
@@ -70,13 +81,25 @@ class CoalesceBucketsInJoinSuite extends SharedSparkSession
{
location = new InMemoryFileIndex(spark, Nil, Map.empty, None),
partitionSchema = PartitionSpec.emptySpec.partitionColumns,
dataSchema = DataTypeUtils.fromAttributes(setting.cols),
- bucketSpec = Some(BucketSpec(setting.numBuckets,
setting.cols.map(_.name), Nil)),
+ bucketSpec = Some(BucketSpec(setting.numBuckets,
setting.bucketCols.map(_.name), Nil)),
fileFormat = new ParquetFileFormat(),
options = Map.empty)(spark)
FileSourceScanExec(relation, None, setting.cols, relation.dataSchema, Nil,
None, None, Nil,
None)
}
+ // Buckets only on the first column, even when `cols` has more, so the
scan's partitioning
+ // matches the outer join's key regardless of an inner broadcast join's own
join key.
+ private def testScan(cols: Seq[Attribute], numBuckets: Int):
FileSourceScanExec = {
+ newFileSourceScanExec(RelationSetting(cols, numBuckets, None, bucketCols =
Seq(cols.head)))
+ }
+
+ private def coalescedBuckets(plan: SparkPlan): Seq[(Int, Option[Int])] = {
+ plan.collect { case f: FileSourceScanExec =>
+ (f.relation.bucketSpec.get.numBuckets, f.optionalNumCoalescedBuckets)
+ }
+ }
+
private def run(setting: JoinSetting): Unit = {
val swappedSetting = setting.copy(
leftKeys = setting.rightKeys,
@@ -262,6 +285,148 @@ class CoalesceBucketsInJoinSuite extends
SharedSparkSession {
}
}
+ test("SPARK-60382: broadcast join coalescing uses the streamed side bucket
count") {
+ withSQLConf(SQLConf.COALESCE_BUCKETS_IN_JOIN_ENABLED.key -> "true") {
+ def cols(): Seq[Attribute] = Seq(
+ AttributeReference("i", IntegerType)(),
+ AttributeReference("k", IntegerType)())
+
+ // Streamed side is 100 buckets. 100 % 8 != 0, so nothing is coalesced,
+ // including the 16-bucket build scan that sits on the left.
+ val build = cols()
+ val stream = cols()
+ val other = Seq(AttributeReference("i", IntegerType)())
+ val hashJoin = BroadcastHashJoinExec(
+ Seq(build(1)), Seq(stream(1)), Inner, BuildLeft, None,
+ testScan(build, 16), testScan(stream, 100))
+ val plan = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(stream.head), Seq(other.head), Inner, None, hashJoin,
testScan(other, 8)))
+ assert(coalescedBuckets(plan) == Seq((16, None), (100, None), (8, None)))
+
+ val nestedLoop = BroadcastNestedLoopJoinExec(
+ testScan(build, 16), testScan(stream, 100), BuildLeft, Inner, None)
+ val nestedPlan = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(stream.head), Seq(other.head), Inner, None, nestedLoop,
testScan(other, 8)))
+ assert(coalescedBuckets(nestedPlan) == Seq((16, None), (100, None), (8,
None)))
+
+ // Streamed side is 16 buckets and the other input is 8. Only the
+ // streamed scan is rewritten to 8. The 100-bucket build scan is not.
+ val buildDiv = cols()
+ val streamDiv = cols()
+ val otherDiv = Seq(AttributeReference("i", IntegerType)())
+ val hashJoinDiv = BroadcastHashJoinExec(
+ Seq(buildDiv(1)), Seq(streamDiv(1)), Inner, BuildLeft, None,
+ testScan(buildDiv, 100), testScan(streamDiv, 16))
+ val planDiv = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(streamDiv.head), Seq(otherDiv.head), Inner, None,
+ hashJoinDiv, testScan(otherDiv, 8)))
+ assert(coalescedBuckets(planDiv) == Seq((100, None), (16, Some(8)), (8,
None)))
+
+ val nestedLoopDiv = BroadcastNestedLoopJoinExec(
+ testScan(buildDiv, 100), testScan(streamDiv, 16), BuildLeft, Inner,
None)
+ val nestedPlanDiv = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(streamDiv.head), Seq(otherDiv.head), Inner, None,
+ nestedLoopDiv, testScan(otherDiv, 8)))
+ assert(coalescedBuckets(nestedPlanDiv) == Seq((100, None), (16,
Some(8)), (8, None)))
+
+ // ShuffledHashJoinExec parent over a broadcast join: BuildRight
coalesces
+ // the streamed scan to 8, BuildLeft changes nothing.
+ val shjRight = CoalesceBucketsInJoin(ShuffledHashJoinExec(
+ Seq(streamDiv.head), Seq(otherDiv.head), Inner, BuildRight, None,
+ hashJoinDiv, testScan(otherDiv, 8)))
+ assert(coalescedBuckets(shjRight) == Seq((100, None), (16, Some(8)), (8,
None)))
+
+ val shjLeft = CoalesceBucketsInJoin(ShuffledHashJoinExec(
+ Seq(streamDiv.head), Seq(otherDiv.head), Inner, BuildLeft, None,
+ hashJoinDiv, testScan(otherDiv, 8)))
+ assert(coalescedBuckets(shjLeft) == Seq((100, None), (16, None), (8,
None)))
+ }
+ }
+
+ test("SPARK-60382: a bucketed join inside a broadcast build side keeps its
own bucket count") {
+ withSQLConf(SQLConf.COALESCE_BUCKETS_IN_JOIN_ENABLED.key -> "true") {
+ // SMJ(s.i = o.i)(BHJ(BuildRight, s16, SMJ(a.i = c.i)(a100, c8)), o8).
The outer join
+ // coalesces s16 (the streamed side of the inner broadcast join) to 8.
The inner
+ // sort-merge join is then judged on its own: 100 is not divisible by 8,
so a100 and
+ // c8 are left untouched even though they sit inside the outer join's
coalesced side.
+ val s = Seq(
+ AttributeReference("i", IntegerType)(), AttributeReference("k",
IntegerType)())
+ val a = Seq(
+ AttributeReference("i", IntegerType)(), AttributeReference("k",
IntegerType)())
+ val c = Seq(AttributeReference("i", IntegerType)())
+ val o = Seq(AttributeReference("i", IntegerType)())
+
+ val inner = SortMergeJoinExec(
+ Seq(a.head), Seq(c.head), Inner, None, testScan(a, 100), testScan(c,
8))
+ val bhj = BroadcastHashJoinExec(
+ Seq(s(1)), Seq(a(1)), Inner, BuildRight, None, testScan(s, 16), inner)
+ val plan = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(s.head), Seq(o.head), Inner, None, bhj, testScan(o, 8)))
+ assert(coalescedBuckets(plan) == Seq((16, Some(8)), (100, None), (8,
None), (8, None)))
+
+ // Also under BuildLeft, the nested sort-merge join on the build side
+ // is not corrupted: only the streamed scan s16 is coalesced to 8.
+ val innerLeft = SortMergeJoinExec(
+ Seq(a.head), Seq(c.head), Inner, None, testScan(a, 16), testScan(c,
12))
+ val bhjLeft = BroadcastHashJoinExec(
+ Seq(a(1)), Seq(s(1)), Inner, BuildLeft, None, innerLeft, testScan(s,
16))
+ val planLeft = CoalesceBucketsInJoin(SortMergeJoinExec(
+ Seq(s.head), Seq(o.head), Inner, None, bhjLeft, testScan(o, 8)))
+ assert(coalescedBuckets(planLeft) ==
+ Seq((16, None), (12, None), (16, Some(8)), (8, None)))
+ }
+ }
+
+ test("SPARK-60382: broadcast hash join bucket coalescing keeps the
sort-merge match") {
+ Seq(true, false).foreach { aqeEnabled =>
+ withSQLConf(
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled.toString,
+ SQLConf.COALESCE_BUCKETS_IN_JOIN_ENABLED.key -> "true") {
+ withTable("dim16", "fact100", "other8") {
+ withTempView("picked") {
+ spark.sql(
+ """CREATE TABLE dim16 (i INT, k INT) USING parquet
+ |CLUSTERED BY (i) INTO 16 BUCKETS""".stripMargin)
+ spark.sql(
+ """CREATE TABLE fact100 (i INT, k INT, v STRING) USING parquet
+ |CLUSTERED BY (i) INTO 100 BUCKETS""".stripMargin)
+ spark.sql(
+ """CREATE TABLE other8 (i INT, v STRING) USING parquet
+ |CLUSTERED BY (i) INTO 8 BUCKETS""".stripMargin)
+ spark.sql("INSERT INTO dim16 VALUES (0, 1)")
+ spark.sql(
+ """CREATE OR REPLACE TEMP VIEW picked AS
+ |SELECT CAST(id AS INT) AS i
+ |FROM range(0, 4000)
+ |WHERE pmod(pmod(hash(CAST(id AS INT)), 100), 8)
+ | <> pmod(hash(CAST(id AS INT)), 8)
+ |ORDER BY id
+ |LIMIT 1""".stripMargin)
+ spark.sql("INSERT INTO fact100 SELECT i, 1, 'fact' FROM picked")
+ spark.sql("INSERT INTO other8 SELECT i, 'other' FROM picked")
+ val key = spark.sql("SELECT i FROM picked").head().getInt(0)
+
+ val query =
+ """SELECT /*+ BROADCAST(dim16), MERGE(fact100, other8) */
+ | fact100.i, fact100.v, other8.v
+ |FROM dim16
+ |JOIN fact100 ON dim16.k = fact100.k
+ |JOIN other8 ON fact100.i = other8.i""".stripMargin
+ val df = spark.sql(query)
+ checkAnswer(df, Seq(Row(key, "fact", "other")))
+ val executed = df.queryExecution.executedPlan
+ val scans = collect(executed) { case f: FileSourceScanExec =>
+ (f.relation.bucketSpec.map(_.numBuckets),
f.optionalNumCoalescedBuckets)
+ }
+ assert(scans == Seq((Some(16), None), (Some(100), None), (Some(8),
None)), executed)
+ assert(collectFirst(executed) { case b: BroadcastHashJoinExec =>
b.buildSide }
+ .contains(BuildLeft), executed)
+ }
+ }
+ }
+ }
+ }
+
test("FileSourceScanExec's metadata should be updated with coalesced info") {
val scan = newFileSourceScanExec(RelationSetting(8, None))
val value = scan.metadata("SelectedBucketsCount")
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]