Skip to content

Commit 8207e2f

Browse files
c21maropu
authored andcommitted
[SPARK-34781][SQL] Eliminate LEFT SEMI/ANTI joins to its left child side in AQE
### What changes were proposed in this pull request? In `EliminateJoinToEmptyRelation.scala`, we can extend it to cover more cases for LEFT SEMI and LEFT ANI joins: * Join is left semi join, join right side is non-empty and condition is empty. Eliminate join to its left side. * Join is left anti join, join right side is empty. Eliminate join to its left side. Given we eliminate join to its left side here, renaming the current optimization rule to `EliminateUnnecessaryJoin` instead. In addition, also change to use `checkRowCount()` to check run time row count, instead of using `EmptyHashedRelation`. So this can cover `BroadcastNestedLoopJoin` as well. (`BroadcastNestedLoopJoin`'s broadcast side is `Array[InternalRow]`, not `HashedRelation`). ### Why are the changes needed? Cover more join cases, and improve query performance for affected queries. ### Does this PR introduce _any_ user-facing change? No. ### How was this patch tested? Added unit tests in `AdaptiveQueryExecSuite.scala`. Closes apache#31873 from c21/aqe-join. Authored-by: Cheng Su <[email protected]> Signed-off-by: Takeshi Yamamuro <[email protected]>
1 parent 5570f81 commit 8207e2f

File tree

5 files changed

+127
-90
lines changed

5 files changed

+127
-90
lines changed

sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEOptimizer.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class AQEOptimizer(conf: SQLConf) extends RuleExecutor[LogicalPlan] {
2929
private val defaultBatches = Seq(
3030
Batch("Demote BroadcastHashJoin", Once,
3131
DemoteBroadcastHashJoin),
32-
Batch("Eliminate Join to Empty Relation", Once, EliminateJoinToEmptyRelation)
32+
Batch("Eliminate Unnecessary Join", Once, EliminateUnnecessaryJoin)
3333
)
3434

3535
final override protected def batches: Seq[Batch] = {

sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/EliminateJoinToEmptyRelation.scala

-71
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.spark.sql.execution.adaptive
19+
20+
import org.apache.spark.sql.catalyst.planning.ExtractSingleColumnNullAwareAntiJoin
21+
import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftSemi}
22+
import org.apache.spark.sql.catalyst.plans.logical.{Join, LocalRelation, LogicalPlan}
23+
import org.apache.spark.sql.catalyst.rules.Rule
24+
import org.apache.spark.sql.execution.joins.HashedRelationWithAllNullKeys
25+
26+
/**
27+
* This optimization rule detects and eliminates unnecessary Join:
28+
* 1. Join is single column NULL-aware anti join (NAAJ), and broadcasted [[HashedRelation]]
29+
* is [[HashedRelationWithAllNullKeys]]. Eliminate join to an empty [[LocalRelation]].
30+
*
31+
* 2. Join is inner join, and either side of join is empty. Eliminate join to an empty
32+
* [[LocalRelation]].
33+
*
34+
* 3. Join is left semi join
35+
* 3.1. Join right side is empty. Eliminate join to an empty [[LocalRelation]].
36+
* 3.2. Join right side is non-empty and condition is empty. Eliminate join to its left side.
37+
*
38+
* 4. Join is left anti join
39+
* 4.1. Join right side is empty. Eliminate join to its left side.
40+
* 4.2. Join right side is non-empty and condition is empty. Eliminate join to an empty
41+
* [[LocalRelation]].
42+
*
43+
* This applies to all joins (sort merge join, shuffled hash join, broadcast hash join, and
44+
* broadcast nested loop join), because sort merge join and shuffled hash join will be changed
45+
* to broadcast hash join with AQE at the first place.
46+
*/
47+
object EliminateUnnecessaryJoin extends Rule[LogicalPlan] {
48+
49+
private def isRelationWithAllNullKeys(plan: LogicalPlan) = plan match {
50+
case LogicalQueryStage(_, stage: BroadcastQueryStageExec)
51+
if stage.resultOption.get().isDefined =>
52+
stage.broadcast.relationFuture.get().value == HashedRelationWithAllNullKeys
53+
case _ => false
54+
}
55+
56+
private def checkRowCount(plan: LogicalPlan, hasRow: Boolean): Boolean = plan match {
57+
case LogicalQueryStage(_, stage: QueryStageExec) if stage.resultOption.get().isDefined =>
58+
stage.getRuntimeStatistics.rowCount match {
59+
case Some(count) => hasRow == (count > 0)
60+
case _ => false
61+
}
62+
case _ => false
63+
}
64+
65+
def apply(plan: LogicalPlan): LogicalPlan = plan.transformDown {
66+
case j @ ExtractSingleColumnNullAwareAntiJoin(_, _) if isRelationWithAllNullKeys(j.right) =>
67+
LocalRelation(j.output, data = Seq.empty, isStreaming = j.isStreaming)
68+
69+
case j @ Join(_, _, Inner, _, _) if checkRowCount(j.left, hasRow = false) ||
70+
checkRowCount(j.right, hasRow = false) =>
71+
LocalRelation(j.output, data = Seq.empty, isStreaming = j.isStreaming)
72+
73+
case j @ Join(_, _, LeftSemi, condition, _) =>
74+
if (checkRowCount(j.right, hasRow = false)) {
75+
LocalRelation(j.output, data = Seq.empty, isStreaming = j.isStreaming)
76+
} else if (condition.isEmpty && checkRowCount(j.right, hasRow = true)) {
77+
j.left
78+
} else {
79+
j
80+
}
81+
82+
case j @ Join(_, _, LeftAnti, condition, _) =>
83+
if (checkRowCount(j.right, hasRow = false)) {
84+
j.left
85+
} else if (condition.isEmpty && checkRowCount(j.right, hasRow = true)) {
86+
LocalRelation(j.output, data = Seq.empty, isStreaming = j.isStreaming)
87+
} else {
88+
j
89+
}
90+
}
91+
}

sql/core/src/test/scala/org/apache/spark/sql/DynamicPartitionPruningSuite.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -1370,7 +1370,7 @@ abstract class DynamicPartitionPruningSuiteBase
13701370
withSQLConf(
13711371
SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "true",
13721372
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true",
1373-
SQLConf.ADAPTIVE_OPTIMIZER_EXCLUDED_RULES.key -> EliminateJoinToEmptyRelation.ruleName) {
1373+
SQLConf.ADAPTIVE_OPTIMIZER_EXCLUDED_RULES.key -> EliminateUnnecessaryJoin.ruleName) {
13741374
val df = sql(
13751375
"""
13761376
|SELECT * FROM fact_sk f

sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AdaptiveQueryExecSuite.scala

+34-17
Original file line numberDiff line numberDiff line change
@@ -1216,14 +1216,14 @@ class AdaptiveQueryExecSuite
12161216
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> Long.MaxValue.toString,
12171217
// This test is a copy of test(SPARK-32573), in order to test the configuration
12181218
// `spark.sql.adaptive.optimizer.excludedRules` works as expect.
1219-
SQLConf.ADAPTIVE_OPTIMIZER_EXCLUDED_RULES.key -> EliminateJoinToEmptyRelation.ruleName) {
1219+
SQLConf.ADAPTIVE_OPTIMIZER_EXCLUDED_RULES.key -> EliminateUnnecessaryJoin.ruleName) {
12201220
val (plan, adaptivePlan) = runAdaptiveAndVerifyResult(
12211221
"SELECT * FROM testData2 t1 WHERE t1.b NOT IN (SELECT b FROM testData3)")
12221222
val bhj = findTopLevelBroadcastHashJoin(plan)
12231223
assert(bhj.size == 1)
12241224
val join = findTopLevelBaseJoin(adaptivePlan)
12251225
// this is different compares to test(SPARK-32573) due to the rule
1226-
// `EliminateJoinToEmptyRelation` has been excluded.
1226+
// `EliminateUnnecessaryJoin` has been excluded.
12271227
assert(join.nonEmpty)
12281228
checkNumLocalShuffleReaders(adaptivePlan)
12291229
}
@@ -1254,21 +1254,38 @@ class AdaptiveQueryExecSuite
12541254
test("SPARK-34533: Eliminate left anti join to empty relation") {
12551255
withSQLConf(
12561256
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true") {
1257-
withTable("emptyTestData") {
1258-
spark.range(0).write.saveAsTable("emptyTestData")
1259-
Seq(
1260-
// broadcast non-empty right side
1261-
("SELECT /*+ broadcast(testData3) */ * FROM testData LEFT ANTI JOIN testData3", true),
1262-
// broadcast empty right side
1263-
("SELECT /*+ broadcast(emptyTestData) */ * FROM testData LEFT ANTI JOIN emptyTestData",
1264-
false),
1265-
// broadcast left side
1266-
("SELECT /*+ broadcast(testData) */ * FROM testData LEFT ANTI JOIN testData3", false)
1267-
).foreach { case (query, isEliminated) =>
1268-
val (plan, adaptivePlan) = runAdaptiveAndVerifyResult(query)
1269-
assert(findTopLevelBaseJoin(plan).size == 1)
1270-
assert(findTopLevelBaseJoin(adaptivePlan).isEmpty == isEliminated)
1271-
}
1257+
Seq(
1258+
// broadcast non-empty right side
1259+
("SELECT /*+ broadcast(testData3) */ * FROM testData LEFT ANTI JOIN testData3", true),
1260+
// broadcast empty right side
1261+
("SELECT /*+ broadcast(emptyTestData) */ * FROM testData LEFT ANTI JOIN emptyTestData",
1262+
true),
1263+
// broadcast left side
1264+
("SELECT /*+ broadcast(testData) */ * FROM testData LEFT ANTI JOIN testData3", false)
1265+
).foreach { case (query, isEliminated) =>
1266+
val (plan, adaptivePlan) = runAdaptiveAndVerifyResult(query)
1267+
assert(findTopLevelBaseJoin(plan).size == 1)
1268+
assert(findTopLevelBaseJoin(adaptivePlan).isEmpty == isEliminated)
1269+
}
1270+
}
1271+
}
1272+
1273+
test("SPARK-34781: Eliminate left semi/anti join to its left side") {
1274+
withSQLConf(
1275+
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true") {
1276+
Seq(
1277+
// left semi join and non-empty right side
1278+
("SELECT * FROM testData LEFT SEMI JOIN testData3", true),
1279+
// left semi join, non-empty right side and non-empty join condition
1280+
("SELECT * FROM testData t1 LEFT SEMI JOIN testData3 t2 ON t1.key = t2.a", false),
1281+
// left anti join and empty right side
1282+
("SELECT * FROM testData LEFT ANTI JOIN emptyTestData", true),
1283+
// left anti join, empty right side and non-empty join condition
1284+
("SELECT * FROM testData t1 LEFT ANTI JOIN emptyTestData t2 ON t1.key = t2.key", true)
1285+
).foreach { case (query, isEliminated) =>
1286+
val (plan, adaptivePlan) = runAdaptiveAndVerifyResult(query)
1287+
assert(findTopLevelBaseJoin(plan).size == 1)
1288+
assert(findTopLevelBaseJoin(adaptivePlan).isEmpty == isEliminated)
12721289
}
12731290
}
12741291
}

0 commit comments

Comments
 (0)