wangyum commented on code in PR #59027: URL: https://github.com/apache/spark/pull/59027#discussion_r4257318069
########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/RangeIndex.scala: ########## @@ -0,0 +1,329 @@ +/* + * 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 scala.collection.mutable.ArrayBuffer + +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Expression, InterpretedProjection} +import org.apache.spark.sql.catalyst.types.PhysicalDataType +import org.apache.spark.sql.types.DataType +import org.apache.spark.util.SizeEstimator + +/** + * Broadcast payload of a range join. An index only names candidate rows. + * [[BroadcastRangeJoinExec]] evaluates the original join condition to filter candidates. + * + * - [[IntervalIndex]] answers "which ranges overlap this window?" + * - [[PointIndex]] answers "which points lie on this side of a bound?" + */ +private[execution] sealed trait RangeRelation extends Serializable { + def estimatedSize(): Long + def keyType: DataType +} + +private[execution] object RangeIndex { + + /** Accessor reading a single field from `InternalRow` as a boxed value (or null). */ + def getValue(dt: DataType, ordinal: Int): InternalRow => Any = { + val accessor = InternalRow.getAccessor(dt) + (input: InternalRow) => accessor(input, ordinal) + } +} + +/** + * Augmented interval tree of build-side intervals, stored as flat arrays. + * + * Intervals are sorted by low bound. For any span `[start, end)`, its midpoint + * is the subtree root, and `maxHighs(mid)` records the maximum high bound in + * that span. Subtrees whose max high is below the probe window, or whose low + * starts after it, are pruned during search. + */ +private[execution] object IntervalIndex { + + def build( + keyType: DataType, + buildKeys: Seq[Expression], + rows: Iterator[InternalRow], + sizeHint: Option[Long]): IntervalIndex = { + val initialCapacity = sizeHint.map(n => math.min(n, Int.MaxValue).toInt).getOrElse(64) + val buffer = new ArrayBuffer[(Any, Any, InternalRow)](initialCapacity) + val projection = new InterpretedProjection(buildKeys) + val lowOf = RangeIndex.getValue(buildKeys.head.dataType, 0) + val highOf = + if (buildKeys.length == 1) lowOf else RangeIndex.getValue(buildKeys(1).dataType, 1) + val ordering = PhysicalDataType.ordering(keyType) + + while (rows.hasNext) { + val r = rows.next() + val p = projection(r) + normalizedInterval(ordering, lowOf(p), highOf(p), r, buffer) + } + + sortAndBuild(keyType, ordering, buffer.toArray) + } + + def build( + keyType: DataType, + intervals: Array[(Any, Any, InternalRow)]): IntervalIndex = { + val ordering = PhysicalDataType.ordering(keyType) + val buffer = new ArrayBuffer[(Any, Any, InternalRow)](intervals.length) + var i = 0 + while (i < intervals.length) { + val (rawLo, rawHi, r) = intervals(i) + normalizedInterval(ordering, rawLo, rawHi, r, buffer) + i += 1 + } + sortAndBuild(keyType, ordering, buffer.toArray) + } + + /** Drops a null-bounded interval; otherwise orders (lo, hi) and copies the key and row. */ + private def normalizedInterval( + ordering: Ordering[Any], + rawLo: Any, + rawHi: Any, + r: InternalRow, + buffer: ArrayBuffer[(Any, Any, InternalRow)]): Unit = { + if (rawLo != null && rawHi != null) { + val lo = InternalRow.copyValue(rawLo) + val hi = InternalRow.copyValue(rawHi) + val (normLo, normHi) = if (ordering.lteq(lo, hi)) (lo, hi) else (hi, lo) + buffer += ((normLo, normHi, r.copy())) + } + } + + private def sortAndBuild( + keyType: DataType, + ordering: Ordering[Any], + valid: Array[(Any, Any, InternalRow)]): IntervalIndex = { + java.util.Arrays.sort(valid, Ordering.by[(Any, Any, InternalRow), Any](_._1)(ordering)) + val length = valid.length + val maxHighs = new Array[Any](length) + + def fillMaxHigh(start: Int, end: Int): Any = { + if (start >= end) return null + val mid = (start + end) >>> 1 + var max = valid(mid)._2 + val left = fillMaxHigh(start, mid) + val right = fillMaxHigh(mid + 1, end) + if (left != null) max = ordering.max(max, left) + if (right != null) max = ordering.max(max, right) + maxHighs(mid) = max + max + } + + fillMaxHigh(0, length) + new IntervalIndex(keyType, valid, maxHighs) + } +} + +private[execution] class IntervalIndex private[joins] ( + val keyType: DataType, + private[this] val intervals: Array[(Any, Any, InternalRow)], + private[this] val maxHighs: Array[Any]) + extends RangeRelation { + + @transient + @volatile private[this] var _ordering: Ordering[Any] = _ + + private[joins] def ordering: Ordering[Any] = { + var ord = _ordering + if (ord == null) { + ord = PhysicalDataType.ordering(keyType) + _ordering = ord + } + ord + } Review Comment: In Scala 2.13, `@transient lazy val` desugars into a synchronized monitor lock (`synchronized(this)`) with a volatile bitmap check. Because a broadcast relation (`Broadcast[RangeRelation]`) is shared across all concurrent task threads on a multi-core executor, multiple threads accessing it simultaneously could suffer severe monitor lock contention. `RangeRelation` now stores serializable `keyType: DataType` and reconstructs `ordering` via `@transient @volatile private var _ordering` using a benign data race and local-variable register capture, ensuring zero lock contention and zero volatile reads in the inner probe loop. -- 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]
