Skip to content

[SPARK-60382][SQL] CoalesceBucketsInJoin should see only the streamed side of a broadcast join - #59636

Closed
wangyum wants to merge 4 commits into
apache:masterfrom
wangyum:SPARK-60382
Closed

wangyum wants to merge 4 commits into
apache:masterfrom
wangyum:SPARK-60382

Conversation

@wangyum

@wangyum wangyum commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

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 one -- keeps its own bucket count.

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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's BuildLeft/BuildRight choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

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 scan collectFirst happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

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

@wangyum

wangyum commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

@cloud-fan Please help review this, it's data issue.

@cloud-fan cloud-fan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

The fix to CoalesceBucketsInJoin holds up. findBucketedScan follows the same path that partitioning takes to the parent shuffled join: FilterExec, ProjectExec, and the streamed child of a broadcast hash or nested-loop join. The rewrite now stamps only the scan it found, and only after isDivisible has accepted that scan's own bucket count. So a broadcast build scan's count can no longer leak into the streamed scan's coalescing. Both preparation paths (non-AQE QueryExecution.preparations and AQE queryStagePreparationRules) run the rule before EnsureRequirements. Any node the walk does not recognize still makes the rule skip the rewrite, and the existing satisfiesOutputPartitioning check still rejects nested-loop join types that do not propagate the streamed side's partitioning. I found no new wrong-result path. The new tests are well targeted: the plan-level test pins the exact stamping for the non-divisible 100-vs-8 case and the newly enabled 16-to-8 case, and the end-to-end query checks the row that was previously dropped. Both would fail on the baseline. The only issue is test hygiene: the end-to-end test leaves its temp view in the shared session.

Findings

1 total: 0 P0, 0 P1, 0 P2, 1 P3.

Nit (P3)

  • End-to-end SPARK-60382 test leaks the picked temp view — sql/core/src/test/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInJoinSuite.scala:342 — see inline.

@dongjoon-hyun dongjoon-hyun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the fix, @wangyum. I reviewed the latest commit, 8cdfbed, and left 13 inline comments. The fix itself looks right to me: findBucketedScan follows the path that the partitioning takes to the parent join, and the rewrite now stamps only the scan whose own count isDivisible accepted, so I found no remaining wrong-result path in the new walk or rewrite. Most items below are about what the tests and the PR description cover. Here is a summary, ordered by priority.

Tests

  1. CoalesceBucketsInJoin L48: the narrowing also fixes a second wrong-result shape that needs no BuildLeft (scans inside a broadcast build side were stamped too), but the description and the JIRA scope the bug to BuildLeft, and no test covers it.
  2. CoalesceBucketsInJoinSuite L325: the end-to-end test runs only with AQE off, although the base bug also reproduces on the default AQE path.
  3. CoalesceBucketsInJoinSuite L276: the plan-level test does not carry over to branch-3.5, which has had the bug since 3.5.0: it does not compile there, and without SPARK-43228 two of its broadcast hash join cases change meaning.
  4. CoalesceBucketsInJoinSuite L313: only the broadcast hash join case rewrites a scan, while the description says the divisible case is checked for both broadcast hash and broadcast nested-loop joins.
  5. CoalesceBucketsInJoinSuite L364: the end-to-end test does not assert the BuildLeft broadcast hash join under the sort-merge join that it relies on.
  6. CoalesceBucketsInJoinSuite L329: three of the five confs have no effect on this query, and the excludedRules override drops the suite-wide ConvertToLocalRelation exclusion.

Performance

  1. CoalesceBucketsInJoin L94: the ratio check now uses the streamed scan's count, so some plans that the base coalesced correctly now get a shuffle, which the user-facing section does not mention.

Docs and comments

  1. CoalesceBucketsInJoin L125: the new findBucketedScan doc says more than the function checks; the real guard is satisfiesOutputPartitioning at L177-178.

PR description

  1. the generative AI section lists only Generated-by: Cursor (GLM 5.3), but 8cdfbed carries Co-Authored-By: Claude Sonnet 5, and dev/merge_spark_pr.py squash-merges with only the PR title and body, so that trailer would be lost (no inline comment).

Cleanup

  1. CoalesceBucketsInJoin L119: streamedSide could be the one-line if that the base used.
  2. CoalesceBucketsInJoin L143: getBucketSpec could fold into the leaf guard of the walk.
  3. CoalesceBucketsInJoinSuite L268: the local scan duplicates newFileSourceScanExec.
  4. CoalesceBucketsInJoinSuite L346: the picked view re-writes the bucket-id formula in SQL and is evaluated three times.
  5. CoalesceBucketsInJoinSuite L360: the query is planned once for the plan check and again for checkAnswer.

Items 1 and 2 are the most important. Items 1, 4, 7 and 9 also touch the PR description, which becomes the commit message.

// scan in the same subtree keeps its own bucket count.
plan transformUp {
case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty =>
case f: FileSourceScanExec if f eq targetScan =>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This narrowing also fixes a second wrong-result shape that needs no BuildLeft, but the description and the JIRA scope the bug to BuildLeft children, and no test covers it. The base stamped every bucketed scan of the coalesced side (case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty), including scans inside a broadcast build side. For example, take SMJ(s.i = o.i)(BHJ(BuildRight, s16, SMJ(a.i = c.i)(a100, c8)), o8):

  • collectFirst correctly finds the streamed s16, so the left side is coalesced from 16 to 8.
  • The base transformUp also stamps a100 and c8 inside the build side with Some(8).
  • When the top-down pass reaches the inner join, the old getBucketSpec skips the stamped scans, so that join makes no decision of its own.
  • a100 then reports HashPartitioning(i, 8) while it groups its files by bucketId % 8, and 100 % 8 != 0. EnsureRequirements adds no shuffle for the inner join, so the broadcast relation loses the rows whose keys land in different partitions.

With this PR only s16 is stamped, and the inner join is judged on its own (100 vs 8 is not divisible). So a bucketed join under a BuildRight broadcast is affected too, which matters for the JIRA and the release note. I traced this by reading the code and did not run it. Could the description and the JIRA also cover bucketed scans inside a broadcast build side, on either build side, and could the plan-level test add a case like this?

val s = cols()
val a = cols()
val c = Seq(AttributeReference("i", IntegerType)())
val o = Seq(AttributeReference("i", IntegerType)())
val inner = SortMergeJoinExec(
  Seq(a.head), Seq(c.head), Inner, None, scan(a, 100), scan(c, 8))
val bhj = BroadcastHashJoinExec(
  Seq(s(1)), Seq(a(1)), Inner, BuildRight, None, scan(s, 16), inner)
val p = CoalesceBucketsInJoin(SortMergeJoinExec(
  Seq(s.head), Seq(o.head), Inner, None, bhj, scan(o, 8)))
assert(coalesced(p) == Seq((16, Some(8)), (100, None), (8, None), (8, None)))

The base returns (100, Some(8)) and (8, Some(8)) for the inner pair.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 081b027: added SPARK-60382: a bucketed join inside a broadcast build side keeps its own bucket count, reproduced against the pre-fix code, and widened the PR description beyond BuildLeft.


test("SPARK-60382: broadcast hash join bucket coalescing keeps the sort-merge match") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pins AQE off, so the default AQE path has no end-to-end coverage, although the base bug reproduces there too. CoalesceBucketsInJoin is also the first rule of queryStagePreparationRules (AdaptiveSparkPlanExec.scala:145). With AQE on, the base code stamps fact100 with 8 in the initial plan, so EnsureRequirements adds no shuffle under the sort-merge join. After the dim16 broadcast stage materializes, the re-planned join has a BroadcastQueryStageExec leaf on its build side, so the base collectFirst finds 100 and the new plan needs a shuffle. AQE keeps the current plan unless the new one is cheaper (AdaptiveSparkPlanExec.scala:451), so the 0-shuffle wrong plan runs and the query returns no rows. I traced this by reading the code and did not run it. Could this test loop over Seq(true, false) for AQE as BucketedReadSuite.scala:1031 does, and mix in AdaptiveSparkPlanHelper so that collect(executed) sees the scans inside AdaptiveSparkPlanExec?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 081b027: the end-to-end test now loops spark.sql.adaptive.enabled over true/false via AdaptiveSparkPlanHelper.collect, verified against the pre-fix code.

bucketSpec = Some(BucketSpec(numBuckets, Seq("i"), Nil)),
fileFormat = new ParquetFileFormat(),
options = Map.empty)(spark)
FileSourceScanExec(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this test does not carry over to branch-3.5 as it is, although the bug has been there since 3.5.0 (SPARK-43107). On branch-3.5:

  • FileSourceScanExec has no stream parameter, so FileSourceScanExec(relation, None, cols, ...) does not compile.
  • satisfiesOutputPartitioning has no PartitioningCollection case, because SPARK-43228 is only in 4.0.0 and later, while an inner BroadcastHashJoinExec always reports a PartitioningCollection there (BroadcastHashJoinExec.scala:76 and :115 on branch-3.5). With the arity fixed, planDiv at L319 fails even with the fix, and the first case at L300 passes even without it.
  • The nested-loop case and the end-to-end test still tell the base and the fix apart, because a ProjectExec unwraps a one-element collection there (AliasAwareOutputExpression.scala:58 on branch-3.5).

I checked this by reading branch-3.5 and did not run it. The rule file is unchanged on branch-4.0 and later, so only a 3.5 backport is affected. Could the broadcast hash join cases put a ProjectExec over the broadcast join, or set spark.sql.execution.broadcastHashJoin.outputPartitioningExpandLimit to 0, so that the same test works on branch-3.5?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is: out of scope for this master-only PR, will address at backport time if this is backported to branch-3.5.

val buildDiv = cols()
val streamDiv = cols()
val otherDiv = Seq(AttributeReference("i", IntegerType)())
val hashJoinDiv = BroadcastHashJoinExec(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this is the only plan-level case that rewrites a scan, and it uses a broadcast hash join, while the PR description says the divisible 16-to-8 case is checked "for both broadcast hash and broadcast nested-loop joins". The nested-loop join at L302-306 covers only the 100-vs-8 case, where nothing is rewritten. A nested-loop rewrite through BuildRight is still pinned by BucketedReadSuite.scala:1067-1073, so this is a coverage gap rather than an untested branch. Could this add the nested-loop variant, e.g. BroadcastNestedLoopJoinExec(scan(buildDiv, 100), scan(streamDiv, 16), BuildLeft, Inner, None) under the same sort-merge join with the expected Seq((100, None), (16, Some(8)), (8, None)), or could the description sentence be narrowed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 081b027: added the BroadcastNestedLoopJoinExec divisible-rewrite variant alongside the existing broadcast-hash-join case.

val scans = executed.collect { case f: FileSourceScanExec =>
(f.relation.bucketSpec.map(_.numBuckets), f.optionalNumCoalescedBuckets)
}
assert(scans == Seq((Some(16), None), (Some(100), None), (Some(8), None)), executed)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: these two checks would also pass on the base code if the inner join stopped being a BuildLeft broadcast hash join. If it were planned as a sort-merge join, or with dim16 as the streamed side, the base rule would not coalesce anything either: all three scans would stay (Some(n), None) in the same order, and the answer would be right. That is unlikely today, since BROADCAST takes precedence over MERGE on the same join, and the plan-level test above still guards the rule. Could this also assert the shape that the test relies on, e.g. assert(executed.collectFirst { case b: BroadcastHashJoinExec => b.buildSide }.contains(BuildLeft), executed)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 081b027: added an assertion that the BroadcastHashJoinExec in the executed plan has buildSide == BuildLeft.

if (j.buildSide == BuildLeft) hasScanOperation(j.right) else hasScanOperation(j.left)
case f: FileSourceScanExec => f.relation.bucketSpec.nonEmpty
case _ => false
private def streamedSide(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the base already used a one-line form for these two cases (if (j.buildSide == BuildLeft) hasScanOperation(j.right) else hasScanOperation(j.left)). The helper does not let the two cases merge, since no common trait exposes buildSide, and both branches of the inline form are tail calls, so @tailrec still holds. Could L135 and L137 be if (j.buildSide == BuildLeft) findBucketedScan(j.right) else findBucketedScan(j.left), dropping streamedSide and the BuildSide import at L24?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is for now to avoid further churn on the already-reviewed rule file; happy to inline this if you'd still like it.

}
}

private def getBucketSpec(scan: FileSourceScanExec): Option[BucketSpec] = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: findBucketedScan already guarantees relation.bucketSpec.nonEmpty (L138), so this helper only rejects a scan that is already coalesced. Could that check move into the walk's leaf case, case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty && f.optionalNumCoalescedBuckets.isEmpty => Some(f), with L179-180 reading leftScan.relation.bucketSpec and rightScan.relation.bucketSpec? A coalesced leaf then falls to case _ => None, so the extractor still returns None, and the BucketSpec import at L22 goes away.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is for now, same reasoning as the streamedSide nit above.


test("SPARK-60382: broadcast join coalescing uses the streamed side bucket count") {
withSQLConf(SQLConf.COALESCE_BUCKETS_IN_JOIN_ENABLED.key -> "true") {
def scan(cols: Seq[Attribute], numBuckets: Int): FileSourceScanExec = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this copies newFileSourceScanExec (L69-79) line for line except for the bucket columns (Seq("i") instead of all columns). That constructor call has already needed two edits in the helper (SPARK-44475 and SPARK-50144), and the next one would have to be made in both places. Could newFileSourceScanExec take an optional list of bucket columns, or could these cases use single-column RelationSetting(n, None) scans with the broadcast join keyed on i? In the latter form the base code still fails all three assertions, because collectFirst reaches the build scan first whatever the join keys are.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is for now; agreed this duplicates newFileSourceScanExec, can follow up if you'd like it deduped.

"""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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this view re-writes Spark's bucket-id function in SQL and is evaluated three times, by the two INSERT ... SELECT statements and by the read-back at L352. BucketingUtils.getBucketIdFromValue already computes the writer's bucket id, and BucketedReadSuite.scala:140 uses it that way. SQL hash and the writer's hash agree for an INT key, so this is about clarity and cost, not correctness today. Could the key be computed once, e.g. val iAttr = AttributeReference("i", IntegerType)() and val key = (0 until 4000).find(v => BucketingUtils.getBucketIdFromValue(iAttr, 100, v) % 8 != BucketingUtils.getBucketIdFromValue(iAttr, 8, v)).get, and inserted with VALUES? That also removes the view and its withTempView.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is for now; this is correct today, can follow up with the BucketingUtils version if you'd like.

|FROM dim16
|JOIN fact100 ON dim16.k = fact100.k
|JOIN other8 ON fact100.i = other8.i""".stripMargin
val executed = spark.sql(query).queryExecution.executedPlan

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the plan check builds its own Dataset here, and checkAnswer at L365 builds and plans another one, so the asserted plan is not the one that runs. They are the same today with AQE off. Could this be val df = spark.sql(query), with df.queryExecution.executedPlan here and checkAnswer(df, Seq(Row(key, "fact", "other"))) at L365?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as-is for now; no behavior difference today since the query is deterministic, can follow up if you'd like it unified.

@dongjoon-hyun dongjoon-hyun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for addressing items 1-14, @wangyum. I reviewed the latest commit, 081b027, and left 7 inline comments, continuing the numbering from items 1-14. I found no new wrong-result path: findBucketedScan follows the same path that outputPartitioning takes to the parent join, and the rule makes the same decision when AQE runs it again during re-optimization. Most items below are about test coverage. Here is a summary, ordered by priority.

Robustness

  1. CoalesceBucketsInJoin L47: the rewrite still runs transformUp over the whole coalesced side and matches the target by reference, so a scan instance that appeared both on the streamed path and inside a broadcast build side would be stamped twice. This is unlikely with today's planner.

Tests

  1. CoalesceBucketsInJoinSuite L408: with AQE on, the plan asserts run before checkAnswer, so they check only the initial adaptive plan, not the re-optimized plan that runs.
  2. CoalesceBucketsInJoinSuite L365: following up on item 1, the nested-join case covers only a BuildRight broadcast, while the description now says either build side.
  3. CoalesceBucketsInJoinSuite L317: no case uses a ShuffledHashJoinExec parent over a broadcast join, where isCoalesceSHJStreamSide now gets the streamed scan's count.

Docs and comments

  1. CoalesceBucketsInJoin L116: the ExtractJoinWithBuckets scaladoc does not mention the two scans that unapply now returns, which are the only ones the rule may stamp.

PR description

  1. the SQL repro still sets spark.sql.autoBroadcastJoinThreshold and the ReorderJoin exclusion, which the test dropped in 081b027 as no-ops (item 6), so the commit message would suggest that both are needed to reproduce the bug (no inline comment).

Cleanup

  1. CoalesceBucketsInJoinSuite L333: the second new test copies scan and coalesced from the first one, which adds to item 12.
  2. CoalesceBucketsInJoinSuite L35: the edited class declaration could mix in QueryTest explicitly.

Items 15 and 16 are the most important. Item 20 only needs the PR description, which becomes the commit message.

numCoalescedBuckets: Int): SparkPlan = {
// Only the scan whose partitioning reaches this join. A broadcast build
// scan in the same subtree keeps its own bucket count.
plan transformUp {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this still runs transformUp over the whole coalesced side and finds the target by reference (f eq targetScan), instead of rewriting along the path that findBucketedScan walked, so every occurrence of that instance is stamped. If the same FileSourceScanExec instance appeared twice in the coalesced side, e.g. once on the streamed path and once inside a bucketed sort-merge join under a broadcast build side, both copies would get Some(numCoalescedBuckets), which brings back the nested-join corruption this PR fixes. The planner creates a new scan instance for each logical node, so I do not think this happens today. It would take a hand-built plan or a later rule that shares subtrees by reference. Could the rewrite follow the same FilterExec, ProjectExec and streamed-child path as findBucketedScan, rebuilding each node with withNewChildren, so that it stamps exactly the walked leaf? If that is too much code for this PR, could the comment at L45-46 at least say that it relies on the scan instance not being shared?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: added a comment at L45-47 noting the rewrite relies on the scan instance not being shared across subtrees, per the suggested fallback, to avoid the larger path-rebuilding change on this already-reviewed file.

|JOIN fact100 ON dim16.k = fact100.k
|JOIN other8 ON fact100.i = other8.i""".stripMargin
val df = spark.sql(query)
val executed = df.queryExecution.executedPlan

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: with AQE on, executed is an AdaptiveSparkPlanExec that has not run yet, so collect(executed) walks its initial plan (executedPlan returns currentPhysicalPlan, AdaptiveSparkPlanExec.scala:302), and these two asserts check only the rule's first decision. CoalesceBucketsInJoin runs again in reOptimize (AdaptiveSparkPlanExec.scala:1150) after the dim16 broadcast stage materializes, which is where AQE kept the base code's wrong 0-shuffle plan (item 2), but nothing here pins the plan that AQE finally runs. checkAnswer at L415 runs this same df, since df.collect() uses df.queryExecution, so afterwards executedPlan holds the final plan. Could checkAnswer move above L408, so that these asserts check the plan that produced the answer? I traced this by reading the code and did not run it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: moved checkAnswer before the plan assertions, so they check the plan AQE actually runs (after re-optimization) rather than the initial plan.

val inner = SortMergeJoinExec(
Seq(a.head), Seq(c.head), Inner, None, scan(a, 100), scan(c, 8))
val bhj = BroadcastHashJoinExec(
Seq(s(1)), Seq(a(1)), Inner, BuildRight, None, scan(s, 16), inner)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor, following up on my item 1: this covers a nested bucketed join only under a BuildRight broadcast, while the description now says the corruption happens "on either build side". Under BuildLeft, the base reads the count from the nested join, because collectFirst reaches its left scan first. For example, in SMJ(BHJ(BuildLeft, SMJ(a16, c12), s16), o8) the base reads 16 from a16, accepts 16 vs 8, and stamps a16, c12 and s16 with Some(8). Since 12 % 8 != 0, the inner join then runs without a shuffle and drops rows, while this PR stamps only s16. I traced this by reading the code and did not run it. Could this test add that case?

val innerLeft = SortMergeJoinExec(
  Seq(a.head), Seq(c.head), Inner, None, scan(a, 16), scan(c, 12))
val bhjLeft = BroadcastHashJoinExec(
  Seq(a(1)), Seq(s(1)), Inner, BuildLeft, None, innerLeft, scan(s, 16))
val planLeft = CoalesceBucketsInJoin(SortMergeJoinExec(
  Seq(s.head), Seq(o.head), Inner, None, bhjLeft, scan(o, 8)))
assert(coalesced(planLeft) == Seq((16, None), (12, None), (16, Some(8)), (8, None)))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: added the BuildLeft variant (innerLeft/bhjLeft/planLeft) to this test, asserting that only the streamed scan s16 is coalesced to 8 while the nested a16/c12 sort-merge join on the build side is left untouched.

val hashJoinDiv = BroadcastHashJoinExec(
Seq(buildDiv(1)), Seq(streamDiv(1)), Inner, BuildLeft, None,
scan(buildDiv, 100), scan(streamDiv, 16))
val planDiv = CoalesceBucketsInJoin(SortMergeJoinExec(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: every new plan-level case puts a SortMergeJoinExec over the broadcast join, so no case covers a ShuffledHashJoinExec parent, where isCoalesceSHJStreamSide (CoalesceBucketsInJoin.scala:103) now gets the streamed scan's count. For example, over hashJoinDiv (a BuildLeft join of a 100-bucket build scan and a 16-bucket streamed scan) and an 8-bucket scan, a shuffled hash join should coalesce the streamed scan to 8 when it builds on the right, and change nothing when it builds on the left. The base coalesces nothing in either case, because it reads 100. Could this test add those two cases?

val shj = CoalesceBucketsInJoin(ShuffledHashJoinExec(
  Seq(streamDiv.head), Seq(otherDiv.head), Inner, BuildRight, None,
  hashJoinDiv, scan(otherDiv, 8)))
assert(coalesced(shj) == Seq((100, None), (16, Some(8)), (8, None)))

With BuildLeft, the expected value is Seq((100, None), (16, None), (8, None)).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: added ShuffledHashJoinExec parent cases (shjRight/shjLeft) over the broadcast join, covering both the coalescing outcome (BuildRight) and the no-op outcome (BuildLeft).

@@ -111,26 +116,35 @@ object CoalesceBucketsInJoin extends Rule[SparkPlan] {
* and numbers of buckets are not equal but divisible.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this scaladoc still describes the old extractor. It does not say that unapply now also returns the bucketed scan of each side, which is the only scan the rule may stamp and the invariant this PR relies on. Also, "are consisted of only the scan operation" did not match the walk through filters, projects and broadcast joins even before this PR. Could L112-117 say something like this?

/**
 * 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.
 */

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: reworded the scaladoc to describe the walk through filters, projects, and the streamed child of a broadcast join, and to say that unapply returns the bucketed scan of each side, which is the only one the rule may stamp and whose partitioning satisfiesOutputPartitioning still checks.


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") {
def scan(cols: Seq[Attribute], numBuckets: Int): FileSourceScanExec = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this scan and the coalesced helper at L345-349 are line-for-line copies of the ones in the previous test (L269-279 and L285-289), so the file now has three copies of this FileSourceScanExec construction, counting newFileSourceScanExec at L70-80. This adds to my item 12, which you left for a follow-up, but this second copy is new in 081b027. Could the two helpers at least move to private suite-level methods that both tests share?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: deduped the scan/coalesced helpers from both new tests into shared suite-level testScan/coalescedBuckets helpers. While doing this I noticed testScan itself duplicated newFileSourceScanExec's relation-building code and hardcoded the bucket column to "i" instead of deriving it, so I also had it delegate to newFileSourceScanExec with an explicit bucketCols override.

import org.apache.spark.sql.types.IntegerType

class CoalesceBucketsInJoinSuite extends SharedSparkSession {
class CoalesceBucketsInJoinSuite extends SharedSparkSession with AdaptiveSparkPlanHelper {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: since this line changes anyway and the suite now calls checkAnswer, could it mix in QueryTest explicitly, with import org.apache.spark.sql.{QueryTest, Row} at L20? SharedSparkSession already extends QueryTest, so nothing changes at runtime, but AGENTS.md:61 asks for the explicit mix-in. The one-line form would be 105 characters, so it needs a break:

class CoalesceBucketsInJoinSuite extends QueryTest with SharedSparkSession
  with AdaptiveSparkPlanHelper {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dd98616: the suite now extends QueryTest with SharedSparkSession with AdaptiveSparkPlanHelper explicitly, with the line break AGENTS.md asks for.

wangyum and others added 2 commits November 4, 2026 14:15
… side of a broadcast join

When spark.sql.bucketing.coalesceBucketsInJoin.enabled is true, a sort-merge
or shuffled-hash join whose child is a BuildLeft broadcast hash join or
broadcast nested-loop join reads the build side's bucket count instead of the
streamed side's, and stamps every bucketed scan in that subtree with the
coalesced count, including the streamed scan whose partitioning the parent
join actually uses. Bucket files are then grouped by their original bucket id
modulo the coalesced count while the scan advertises HashPartitioning of that
count, so when the streamed count is not divisible by it, matching rows land
in different partitions and the join drops them.

ExtractJoinWithBuckets now finds each side's bucketed scan by walking only
the child that exposes its partitioning (Filter, Project, then the streamed
child of a broadcast hash or nested-loop join), returns that scan along with
its bucket count, and the rewrite updates only that scan.

Co-authored-by: Cursor <cursoragent@cursor.com>
…n the end-to-end test

CREATE OR REPLACE TEMP VIEW picked left the view registered in the shared
session beyond this test, since only the tables were scoped by withTable.
Wrap it in withTempView alongside the existing table scoping.

Also assert the exact set of scan/coalesced-bucket pairs instead of only
checking the absence of the specific bad one, and use checkAnswer for the
row-correctness check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…, test coverage, and cleanup

- Move checkAnswer before plan asserts in the AQE test to check the executed adaptive plan.
- Add BuildLeft nested sort-merge join and ShuffledHashJoinExec outer join test cases.
- Deduplicate testScan and coalescedBuckets helpers in CoalesceBucketsInJoinSuite.
- Explicitly mix in QueryTest in CoalesceBucketsInJoinSuite.
- Update ExtractJoinWithBuckets scaladoc and add note about non-shared scan instances.
testScan duplicated newFileSourceScanExec's relation-building code and
hardcoded the bucket column to the literal "i" instead of deriving it,
so it now delegates to newFileSourceScanExec with an explicit bucketCols
override.

@spark-test spark-test left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

This round found no defects. CoalesceBucketsInJoin now takes each side's bucket count from, and coalesces only, the bucketed scan whose partitioning reaches the join. findBucketedScan follows the same filter, project and broadcast streamed-child path that the join's output partitioning comes from, and any other node still disables coalescing. This review found no remaining path that coalesces a scan to a count that does not divide its own bucket count. The new plan-level tests and the end-to-end query tell the fix apart from the base branch, and the end-to-end query returns the previously dropped row with AQE on and off. The temp-view leak from the earlier review is fixed: the end-to-end test now scopes picked with withTempView. Two questions for the author follow.

Cross-cutting observations

  • Both shuffle trade-offs come from the same correction. Coalescing decisions now apply the documented divisibility, maxBucketRatio and shuffled-hash-join stream-side conditions to the scans whose partitioning actually reaches each join. Any plan the base branch coalesced only by reading or stamping a broadcast build side's scans can therefore end up with an exchange it did not have before.

    One decision can settle both, but the nested-join case comes from the narrower rewrite rather than the bucket-count lookup and has its own alternative, so accepting the ratio behavior does not by itself settle it.

Findings

0 total: 0 P0, 0 P1, 0 P2, 0 P3.

No findings.

Re-review status

Prior AI findings: 1 no longer raised, 0 still raised; additional unresolved findings in this review: 0.

New attribution: 0 newly introduced, 0 late catch, 0 previously raised, 0 unattributed.

PR description suggestions

  • Update 'How was this patch tested?'. The nested-join bullet says the test covers a BuildRight broadcast build side, but it now also covers a BuildLeft one. The first bullet does not mention the new shuffled hash join parent cases. The description becomes the commit message, so listing both keeps it in line with the tests.
  • In the 'Was this patch authored or co-authored using generative AI tooling?' section, also disclose Claude Sonnet 5, which commit dad37a3 credits with a Co-Authored-By trailer; dev/merge_spark_pr.py squash-merges with only the PR title and body, so that trailer would otherwise be lost. This follows up on an existing discussion.
  • Drop SET spark.sql.autoBroadcastJoinThreshold = -1; and SET spark.sql.optimizer.excludedRules = org.apache.spark.sql.catalyst.optimizer.ReorderJoin; from the SQL repro. The BROADCAST and MERGE hints already fix both join strategies, ReorderJoin does not reorder hinted joins, and the end-to-end test reproduces the bug without either setting, so keeping them in the commit message suggests they are needed. This follows up on an existing discussion.

Decision challenges

Accept the added shuffle when the streamed scan's bucket ratio exceeds maxBucketRatio

Following up on the ratio discussion: this review traced the same case in the code (not run) and agrees that the new decision matches the documented meaning of spark.sql.bucketing.coalesceBucketsInJoin.maxBucketRatio. It adds three details.

  • For SMJ(BHJ(BuildLeft, dim16, fact64), other8) at the default ratio of 4, EnsureRequirements keeps the 64-partition side and shuffles other8 into 64 partitions. The join therefore runs 64 tasks instead of 8, behind one extra exchange. The rows are the same on the base branch and with this change.
  • The same happens when the BuildLeft build side is itself a bucketed join whose first scan the base branch read, and under a shuffled hash join parent whose stream side is the broadcast join.
  • A user who prefers the old plan for such a query can get it back by raising maxBucketRatio to the streamed ratio (8 here). That also allows coalescing at that ratio for other joins.

Keeping the old plan in code would mean coalescing above the configured ratio, so this review recommends keeping the fix as it is. The PR description now records the trade-off, so the open question is only whether reviewers accept it as the final behavior.

This follows up on existing discussions 1, 2.

Accept the added shuffle for nested bucketed joins inside a broadcast build side

updateNumCoalescedBucketsInScan now stamps only the extracted scan. So a bucketed sort-merge or shuffled hash join nested inside a broadcast build side is judged on its own bucket counts, instead of inheriting the outer join's coalesced count. That removes the wrong results the new nested-join test covers, such as an a100/c8 pair stamped with 8. It also adds an exchange to some nested joins that already returned correct rows on the base branch, because the outer count happened to divide both nested counts. This review traced the cases below in the code; it did not run them. Take SMJ(s.i = o.i)(BHJ(BuildRight, s16, SMJ(a.i = c.i)(a12, c8)), o4) with coalescing enabled and the default maxBucketRatio of 4:

  • Base branch: the outer join coalesces s16 to 4, and the whole-side rewrite also stamps a12 and c8 with 4. Since 4 divides both counts, the nested join needs no exchange and returns correct rows.
  • This PR: only s16 is stamped. The nested join rejects 12 vs 8 on its own, so EnsureRequirements shuffles c8 into 12 partitions inside the broadcast build side, before the broadcast.

Two more shapes behave the same way:

  • A nested a64/c8 pair under an outer count of 8, which the nested join now rejects as ratio 8.
  • A nested BuildRight shuffled hash join with stream a8 and build c16 under an outer count of 8. The base branch coalesced the hash join's build side to 8; the stream-side guard now declines.

In return, the nested join keeps its own parallelism and no longer gets its hash join build side coalesced past the OOM guard. Nested pairs that the rule accepts on their own keep the same or better plans. Keeping the old plans would need a new policy that ties a nested join to the outer join's count, such as coalescing both nested sides to a common divisor, and the rule has no such policy today. The user-facing section of the PR description mentions added shuffles only for the bucket-count lookup, not for nested joins. Is this nested-join trade-off intended? This review recommends accepting it rather than narrowing the fix. If you agree, add a sentence to that section.

Generated by Omnigent on Databricks

@wangyum wangyum closed this in 8754d79 Nov 10, 2026
wangyum added a commit that referenced this pull request Nov 10, 2026
… 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 one -- keeps its own bucket count.

### 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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

### 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 <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>


skip-checks: true
wangyum added a commit that referenced this pull request Nov 10, 2026
… 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 one -- keeps its own bucket count.

### 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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

### 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 <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>
wangyum added a commit that referenced this pull request Nov 10, 2026
… 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 one -- keeps its own bucket count.

### 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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

### 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 <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>
wangyum added a commit that referenced this pull request Nov 10, 2026
… side of a broadcast join

`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 one -- keeps its own bucket count.

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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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.

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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

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'`.

Generated-by: Cursor (GLM 5.3)

Made with [Cursor](https://cursor.com)

Closes #59636 from wangyum/SPARK-60382.

Authored-by: Yuming Wang <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>
wangyum added a commit that referenced this pull request Nov 10, 2026
… side of a broadcast join

`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 one -- keeps its own bucket count.

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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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.

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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

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'`.

Generated-by: Cursor (GLM 5.3)

Made with [Cursor](https://cursor.com)

Closes #59636 from wangyum/SPARK-60382.

Authored-by: Yuming Wang <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>
wangyum added a commit that referenced this pull request Nov 10, 2026
… side of a broadcast join

`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 one -- keeps its own bucket count.

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 could also stamp a bucketed join nested further inside a broadcast build side (on either build side), even when that inner join's own bucket counts were not divisible -- independent of the top-level join's `BuildLeft`/`BuildRight` choice.

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 drops matching rows (or null-pads them for outer joins). Repro:

```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.

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 scan `collectFirst` happened to see first, a small number of plans that the old code coalesced using a build-side scan's bucket count may now take a different (and correct) coalescing decision, including adding a shuffle where the old, incorrect decision avoided one. No API, config, or default behavior change.

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'`.

Generated-by: Cursor (GLM 5.3)

Made with [Cursor](https://cursor.com)

Closes #59636 from wangyum/SPARK-60382.

Authored-by: Yuming Wang <yumwang@apache.org>
Signed-off-by: Yuming Wang <yumwang@ebay.com>

(cherry picked from commit 8754d79)
Signed-off-by: Yuming Wang <yumwang@ebay.com>
@wangyum

wangyum commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Merge Summary:

Posted by merge_spark_pr.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants