cloud-fan commented on code in PR #57181: URL: https://github.com/apache/spark/pull/57181#discussion_r3566894786
########## sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/ReplaceSortMergeJoinToShuffledHashJoin.scala: ########## @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.adaptive + +import scala.annotation.tailrec + +import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight, BuildSide, JoinSelectionHelper} +import org.apache.spark.sql.catalyst.plans.LeftExistence +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.execution.{FilterExec, ProjectExec, SortExec, SparkPlan} +import org.apache.spark.sql.execution.aggregate.BaseAggregateExec +import org.apache.spark.sql.execution.exchange.{ENSURE_REQUIREMENTS, EnsureRequirements} +import org.apache.spark.sql.execution.joins.{BaseJoinExec, ShuffledHashJoinExec, SortMergeJoinExec} +import org.apache.spark.sql.execution.window.{WindowExecBase, WindowGroupLimitExec} + +/** + * Converts a [[SortMergeJoinExec]] into a [[ShuffledHashJoinExec]] during adaptive execution when + * a build side's materialized shuffle statistics show it is small enough for a local hash map. + * Unlike [[DynamicJoinSelection]], this runs on the physical plan, so it can reach the input + * shuffle through operators (aggregate, project, filter, window, etc...) sitting above it. + * + * The swap is shuffle-free since both joins are `ShuffledJoin`s with the same distribution and + * partitioning; only the child sorts become unnecessary. As a shuffled hash join loses the sort + * merge join's output ordering, [[EnsureRequirements]] is re-run to restore any ordering an + * ancestor still needs, and AQE's [[CostEvaluator]] decides whether to adopt the converted plan. + */ +case class ReplaceSortMergeJoinToShuffledHashJoin(ensureRequirements: EnsureRequirements) + extends Rule[SparkPlan] with JoinSelectionHelper { + + /** + * Chooses the build side for the shuffled hash join. A side is eligible only if it is allowed + * as a build side for this join type and its input shuffle is small enough to build a local + * hash map. When both sides are eligible, the smaller one (by total shuffle bytes) is chosen. + */ + private def selectBuildSide( + smj: SortMergeJoinExec, + left: ShuffleQueryStageExec, + right: ShuffleQueryStageExec): Option[BuildSide] = { + val canBuildLeft = canBuildShuffledHashJoinLeft(smj.joinType) && + preferShuffledHashJoin(left.mapStats.get) + val canBuildRight = canBuildShuffledHashJoinRight(smj.joinType) && + preferShuffledHashJoin(right.mapStats.get) + if (canBuildLeft && canBuildRight) { + if (left.mapStats.get.bytesByPartitionId.sum < right.mapStats.get.bytesByPartitionId.sum) { + Some(BuildLeft) + } else { + Some(BuildRight) + } + } else if (canBuildLeft) { + Some(BuildLeft) + } else if (canBuildRight) { + Some(BuildRight) + } else { + None + } + } + + override def apply(plan: SparkPlan): SparkPlan = { + if (!conf.convertSortMergeJoinToShuffledHashJoinEnabled) { + return plan + } + val optimizedPlan = plan.transformUp { + case smj @ SortMergeJoinExec(leftKeys, rightKeys, joinType, condition, + ExtractShuffleStage(left), ExtractShuffleStage(right), false) => + selectBuildSide(smj, left, right) match { + case Some(buildSide) => + ShuffledHashJoinExec(leftKeys, rightKeys, joinType, buildSide, condition, Review Comment: This builds a `ShuffledHashJoinExec` as soon as a build side fits the size threshold, but never checks that the join keys are hash-join-compatible. Both peer SHJ-construction paths gate on `hashJoinSupported` first — `JoinSelection.createShuffleHashJoin` (`SparkStrategies.scala:240,262`) returns `None` for non-binary-stable keys and falls through to SMJ, and the `DynamicJoinSelection` hint path reaches SHJ only through that same guard. A join on collated / non-binary-stable string keys (e.g. `UTF8_LCASE`) is orderable — so `SortMergeJoinExec` is chosen (`OrderUtils.isOrderable` treats every `AtomicType` as orderable) — but not binary-stable (`UnsafeRowUtils.isBinaryStable` is false), which is exactly why SHJ was rejected on those paths. Converting such an SMJ here matches keys by `UnsafeRow` binary equality instead of collation-aware equality, so it silently misses matches and returns wrong results once the config is enabled. Gate each side (or the whole conversion) on `hashJoinSupported` / `isBinaryStable(keys)` before converting, and add a collated-key regression test. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
