cloud-fan commented on code in PR #59027: URL: https://github.com/apache/spark/pull/59027#discussion_r4524202266
########## sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/RangeJoinBenchmark.scala: ########## @@ -0,0 +1,597 @@ +/* + * 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.benchmark + +import java.sql.Date + +import org.apache.spark.benchmark.Benchmark +import org.apache.spark.sql.{Column, DataFrame} +import org.apache.spark.sql.catalyst.planning.{GreaterPartialRangeJoin, IntervalOverlapJoin, LessPartialRangeJoin, PointInRangeJoin, RangeJoinKind} +import org.apache.spark.sql.execution.joins.{BroadcastNestedLoopJoinExec, BroadcastRangeJoinExec} +import org.apache.spark.sql.functions.{broadcast, col, date_add, lit, lpad, when} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.StringType + +/** + * Benchmark broadcast range join against broadcast nested loop join. + * + * Long keys cross every supported shape with every supported join type. + * Inner joins broadcast each side once. Left anti probes values that match + * nothing. A partial range whose bound sits at the median is not selective. + * Wide interval overlap is mostly selective: a probe overlaps a build + * interval only when |i - j| <= 20, so about 2% of the 100,000 probes hit + * up to 41 of the 2,000 build intervals each and the rest hit nothing. + * Point-in-range inner is repeated for date, timestamp, decimal, + * and UNICODE_CI strings. + * + * More cases probe the cost model directly: a streamed side of 1, 10, 100, + * 1000, 5000, or 10000 rows, where range join pays to sort the whole build + * side instead of one nested-loop scan, and a fully overlapping inner join, + * where every pair matches and the index prunes nothing. The same tiny-probe + * shape is repeated against a 1,000,000-row build: a `BROADCAST`-hinted large + * dimension table probed by a handful of streamed keys, where the one-time + * build cost this measures is largest relative to the nested-loop scan it + * replaces. + * + * Staggered-overlap builds cover the regime between those: a fraction of build + * intervals -- from a small minority at 5%/10%/25% to half or more at 50%/90% -- + * overlap each probe window, and the build has no common core, so no shortcut + * answers the probe outright. At 50% and 90% each miss is isolated, so the + * walk prunes no multi-node subtree. It does drop size-1 miss spans whose max + * high is below the probe (504 and 100 in the 2,000-row build); the other + * misses are visited and rejected. At 5%, 10%, and 25%, misses run in long + * stretches, so the walk also prunes whole subtrees; see the comment above + * `staggerBuild` for those counts. + * Long and double keys run at 5%, 10%, 25%, 50%, and 90% overlap. Tiny builds + * of 8 and 16 ranges measure the small-build linear scan; the 32- and 64-range + * builds are disjoint and just past that cutoff, so they measure the tree walk + * instead. + * + * To run this benchmark: + * {{{ + * 1. build/sbt "sql/Test/runMain org.apache.spark.sql.execution.benchmark.RangeJoinBenchmark" + * 2. generate result: + * SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt \ + * "sql/Test/runMain org.apache.spark.sql.execution.benchmark.RangeJoinBenchmark" + * Results will be written to "benchmarks/RangeJoinBenchmark-results.txt". + * }}} + */ +object RangeJoinBenchmark extends SqlBasedBenchmark { + + // An optional regex in the environment variable RANGE_BENCH_FILTER runs only the + // sections whose name matches, e.g. RANGE_BENCH_FILTER=".*tiny probe.*|.*full overlap.*". + // A workaround for sbt splitting runMain arguments on spaces. + private var nameFilter: Option[String] = Option(System.getenv("RANGE_BENCH_FILTER")) + + private def shouldRun(name: String): Boolean = nameFilter.forall(name.matches) + + private val buildRows = 4000 + private val probeRows = 400000 + private val width = 10 + // Wide overlap is measured over 100,000 probes and 2,000 build intervals. + private val heavyBuildRows = 2000 + private val heavyProbeRows = 100000 + private val halfBuildRows = 1000 + private val halfProbeRows = 10000 + private val wideSpan = 20 * width + + private val epoch = lit(Date.valueOf("1970-01-01")) + + // [0, buildRows * width). Each range covers `width` values and none overlap. + private lazy val ranges: DataFrame = cached(spark.range(buildRows).select( + (col("id") * width).as("lo"), + (col("id") * width + (width - 1)).as("hi"))) + + // One hit per point: the value falls in exactly one range above. + private lazy val points: DataFrame = cached(spark.range(probeRows).select( + (col("id") % (buildRows.toLong * width)).as("p"))) + + // Above every range, so a point-in-range probe matches nothing. + private lazy val misses: DataFrame = cached(spark.range(probeRows).select( + (lit(buildRows.toLong * width) + (col("id") % width)).as("p"))) + + // Short intervals. A probe overlaps the build intervals whose starts are near it. + private lazy val probeIntervals: DataFrame = + cached(intervals(probeRows, "a", width + width / 2)) + private lazy val buildIntervals: DataFrame = + cached(intervals(buildRows, "b", width + width / 2)) + // Starts after every build interval. + private lazy val missIntervals: DataFrame = cached(spark.range(probeRows).select( + (lit(buildRows.toLong * width + width) + col("id") * width).as("alo"), + (lit(buildRows.toLong * width + width * 2) + col("id") * width).as("ahi"))) + + // Mostly selective: a probe overlaps a build interval only when |i - j| <= 20, + // so about 2% of the 100,000 probes hit up to 41 of the 2,000 build intervals + // each and the rest hit nothing (see the class doc above). + private lazy val wideProbe: DataFrame = cached(intervals(heavyProbeRows, "a", wideSpan)) + private lazy val wideBuild: DataFrame = cached(intervals(heavyBuildRows, "b", wideSpan)) + + // Build keys 0 .. buildRows - 1. High probes sit at the top, low probes at the bottom, + // so a selective inequality returns only a few candidates. + private lazy val bounds: DataFrame = cached(spark.range(buildRows).select(col("id").as("b"))) + private lazy val highProbes: DataFrame = cached(spark.range(probeRows).select( + (lit(buildRows - 1) - (col("id") % width)).as("a"))) + private lazy val lowProbes: DataFrame = cached(spark.range(probeRows).select( + (col("id") % width).as("a"))) + // Strictly above every bound, so `a < b` matches nothing. + private lazy val lessMisses: DataFrame = cached(spark.range(probeRows).select( + lit(buildRows.toLong).as("a"))) + // `a > b` matches nothing when every bound is non-negative. + private lazy val greaterMisses: DataFrame = cached(spark.range(probeRows).select(lit(0L).as("a"))) + + // `a` is the median bound, so each inequality matches about half the build side. + private lazy val halfBounds: DataFrame = + cached(spark.range(halfBuildRows).select(col("id").as("b"))) + private lazy val halfProbes: DataFrame = cached(spark.range(halfProbeRows).select( + lit(halfBuildRows.toLong / 2).as("a"))) + + // M approx 1, 10, 100, 1000, 5000, and 10000. The build side still has to be + // sorted to answer a few streamed probes, so this weighs that one-time O(N log N) + // cost against one O(N) nested-loop scan of the same build side, and shows how + // fast that cost amortizes Review Comment: **Nit (P3):** This sentence breaks after "amortizes" and leaves "as M grows just past one." on a line of its own. Could the two lines be rewrapped into one sentence? **Verification:** - **Inspection:** The comment above the tiny-probe row counts has no line holding only the tail of a broken sentence. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala: ########## @@ -351,28 +358,68 @@ abstract class SparkStrategies extends QueryPlanner[SparkPlan] { Seq(joins.BroadcastHashJoinExec(leftKeys, rightKeys, LeftAnti, BuildRight, None, planLater(j.left), planLater(j.right), isNullAwareAntiJoin = true)) - // If it is not an equi-join, we first look at the join hints w.r.t. the following order: - // 1. broadcast hint: pick broadcast nested loop join. If both sides have the broadcast - // hints, choose the smaller side (based on stats) to broadcast for inner and full joins, - // choose the left side for right join, and choose right side for left join. - // 2. shuffle replicate NL hint: pick cartesian product if join type is inner like. + // If it is not an equi-join, a broadcast hint is considered first: + // 1. When range join is enabled and the condition is a range predicate, + // pick a broadcast range join if a hinted build side is one + // BroadcastRangeJoinExec supports. Both sides hinted: an unsupported + // hinted side is dropped first, so an inner join builds the smaller + // side, left outer/semi/anti build the right side, and right outer + // builds the left side. Only when every hinted side is unsupported + // does planning fall through. + // 2. Otherwise a broadcast hint picks broadcast nested loop join. Both + // sides hinted: the smaller side for inner and full joins, the left + // side for a right join, and the right side for a left join. + // 3. A shuffle replicate NL hint picks cartesian product for an + // inner-like join. // - // If there is no hint or the hints are not applicable, we follow these rules one by one: - // 1. Pick broadcast nested loop join if one side is small enough to broadcast. If only left - // side is broadcast-able and it's left join, or only right side is broadcast-able and - // it's right join, we skip this rule. If both sides are small, broadcasts the smaller - // side for inner and full joins, broadcasts the left side for right join, and broadcasts - // right side for left join. - // 2. Pick cartesian product if join type is inner like. - // 3. Pick broadcast nested loop join as the final solution. It may OOM but we don't have - // other choice. It broadcasts the smaller side for inner and full joins, broadcasts the - // left side for right join, and broadcasts right side for left join. + // If there is no hint, or none of those hints apply: + // 1. When range join is enabled and a side is small enough to broadcast, + // pick a broadcast range join on a side BroadcastRangeJoinExec + // supports. Both sides small: the smaller side when it is supported. Review Comment: **Nit (P3):** With no hint and both sides under the broadcast threshold, `getNonEquiJoinBuildSide` returns `desiredBuildSide`, which is the smaller side only for inner-like and full outer joins. A left outer, semi, or anti join gets `BuildRight` and a right outer join `BuildLeft` whichever side is smaller, and `BroadcastRangeJoinExec.supports` admits both. So for `a LEFT JOIN b ON a.lo < b.hi` with a smaller `a`, this rule reads as building `a`, which the range join can't build, while the planner builds `b` as a range join. Could it use the per-join-type wording the hinted rule above now has: an inner join builds the smaller side, left outer, semi, and anti joins build the right side, and a right outer join builds the left side? This extends an [existing discussion](https://github.com/apache/spark/pull/59027#discussion_r4494427397). **Verification:** - **Inspection:** For inner, left outer, left semi, left anti, and right outer joins with both sides under the broadcast threshold, the build side the comment states matches the side getNonEquiJoinBuildSide returns and BroadcastRangeJoinExec builds. ########## sql/core/src/test/scala/org/apache/spark/sql/execution/joins/RangeJoinSQLSuite.scala: ########## @@ -0,0 +1,1019 @@ +/* + * 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", + // FLOAT keys route through the same DoublePrefixComparator bridge as DOUBLE, building + // a LongPointIndex; -0.0F/0.0F and NaN rows pin that build and probe agree on the + // widened-to-double encoding (see setupFloatPartialViews). + "SELECT p.f, b.lo FROM flt_partial_points p JOIN flt_partial_bounds b ON p.f < 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. These three + // queries are covered, under both codegen modes, by this pair of tests. + "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 too, defeating the point of + // this view. The `D` suffix keeps these columns typed DOUBLE, which routes here through + // `RangeIndex.longKey`'s `DoublePrefixComparator` bridge rather than DECIMAL's unscaled + // long. -0.0D/0.0D and NaN rows pin that build and probe agree on the long encoding of Review Comment: **Nit (P3):** Under `a.lo < b.hi AND b.lo < a.hi`, none of the added `(-0.0D, 0.0D)`, `(0.0D, 0.0D)`, or `(NaN, NaN)` rows matches any row: -0.0 equals 0.0 under SQL comparison, so `-0.0 < 0.0` is false, and nothing is greater than NaN. A probe whose encoding drifted on a special value would change only its own window, so the finite rows can't surface the drift either, and with six rows per view the build takes the linear scan anyway. In `setupFloatPartialViews`, `CAST(-0.0 AS FLOAT)` casts the unsuffixed literal `-0.0`, a DECIMAL whose zero has no sign, so that row is +0.0F, and its NaN point matches nothing under `p.f < b.lo`. Could the fixtures add rows whose matches depend on the special values, such as an inclusive comparison of -0.0 against 0.0 with each on the build side once, and an interval with a finite lower bound and a NaN upper bound under `<`, write the FLOAT negative zero as `CAST(-0.0D AS FLOAT)`, and have both comments say which rows pin which value? This extends an [existing discussion](https://github.com/apache/spark/pull/59027#discussion_r4512581502). **Verification:** - **Regression:** With whole-stage codegen enabled and disabled, the DOUBLE and FLOAT range joins return the nested-loop answer; the codegen-enabled run fails if the generated probe conversion stops folding -0.0 into 0.0 or stops ordering NaN above every finite value, and both runs fail if the conversion that the build side and the interpreted probe share does. - **Inspection:** The FLOAT fixture's negative zero is written with a double literal or cast, so its column value is -0.0F. ########## sql/core/src/test/scala/org/apache/spark/sql/execution/joins/RangeJoinSuite.scala: ########## @@ -0,0 +1,474 @@ +/* + * 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.sql.{DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{And, Expression, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, UnaryExpression} +import org.apache.spark.sql.catalyst.expressions.codegen._ +import org.apache.spark.sql.catalyst.expressions.codegen.Block._ +import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight, BuildSide} +import org.apache.spark.sql.catalyst.planning.{GreaterPartialRangeJoin, IntervalOverlapJoin, LessPartialRangeJoin, PartialRangeJoin, PointInRangeJoin, RangeJoinKind} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter} +import org.apache.spark.sql.execution.SparkPlan +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{DataType, IntegerType, StructType} +import org.apache.spark.util.LongAccumulator + +/** + * Wraps `child` and adds to `counter` each time it is evaluated, interpreted or + * generated. Lets a test count how many build-side candidates a join actually probes, + * without needing a metric on the operator under test. + */ +private[joins] case class CountingPredicate(counter: LongAccumulator, child: Expression) + extends UnaryExpression { + + override def dataType: DataType = child.dataType + override def nullable: Boolean = child.nullable + + override def eval(input: InternalRow): Any = { + counter.add(1) + child.eval(input) + } + + override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { + val childGen = child.genCode(ctx) + val counterTerm = ctx.addReferenceObj("counter", counter) + val code = code""" + |$counterTerm.add(1); + |${childGen.code} + |""" + ev.copy(code = code, isNull = childGen.isNull, value = childGen.value) + } + + override protected def withNewChildInternal(newChild: Expression): CountingPredicate = + copy(child = newChild) +} + +/** + * Operator results for [[BroadcastRangeJoinExec]]. The planner is covered by + * `RangeJoinSQLSuite`; recognition and the index are covered below that. + */ +class RangeJoinSuite extends QueryTest with SharedSparkSession { + private lazy val intervals1: DataFrame = spark.createDataFrame( + sparkContext.parallelize(Seq( + Row(-1, 0), + Row(0, 1), + Row(0, 2), + Row(1, 5) + )), new StructType().add("low1", IntegerType).add("high1", IntegerType)) + + private lazy val intervals2: DataFrame = spark.createDataFrame( + sparkContext.parallelize(Seq( + Row(-2, -1), + Row(1, 3), + Row(5, 7) + )), new StructType().add("low2", IntegerType).add("high2", IntegerType)) + + private lazy val points: DataFrame = spark.createDataFrame( + sparkContext.parallelize(Seq( + Row(-3), + Row(1), + Row(3), + Row(6) + )), new StructType().add("point", IntegerType)) + + /** + * Operator-level helper. Keys are the original expressions from each child. + * `condition` is the original join predicate and the only accept/reject check. + */ + private def rangeJoinExec( + left: SparkPlan, + right: SparkPlan, + buildSide: BuildSide, + joinType: JoinType, + buildKeys: Seq[Expression], + streamedKeys: Seq[Expression], + condition: Expression, + rangeJoinKind: RangeJoinKind = PointInRangeJoin): BroadcastRangeJoinExec = { + val (leftKeys, rightKeys) = buildSide match { + case BuildLeft => (buildKeys, streamedKeys) + case BuildRight => (streamedKeys, buildKeys) + } + BroadcastRangeJoinExec( + left, right, buildSide, joinType, leftKeys, rightKeys, Some(condition), rangeJoinKind) + } + + private def pointCondition( + point: Expression, + low: Expression, + high: Expression, + lowInclusive: Boolean, + highInclusive: Boolean, + highFirst: Boolean = false): Expression = { + val lowPred = if (lowInclusive) GreaterThanOrEqual(point, low) else GreaterThan(point, low) + val highPred = if (highInclusive) LessThanOrEqual(point, high) else LessThan(point, high) + if (highFirst) And(highPred, lowPred) else And(lowPred, highPred) + } + + private def checkAnswerBothModes( + left: DataFrame, + right: DataFrame, + plan: (SparkPlan, SparkPlan) => SparkPlan, + expected: Seq[Row]): Unit = { + Seq(true, false).foreach { codegen => + withSQLConf( + org.apache.spark.sql.internal.SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString, + org.apache.spark.sql.internal.SQLConf.CODEGEN_FALLBACK.key -> "false") { + checkAnswer2(left, right, plan, expected) + } + } + } + + private def checkPointJoin( + left: DataFrame, + right: DataFrame, + pointOnLeft: Boolean, + buildSide: BuildSide, + joinType: JoinType, + lowInclusive: Boolean, + highInclusive: Boolean, + expected: Seq[Row], + highFirst: Boolean = false): Unit = { + checkAnswerBothModes(left, right, (leftPlan: SparkPlan, rightPlan: SparkPlan) => { + val pointPlan = if (pointOnLeft) leftPlan else rightPlan + val boundPlan = if (pointOnLeft) rightPlan else leftPlan + val point = pointPlan.output.head + val bounds = boundPlan.output + val pointKeys = point :: Nil + val buildIsPoint = buildSide match { + case BuildRight => !pointOnLeft + case BuildLeft => pointOnLeft + } + val (buildKeys, streamedKeys): (Seq[Expression], Seq[Expression]) = + if (buildIsPoint) (pointKeys, bounds) else (bounds, pointKeys) + rangeJoinExec( + leftPlan, rightPlan, buildSide, joinType, buildKeys, streamedKeys, + pointCondition(point, bounds(0), bounds(1), lowInclusive, highInclusive, highFirst)) + }, expected) + } + + test("point-in-range keeps boundary inclusivity on the condition") { + val lowInclHighExcl = Seq((0, 2, 1), (1, 5, 1), (1, 5, 3)).map(Row.fromTuple) + val bothExcl = Seq((0, 2, 1), (1, 5, 3)).map(Row.fromTuple) + val bothIncl = Seq((1, 0, 1), (1, 0, 2), (1, 1, 5), (3, 1, 5)).map(Row.fromTuple) + + Seq(false, true).foreach { highFirst => + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildRight, Inner, + lowInclusive = true, highInclusive = false, lowInclHighExcl, highFirst) + } + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildRight, Inner, + lowInclusive = false, highInclusive = false, bothExcl) + checkPointJoin( + points, intervals1, pointOnLeft = true, BuildRight, Inner, + lowInclusive = true, highInclusive = true, bothIncl) + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildLeft, Inner, + lowInclusive = false, highInclusive = false, bothExcl) + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildLeft, Inner, + lowInclusive = true, highInclusive = false, lowInclHighExcl) + } + + test("outer, semi, and anti preserve unmatched streamed rows") { + // low <= point && point < high. (-1, 0) and (0, 1) contain no point. + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildRight, LeftOuter, + lowInclusive = true, highInclusive = false, + Seq((-1, 0, null), (0, 1, null), (0, 2, 1), (1, 5, 1), (1, 5, 3)).map(Row.fromTuple)) + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildLeft, RightOuter, + lowInclusive = true, highInclusive = false, + Seq((null, null, -3), (0, 2, 1), (1, 5, 1), (1, 5, 3), (null, null, 6)).map(Row.fromTuple)) + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildRight, LeftSemi, + lowInclusive = true, highInclusive = false, + Seq((0, 2), (1, 5)).map(Row.fromTuple)) + checkPointJoin( + intervals1, points, pointOnLeft = false, BuildRight, LeftAnti, + lowInclusive = true, highInclusive = false, + Seq((-1, 0), (0, 1)).map(Row.fromTuple)) + } + + test("a null streamed bound is not a match") { + val nullInterval = spark.createDataFrame( + sparkContext.parallelize(Seq(Row(null, 5))), + new StructType().add("low1", IntegerType).add("high1", IntegerType)) + checkPointJoin( + nullInterval, points, pointOnLeft = false, BuildRight, LeftOuter, + lowInclusive = true, highInclusive = false, Seq(Row(null, 5, null))) + checkPointJoin( + nullInterval, points, pointOnLeft = false, BuildRight, LeftSemi, + lowInclusive = true, highInclusive = false, Seq.empty) + checkPointJoin( + nullInterval, points, pointOnLeft = false, BuildRight, LeftAnti, + lowInclusive = true, highInclusive = false, Seq(Row(null, 5))) + } + + test("partial range scans upTo or from according to the lower bound") { + // a.lo < b.hi builds the high side and scans from the stream key. + // a.lo > b.hi builds the low side and scans up to the stream key. + def check( + rangeJoinKind: RangeJoinKind, + condition: (SparkPlan, SparkPlan) => Expression, + expected: Seq[Row], + buildSide: BuildSide = BuildRight): Unit = { + checkAnswerBothModes(intervals1, intervals2, (left: SparkPlan, right: SparkPlan) => { + val (buildKeys, streamedKeys) = buildSide match { + case BuildRight => (right.output(1) :: Nil, left.output.head :: Nil) + case BuildLeft => (left.output.head :: Nil, right.output(1) :: Nil) + } + rangeJoinExec( + left, right, buildSide, Inner, + buildKeys = buildKeys, + streamedKeys = streamedKeys, + condition = condition(left, right), + rangeJoinKind = rangeJoinKind) + }, expected) + } + check( + LessPartialRangeJoin(strict = true), + (left, right) => LessThan(left.output.head, right.output(1)), + Seq( + (-1, 0, 1, 3), (-1, 0, 5, 7), + (0, 1, 1, 3), (0, 1, 5, 7), + (0, 2, 1, 3), (0, 2, 5, 7), + (1, 5, 1, 3), (1, 5, 5, 7)).map(Row.fromTuple)) + check( + GreaterPartialRangeJoin(strict = true), + (left, right) => GreaterThan(left.output.head, right.output(1)), + Seq((0, 1, -2, -1), (0, 2, -2, -1), (1, 5, -2, -1)).map(Row.fromTuple)) + // Same join, built from the other side: GreaterPartialRangeJoin + BuildLeft takes the + // opposite PointIndex scan arm (from, not upTo) from the BuildRight case above. Review Comment: **Nit (P3):** These fixtures use `IntegerType` keys, which `RangeIndex.canMapKeysToLong` routes to `LongPointIndex`, so this case takes the long point index's `from` arm, not the boxed `PointIndex`'s. The `PointScan` scaladoc depends on that distinction, crediting only RangeJoinSQLSuite's wide-decimal and string queries with the boxed scans. ```suggestion // opposite LongPointIndex scan arm (from, not upTo) from the BuildRight case above. ``` **Verification:** - **Inspection:** The partial-range test's comment names the long point index, or no specific class, for its int-keyed build. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala: ########## @@ -351,28 +358,68 @@ abstract class SparkStrategies extends QueryPlanner[SparkPlan] { Seq(joins.BroadcastHashJoinExec(leftKeys, rightKeys, LeftAnti, BuildRight, None, planLater(j.left), planLater(j.right), isNullAwareAntiJoin = true)) - // If it is not an equi-join, we first look at the join hints w.r.t. the following order: - // 1. broadcast hint: pick broadcast nested loop join. If both sides have the broadcast - // hints, choose the smaller side (based on stats) to broadcast for inner and full joins, - // choose the left side for right join, and choose right side for left join. - // 2. shuffle replicate NL hint: pick cartesian product if join type is inner like. + // If it is not an equi-join, a broadcast hint is considered first: + // 1. When range join is enabled and the condition is a range predicate, + // pick a broadcast range join if a hinted build side is one + // BroadcastRangeJoinExec supports. Both sides hinted: an unsupported + // hinted side is dropped first, so an inner join builds the smaller + // side, left outer/semi/anti build the right side, and right outer + // builds the left side. Only when every hinted side is unsupported + // does planning fall through. + // 2. Otherwise a broadcast hint picks broadcast nested loop join. Both + // sides hinted: the smaller side for inner and full joins, the left + // side for a right join, and the right side for a left join. + // 3. A shuffle replicate NL hint picks cartesian product for an + // inner-like join. // - // If there is no hint or the hints are not applicable, we follow these rules one by one: - // 1. Pick broadcast nested loop join if one side is small enough to broadcast. If only left - // side is broadcast-able and it's left join, or only right side is broadcast-able and - // it's right join, we skip this rule. If both sides are small, broadcasts the smaller - // side for inner and full joins, broadcasts the left side for right join, and broadcasts - // right side for left join. - // 2. Pick cartesian product if join type is inner like. - // 3. Pick broadcast nested loop join as the final solution. It may OOM but we don't have - // other choice. It broadcasts the smaller side for inner and full joins, broadcasts the - // left side for right join, and broadcasts right side for left join. + // If there is no hint, or none of those hints apply: + // 1. When range join is enabled and a side is small enough to broadcast, + // pick a broadcast range join on a side BroadcastRangeJoinExec + // supports. Both sides small: the smaller side when it is supported. + // The preserved side of an outer, semi, or anti join is not built. + // A last-resort nested-loop build side that was never confirmed + // broadcastable by hint or size is not upgraded to a range join. + // 2. Pick broadcast nested loop join if one side is small enough to + // broadcast. If only the left side is broadcastable and it is a left + // join, or only the right side is broadcastable and it is a right + // join, skip this rule. Both sides small: the smaller side for inner + // and full joins, the left side for a right join, and the right side + // for a left join. + // 3. Pick cartesian product if the join type is inner-like. + // 4. Pick broadcast nested loop join as the final solution. It may OOM. + // It broadcasts the smaller side for inner and full joins, the left + // side for a right join, and the right side for a left join. case j @ logical.Join(left, right, joinType, condition, hint) => checkHintNonEquiJoin(hint) + // Range join needs a side that is actually broadcastable by hint or size. + // getNonEquiJoinBuildSide's last resort still returns a build side for + // non-inner-like joins when nothing qualifies; BroadcastRangeJoinExec.supports + // is only structural, so upgrading that side would plan an unbounded range join. + def sideBroadcastQualified(buildSide: BuildSide): Boolean = buildSide match { + case BuildLeft => + hintToBroadcastLeft(hint) || Review Comment: **Nit (P3):** Every hinted range-join query in RangeJoinSQLSuite and SQLMetricsSuite hints a side that is also under the default broadcast threshold, so `canBroadcastBySize` qualifies it on its own, and the two tests that set `spark.sql.autoBroadcastJoinThreshold` to -1 have no hint. Deleting `hintToBroadcastLeft(hint) ||` here, or its `BuildRight` counterpart, would plan a BROADCAST-hinted range join over a large table, such as an IP range table, as a broadcast nested loop join, and only the benchmark, which CI doesn't run, would notice. Results would stay correct; the range join would just be lost. Could you add a hinted query for each arm with the threshold disabled, asserting a broadcast range join that builds the hinted side? **Verification:** - **Regression:** With the broadcast threshold disabled, a hinted right side and a hinted left side each plan a broadcast range join that builds the hinted side, and each check fails if that arm's hint disjunct is removed. - **Behavior:** Both hinted queries return the same rows as with the range join disabled. ########## sql/core/src/test/scala/org/apache/spark/sql/execution/joins/RangeRelationSuite.scala: ########## @@ -0,0 +1,1311 @@ +/* + * 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 java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream} + +import org.apache.spark.SparkFunSuite +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.BoundReference +import org.apache.spark.sql.catalyst.types.PhysicalDataType +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.Platform +import org.apache.spark.unsafe.types.UTF8String + +/** + * Unit tests for the range-join indexes: the boxed pair ([[IntervalIndex]], + * [[PointIndex]]), the raw-long pair ([[LongIntervalIndex]], [[LongPointIndex]]), + * and the broadcast-mode routing that picks between the two families. + * Operator-level behavior is covered by `RangeJoinSuite`. + */ +class RangeRelationSuite extends SparkFunSuite { + + private def row(id: Int): InternalRow = InternalRow(id) + + private def span(lo: Any, hi: Any, id: Int): (Any, Any, InternalRow) = (lo, hi, row(id)) + + private def buildIntervals(spans: Seq[(Any, Any, InternalRow)]): IntervalIndex = + buildIntervals(IntegerType, spans) + + /** + * Builds the boxed interval index through `IntervalIndex.apply`. The row + * layout puts the asserted id at ordinal 0, exactly where a real build row + * carries its columns; the keys bind to ordinals 1 and 2. + */ + private def buildIntervals( + keyType: DataType, + spans: Seq[(Any, Any, InternalRow)]): IntervalIndex = { + val keys = Seq( + BoundReference(1, keyType, nullable = true), + BoundReference(2, keyType, nullable = true)) + IntervalIndex(keyType, keys, + spans.iterator.map(t => InternalRow(t._3.getInt(0), t._1, t._2)), + Some(spans.size.toLong)) + } + + /** The point-index build with the same row layout: id at 0, key at 1. */ + private def buildPoints(keyType: DataType, keyed: Seq[(Any, InternalRow)]): PointIndex = { + val key = Seq(BoundReference(1, keyType, nullable = true)) + PointIndex(keyType, key, + keyed.iterator.map(t => InternalRow(t._2.getInt(0), t._1)), + Some(keyed.size.toLong)) + } + + private def ids(rows: Iterator[InternalRow]): List[Int] = rows.map(_.getInt(0)).toList + + private def probeIds(index: IntervalIndex, low: Any, high: Any): List[Int] = + ids(index.overlapping(low, high)) + + /** + * An iterator that hands back the same mutable row on every `next()` call, each field + * set to the current index. Mirrors how Spark's row iterators commonly reuse a single + * buffer (e.g. `UnsafeRow` deserialization) instead of allocating a fresh row per record. + */ + private def reusingRowIterator( + fields: Int, + n: Int): (org.apache.spark.sql.catalyst.expressions.GenericInternalRow, + Iterator[InternalRow]) = { + val shared = new org.apache.spark.sql.catalyst.expressions.GenericInternalRow(fields) + val iter = new Iterator[InternalRow] { + private var i = 0 + override def hasNext: Boolean = i < n + override def next(): InternalRow = { + var c = 0 + while (c < fields) { shared.update(c, i); c += 1 } + i += 1 + shared + } + } + (shared, iter) + } + + private def reusingByteBufferStringIterator( + n: Int): (Array[Byte], Iterator[InternalRow]) = { + val sharedBytes = new Array[Byte](4) + val sharedRow = new org.apache.spark.sql.catalyst.expressions.GenericInternalRow(2) + val iter = new Iterator[InternalRow] { + private var i = 0 + override def hasNext: Boolean = i < n + override def next(): InternalRow = { + val s = f"$i%04d" + java.lang.System.arraycopy(s.getBytes("UTF-8"), 0, sharedBytes, 0, 4) + val utf8 = UTF8String.fromAddress(sharedBytes, Platform.BYTE_ARRAY_OFFSET, 4) + sharedRow.update(0, utf8) + sharedRow.update(1, i) + i += 1 + sharedRow + } + } + (sharedBytes, iter) + } + + private def javaRoundTrip(index: IntervalIndex): (Array[Byte], IntervalIndex) = { + val bytes = new ByteArrayOutputStream() + val out = new ObjectOutputStream(bytes) + out.writeObject(index) + out.close() + val raw = bytes.toByteArray + val in = new ObjectInputStream(new ByteArrayInputStream(raw)) + try { + (raw, in.readObject().asInstanceOf[IntervalIndex]) + } finally { + in.close() + } + } + + test("build keeps a point, orders an inverted interval, and drops a null bound") { + val index = buildIntervals(Seq( + span(5, 5, 5), + span(1, 3, 1), + span(3, 1, 3), + (null, 1, row(1)))) + // (3, 1) is stored as [1, 3]. The null bound is absent. + assert(ids(index.overlapping(2, 2)).sorted == List(1, 3)) + assert(ids(index.overlapping(5, 5)) == List(5)) + assert(ids(index.overlapping(4, 4)).isEmpty) + } + + test("IntervalIndex.apply defends against a build-side iterator reusing its row buffer") { + // If apply() captured keys or rows by reference instead of copying them, every stored + // entry would collapse to the iterator's last value once the shared buffer is mutated + // again after the build-side iterator is drained -- the hazard guarded against is any + // producer whose rows or projected keys alias a reused buffer (e.g. a typed UDF result), + // not specifically BroadcastExchangeExec: its own row iterator decodes a fresh UnsafeRow + // per record. + val n = 50 + val buildKeys = Seq( + BoundReference(0, IntegerType, nullable = true), + BoundReference(1, IntegerType, nullable = true)) + val (shared, rows) = reusingRowIterator(fields = 3, n) + val index = IntervalIndex(IntegerType, buildKeys, rows, Some(n)) + + // Simulate the caller reusing the buffer after the build-side iterator is exhausted. + shared.update(0, -1) + shared.update(1, -1) + shared.update(2, -1) + + (0 until n).foreach { i => + val payloads = index.overlapping(i, i).map(_.getInt(2)).toList + assert(payloads == List(i), s"interval $i was corrupted by later reuse of the row buffer") + } + } + + test("IntervalIndex.apply defends against string keys sharing a reused byte buffer") { + val n = 50 + val buildKeys = Seq( + BoundReference(0, StringType, nullable = true), + BoundReference(0, StringType, nullable = true)) + val (sharedBytes, rows) = reusingByteBufferStringIterator(n) + val index = IntervalIndex(StringType, buildKeys, rows, Some(n)) + + java.util.Arrays.fill(sharedBytes, 'X'.toByte) + + (0 until n).foreach { i => + val key = UTF8String.fromString(f"$i%04d") + val matching = index.overlapping(key, key).toList + assert(matching.size == 1, s"interval $i was corrupted by shared buffer reuse") + assert(matching.head.getInt(1) == i) + } + } + + test("a one-key interval build owns a single copy of the point key") { + // One build key is one key used as both ends. The build must copy it once + // and serve both bounds from that copy, instead of copying twice. + val n = 50 + val oneKey = Seq(BoundReference(0, StringType, nullable = true)) + val (sharedBytes, rows) = reusingByteBufferStringIterator(n) + val index = IntervalIndex(StringType, oneKey, rows, Some(n)) + + java.util.Arrays.fill(sharedBytes, 'X'.toByte) + + (0 until n).foreach { i => + val key = UTF8String.fromString(f"$i%04d") + val matching = index.overlapping(key, key).toList + assert(matching.size == 1, s"interval $i was corrupted by shared buffer reuse") + assert(matching.head.getInt(1) == i) + } + + // SizeEstimator's identity tracking charges the shared bounds once, so the + // estimate stays below the same build made from two independently copied keys. + val twoKeys = Seq( + BoundReference(0, StringType, nullable = true), + BoundReference(0, StringType, nullable = true)) + val (_, moreRows) = reusingByteBufferStringIterator(n) + val twoCopy = IntervalIndex(StringType, twoKeys, moreRows, Some(n)) + assert(index.estimatedSize < twoCopy.estimatedSize) + } + + test("an inverted build interval reaches the windows the condition accepts") { + // Int keys route to the long index, so this also pins swap normalization there. + val index = RangeRelationBroadcastMode( + Seq(BoundReference(0, IntegerType, nullable = true), + BoundReference(1, IntegerType, nullable = true)), + IntervalIndexKind) + .transform(Array(InternalRow(3, 1), InternalRow(0, 5))) + .asInstanceOf[LongIntervalIndex] + assert(index.overlapping(0L, 4L).map(_.getInt(0)).toSet == Set(3, 0)) + assert(index.overlapping(4L, 9L).map(_.getInt(0)).toList == List(0)) + } + + test("interval tree returns each overlapping row once") { + // Padding far outside every probe window below (and outside any padded + // scenario's own core), so the padded builds exceed SMALL_BUILD_OVERLAP_ROWS + // and these multiplicity checks run against OverlapIterator's tree walk, + // not the tiny-build linear scan - without the padding rows ever being a + // candidate, so expected answers are unchanged. + val cutoff = RangeIndex.SMALL_BUILD_OVERLAP_ROWS + def padded(spans: Seq[(Any, Any, InternalRow)]): Seq[(Any, Any, InternalRow)] = + spans ++ (0 until cutoff).map(i => span(-1000000 - i, -1000000 - i + 1, -1000 - i)) + + // Spans arrive out of low order: [10, 20] then [0, 5]. + val unsorted = buildIntervals(Seq(span(10, 20, 0), span(0, 5, 1))) + assert(probeIds(unsorted, 3, 3) == List(1)) + assert(probeIds(unsorted, 15, 15) == List(0)) + + // Probe 50 is a build key. Row 0 spans it; row 1 starts there. + val spanning = buildIntervals(Seq(span(0, 100, 0), span(50, 200, 1))) + assert(probeIds(spanning, 50, 50).toSet == Set(0, 1)) + assert(probeIds(spanning, 25, 25) == List(0)) + assert(probeIds(spanning, 150, 150) == List(1)) + + val duplicated = buildIntervals(padded(Seq(span(0, 100, 0), span(0, 100, 1)))) + assert(duplicated.overlapping(50, 50).isInstanceOf[OverlapIterator]) + assert(probeIds(duplicated, 50, 50).sorted == List(0, 1)) + + val nested = buildIntervals(padded(Seq( + span(0, 100, 0), span(10, 20, 1), span(10, 50, 2), span(90, 110, 3)))) + assert(nested.overlapping(10, 10).isInstanceOf[OverlapIterator]) + def assertOnce(low: Int, expected: Set[Int]): Unit = { + val actual = probeIds(nested, low, low) + assert(actual.toSet == expected, s"probe $low -> $actual") + assert(actual.size == expected.size, s"probe $low duplicated $actual") + } + assertOnce(0, Set(0)) + assertOnce(10, Set(0, 1, 2)) + assertOnce(15, Set(0, 1, 2)) + assertOnce(30, Set(0, 2)) + assertOnce(95, Set(0, 3)) + assertOnce(105, Set(3)) + assertOnce(200, Set.empty) + + assert(probeIds(buildIntervals(Seq.empty), 1, 1).isEmpty) + + val withNull = buildIntervals(Seq(span(0, 10, 0), span(5, 5, 1), (null, 4, row(9)))) + assert(probeIds(withNull, null, 5).isEmpty) + assert(probeIds(withNull, 5, null).isEmpty) + // The null bound is dropped, so two intervals remain and the estimate covers both. + val one = buildIntervals(Seq(span(0, 10, 0))) + assert(withNull.estimatedSize > one.estimatedSize) + + // At an interior endpoint, the range that ends and the one that starts + // are each a candidate once. + val chained = buildIntervals(padded(Seq(span(0, 1, 0), span(1, 2, 1), span(2, 3, 2)))) + assert(chained.overlapping(1, 1).isInstanceOf[OverlapIterator]) + assert(probeIds(chained, 0, 0) == List(0)) + assert(probeIds(chained, 1, 1).sorted == List(0, 1)) + assert(probeIds(chained, 2, 2).sorted == List(1, 2)) + assert(probeIds(chained, 3, 3) == List(2)) + + // A probe whose endpoints are reversed is the closed window between them. + // [10, 25] meets [0, 30], [15, 40], and the point at 15. + val inverted = buildIntervals(padded(Seq(span(0, 30, 0), span(15, 40, 1), span(15, 15, 2)))) + assert(inverted.overlapping(25, 10).isInstanceOf[OverlapIterator]) + assert(probeIds(inverted, 25, 10).sorted == List(0, 1, 2)) + assert(probeIds(inverted, 10, 20).sorted == List(0, 1, 2)) + } + + test("interval tree is correct under heavy build-side overlap") { + // Every interval nests inside the one before it and contains n, so the probe + // at n hits all 300 rows; the probe at n/2 hits about half (151), since only + // intervals with i <= n/2 reach that far. The tree still stores one node per row. + val n = 300 + val nested = buildIntervals((0 until n).map(i => span(i, 2 * n - i, i))) + + def expected(probe: Int): Set[Int] = + (0 until n).filter(i => i <= probe && probe <= 2 * n - i).toSet + + Seq(0, 1, n / 2, n, 2 * n - 1, 2 * n).foreach { probe => + assert(probeIds(nested, probe, probe).toSet == expected(probe), s"probe $probe") + } + } + + test("broadcast of heavily overlapping intervals stays linear") { + // [i, i + n] for i in 0 until n. Every interval contains n. The broadcast + // is the flat arrays, one slot per interval, so serialization stays linear. + val n = 200 + val index = buildIntervals((0 until n).map(i => span(i, i + n, i))) + val (raw, restored) = javaRoundTrip(index) + assert(raw.length < n * 1024, s"serialized ${raw.length} bytes") + val probe = n + assert(probeIds(restored, probe, probe).toSet == probeIds(index, probe, probe).toSet) + assert(probeIds(restored, probe, probe).size == n) + } + + test("estimatedSize depends on the interval count, not the overlap depth") { + val n = 200 + val one = buildIntervals(Seq(span(0, 1, 0))) + val disjoint = buildIntervals((0 until n).map(i => span(2 * i, 2 * i + 1, i))) + val overlap = buildIntervals((0 until n).map(i => span(i, i + n, i))) + val again = buildIntervals((0 until n).map(i => span(2 * i, 2 * i + 1, i))) + assert(disjoint.estimatedSize > one.estimatedSize) + assert(overlap.estimatedSize > one.estimatedSize) + assert(disjoint.estimatedSize == again.estimatedSize) + // Nesting stores no extra copy of the rows. Key objects differ, so the two + // indexes need not be equal, but overlap stays the same order of magnitude. + assert(overlap.estimatedSize < disjoint.estimatedSize * 3) + } + + test("estimatedSize includes distinct key objects") { + val ints = buildIntervals(Seq(span(0, 1, 0))) + val wide = UTF8String.fromString("x" * 64) + val strings = buildIntervals(StringType, Seq((wide, wide, row(0)))) + assert(strings.estimatedSize > ints.estimatedSize) + } + + test("interval tree treats NaN as its own point and Infinity as a bound") { + // PhysicalDoubleType's ordering (SQLOrderingUtil.compareDoubles) totally orders + // -Inf < ... < +Inf < NaN, with NaN comparing equal only to itself. So [1.0, +Inf] + // includes +Inf under inclusive probe, and a NaN key overlaps only a probe that + // also lands exactly on NaN. + val index = buildIntervals(DoubleType, Seq( + (1.0, Double.PositiveInfinity, row(1)), + (Double.NegativeInfinity, -1.0, row(2)), + (Double.NaN, Double.NaN, row(3)))) + + assert(ids(index.overlapping(5.0, 5.0)) == List(1)) + assert(ids(index.overlapping(Double.PositiveInfinity, Double.PositiveInfinity)) == List(1)) + assert(ids(index.overlapping(-5.0, -5.0)) == List(2)) + assert(ids(index.overlapping(Double.NegativeInfinity, Double.NegativeInfinity)) == List(2)) + assert(ids(index.overlapping(Double.NaN, Double.NaN)) == List(3)) + assert(ids(index.overlapping(0.0, 0.0)).isEmpty) + } + + test("interval index merges keys that compare equal but are not equal") { + // Array equals is identity, and UTF8String equals is binary, so these keys + // compare equal under the index ordering without being equal. The tree Review Comment: **Nit (P3):** Every build `assertMerged` makes has at most four intervals, so with `SMALL_BUILD_OVERLAP_ROWS` at 16 each `overlapping` call returns `linearOverlap`, which checks rows one by one and never reads the sorted `lows` or `maxHighIdx`. No other test walks a boxed `IntervalIndex` above the cutoff with keys like these: the boxed walk tests use Int, Double, or UTF8_BINARY keys, and RangeJoinSQLSuite's collated and string interval fixtures have four rows each. If `sortAndBuild` sorted the lows or filled `maxHighIdx` in binary order instead of the UNICODE_CI ordering, a larger collated build could prune the span holding 'M' when probed with 'm', and every test would still pass. Could the point and interval builds here be padded past the cutoff with keys that sort after every probe key, which keeps the expected answers, with the probes asserting `OverlapIterator`? **Verification:** - **Regression:** With the build above the small-build cutoff, the common-core test fails if the all-covering check is skipped for a window that reaches the core or applied to a window outside it. - **Regression:** With builds above the cutoff, the merged-keys test fails if the boxed interval index sorts its lows or fills its maximum-high indexes with binary order instead of the key type's collation-aware ordering. - **Behavior:** Every probe in both resized tests returns exactly the rows a brute-force overlap check over the padded build returns. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/BroadcastRangeJoinExec.scala: ########## @@ -0,0 +1,589 @@ +/* + * 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.broadcast.Broadcast +import org.apache.spark.rdd.RDD +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.codegen._ +import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight, BuildSide} +import org.apache.spark.sql.catalyst.planning.RangeJoinKind +import org.apache.spark.sql.catalyst.plans._ +import org.apache.spark.sql.catalyst.plans.physical.{BroadcastDistribution, Distribution, Partitioning, UnspecifiedDistribution} +import org.apache.spark.sql.execution.{CodegenSupport, ExplainUtils, SparkPlan} +import org.apache.spark.sql.execution.metric.SQLMetrics + +/** + * Performs a range join on two tables. Supported types are inner, left outer, right outer, + * left semi, and left anti. The preserved side is streamed: unmatched build rows are not + * emitted, because the broadcast is copied to every partition. See `ExtractRangeJoinKeys` + * for the exact set of join-condition shapes that are recognized as a range join. + * + * The build side is an index. Point-in-range and interval overlap both build an + * [[IntervalIndex]] and probe it with `overlapping`. A single inequality builds a + * [[PointIndex]] and scans the side of the bound the build side holds. Keys that + * map to one order-preserving long instead build [[LongIntervalIndex]] or + * [[LongPointIndex]], so their probes compare raw longs without boxing. Either + * probe returns a superset. A candidate is kept only when the original join + * condition is true, so inclusivity stays on the predicate. Heavy overlap can + * make one probe return almost every build row. + */ +case class BroadcastRangeJoinExec( + left: SparkPlan, + right: SparkPlan, + buildSide: BuildSide, + joinType: JoinType, + leftKeys: Seq[Expression], + rightKeys: Seq[Expression], + condition: Option[Expression], + rangeJoinKind: RangeJoinKind) + extends JoinCodegenSupport { + + if (condition.isEmpty) { + throw SparkException.internalError("BroadcastRangeJoinExec requires a join condition.") + } + + override lazy val metrics = Map( + "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows")) + + /** BuildRight means the right relation is the broadcast relation. */ + private val (streamed, broadcast, streamedKeys, buildKeys) = buildSide match { + case BuildRight => (left, right, leftKeys, rightKeys) + case BuildLeft => (right, left, rightKeys, leftKeys) + } + + override def simpleStringWithNodeId(): String = { + val opId = ExplainUtils.getOpId(this) + s"$nodeName $joinType $buildSide ($opId)".trim + } + + override def requiredChildDistribution: Seq[Distribution] = { + val mode = RangeRelationBroadcastMode( + BindReferences.bindReferences(buildKeys, broadcast.output), + RangeIndexKind(rangeJoinKind)) + buildSide match { + case BuildLeft => + BroadcastDistribution(mode) :: UnspecifiedDistribution :: Nil + case BuildRight => + UnspecifiedDistribution :: BroadcastDistribution(mode) :: Nil + } + } + + override def outputPartitioning: Partitioning = streamed.outputPartitioning + + override def outputOrdering: Seq[SortOrder] = streamed.outputOrdering + + override def output: Seq[Attribute] = { + joinType match { + case _: InnerLike => + left.output ++ right.output + case LeftOuter => + left.output ++ right.output.map(_.withNullability(true)) + case RightOuter => + left.output.map(_.withNullability(true)) ++ right.output + case LeftSemi | LeftAnti => + left.output + case t => + throw SparkException.internalError(s"BroadcastRangeJoin should not take $t as the JoinType") + } + } + + // The point-index scan direction and strictness used to probe this join's build + // side. See `PointScan.forJoin`. + private lazy val pointScan: (PointScan, Boolean) = PointScan.forJoin(rangeJoinKind, buildSide) + + private def perPartition( + relation: Broadcast[RangeRelation])( + f: BroadcastRangeJoinExec.ProbeContext => Iterator[InternalRow]): RDD[InternalRow] = { + val boundStreamKeys = BindReferences.bindReferences(streamedKeys, streamed.output) + val cond = condition.get + val schema = left.output ++ right.output + val numBuildFields = broadcast.output.length + val kind = rangeJoinKind + val side = buildSide + streamed.execute().mapPartitionsInternal { streamedIter => + val candidateFn = BroadcastRangeJoinExec.makeCandidateFn( + relation.value, boundStreamKeys, PointScan.forJoin(kind, side)) + f(new BroadcastRangeJoinExec.ProbeContext( + streamedIter, + Predicate.create(cond, schema).eval _, + new JoinedRow, + new GenericInternalRow(numBuildFields), + candidateFn, + side)) + } + } + + private def innerJoin(relation: Broadcast[RangeRelation]): RDD[InternalRow] = { + perPartition(relation) { p => + p.stream.flatMap { row => + p.candidates(row).map(p.join(row, _)).filter(p.condition) + } + } + } + + /** + * Emit each candidate the condition accepts. When none were, emit the stream + * row once with the build side padded by nulls. + * + * The loop test checks `streamRow` before `stream.hasNext`. A whole-stage + * stream reuses one `UnsafeRow`, and `hasNext` fills that buffer. It must + * not run while the current row is still being joined. + */ + private def outerJoin(relation: Broadcast[RangeRelation]): RDD[InternalRow] = { + perPartition(relation) { p => + new Iterator[InternalRow] { + private var streamRow: InternalRow = null + private var matches: Iterator[InternalRow] = Iterator.empty + private var foundMatch: Boolean = false + private var resultRow: InternalRow = null + + private def findNext(): Boolean = { + while (streamRow != null || p.stream.hasNext) { + if (streamRow == null) { + streamRow = p.stream.next() + foundMatch = false + matches = p.candidates(streamRow) + } + while (matches.hasNext) { + val joined = p.join(streamRow, matches.next()) + if (p.condition(joined)) { + foundMatch = true + resultRow = joined + return true + } + } + if (!foundMatch) { + resultRow = p.join(streamRow, p.nullBuild) + streamRow = null + return true + } + streamRow = null + } + false + } + + override def hasNext: Boolean = resultRow != null || findNext() + + override def next(): InternalRow = { + val r = resultRow + resultRow = null + r + } + } + } + } + + /** + * The implementation for LeftSemi and LeftAnti joins. + */ + private def leftExistenceJoin( + relation: Broadcast[RangeRelation], + exists: Boolean): RDD[InternalRow] = { + perPartition(relation) { p => + p.stream.filter { row => + val matched = p.candidates(row).exists { buildRow => + p.condition(p.join(row, buildRow)) + } + matched == exists + } + } + } + + protected override def doExecute(): RDD[InternalRow] = { + if (!BroadcastRangeJoinExec.supports(joinType, buildSide)) { + throw SparkException.internalError( + s"BroadcastRangeJoin does not support $joinType with $buildSide") + } + val broadcastedRelation = broadcast.executeBroadcast[RangeRelation]() + val resultRdd = joinType match { + case _: InnerLike => innerJoin(broadcastedRelation) + case LeftOuter | RightOuter => outerJoin(broadcastedRelation) + case LeftSemi => leftExistenceJoin(broadcastedRelation, exists = true) + case LeftAnti => leftExistenceJoin(broadcastedRelation, exists = false) + case t => + throw SparkException.internalError( + s"BroadcastRangeJoin should not take $t as the JoinType") + } + val (resultOutput, resultInput) = joinType match { + case LeftSemi | LeftAnti => + (output, output) + case _ => + (output, (left.output ++ right.output).map(_.withNullability(true))) + } + val numOutputRows = longMetric("numOutputRows") + resultRdd.mapPartitionsWithIndexInternal { (index, iter) => + val resultProj = UnsafeProjection.create(resultOutput, resultInput) + resultProj.initialize(index) + iter.map { r => + numOutputRows += 1 + resultProj(r) + } + } + } + + override def supportCodegen: Boolean = { + BroadcastRangeJoinExec.supports(joinType, buildSide) + } + + override def inputRDDs(): Seq[RDD[InternalRow]] = { + streamed.asInstanceOf[CodegenSupport].inputRDDs() + } + + private def multipleOutputForOneInput: Boolean = joinType match { + case _: InnerLike | LeftOuter | RightOuter => true + case _ => false + } + + override def needCopyResult: Boolean = { + streamed.asInstanceOf[CodegenSupport].needCopyResult || multipleOutputForOneInput + } + + override def doProduce(ctx: CodegenContext): String = { + streamed.asInstanceOf[CodegenSupport].produce(ctx, this) + } + + override def doConsume(ctx: CodegenContext, input: Seq[ExprCode], row: ExprCode): String = { + joinType match { + case _: InnerLike => codegenInner(ctx, input) + case LeftOuter | RightOuter => codegenOuter(ctx, input) + case LeftSemi => codegenLeftExistence(ctx, input, exists = true) + case LeftAnti => codegenLeftExistence(ctx, input, exists = false) + case t => + throw SparkException.internalError( + s"BroadcastRangeJoin code-gen should not take $t as the JoinType") + } + } + + private def prepareBroadcast(ctx: CodegenContext): String = { + val broadcastRelation = broadcast.executeBroadcast[RangeRelation]() + val broadcastTerm = ctx.addReferenceObj("broadcast", broadcastRelation) + val clsName = broadcastRelation.value.getClass.getName + ctx.addMutableState(clsName, "rangeRelation", + v => s"$v = ($clsName) $broadcastTerm.value();", forceInline = true) + } + + /** + * Box each streamed range key. The index compares the same boxed values + * each build key expression evaluates to on the build side. + */ + private def genProbeKeys( + ctx: CodegenContext, + input: Seq[ExprCode]): (String, Seq[String]) = { + ctx.currentVars = input + val keys = streamedKeys.map { key => + val bound = BindReferences.bindReference(key, streamed.output) + val ev = bound.genCode(ctx) + val name = ctx.freshName("probeKey") + val javaType = CodeGenerator.javaType(key.dataType) + val boxed = CodeGenerator.boxedType(key.dataType) + val valueExpr = if (javaType == boxed) { + s"${ev.value}" + } else { + s"$boxed.valueOf(${ev.value})" + } + val code = + s""" + |${ev.code} + |Object $name = ${ev.isNull} ? null : $valueExpr; + """.stripMargin + (code, name) + } + (keys.map(_._1).mkString("\n"), keys.map(_._2)) + } + + /** + * Probe the broadcast index. The index kind and scan direction are fixed + * when the plan is built, so generated code calls the concrete index + * method directly. Keys either stay boxed per `genProbeKeys`, or arrive as + * primitive longs from `genLongProbeKeys` with a null term each that the + * long indexes cannot see; the call then yields the shared empty scan for + * a null key. Generated code does not allocate a key array. An interval + * probe owns its walk stack. + */ + private def genCandidateIterator( + ctx: CodegenContext, + relationTerm: String, + keyVars: Seq[String], + nullVars: Seq[String]): (String, String) = { + val matches = ctx.freshName("matches") + val iterCls = classOf[Iterator[InternalRow]].getName + // Dispatches on RangeIndexKind, the same source `requiredChildDistribution` uses to + // decide which structure got built, instead of re-deriving "point or interval" from + // rangeJoinKind a second time. + val call = RangeIndexKind(rangeJoinKind) match { + case PointIndexKind => + val points = (if (usesLongKeys) classOf[LongPointIndex] else classOf[PointIndex]).getName + val (scan, strict) = pointScan + s"(($points) $relationTerm).${scan.methodName}(${keyVars.head}, $strict)" + case IntervalIndexKind => + val intervals = + (if (usesLongKeys) classOf[LongIntervalIndex] else classOf[IntervalIndex]).getName + // A point probe has one key. Reuse it as both ends so it is evaluated once. + val high = if (keyVars.length == 1) keyVars.head else keyVars(1) + s"(($intervals) $relationTerm).overlapping(${keyVars.head}, $high)" + } + val code = if (nullVars.isEmpty) { + s"$iterCls $matches = $call;" + } else { + val emptyScan = s"${classOf[RowSlice].getName}$$.MODULE$$.empty()" + s"$iterCls $matches = ${nullVars.mkString(" || ")} ? ($iterCls) $emptyScan : $call;" + } + (matches, code) + } + + /** + * Keys that map to one order-preserving long (`RangeIndex.longKey`) route + * to the long indexes: build and probe keys then cross as raw longs, with + * no boxing on either side, and every other supported key stays boxed. + * One test picks both the `RangeRelationBroadcastMode` index family and + * the generated probe code, so they cannot disagree. + */ + private[this] lazy val usesLongKeys: Boolean = RangeIndex.canMapKeysToLong(buildKeys) + + /** + * Evaluate each streamed key into a primitive long. Each key keeps the null + * term of its expression; the candidate call turns a null into an empty scan. + */ + private def genLongProbeKeys( + ctx: CodegenContext, + input: Seq[ExprCode]): (String, Seq[String], Seq[String]) = { + ctx.currentVars = input + val keys = streamedKeys.map { key => + val bound = BindReferences.bindReference(key, streamed.output) + val ev = bound.genCode(ctx) + val toLong = RangeIndex.requiredLongKey(key.dataType) + val name = ctx.freshName("probeKey") + val code = + s""" + |${ev.code} + |long $name = ${ev.isNull} ? 0L : ${toLong.code(ev.value)}; + """.stripMargin + (code, name, ev.isNull) + } + (keys.map(_._1).mkString("\n"), keys.map(_._2), keys.map(_._3)) + } + + /** + * Shared init for every doConsume path: broadcasts the relation, evaluates the + * streamed probe keys, and opens the candidate iterator over it. + */ + private def prepareProbe(ctx: CodegenContext, input: Seq[ExprCode]): (String, String, String) = { + val relationTerm = prepareBroadcast(ctx) + val (keyCode, keyVars, nullVars) = if (usesLongKeys) { + genLongProbeKeys(ctx, input) + } else { + val (code, vars) = genProbeKeys(ctx, input) + (code, vars, Nil) + } + val (matches, iteratorCode) = genCandidateIterator(ctx, relationTerm, keyVars, nullVars) + (keyCode, iteratorCode, matches) + } + + private def orderResultVars( + streamVars: Seq[ExprCode], + buildVars: Seq[ExprCode]): Seq[ExprCode] = { + buildSide match { + case BuildLeft => buildVars ++ streamVars + case BuildRight => streamVars ++ buildVars + } + } + + private def codegenInner(ctx: CodegenContext, input: Seq[ExprCode]): String = { + val (keyCode, iteratorCode, matches) = prepareProbe(ctx, input) + val (buildRow, checkCondition, buildVars) = getJoinCondition(ctx, input, streamed, broadcast) + val resultVars = orderResultVars(input, buildVars) + val numOutput = metricTerm(ctx, "numOutputRows") + + s""" + |$keyCode + |$iteratorCode + |while ($matches.hasNext()) { + | InternalRow $buildRow = (InternalRow) $matches.next(); + | $checkCondition { + | $numOutput.add(1); + | ${consume(ctx, resultVars)} + | } + |} + """.stripMargin + } + + private def codegenOuter(ctx: CodegenContext, input: Seq[ExprCode]): String = { + val (keyCode, iteratorCode, matches) = prepareProbe(ctx, input) + val buildRow = ctx.freshName("buildRow") + val (_, checkCondition, _) = getJoinCondition(ctx, input, streamed, broadcast, Some(buildRow)) + val buildVars = genOneSideJoinVars(ctx, buildRow, broadcast, setDefaultValue = true) + val resultVars = orderResultVars(input, buildVars) + val shouldOutputRow = ctx.freshName("shouldOutputRow") + val foundMatch = ctx.freshName("foundMatch") + val numOutput = metricTerm(ctx, "numOutputRows") + + // One consume site, inside the loop. The last iteration pads the build side + // when no candidate satisfied the original condition. + s""" + |$keyCode + |$iteratorCode + |boolean $foundMatch = false; + |while ($matches.hasNext() || !$foundMatch) { + | InternalRow $buildRow = $matches.hasNext() ? + | (InternalRow) $matches.next() : null; + | boolean $shouldOutputRow = false; + | if ($buildRow != null) { + | $checkCondition { + | $shouldOutputRow = true; + | $foundMatch = true; + | } + | } else { + | $shouldOutputRow = true; + | $foundMatch = true; + | } + | if ($shouldOutputRow) { + | $numOutput.add(1); + | ${consume(ctx, resultVars)} + | } + |} + """.stripMargin + } + + private def codegenLeftExistence( + ctx: CodegenContext, + input: Seq[ExprCode], + exists: Boolean): String = { + val (keyCode, iteratorCode, matches) = prepareProbe(ctx, input) + val (buildRow, checkCondition, _) = + getJoinCondition(ctx, input, streamed, broadcast) + val foundMatch = ctx.freshName("foundMatch") + val numOutput = metricTerm(ctx, "numOutputRows") + + s""" + |$keyCode + |$iteratorCode + |boolean $foundMatch = false; + |while (!$foundMatch && $matches.hasNext()) { + | InternalRow $buildRow = (InternalRow) $matches.next(); + | $checkCondition { + | $foundMatch = true; + | } + |} + |if ($foundMatch == $exists) { + | $numOutput.add(1); + | ${consume(ctx, input)} + |} + """.stripMargin + } + + override protected def withNewChildrenInternal( + newLeft: SparkPlan, newRight: SparkPlan): SparkPlan = + copy(left = newLeft, right = newRight) +} + +object BroadcastRangeJoinExec { + + /** + * Stream-preserving combinations. Left outer, left semi, and left anti broadcast the + * right side. Right outer broadcasts the left side. Inner may broadcast either side. + */ + def supports(joinType: JoinType, buildSide: BuildSide): Boolean = (joinType, buildSide) match { + case (_: InnerLike, _) => true + case (RightOuter, BuildLeft) => true + case (LeftOuter | LeftSemi | LeftAnti, BuildRight) => true + case _ => false + } + + /** + * Create candidate probe function for a broadcast relation and bound probe keys. + * Constructed once per partition in `perPartition`, avoiding per-row relation dispatch. + * Lives here rather than on [[BroadcastRangeJoinExec]] so the closure that calls it + * does not capture the enclosing plan node. `pointScan` is by-name so it is only + * forced - and only throws for a non-partial-range join - inside the point-index + * branches below, matching the laziness `perPartition` relies on. + */ + private def makeCandidateFn( + relation: RangeRelation, + boundStreamKeys: Seq[Expression], + pointScan: => (PointScan, Boolean)): InternalRow => Iterator[InternalRow] = { + val isOneKey = boundStreamKeys.length == 1 + val lowExpr = boundStreamKeys.head + val highExpr = if (isOneKey) null else boundStreamKeys(1) + + relation match { + case longs: LongIntervalIndex => row => + val low = lowExpr.eval(row) + if (low == null) { + Iterator.empty + } else { + val high = if (isOneKey) low else highExpr.eval(row) + if (high == null) { + Iterator.empty + } else { + longs.overlapping(longs.toLong(low), longs.toLong(high)) + } + } + case points: LongPointIndex => + val (direction, strict) = pointScan + val scan: Long => Iterator[InternalRow] = direction match { + case PointScan.UpTo => points.upTo(_, strict) + case PointScan.From => points.from(_, strict) + } + row => + val low = lowExpr.eval(row) + if (low == null) Iterator.empty else scan(points.toLong(low)) Review Comment: **Nit (P3):** This guard, and the null term the generated probe checks, are what keep a NULL streamed key away from `points.toLong`; for a compact decimal, `toLong(null)` calls `toUnscaledLong` on null and throws, while an int key would quietly probe with 0. No test reaches either guard: `wide_dec_partial_points` carries the only NULL among the single-inequality fixtures and is used only in inner joins, where the inferred not-null filter removes it, and RangeJoinSuite's "a null streamed bound is not a match" uses the interval index. Could you add left outer and left anti single-inequality joins whose preserved side has a NULL key, over a `DECIMAL(10, 2)` key and an int key, with codegen on and off? **Verification:** - **Regression:** With whole-stage codegen disabled, a left outer and a left anti single-inequality join over DECIMAL(10,2) keys whose streamed side has a NULL key return the nested-loop answer, and the check fails if the interpreted point-index null guard is removed. - **Behavior:** The same joins, and the integer-key variants, return the nested-loop answer with whole-stage codegen enabled. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala: ########## @@ -350,22 +357,33 @@ abstract class SparkStrategies extends QueryPlanner[SparkPlan] { Seq(joins.BroadcastHashJoinExec(leftKeys, rightKeys, LeftAnti, BuildRight, None, planLater(j.left), planLater(j.right), isNullAwareAntiJoin = true)) - // If it is not an equi-join, we first look at the join hints w.r.t. the following order: - // 1. broadcast hint: pick broadcast nested loop join. If both sides have the broadcast - // hints, choose the smaller side (based on stats) to broadcast for inner and full joins, - // choose the left side for right join, and choose right side for left join. - // 2. shuffle replicate NL hint: pick cartesian product if join type is inner like. + // If it is not an equi-join, a broadcast hint is considered first: + // 1. When range join is enabled and the condition is a range predicate, + // pick a broadcast range join if the hinted build side is one + // BroadcastRangeJoinExec supports. Both sides hinted: the smaller Review Comment: Thanks, the hinted rule now matches what the planner does. No-hint rule 1 just below it has the same build-side wording problem, which this review raises separately. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4494427397","thread_id":"inline:4494427397","verdict_sha256":"4595cf4eb3bb3f392678aa394d30b9b8d753a6c4fcbf334ae0ec7217525fac49"} --> ########## 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. Review Comment: Thanks, the comments now name the long index, and the views carry -0.0, 0.0, and NaN rows. None of those rows changes any query's answer yet, so comparing with the nested loop join still can't catch a mismatch between the build and probe conversions; this review raises that separately. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4512581502","thread_id":"inline:4512581502","verdict_sha256":"4595cf4eb3bb3f392678aa394d30b9b8d753a6c4fcbf334ae0ec7217525fac49"} --> ########## sql/core/src/test/scala/org/apache/spark/sql/execution/joins/RangeRelationSuite.scala: ########## @@ -0,0 +1,1297 @@ +/* + * 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 java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream} + +import org.apache.spark.SparkFunSuite +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.BoundReference +import org.apache.spark.sql.catalyst.types.PhysicalDataType +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.Platform +import org.apache.spark.unsafe.types.UTF8String + +/** + * Unit tests for the range-join indexes: the boxed pair ([[IntervalIndex]], + * [[PointIndex]]), the raw-long pair ([[LongIntervalIndex]], [[LongPointIndex]]), + * and the broadcast-mode routing that picks between the two families. + * Operator-level behavior is covered by `RangeJoinSuite`. + */ +class RangeRelationSuite extends SparkFunSuite { + + private def row(id: Int): InternalRow = InternalRow(id) + + private def span(lo: Any, hi: Any, id: Int): (Any, Any, InternalRow) = (lo, hi, row(id)) + + private def buildIntervals(spans: Seq[(Any, Any, InternalRow)]): IntervalIndex = + buildIntervals(IntegerType, spans) + + /** + * Builds the boxed interval index through `IntervalIndex.apply`. The row + * layout puts the asserted id at ordinal 0, exactly where a real build row + * carries its columns; the keys bind to ordinals 1 and 2. + */ + private def buildIntervals( + keyType: DataType, + spans: Seq[(Any, Any, InternalRow)]): IntervalIndex = { + val keys = Seq( + BoundReference(1, keyType, nullable = true), + BoundReference(2, keyType, nullable = true)) + IntervalIndex(keyType, keys, + spans.iterator.map(t => InternalRow(t._3.getInt(0), t._1, t._2)), + Some(spans.size.toLong)) + } + + /** The point-index build with the same row layout: id at 0, key at 1. */ + private def buildPoints(keyType: DataType, keyed: Seq[(Any, InternalRow)]): PointIndex = { + val key = Seq(BoundReference(1, keyType, nullable = true)) + PointIndex(keyType, key, + keyed.iterator.map(t => InternalRow(t._2.getInt(0), t._1)), + Some(keyed.size.toLong)) + } + + private def ids(rows: Iterator[InternalRow]): List[Int] = rows.map(_.getInt(0)).toList + + private def probeIds(index: IntervalIndex, low: Any, high: Any): List[Int] = + ids(index.overlapping(low, high)) + + /** + * An iterator that hands back the same mutable row on every `next()` call, each field + * set to the current index. Mirrors how Spark's row iterators commonly reuse a single + * buffer (e.g. `UnsafeRow` deserialization) instead of allocating a fresh row per record. + */ + private def reusingRowIterator( + fields: Int, + n: Int): (org.apache.spark.sql.catalyst.expressions.GenericInternalRow, + Iterator[InternalRow]) = { + val shared = new org.apache.spark.sql.catalyst.expressions.GenericInternalRow(fields) + val iter = new Iterator[InternalRow] { + private var i = 0 + override def hasNext: Boolean = i < n + override def next(): InternalRow = { + var c = 0 + while (c < fields) { shared.update(c, i); c += 1 } + i += 1 + shared + } + } + (shared, iter) + } + + private def reusingByteBufferStringIterator( + n: Int): (Array[Byte], Iterator[InternalRow]) = { + val sharedBytes = new Array[Byte](4) + val sharedRow = new org.apache.spark.sql.catalyst.expressions.GenericInternalRow(2) + val iter = new Iterator[InternalRow] { + private var i = 0 + override def hasNext: Boolean = i < n + override def next(): InternalRow = { + val s = f"$i%04d" + java.lang.System.arraycopy(s.getBytes("UTF-8"), 0, sharedBytes, 0, 4) + val utf8 = UTF8String.fromAddress(sharedBytes, Platform.BYTE_ARRAY_OFFSET, 4) + sharedRow.update(0, utf8) + sharedRow.update(1, i) + i += 1 + sharedRow + } + } + (sharedBytes, iter) + } + + private def javaRoundTrip(index: IntervalIndex): (Array[Byte], IntervalIndex) = { + val bytes = new ByteArrayOutputStream() + val out = new ObjectOutputStream(bytes) + out.writeObject(index) + out.close() + val raw = bytes.toByteArray + val in = new ObjectInputStream(new ByteArrayInputStream(raw)) + try { + (raw, in.readObject().asInstanceOf[IntervalIndex]) + } finally { + in.close() + } + } + + test("build keeps a point, orders an inverted interval, and drops a null bound") { + val index = buildIntervals(Seq( + span(5, 5, 5), + span(1, 3, 1), + span(3, 1, 3), + (null, 1, row(1)))) + // (3, 1) is stored as [1, 3]. The null bound is absent. + assert(ids(index.overlapping(2, 2)).sorted == List(1, 3)) + assert(ids(index.overlapping(5, 5)) == List(5)) + assert(ids(index.overlapping(4, 4)).isEmpty) + } + + test("IntervalIndex.apply defends against a build-side iterator reusing its row buffer") { + // If apply() captured keys or rows by reference instead of copying them, every stored + // entry would collapse to the iterator's last value once the shared buffer is mutated + // again after the build-side iterator is drained -- the hazard guarded against is any + // producer whose rows or projected keys alias a reused buffer (e.g. a typed UDF result), + // not specifically BroadcastExchangeExec: its own row iterator decodes a fresh UnsafeRow + // per record. + val n = 50 + val buildKeys = Seq( + BoundReference(0, IntegerType, nullable = true), + BoundReference(1, IntegerType, nullable = true)) + val (shared, rows) = reusingRowIterator(fields = 3, n) + val index = IntervalIndex(IntegerType, buildKeys, rows, Some(n)) + + // Simulate the caller reusing the buffer after the build-side iterator is exhausted. + shared.update(0, -1) + shared.update(1, -1) + shared.update(2, -1) + + (0 until n).foreach { i => + val payloads = index.overlapping(i, i).map(_.getInt(2)).toList + assert(payloads == List(i), s"interval $i was corrupted by later reuse of the row buffer") + } + } + + test("IntervalIndex.apply defends against string keys sharing a reused byte buffer") { + val n = 50 + val buildKeys = Seq( + BoundReference(0, StringType, nullable = true), + BoundReference(0, StringType, nullable = true)) + val (sharedBytes, rows) = reusingByteBufferStringIterator(n) + val index = IntervalIndex(StringType, buildKeys, rows, Some(n)) + + java.util.Arrays.fill(sharedBytes, 'X'.toByte) + + (0 until n).foreach { i => + val key = UTF8String.fromString(f"$i%04d") + val matching = index.overlapping(key, key).toList + assert(matching.size == 1, s"interval $i was corrupted by shared buffer reuse") + assert(matching.head.getInt(1) == i) + } + } + + test("a one-key interval build owns a single copy of the point key") { + // One build key is one key used as both ends. The build must copy it once + // and serve both bounds from that copy, instead of copying twice. + val n = 50 + val oneKey = Seq(BoundReference(0, StringType, nullable = true)) + val (sharedBytes, rows) = reusingByteBufferStringIterator(n) + val index = IntervalIndex(StringType, oneKey, rows, Some(n)) + + java.util.Arrays.fill(sharedBytes, 'X'.toByte) + + (0 until n).foreach { i => + val key = UTF8String.fromString(f"$i%04d") + val matching = index.overlapping(key, key).toList + assert(matching.size == 1, s"interval $i was corrupted by shared buffer reuse") + assert(matching.head.getInt(1) == i) + } + + // SizeEstimator's identity tracking charges the shared bounds once, so the + // estimate stays below the same build made from two independently copied keys. + val twoKeys = Seq( + BoundReference(0, StringType, nullable = true), + BoundReference(0, StringType, nullable = true)) + val (_, moreRows) = reusingByteBufferStringIterator(n) + val twoCopy = IntervalIndex(StringType, twoKeys, moreRows, Some(n)) + assert(index.estimatedSize < twoCopy.estimatedSize) + } + + test("an inverted build interval reaches the windows the condition accepts") { + // Int keys route to the long index, so this also pins swap normalization there. + val index = RangeRelationBroadcastMode( + Seq(BoundReference(0, IntegerType, nullable = true), + BoundReference(1, IntegerType, nullable = true)), + IntervalIndexKind) + .transform(Array(InternalRow(3, 1), InternalRow(0, 5))) + .asInstanceOf[LongIntervalIndex] + assert(index.overlapping(0L, 4L).map(_.getInt(0)).toSet == Set(3, 0)) + assert(index.overlapping(4L, 9L).map(_.getInt(0)).toList == List(0)) + } + + test("interval tree returns each overlapping row once") { + // Spans arrive out of low order: [10, 20] then [0, 5]. + val unsorted = buildIntervals(Seq(span(10, 20, 0), span(0, 5, 1))) + assert(probeIds(unsorted, 3, 3) == List(1)) + assert(probeIds(unsorted, 15, 15) == List(0)) + + // Probe 50 is a build key. Row 0 spans it; row 1 starts there. + val spanning = buildIntervals(Seq(span(0, 100, 0), span(50, 200, 1))) + assert(probeIds(spanning, 50, 50).toSet == Set(0, 1)) + assert(probeIds(spanning, 25, 25) == List(0)) + assert(probeIds(spanning, 150, 150) == List(1)) + + val duplicated = buildIntervals(Seq(span(0, 100, 0), span(0, 100, 1))) + assert(probeIds(duplicated, 50, 50).sorted == List(0, 1)) + + val nested = buildIntervals(Seq( + span(0, 100, 0), span(10, 20, 1), span(10, 50, 2), span(90, 110, 3))) + def assertOnce(low: Int, expected: Set[Int]): Unit = { + val actual = probeIds(nested, low, low) + assert(actual.toSet == expected, s"probe $low -> $actual") + assert(actual.size == expected.size, s"probe $low duplicated $actual") + } + assertOnce(0, Set(0)) + assertOnce(10, Set(0, 1, 2)) + assertOnce(15, Set(0, 1, 2)) + assertOnce(30, Set(0, 2)) + assertOnce(95, Set(0, 3)) + assertOnce(105, Set(3)) + assertOnce(200, Set.empty) + + assert(probeIds(buildIntervals(Seq.empty), 1, 1).isEmpty) + + val withNull = buildIntervals(Seq(span(0, 10, 0), span(5, 5, 1), (null, 4, row(9)))) + assert(probeIds(withNull, null, 5).isEmpty) + assert(probeIds(withNull, 5, null).isEmpty) + // The null bound is dropped, so two intervals remain and the estimate covers both. + val one = buildIntervals(Seq(span(0, 10, 0))) + assert(withNull.estimatedSize > one.estimatedSize) + + // At an interior endpoint, the range that ends and the one that starts + // are each a candidate once. + val chained = buildIntervals(Seq(span(0, 1, 0), span(1, 2, 1), span(2, 3, 2))) + assert(probeIds(chained, 0, 0) == List(0)) + assert(probeIds(chained, 1, 1).sorted == List(0, 1)) + assert(probeIds(chained, 2, 2).sorted == List(1, 2)) + assert(probeIds(chained, 3, 3) == List(2)) + + // A probe whose endpoints are reversed is the closed window between them. + // [10, 25] meets [0, 30], [15, 40], and the point at 15. + val inverted = buildIntervals(Seq(span(0, 30, 0), span(15, 40, 1), span(15, 15, 2))) + assert(probeIds(inverted, 25, 10).sorted == List(0, 1, 2)) + assert(probeIds(inverted, 10, 20).sorted == List(0, 1, 2)) + } + + test("interval tree is correct under heavy build-side overlap") { + // Every interval nests inside the one before it and contains n, so the probe + // at n hits all 300 rows; the probe at n/2 hits about half (151), since only + // intervals with i <= n/2 reach that far. The tree still stores one node per row. + val n = 300 + val nested = buildIntervals((0 until n).map(i => span(i, 2 * n - i, i))) + + def expected(probe: Int): Set[Int] = + (0 until n).filter(i => i <= probe && probe <= 2 * n - i).toSet + + Seq(0, 1, n / 2, n, 2 * n - 1, 2 * n).foreach { probe => + assert(probeIds(nested, probe, probe).toSet == expected(probe), s"probe $probe") + } + } + + test("broadcast of heavily overlapping intervals stays linear") { + // [i, i + n] for i in 0 until n. Every interval contains n. The broadcast + // is the flat arrays, one slot per interval, so serialization stays linear. + val n = 200 + val index = buildIntervals((0 until n).map(i => span(i, i + n, i))) + val (raw, restored) = javaRoundTrip(index) + assert(raw.length < n * 1024, s"serialized ${raw.length} bytes") + val probe = n + assert(probeIds(restored, probe, probe).toSet == probeIds(index, probe, probe).toSet) + assert(probeIds(restored, probe, probe).size == n) + } + + test("estimatedSize depends on the interval count, not the overlap depth") { + val n = 200 + val one = buildIntervals(Seq(span(0, 1, 0))) + val disjoint = buildIntervals((0 until n).map(i => span(2 * i, 2 * i + 1, i))) + val overlap = buildIntervals((0 until n).map(i => span(i, i + n, i))) + val again = buildIntervals((0 until n).map(i => span(2 * i, 2 * i + 1, i))) + assert(disjoint.estimatedSize > one.estimatedSize) + assert(overlap.estimatedSize > one.estimatedSize) + assert(disjoint.estimatedSize == again.estimatedSize) + // Nesting stores no extra copy of the rows. Key objects differ, so the two + // indexes need not be equal, but overlap stays the same order of magnitude. + assert(overlap.estimatedSize < disjoint.estimatedSize * 3) + } + + test("estimatedSize includes distinct key objects") { + val ints = buildIntervals(Seq(span(0, 1, 0))) + val wide = UTF8String.fromString("x" * 64) + val strings = buildIntervals(StringType, Seq((wide, wide, row(0)))) + assert(strings.estimatedSize > ints.estimatedSize) + } + + test("interval tree treats NaN as its own point and Infinity as a bound") { + // PhysicalDoubleType's ordering (SQLOrderingUtil.compareDoubles) totally orders + // -Inf < ... < +Inf < NaN, with NaN comparing equal only to itself. So [1.0, +Inf] + // includes +Inf under inclusive probe, and a NaN key overlaps only a probe that + // also lands exactly on NaN. + val index = buildIntervals(DoubleType, Seq( + (1.0, Double.PositiveInfinity, row(1)), + (Double.NegativeInfinity, -1.0, row(2)), + (Double.NaN, Double.NaN, row(3)))) + + assert(ids(index.overlapping(5.0, 5.0)) == List(1)) + assert(ids(index.overlapping(Double.PositiveInfinity, Double.PositiveInfinity)) == List(1)) + assert(ids(index.overlapping(-5.0, -5.0)) == List(2)) + assert(ids(index.overlapping(Double.NegativeInfinity, Double.NegativeInfinity)) == List(2)) + assert(ids(index.overlapping(Double.NaN, Double.NaN)) == List(3)) + assert(ids(index.overlapping(0.0, 0.0)).isEmpty) + } + + test("interval index merges keys that compare equal but are not equal") { + // Array equals is identity, and UTF8String equals is binary, so these keys + // compare equal under the index ordering without being equal. The tree + // orders them with that comparator, so a probe on either key returns both. + // (Signed zero is the same kind of merge, but Double's == already treats -0.0 + // and 0.0 as equal, which fails this helper's != precondition - see the + // dedicated "-0.0 and 0.0 are treated as one key" test below instead.) + def assertMerged( + dataType: DataType, + low: Any, + leftKey: Any, + rightKey: Any, + high: Any, + earlier: Seq[Any]): Unit = { + val ordering = PhysicalDataType.ordering(dataType) + assert(leftKey != rightKey) + assert(ordering.compare(leftKey, rightKey) == 0) + val points = Array( + (leftKey, leftKey, row(0)), + (rightKey, rightKey, row(1))) + val pointIdx = buildIntervals(dataType, points.toSeq) + assert(ids(pointIdx.overlapping(leftKey, leftKey)).toSet == Set(0, 1)) + assert(ids(pointIdx.overlapping(rightKey, rightKey)).toSet == Set(0, 1)) + + val intervals = earlier.zipWithIndex.map { case (key, i) => + (key, key, row(10 + i)) + }.toArray ++ Array( + (low, leftKey, row(0)), + (rightKey, high, row(1))) + val index = buildIntervals(dataType, intervals.toSeq) + assert(ids(index.overlapping(leftKey, leftKey)).sorted == List(0, 1)) + assert(ids(index.overlapping(rightKey, rightKey)).sorted == List(0, 1)) + } + + val bytes = Array[Byte](1, 2) + val sameBytes = Array[Byte](1, 2) + assertMerged( + BinaryType, + Array[Byte](1, 0), + bytes, + sameBytes, + Array[Byte](2), + Seq(Array[Byte](0), Array[Byte](0, 1))) + + val upper = UTF8String.fromString("M") + val lower = UTF8String.fromString("m") + assertMerged( + StringType("UNICODE_CI"), + UTF8String.fromString("c"), + upper, + lower, + UTF8String.fromString("z"), + Seq(UTF8String.fromString("a"), UTF8String.fromString("b"))) + } + + test("-0.0 and 0.0 are treated as one key") { + // Double's own `==` already treats -0.0 and 0.0 as equal, so `PhysicalDataType.ordering` + // (which SQL requires to distinguish them from every other value, but not from each other) + // merges them exactly like the UTF8String/Array[Byte] keys above: a probe on either + // sign finds rows stored under both. Production float/double builds use the long + // family via DoublePrefixComparator, which also folds -0.0 into 0.0; the long + // assertions below pin that path. + val negZero: Any = -0.0 + val posZero: Any = 0.0 + val ordering = PhysicalDataType.ordering(DoubleType) + assert(ordering.compare(negZero, posZero) == 0) + + val points = Array((negZero, negZero, row(0)), (posZero, posZero, row(1))) + val pointIdx = buildIntervals(DoubleType, points.toSeq) + assert(ids(pointIdx.overlapping(negZero, negZero)).toSet == Set(0, 1)) + assert(ids(pointIdx.overlapping(posZero, posZero)).toSet == Set(0, 1)) + + val intervals = Array((-5.0: Any, negZero, row(0)), (posZero, 5.0: Any, row(1))) + val index = buildIntervals(DoubleType, intervals.toSeq) + assert(ids(index.overlapping(negZero, negZero)).sorted == List(0, 1)) + assert(ids(index.overlapping(posZero, posZero)).sorted == List(0, 1)) + + val longPoints = RangeRelationBroadcastMode( + Seq(BoundReference(0, DoubleType, nullable = true)), PointIndexKind) + .transform(Array(InternalRow(-0.0, 0), InternalRow(0.0, 1))) + .asInstanceOf[LongPointIndex] + val negLong = RangeIndex.requiredLongKey(DoubleType).value(-0.0) + val posLong = RangeIndex.requiredLongKey(DoubleType).value(0.0) + assert(negLong == posLong) + assert(longPoints.upTo(negLong, strict = false).map(_.getInt(1)).toSet == Set(0, 1)) + assert(longPoints.from(posLong, strict = false).map(_.getInt(1)).toSet == Set(0, 1)) + + val longIntervals = RangeRelationBroadcastMode( + Seq(BoundReference(0, DoubleType, nullable = true), + BoundReference(1, DoubleType, nullable = true)), + IntervalIndexKind) + .transform(Array(InternalRow(-5.0, -0.0, 0), InternalRow(0.0, 5.0, 1))) + .asInstanceOf[LongIntervalIndex] + assert(longIntervals.overlapping(negLong, negLong).map(_.getInt(2)).toList.sorted == + List(0, 1)) + assert(longIntervals.overlapping(posLong, posLong).map(_.getInt(2)).toList.sorted == + List(0, 1)) + } + + test("long float and double indexes honor NaN and Infinity SQL order") { + val toLong: Any => Long = RangeIndex.requiredLongKey(DoubleType).value + val longIdx = RangeRelationBroadcastMode( + Seq(BoundReference(0, DoubleType, nullable = true), + BoundReference(1, DoubleType, nullable = true)), + IntervalIndexKind) + .transform(Array( + InternalRow(1.0, Double.PositiveInfinity, 1), + InternalRow(Double.NegativeInfinity, -1.0, 2), + InternalRow(Double.NaN, Double.NaN, 3))) + .asInstanceOf[LongIntervalIndex] + assert(longIdx.overlapping(toLong(5.0), toLong(5.0)).map(_.getInt(2)).toList == List(1)) + assert(longIdx.overlapping(toLong(Double.PositiveInfinity), toLong(Double.PositiveInfinity)) + .map(_.getInt(2)).toList == List(1)) + assert(longIdx.overlapping(toLong(-5.0), toLong(-5.0)).map(_.getInt(2)).toList == List(2)) + assert(longIdx.overlapping(toLong(Double.NegativeInfinity), toLong(Double.NegativeInfinity)) + .map(_.getInt(2)).toList == List(2)) + assert(longIdx.overlapping(toLong(Double.NaN), toLong(Double.NaN)) + .map(_.getInt(2)).toList == List(3)) + assert(longIdx.overlapping(toLong(0.0), toLong(0.0)).isEmpty) + + val floatIdx = RangeRelationBroadcastMode( + Seq(BoundReference(0, FloatType, nullable = true)), PointIndexKind) + .transform(Array(InternalRow(Float.NaN, 0), InternalRow(1.0f, 1))) + .asInstanceOf[LongPointIndex] + val nanLong = RangeIndex.requiredLongKey(FloatType).value(Float.NaN) + assert(floatIdx.upTo(nanLong, strict = false).map(_.getInt(1)).toSet == Set(0, 1)) + assert(floatIdx.from(nanLong, strict = true).map(_.getInt(1)).isEmpty) + } + + test("a nested probe does not drop rows from the outer iterator") { + val spans = (0 until 32).map(i => span(i, i + 10, i)) + val index = buildIntervals(spans) + val longIdx = RangeRelationBroadcastMode( + Seq(BoundReference(0, IntegerType, nullable = true), + BoundReference(1, IntegerType, nullable = true)), + IntervalIndexKind) + .transform(spans.map(t => InternalRow(t._1, t._2, t._3.getInt(0))).toArray) + .asInstanceOf[LongIntervalIndex] + + // [0, 15] does not cover every span (the core is [31, 10]), so this walks the tree + // instead of taking the all-covering shortcut: proof that two concurrent walks can + // run on one index, the shape two interval joins fused in one whole-stage rely on. + val expectedOuter = (0 to 15).toList + val outer = index.overlapping(0, 15) + assert(outer.isInstanceOf[OverlapIterator]) + val seen = scala.collection.mutable.ArrayBuffer.empty[Int] + while (outer.hasNext) { + seen += outer.next().getInt(0) + assert(ids(index.overlapping(0, 5)).sorted == (0 to 5).toList) + } + assert(seen.sorted == expectedOuter) + + val longOuter = longIdx.overlapping(0L, 15L) + assert(longOuter.isInstanceOf[LongOverlapIterator]) + val longSeen = scala.collection.mutable.ArrayBuffer.empty[Int] + while (longOuter.hasNext) { + longSeen += longOuter.next().getInt(2) + assert(longIdx.overlapping(0L, 5L).map(_.getInt(2)).toList.sorted == (0 to 5).toList) + } + assert(longSeen.sorted == expectedOuter) + } + + test("a point probe of disjoint intervals returns only the containing row") { + val n = 1000 + val index = buildIntervals((0 until n).map(i => span(i * 2, i * 2 + 1, i))) + assert(probeIds(index, 2, 2) == List(1)) + assert(probeIds(index, 3, 3) == List(1)) + assert(probeIds(index, 4, 4) == List(2)) + assert(probeIds(index, -1, -1).isEmpty) + assert(probeIds(index, 100000, 100000).isEmpty) + } + + test("point index answers both sides of a bound, including equals") { + // Unsorted, with two rows on key 5. Equals stay, in input order. + val keyed = Array[(Any, InternalRow)]( + (8, row(8)), + (1, row(1)), + (5, row(5)), + (5, row(50)), + (3, row(3)), + (null, row(-1))) + val index = buildPoints(IntegerType, keyed.toSeq) + assert(ids(index.upTo(5, strict = false)) == List(1, 3, 5, 50)) + assert(ids(index.upTo(4, strict = false)) == List(1, 3)) + assert(ids(index.upTo(0, strict = false)).isEmpty) + assert(ids(index.upTo(8, strict = false)) == List(1, 3, 5, 50, 8)) + assert(ids(index.from(5, strict = false)) == List(5, 50, 8)) + assert(ids(index.from(6, strict = false)) == List(8)) + assert(ids(index.from(9, strict = false)).isEmpty) + assert(ids(index.from(1, strict = false)) == List(1, 3, 5, 50, 8)) + assert(index.upTo(null, strict = false).isEmpty) + assert(index.from(null, strict = false).isEmpty) + + val empty = buildPoints(IntegerType, Seq.empty) + assert(empty.upTo(1, strict = false).isEmpty) + assert(empty.from(1, strict = false).isEmpty) + // SizeEstimator charges the two empty arrays' shells, and the five kept + // points on top of them. + assert(empty.estimatedSize > 0) + assert(index.estimatedSize > empty.estimatedSize) + } + + test("exclusive point bounds skip duplicated build keys") { + // 100 duplicate rows per key on both families. A strict partial predicate + // rejects the probe's own key, so the exclusive bound must skip it + // instead of surfacing 100 rows that all fail the condition. + val keyed = (1 to 5).flatMap(k => Seq.fill(100)((k: Any, row(k)))) + val boxed = buildPoints(IntegerType, keyed) + val longPoints = RangeRelationBroadcastMode( + Seq(BoundReference(1, IntegerType, nullable = true)), PointIndexKind) + .transform(keyed.map(t => InternalRow(t._2.getInt(0), t._1)).toArray) + .asInstanceOf[LongPointIndex] + + assert(ids(boxed.upTo(3, strict = false)).size == 300) + assert(ids(boxed.upTo(3, strict = true)).size == 200) + assert(ids(boxed.from(3, strict = false)).size == 300) + assert(ids(boxed.from(3, strict = true)).size == 200) + assert(ids(boxed.upTo(1, strict = true)).isEmpty) + assert(ids(boxed.from(5, strict = true)).isEmpty) + + assert(ids(longPoints.upTo(3L, strict = false)).size == 300) + assert(ids(longPoints.upTo(3L, strict = true)).size == 200) + assert(ids(longPoints.from(3L, strict = false)).size == 300) + assert(ids(longPoints.from(3L, strict = true)).size == 200) + } + + test("PointIndex.apply defends against a build-side iterator reusing its row buffer") { + // Same hazard as the IntervalIndex case above: a point index built straight off a + // reused row buffer must copy both the key and the row, not just reference them. + val n = 50 + val buildKeys = Seq(BoundReference(0, IntegerType, nullable = true)) + val (shared, rows) = reusingRowIterator(fields = 2, n) + val index = PointIndex(IntegerType, buildKeys, rows, Some(n)) + + shared.update(0, -1) + shared.update(1, -1) + + (0 until n).foreach { i => + val payload = index.from(i, strict = false).next().getInt(1) + assert(payload == i, s"point $i was corrupted by later reuse of the row buffer") + } + } + + test("PointIndex.apply defends against string keys sharing a reused byte buffer") { + val n = 50 + val buildKeys = Seq(BoundReference(0, StringType, nullable = true)) + val (sharedBytes, rows) = reusingByteBufferStringIterator(n) + val index = PointIndex(StringType, buildKeys, rows, Some(n)) + + java.util.Arrays.fill(sharedBytes, 'X'.toByte) + + (0 until n).foreach { i => + val key = UTF8String.fromString(f"$i%04d") + val matching = index.from(key, strict = false).take(1).toList + assert(matching.nonEmpty && matching.head.getInt(1) == i, + s"point $i was corrupted by shared buffer reuse") + } + } + + test("point index orders NaN above +Infinity and -Infinity below every finite value") { + // Total order: -Inf < -1.0 < 0.0 < 1.0 < +Inf < NaN, with NaN the unique maximum. + val keyed = Array[(Any, InternalRow)]( + (Double.NaN, row(90)), + (Double.PositiveInfinity, row(80)), + (1.0, row(1)), + (Double.NegativeInfinity, row(-80)), + (-1.0, row(-1)), + (0.0, row(0))) + val index = buildPoints(DoubleType, keyed.toSeq) + assert(ids(index.upTo(0.0, strict = false)) == List(-80, -1, 0)) + assert(ids(index.from(1.0, strict = false)) == List(1, 80, 90)) + // NaN is the unique maximum: only a NaN key is at or above it. + assert(ids(index.from(Double.NaN, strict = false)) == List(90)) + assert(ids(index.upTo(Double.NaN, strict = false)) == List(-80, -1, 0, 1, 80, 90)) + // +Infinity is below NaN but above every finite value. + assert(ids(index.upTo(Double.PositiveInfinity, strict = false)) == List(-80, -1, 0, 1, 80)) + assert(ids(index.from(Double.NegativeInfinity, strict = false)) == List(-80, -1, 0, 1, 80, 90)) + } + + test("upTo/from matches a brute-force reference across randomized point sets") { + // PointIndex's counterpart to "overlapping matches a brute-force reference + // across randomized interval sets": cross-checks the binary-search bound + // scan against an independent O(n) scan, across many random key sets and + // probe values, including duplicate keys. + val rand = new scala.util.Random(42) + val bound = 50 + for (_ <- 0 until 30) { + val n = 1 + rand.nextInt(300) + val raw = (0 until n).map(i => (rand.nextInt(bound), i)) + val index = buildPoints(IntegerType, raw.map { case (k, i) => (k, row(i)) }) + + for (_ <- 0 until 20) { + val probe = rand.nextInt(bound) + val expectedUpTo = raw.collect { case (k, i) if k <= probe => i }.toSet + val expectedFrom = raw.collect { case (k, i) if k >= probe => i }.toSet + assert(ids(index.upTo(probe, strict = false)).toSet == expectedUpTo, + s"n=$n probe=$probe expected=$expectedUpTo") + assert(ids(index.from(probe, strict = false)).toSet == expectedFrom, + s"n=$n probe=$probe expected=$expectedFrom") + } + } + } + + test("indexes round-trip through Java and strict Kryo serialization") { + val serializers = Seq( + "Java" -> new org.apache.spark.serializer.JavaSerializer( + new org.apache.spark.SparkConf()).newInstance(), + "Kryo" -> { + val conf = new org.apache.spark.SparkConf() + .set(org.apache.spark.internal.config.Kryo.KRYO_REGISTRATION_REQUIRED, true) + new org.apache.spark.serializer.KryoSerializer(conf).newInstance() + }) + + // (key type, lo, hi, probe) covering each supported key family: fixed + // width, floating point, decimal, binary, and collated strings. The + // collated probe mixes cases, so a restored index only answers it when + // its collation ordering survived the round trip. The key type itself + // never reaches a serializer: writes cross it as JSON, so this exercises + // the index registrations, not any DataType registration. + val cases: Seq[(DataType, Any, Any, Any)] = Seq( + (ByteType, 0.toByte, 10.toByte, 5.toByte), + (ShortType, 0.toShort, 10.toShort, 5.toShort), + (IntegerType, 0, 10, 5), + (LongType, 0L, 10L, 5L), + (FloatType, 0.0f, 10.0f, 5.0f), + (DoubleType, 0.0, 10.0, 5.0), + (DecimalType(10, 2), Decimal(0.0), Decimal(10.0), Decimal(5.0)), + (StringType("UTF8_LCASE"), + UTF8String.fromString("abc"), UTF8String.fromString("zzz"), UTF8String.fromString("MMM")), + (CharType(3), + UTF8String.fromString("abc"), UTF8String.fromString("zzz"), UTF8String.fromString("mmm")), + (VarcharType(10), + UTF8String.fromString("abc"), UTF8String.fromString("zzz"), UTF8String.fromString("mmm")), + (BinaryType, Array[Byte](0), Array[Byte](10), Array[Byte](5)), + (DateType, 100, 200, 150), + (TimestampType, 1000L, 2000L, 1500L), + (TimestampNTZType, 1000L, 2000L, 1500L), + (BooleanType, false, true, true)) + + def roundTrip[A <: AnyRef: scala.reflect.ClassTag]( + ser: org.apache.spark.serializer.SerializerInstance, index: A): A = + ser.deserialize[A](ser.serialize(index)) + + // One reader for the sealed family, mirroring BroadcastRangeJoinExec.makeCandidateFn dispatch: + // the interval kinds answer a window, the point kinds answer a + // lower-bound scan, and every relation this test builds answers at + // row ordinal 0. + def answer(rel: RangeRelation, low: Any, high: Any): List[Int] = rel match { + case r: LongIntervalIndex => ids(r.overlapping(r.toLong(low), r.toLong(high))) + case r: IntervalIndex => ids(r.overlapping(low, high)) + case r: LongPointIndex => ids(r.from(r.toLong(low), strict = false)) + case r: PointIndex => ids(r.from(low, strict = false)) + } + + cases.foreach { case (dt, lo, hi, probe) => + // One straight span and one inverted span that normalizes to the same + // shape, plus the family the broadcast build routes the type to. Rows + // carry the asserted id at ordinal 0 and the keys at 1 and 2, so one + // reader answers every family. + val interval = buildIntervals(dt, Seq((lo, hi, row(5)), (hi, lo, row(6)))) + val point = buildPoints(dt, Seq((probe, row(7)))) + val routedInterval = RangeRelationBroadcastMode( + Seq(BoundReference(1, dt, nullable = true), BoundReference(2, dt, nullable = true)), + IntervalIndexKind) + .transform(Array(InternalRow(5, lo, hi), InternalRow(6, hi, lo))) + val routedPoint = RangeRelationBroadcastMode( + Seq(BoundReference(1, dt, nullable = true)), PointIndexKind) + .transform(Array(InternalRow(7, probe))) + + val intervalWindow = answer(interval, probe, probe) + val pointScan = answer(point, probe, probe) + assert(intervalWindow.sorted == List(5, 6), s"$dt window") + assert(pointScan.sorted == List(7), s"$dt bound") + // The routed family answers the same query on the same rows. + assert(answer(routedInterval, probe, probe).sorted == intervalWindow.sorted, s"$dt routed") + assert(answer(routedPoint, probe, probe).sorted == pointScan.sorted, s"$dt routed point") + + serializers.foreach { case (name, ser) => + Seq(interval, routedInterval).foreach { rel => + assert(answer(roundTrip(ser, rel), probe, probe).sorted == intervalWindow.sorted, + s"$dt interval via $name") + } + Seq(point, routedPoint).foreach { rel => + assert(answer(roundTrip(ser, rel), probe, probe).sorted == pointScan.sorted, + s"$dt point via $name") + } + } + } + } + + test("restored interval indexes answer windows that need the walk") { + // The round-trip fixtures above place every probe inside a common core, so + // the restored index answers from the row slice without reading the tree + // state. These intervals are disjoint: each probe must walk maxima, lows, + // and highs on the restored index, under every serializer. + val serializers = Seq( + "Java" -> new org.apache.spark.serializer.JavaSerializer( + new org.apache.spark.SparkConf()).newInstance(), + "Kryo" -> { + val conf = new org.apache.spark.SparkConf() + .set(org.apache.spark.internal.config.Kryo.KRYO_REGISTRATION_REQUIRED, true) + new org.apache.spark.serializer.KryoSerializer(conf).newInstance() + }, + // Reference tracking off duplicates any aliased object on the wire, so it + // also probes a restored graph that re-materialized every array entry. + "Kryo without references" -> { + val conf = new org.apache.spark.SparkConf() + .set(org.apache.spark.internal.config.Kryo.KRYO_REGISTRATION_REQUIRED, true) + .set(org.apache.spark.internal.config.Kryo.KRYO_REFERENCE_TRACKING, false) + new org.apache.spark.serializer.KryoSerializer(conf).newInstance() + }) + + def roundTrip[A <: AnyRef: scala.reflect.ClassTag]( + ser: org.apache.spark.serializer.SerializerInstance, index: A): A = + ser.deserialize[A](ser.serialize(index)) + + // Sized above SMALL_BUILD_OVERLAP_ROWS so a restored probe must walk. + val n = RangeIndex.SMALL_BUILD_OVERLAP_ROWS + 4 + val windows = Seq( + (5.0, 5.0, List(0)), + ((n - 1) * 20.0 + 5.0, (n - 1) * 20.0 + 5.0, List(n - 1)), + (5.0, 25.0, List(0, 1))) + val spans = (0 until n).map(i => span(i * 20.0, i * 20.0 + 10.0, i)) + val boxed = buildIntervals(DoubleType, spans) + val longIdx = RangeRelationBroadcastMode( + Seq(BoundReference(1, IntegerType, nullable = true), + BoundReference(2, IntegerType, nullable = true)), + IntervalIndexKind) + .transform((0 until n).map(i => InternalRow(i, i * 20, i * 20 + 10)).toArray) + .asInstanceOf[LongIntervalIndex] + + windows.foreach { case (low, high, expected) => + assert(probeIds(boxed, low, high).sorted == expected, s"fresh boxed $low-$high") + assert(longIdx.overlapping(low.toLong, high.toLong).map(_.getInt(0)).toList.sorted == + expected, s"fresh long $low-$high") + } + + serializers.foreach { case (name, ser) => + val restoredBoxed = roundTrip(ser, boxed) + val restoredLong = roundTrip(ser, longIdx) + windows.foreach { case (low, high, expected) => + // A disjoint build has no all-covering shortcut for these windows, so + // the restored index must answer through a fresh walk iterator. + assert(restoredBoxed.overlapping(low, high).isInstanceOf[OverlapIterator], + s"boxed $low-$high did not walk after $name") + assert(restoredLong.overlapping(low.toLong, high.toLong) + .isInstanceOf[LongOverlapIterator], s"long $low-$high did not walk after $name") + assert(probeIds(restoredBoxed, low, high).sorted == expected, + s"boxed $low-$high via $name") + assert(restoredLong.overlapping(low.toLong, high.toLong) + .map(_.getInt(0)).toList.sorted == expected, s"long $low-$high via $name") + } + } + } + + test("restored point indexes answer multi-entry bound scans") { + // The round-trip fixtures above hold one point equal to the probe, so any + // restore that keeps that single entry answers it whatever ordering it + // re-derives. These indexes hold several entries: duplicated keys, keys on + // both sides of each probe, and - for the collated boxed family - keys + // that compare equal without being equal. Every bound scan the join uses + // answers through the restored ordering, so a restore that reverses, + // truncates, or desynchronizes keys and rows hands back the wrong ids. + // The long family has no distinct-but-equal keys; it gets the duplicates. + val serializers = Seq( + "Java" -> new org.apache.spark.serializer.JavaSerializer( + new org.apache.spark.SparkConf()).newInstance(), + "Kryo" -> { + val conf = new org.apache.spark.SparkConf() + .set(org.apache.spark.internal.config.Kryo.KRYO_REGISTRATION_REQUIRED, true) + new org.apache.spark.serializer.KryoSerializer(conf).newInstance() + }, + // Reference tracking off duplicates any aliased object on the wire, so it + // also probes a restored graph that re-materialized every array entry. + "Kryo without references" -> { + val conf = new org.apache.spark.SparkConf() + .set(org.apache.spark.internal.config.Kryo.KRYO_REGISTRATION_REQUIRED, true) + .set(org.apache.spark.internal.config.Kryo.KRYO_REFERENCE_TRACKING, false) + new org.apache.spark.serializer.KryoSerializer(conf).newInstance() + }) + + def roundTrip[A <: AnyRef: scala.reflect.ClassTag]( + ser: org.apache.spark.serializer.SerializerInstance, index: A): A = + ser.deserialize[A](ser.serialize(index)) + + // UNICODE_CI sorts "M" with "m", so rows 3, 4, and 5 stay in input order as + // one collation class, and an exclusive scan skips all of them. Probes use + // both spellings and two off-key bounds, so the scans must consult the + // restored ordering rather than remembered positions. + val boxed = buildPoints(StringType("UNICODE_CI"), Seq( + (UTF8String.fromString("a"), row(1)), + (UTF8String.fromString("m"), row(3)), + (UTF8String.fromString("M"), row(4)), + (UTF8String.fromString("m"), row(5)), + (UTF8String.fromString("z"), row(9)))) + // (probe, upTo, upTo strict, from, from strict) + val boxedBounds: Seq[(UTF8String, List[Int], List[Int], List[Int], List[Int])] = Seq( + (UTF8String.fromString("m"), List(1, 3, 4, 5), List(1), List(3, 4, 5, 9), List(9)), + (UTF8String.fromString("M"), List(1, 3, 4, 5), List(1), List(3, 4, 5, 9), List(9)), + (UTF8String.fromString("n"), List(1, 3, 4, 5), List(1, 3, 4, 5), List(9), List(9)), + (UTF8String.fromString("l"), List(1), List(1), List(3, 4, 5, 9), List(3, 4, 5, 9))) + + val longPoints = RangeRelationBroadcastMode( + Seq(BoundReference(1, IntegerType, nullable = true)), PointIndexKind) + .transform(Array( + InternalRow(1, 1), InternalRow(3, 5), InternalRow(4, 5), + InternalRow(5, 5), InternalRow(9, 9))) + .asInstanceOf[LongPointIndex] + val longBounds: Seq[(Long, List[Int], List[Int], List[Int], List[Int])] = Seq( + (5L, List(1, 3, 4, 5), List(1), List(3, 4, 5, 9), List(9)), + (4L, List(1), List(1), List(3, 4, 5, 9), List(3, 4, 5, 9)), + (6L, List(1, 3, 4, 5), List(1, 3, 4, 5), List(9), List(9))) + + boxedBounds.foreach { case (probe, upTo, upToEx, from, fromEx) => + assert(ids(boxed.upTo(probe, strict = false)) == upTo, s"fresh boxed upTo($probe)") + assert(ids(boxed.upTo(probe, strict = true)) == upToEx, s"fresh boxed strict upTo($probe)") + assert(ids(boxed.from(probe, strict = false)) == from, s"fresh boxed from($probe)") + assert(ids(boxed.from(probe, strict = true)) == fromEx, s"fresh boxed strict from($probe)") + } + longBounds.foreach { case (probe, upTo, upToEx, from, fromEx) => + assert(ids(longPoints.upTo(probe, strict = false)) == upTo, s"fresh long upTo($probe)") + assert(ids(longPoints.upTo(probe, strict = true)) == upToEx, + s"fresh long strict upTo($probe)") + assert(ids(longPoints.from(probe, strict = false)) == from, s"fresh long from($probe)") + assert(ids(longPoints.from(probe, strict = true)) == fromEx, + s"fresh long strict from($probe)") + } + + serializers.foreach { case (name, ser) => + val restoredBoxed = roundTrip(ser, boxed) + val restoredLong = roundTrip(ser, longPoints) + boxedBounds.foreach { case (probe, upTo, upToEx, from, fromEx) => + assert(ids(restoredBoxed.upTo(probe, strict = false)) == upTo, + s"boxed upTo($probe) via $name") + assert(ids(restoredBoxed.upTo(probe, strict = true)) == upToEx, + s"boxed strict upTo($probe) via $name") + assert(ids(restoredBoxed.from(probe, strict = false)) == from, + s"boxed from($probe) via $name") + assert(ids(restoredBoxed.from(probe, strict = true)) == fromEx, + s"boxed strict from($probe) via $name") + } + longBounds.foreach { case (probe, upTo, upToEx, from, fromEx) => + assert(ids(restoredLong.upTo(probe, strict = false)) == upTo, + s"long upTo($probe) via $name") + assert(ids(restoredLong.upTo(probe, strict = true)) == upToEx, + s"long strict upTo($probe) via $name") + assert(ids(restoredLong.from(probe, strict = false)) == from, + s"long from($probe) via $name") + assert(ids(restoredLong.from(probe, strict = true)) == fromEx, + s"long strict from($probe) via $name") + } + } + } + + test("overlapping uses the common-core short cut without changing the answer") { + // [0, 10], [5, 15], and [8, 20] share the core [8, 10] (1-D Helly). Any + // window that reaches it overlaps every interval, so the index returns + // all rows directly; windows outside keep the walk's selective answer. + val index = buildIntervals(Seq(span(0, 10, 0), span(5, 15, 1), span(8, 20, 2))) + assert(probeIds(index, 9, 9).sorted == List(0, 1, 2)) + assert(probeIds(index, 8, 10).sorted == List(0, 1, 2)) + assert(probeIds(index, 6, 12).sorted == List(0, 1, 2)) + // Endpoints are normalized first, so a reversed window reaches the core too. + assert(probeIds(index, 12, 6).sorted == List(0, 1, 2)) + // The short cut skips the walk's iterator for a core window, and only there. + assert(!index.overlapping(9, 9).isInstanceOf[OverlapIterator]) Review Comment: Thanks, the padded multiplicity fixtures and the round-trip comment look right now. The common-core shortcut test still builds only three intervals, though, so every probe in it takes the linear scan, and its check that a core window skips OverlapIterator passes whether or not the shortcut fires. Could that build be padded past the cutoff with intervals that contain the shared core, such as copies of [8, 10], so the core stays the same, and could the windows outside the core assert OverlapIterator? <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4512581512","thread_id":"inline:4512581512","verdict_sha256":"4595cf4eb3bb3f392678aa394d30b9b8d753a6c4fcbf334ae0ec7217525fac49"} --> -- 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]
