wangyum commented on code in PR #59027: URL: https://github.com/apache/spark/pull/59027#discussion_r4526069431
########## 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: Done: rewrapped the sentence onto one line. ########## 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: Done: reworded the no-hint build-side comment to match the per-join-type wording used in the hinted rule above. ########## 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: Done: applied the suggested fix verbatim. ########## 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: Done: padded both builds in assertMerged past SMALL_BUILD_OVERLAP_ROWS with keys sorting after every probe key, and added OverlapIterator assertions on the probes. -- 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]
