wangyum commented on code in PR #59027: URL: https://github.com/apache/spark/pull/59027#discussion_r4513849444
########## sql/core/benchmarks/RangeJoinBenchmark-jdk21-results.txt: ########## @@ -0,0 +1,390 @@ +================================================================================================ +Range Join Benchmark +================================================================================================ + +OpenJDK 64-Bit Server VM 21.0.13+9-LTS on Linux 6.17.0-1022-azure Review Comment: Deleted at ef9063b638d: JDK 21 writes the unsuffixed file, and this name predated the float/double routing - the two files the harness's suffix rule maintains are left. ########## sql/core/src/test/scala/org/apache/spark/sql/execution/joins/RangeJoinSQLSuite.scala: ########## @@ -0,0 +1,975 @@ +/* + * 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.joins + +import org.apache.spark.SparkException +import org.apache.spark.sql.QueryTest +import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight} +import org.apache.spark.sql.catalyst.planning.{IntervalOverlapJoin, LessPartialRangeJoin} +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.execution._ +import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper +import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{Decimal, DecimalType, DoubleType} + +/** + * Planner and end-to-end coverage for broadcast range join. + * + * Which condition is recognized: `ExtractRangeJoinKeysSuite`. + * What the index returns: `RangeRelationSuite`. + * What the operator returns: `RangeJoinSuite`. + * This suite checks that the planner chooses the operator, and that the SQL + * result matches broadcast nested loop join where that comparison is the point. + */ +class RangeJoinSQLSuite extends QueryTest with SharedSparkSession with AdaptiveSparkPlanHelper { + + private val pointCond = + "s.ip_add_int >= l.BEGIN_IP2LONG AND s.ip_add_int <= l.END_IP2LONG" + + private def findRangeJoin(plan: SparkPlan): Seq[BroadcastRangeJoinExec] = { + collect(plan) { case j: BroadcastRangeJoinExec => j } + } + + /** `n` range joins sit in one whole-stage, not in nested stages or input adapters. */ + private def oneCodegenStageOwns(plan: SparkPlan, n: Int): Boolean = { + exists(plan) { + case w: WholeStageCodegenExec => + def count(p: SparkPlan): Int = p match { + case _: InputAdapter | _: WholeStageCodegenExec => 0 + case j: BroadcastRangeJoinExec => 1 + j.children.map(count).sum + case other => other.children.map(count).sum + } + count(w.child) == n + case _ => false + } + } + + /** The range join is compiled into a whole-stage, not hidden under an input adapter. */ + private def rangeJoinIsCodegen(plan: SparkPlan): Boolean = { + exists(plan) { + case w: WholeStageCodegenExec => + def contains(p: SparkPlan): Boolean = p match { + case _: InputAdapter => false + case _: BroadcastRangeJoinExec => true + case other => other.children.exists(contains) + } + contains(w.child) + case _ => false + } + } + + private def findBroadcastNestedLoopJoin(plan: SparkPlan): Seq[BroadcastNestedLoopJoinExec] = { + collect(plan) { case j: BroadcastNestedLoopJoinExec => j } + } + + private def findCartesianProduct(plan: SparkPlan): Seq[CartesianProductExec] = { + collect(plan) { case c: CartesianProductExec => c } + } + + private def withRangeJoin(extra: (String, String)*)(f: => Unit): Unit = { + withSQLConf((Seq(SQLConf.BROADCAST_RANGE_JOIN_ENABLED.key -> "true") ++ extra): _*)(f) + } + + /** + * One query per key family and join type that a range join can plan, shared by + * "whole-stage codegen covers each range-join probe" and "interpreted execution + * covers each range-join probe" so the two coverage lists cannot drift apart. + */ + private def probeCoverageQueries: Seq[String] = Seq( + s"SELECT s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l ON $pointCond", + s"SELECT s.id, l.zip_id FROM signin_ip s LEFT JOIN ip_lookup l ON $pointCond", + s"SELECT s.id, l.zip_id FROM signin_ip s RIGHT JOIN ip_lookup l ON $pointCond", + s"SELECT s.id FROM signin_ip s LEFT SEMI JOIN ip_lookup l ON $pointCond", + s"SELECT s.id FROM signin_ip s LEFT ANTI JOIN ip_lookup l ON $pointCond", + "SELECT p.p, r.lo, r.hi FROM dec_points p JOIN dec_ranges r ON p.p >= r.lo AND p.p <= r.hi", + "SELECT /*+ BROADCAST(r) */ p.s, r.lo, r.hi FROM str_points p JOIN str_ranges r " + + "ON p.s >= r.lo AND p.s <= r.hi", + "SELECT a.lo, a.hi, b.lo, b.hi FROM intervals_a a JOIN intervals_b b " + + "ON a.lo < b.hi AND b.lo < a.hi", + "SELECT a.lo, a.hi, b.lo, b.hi FROM intervals_a a LEFT JOIN intervals_b b ON a.hi < b.lo", + "SELECT /*+ BROADCAST(a) */ a.lo, b.hi FROM intervals_a a JOIN intervals_b b ON a.lo < b.hi", + // DOUBLE keys are long-specialized too (see setupDoubleIntervalViews), same as the + // INT two-key overlap above; str_ranges_a/b below cover the boxed interval index. + "SELECT a.lo, a.hi, b.lo, b.hi FROM dbl_ranges_a a JOIN dbl_ranges_b b " + + "ON a.lo < b.hi AND b.lo < a.hi", + // STRING keys stay on the boxed interval index (see setupStringIntervalViews), with + // two real, distinct per-row bounds on each side - unlike str_points/str_ranges below, + // where the streamed side probes with one point used as both bounds. + "SELECT a.lo, a.hi, b.lo, b.hi FROM str_ranges_a a JOIN str_ranges_b b " + + "ON a.lo < b.hi AND b.lo < a.hi", + // Wide decimal and string keys stay on the boxed point index (DOUBLE does not - + // see setupPartialRangeViews), so these queries reach its generated probe code + // (or, interpreted, the per-index dispatch in + // BroadcastRangeJoinExec.makeCandidateFn), which int partial ranges never do. + // The partial-range fixtures include probe values equal to build keys, so an + // inclusive (<=/>=) scan wired to its exclusive counterpart by mistake would + // drop those boundary matches. + "SELECT p.d, b.lo FROM wide_dec_partial_points p JOIN wide_dec_partial_bounds b " + + "ON p.d < b.lo", + "SELECT p.d, b.lo FROM wide_dec_partial_bounds b JOIN wide_dec_partial_points p " + + "ON p.d > b.lo", + "SELECT p.d, b.lo FROM wide_dec_partial_points p JOIN wide_dec_partial_bounds b " + + "ON p.d <= b.lo", + "SELECT p.d, b.lo FROM wide_dec_partial_bounds b JOIN wide_dec_partial_points p " + + "ON p.d >= b.lo", + "SELECT p.s, b.lo FROM str_partial_points p JOIN str_partial_bounds b ON p.s < b.lo", + "SELECT p.s, b.lo FROM str_partial_bounds b JOIN str_partial_points p ON p.s > b.lo", + "SELECT p.s, b.lo FROM str_partial_points p JOIN str_partial_bounds b ON p.s <= b.lo", + "SELECT p.s, b.lo FROM str_partial_bounds b JOIN str_partial_points p ON p.s >= b.lo", + // Boolean, date, and timestamp keys each map to the long family differently + // (0/1, int, long); the boolean fixture includes a null point. The three + // standalone tests that used to cover these are gone - this pair runs + // every query under both codegen modes. + "SELECT p.p, r.lo, r.hi FROM bool_points p JOIN bool_ranges r ON p.p >= r.lo AND p.p <= r.hi", + "SELECT p.d, r.lo, r.hi FROM dt_points p JOIN dt_ranges r ON p.d BETWEEN r.lo AND r.hi", + "SELECT p.t, r.lo, r.hi FROM ts_points p JOIN ts_ranges r ON p.t BETWEEN r.lo AND r.hi") + + private def setupIpLookupViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW signin_ip(id, ip_add_int) AS VALUES + | ('1', 1467630666L), + | ('2', 1186929717L), + | ('3', 3501544352L), + | ('31', 3501544320L), + | ('32', 3501544383L), + | ('33', 3501544330L), + | ('34', 3501544390L), + | ('4', 1626243295L), + | ('41', 1626243072L), + | ('42', 1626243327L), + | ('5', 1206355995L), + | ('5', 1206355995L), + | ('6', CAST(NULL AS BIGINT)), + | ('7', 0L) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW ip_lookup( + | BEGIN_IP2LONG, END_IP2LONG, TWO_CHAR_CNTRY_CD, zip_id) AS VALUES + | (1467630592L, 1467630847L, 'de', 2380520L), + | (1186929664L, 1186930175L, 'us', 6723936L), + | (1186929664L, 1186930175L, 'us', 6723936L), + | (3501544320L, 3501544383L, 'ca', 12804631L), + | (3501544330L, 3501544390L, 'ca', 12804631001L), + | (1626243072L, 1626243327L, 'us', 8849753L), + | (1206355968L, 1206356223L, 'us', 10138801L), + | (CAST(NULL AS BIGINT), 1206356223L, 'us', 10138801L), + | (1206355968L, CAST(NULL AS BIGINT), 'us', 10138801L), + | (CAST(NULL AS BIGINT), CAST(NULL AS BIGINT), 'us', 10138801L) + |""".stripMargin) + } + + private def setupIntervalViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW intervals_a(lo, hi) AS VALUES + | (-1, 0), (0, 1), (0, 2), (1, 5) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW intervals_b(lo, hi) AS VALUES + | (-2, -1), (-4, -2), (1, 3), (5, 7) + |""".stripMargin) + } + + /** + * Two-column STRING ranges, so a two-key interval-overlap query here builds a boxed + * `IntervalIndex` - the `case intervals: IntervalIndex` branch of + * `BroadcastRangeJoinExec.makeCandidateFn` that `intervals_a`/`intervals_b` (INT) and + * `dbl_ranges_a`/`dbl_ranges_b` (DOUBLE) never reach, since both map to one + * order-preserving long (see `RangeIndex.longKey`) and build `LongIntervalIndex` + * instead. StringType has no such mapping, so this stays on the boxed index with + * two real, distinct per-row bounds on each side. + */ + private def setupStringIntervalViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_ranges_a(lo, hi) AS VALUES + | ('b', 'c'), ('c', 'd'), ('c', 'e'), ('d', 'h') + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_ranges_b(lo, hi) AS VALUES + | ('a', 'b'), ('z', 'zz'), ('d', 'f'), ('h', 'j') + |""".stripMargin) + } + + /** + * Two-column DOUBLE ranges. `DoubleType` maps to one order-preserving long (see + * `RangeIndex.longKey`), so a two-key interval-overlap query here builds a + * `LongIntervalIndex`, same as `intervals_a`/`intervals_b` (INT); boxed `IntervalIndex` + * coverage comes from `str_ranges_a`/`str_ranges_b` above instead. This view still + * covers `DoubleType` specifically: NaN and signed-zero ordering, and the long + * encoding's `DoublePrefixComparator` bridge. + */ + private def setupDoubleIntervalViews(): Unit = { + // An unsuffixed literal like `1.0` resolves to DECIMAL, not DOUBLE (only `1.0D` or a + // cast does), and DECIMAL(2, 1) maps to LongIntervalIndex, defeating the point of this + // view. The `D` suffix keeps these columns on the boxed IntervalIndex path. + sql( + """ + |CREATE OR REPLACE TEMP VIEW dbl_ranges_a(lo, hi) AS VALUES + | (-1.0D, 0.0D), (0.0D, 1.0D), (0.0D, 2.0D), (1.0D, 5.0D) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW dbl_ranges_b(lo, hi) AS VALUES + | (-2.0D, -1.0D), (-4.0D, -2.0D), (1.0D, 3.0D), (5.0D, 7.0D) + |""".stripMargin) + assert(sql("SELECT lo, hi FROM dbl_ranges_a").schema.fields.forall(_.dataType == DoubleType)) + assert(sql("SELECT lo, hi FROM dbl_ranges_b").schema.fields.forall(_.dataType == DoubleType)) + } + + private def setupDecimalViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW dec_ranges(lo, hi) AS VALUES + | (CAST(0.00 AS DECIMAL(10, 2)), CAST(2.50 AS DECIMAL(10, 2))), + | (CAST(3.00 AS DECIMAL(10, 2)), CAST(5.00 AS DECIMAL(10, 2))) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW dec_points(p) AS VALUES + | (CAST(1.25 AS DECIMAL(10, 2))), + | (CAST(3.00 AS DECIMAL(10, 2))), + | (CAST(9.00 AS DECIMAL(10, 2))) + |""".stripMargin) + } + + private def setupCollatedStrings(): Unit = { + // 'M' and 'm' compare equal under UNICODE_CI and differ as bytes. + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_ranges(lo, hi) AS VALUES + | (CAST('a' AS STRING COLLATE UNICODE_CI), CAST('a' AS STRING COLLATE UNICODE_CI)), + | (CAST('b' AS STRING COLLATE UNICODE_CI), CAST('b' AS STRING COLLATE UNICODE_CI)), + | (CAST('c' AS STRING COLLATE UNICODE_CI), CAST('M' AS STRING COLLATE UNICODE_CI)), + | (CAST('m' AS STRING COLLATE UNICODE_CI), CAST('z' AS STRING COLLATE UNICODE_CI)) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_points(s) AS VALUES + | (CAST('M' AS STRING COLLATE UNICODE_CI)), + | (CAST('m' AS STRING COLLATE UNICODE_CI)) + |""".stripMargin) + } + + /** + * Points and bounds for single-inequality joins on boxed key families. Each points + * view includes values equal to a bound, so the inclusive (<=/>=) queries in + * `probeCoverageQueries` exercise the boundary, not just the strict (</>) ones. + * + * DOUBLE is not among these families: like the INT partial-range queries elsewhere, + * it maps to one order-preserving long (see `RangeIndex.longKey`) and builds a + * `LongPointIndex`. `DECIMAL(20, 2)` (precision 20, above `Decimal.MAX_LONG_DIGITS`) + * stands in for the boxed numeric case instead. + */ + private def setupPartialRangeViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW wide_dec_partial_points(d) AS VALUES + | (CAST(0.5 AS DECIMAL(20, 2))), (CAST(1.0 AS DECIMAL(20, 2))), + | (CAST(3.0 AS DECIMAL(20, 2))), (CAST(4.0 AS DECIMAL(20, 2))), + | (CAST(6.0 AS DECIMAL(20, 2))), (CAST(7.5 AS DECIMAL(20, 2))), + | (CAST(NULL AS DECIMAL(20, 2))) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW wide_dec_partial_bounds(lo) AS VALUES + | (CAST(1.0 AS DECIMAL(20, 2))), (CAST(4.0 AS DECIMAL(20, 2))), + | (CAST(7.5 AS DECIMAL(20, 2))) + |""".stripMargin) + assert(sql("SELECT d FROM wide_dec_partial_points").schema.fields.forall { f => + f.dataType.isInstanceOf[DecimalType] && + f.dataType.asInstanceOf[DecimalType].precision > Decimal.MAX_LONG_DIGITS + }) + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_partial_points(s) AS VALUES + | ('a'), ('b'), ('m'), ('n'), ('z') + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW str_partial_bounds(lo) AS VALUES + | ('b'), ('n') + |""".stripMargin) + } + + private def setupDateAndTimestampViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW dt_ranges(lo, hi) AS VALUES + | (DATE'2024-01-01', DATE'2024-01-31'), + | (DATE'2024-06-01', DATE'2024-06-30') + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW dt_points(d) AS VALUES + | (DATE'2024-01-15'), + | (DATE'2024-05-01'), + | (DATE'2024-06-15') + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW ts_ranges(lo, hi) AS VALUES + | (TIMESTAMP'2024-01-01 00:00:00', TIMESTAMP'2024-01-01 12:00:00') + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW ts_points(t) AS VALUES + | (TIMESTAMP'2024-01-01 06:00:00'), + | (TIMESTAMP'2024-01-01 18:00:00') + |""".stripMargin) + } + + private def setupBooleanViews(): Unit = { + sql( + """ + |CREATE OR REPLACE TEMP VIEW bool_ranges(lo, hi) AS VALUES + | (false, true), + | (true, true) + |""".stripMargin) + sql( + """ + |CREATE OR REPLACE TEMP VIEW bool_points(p) AS VALUES + | (false), + | (true), + | (CAST(NULL AS BOOLEAN)) + |""".stripMargin) + } + + test("range join is disabled by default and falls back to nested loop join") { + setupIpLookupViews() + val df = sql(s"SELECT s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l ON $pointCond") + assert(findRangeJoin(df.queryExecution.executedPlan).isEmpty) + assert(findBroadcastNestedLoopJoin(df.queryExecution.executedPlan).size == 1) + } + + test("point-in-range matches the nested loop result") { + setupIpLookupViews() + val query = s"SELECT s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l ON $pointCond" + val expected = sql(query).collect() + withRangeJoin() { + val df = sql(query) + assert(findRangeJoin(df.queryExecution.executedPlan).size == 1) + checkAnswer(df, expected) + } + } + + test("BETWEEN is planned as a point-in-range join") { + setupIpLookupViews() + val query = + "SELECT s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l " + + "ON s.ip_add_int BETWEEN l.BEGIN_IP2LONG AND l.END_IP2LONG" + val expected = sql(query).collect() + withRangeJoin(SQLConf.ALWAYS_INLINE_COMMON_EXPR.key -> "false") { + val df = sql(query) + val planned = findRangeJoin(df.queryExecution.executedPlan) + assert(planned.size == 1) + // BETWEEN lowers to one point expression. The other side keeps (low, high). + val keyCounts = Set(planned.head.leftKeys.length, planned.head.rightKeys.length) + assert(keyCounts == Set(1, 2)) + checkAnswer(df, expected) + } + } + + test("hints select range join, nested loop, or cartesian") { + setupIpLookupViews() + setupIntervalViews() + val expected = sql( + s"SELECT s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l ON $pointCond").collect() + withRangeJoin() { + val broadcast = sql( + "SELECT /*+ BROADCAST(l) */ s.id, l.zip_id FROM signin_ip s JOIN ip_lookup l " + + s"ON $pointCond") + val joins = findRangeJoin(broadcast.queryExecution.executedPlan) + assert(joins.size == 1 && joins.head.buildSide == BuildRight) + checkAnswer(broadcast, expected) + + val dualHintInner = sql( + "SELECT /*+ BROADCAST(s), BROADCAST(l) */ s.id, l.zip_id " + + s"FROM signin_ip s JOIN ip_lookup l ON $pointCond") + val dualJoins = findRangeJoin(dualHintInner.queryExecution.executedPlan) + assert(dualJoins.size == 1 && dualJoins.head.buildSide == BuildRight) + checkAnswer(dualHintInner, expected) + + val dualHintLeftOuter = sql( + "SELECT /*+ BROADCAST(s), BROADCAST(l) */ s.id, l.zip_id " + + s"FROM signin_ip s LEFT JOIN ip_lookup l ON $pointCond") + val dualOuterJoins = findRangeJoin(dualHintLeftOuter.queryExecution.executedPlan) + assert(dualOuterJoins.size == 1 && dualOuterJoins.head.buildSide == BuildRight) + + val unsupported = sql( + "SELECT /*+ BROADCAST(a) */ a.lo, b.hi FROM intervals_a a LEFT JOIN intervals_b b " + + "ON a.lo < b.hi") + val loops = findBroadcastNestedLoopJoin(unsupported.queryExecution.executedPlan) + assert(findRangeJoin(unsupported.queryExecution.executedPlan).isEmpty) + assert(loops.size == 1 && loops.head.buildSide == BuildLeft) + + val cartesian = sql( + "SELECT /*+ SHUFFLE_REPLICATE_NL(s) */ s.id, l.zip_id " + + s"FROM signin_ip s JOIN ip_lookup l ON $pointCond") + val plan = cartesian.queryExecution.executedPlan + assert(findRangeJoin(plan).isEmpty) + assert(findCartesianProduct(plan).size == 1) + } + } + + test("a hint that resolves no broadcast side still allows a by-size range join") { + // MERGE does not apply to a non-equi join (no equi-join keys to sort-merge on), so + // it resolves no side for either a hinted range join or a hinted nested loop join. + // Falling through to `createNonEquiJoin()` without first retrying the by-size range Review Comment: Fixed at ef9063b638d: the MERGE-hint test's comment names `getNonEquiJoinBuildSide`'s `case None => withoutHint` fallback that exists in the tree, and the probe-coverage comment now says the boolean, date, and timestamp queries are covered by that pair of tests under both codegen modes. -- 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]
