HeartSaVioR commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4524188236
########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,861 @@ +/* + * 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.util.concurrent.{ConcurrentHashMap, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder, Weigher} + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, + JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform} +import org.apache.spark.sql.catalyst.util.ArrayData +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReader, ExternalLookupReaderFactory, + ExternalLookupResultCursor} +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric} +import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, MapType, + StructType} +import org.apache.spark.util.Utils + +/** + * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The factory is sent to the + * tasks, so it holds only what they need; the plan node and its scan stay on the driver. + * + * An evaluator joins its partition one batch of up to `maxParameterRowsPerRequest` stream rows at + * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each batch it sends one + * request with the distinct parameters that can match and are not cached, and streams the + * connector's result rows into output rows. Parameters are deduplicated within a batch. With the + * cache enabled, a key whose complete result an earlier request of the same input partition + * returned is served from the cache, within the cache's bounds; otherwise a key repeated in a + * later batch is requested again. + * + * Spark does not trust the connector with the selected lookup predicates: it evaluates + * `lookupKeyCheck` on every row that the connector returns, against the request row that the row + * answers, and drops a row that fails it, before it joins the row. The stream rows that share a + * request row have Spark-equal parameters, so one check serves all of them. + * + * The join condition comes in two parts: `streamCondition` reads only stream columns and is + * evaluated on each stream row before the request, and `residualCondition` is evaluated on the + * joined rows. A stream row that fails `streamCondition` cannot match, so its parameters are not + * sent. + */ +class ExternalLookupJoinEvaluatorFactory( + tableName: String, + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + lookupKeyCheck: Option[Expression], + streamOutput: Seq[Attribute], + lookupInput: Seq[Attribute], + lookupTransforms: Seq[ExternalLookupTransform], + transformedLookup: Seq[Attribute], + output: Seq[Attribute], + joinType: JoinType, + streamCondition: Option[Expression], + residualCondition: Option[Expression], + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + oneKeyPerBatch: Boolean, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + cacheTicker: Ticker, + metrics: ExternalLookupJoinMetrics, + readerMetrics: ExternalLookupReaderMetrics) + extends PartitionEvaluatorFactory[InternalRow, InternalRow] { + + require(lookupParameters.length == nullSafeParameters.length, + "Every external lookup parameter must define its null semantics") + + override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] = + new ExternalLookupJoinEvaluator + + private class ExternalLookupJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] { + override def eval( + partitionIndex: Int, + inputs: Iterator[InternalRow]*): Iterator[InternalRow] = { + assert(inputs.length == 1) + new PartitionJoinIterator(inputs.head, partitionIndex) + } + } + + /** Joins one partition batch by batch, and closes its reader after the last batch. */ + private class PartitionJoinIterator(input: Iterator[InternalRow], partitionIndex: Int) + extends Iterator[InternalRow] { + private val reader = new LookupReader + private val parameters = new LookupParameters(partitionIndex) + private val resultRows = new LookupResultRows + private val transforms = new LookupTransforms(partitionIndex) + private val joinOutput = new JoinOutput(partitionIndex) + private var cache = if (cacheOptions.enabled) Some(new LookupCache) else None + private var batch: Iterator[InternalRow] = Iterator.empty + private var inputExhausted = false + + override def hasNext: Boolean = { + tryAdvance() + batch.hasNext + } + + override def next(): InternalRow = { + tryAdvance() + if (!batch.hasNext) { + throw new SparkIllegalStateException( + errorClass = "INTERNAL_ERROR", + messageParameters = Map("message" -> "External lookup join exhausted")) + } + batch.next() + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryAdvance(): Unit = { + while (!batch.hasNext && !inputExhausted) { + val rows = readBatch() + if (rows.nonEmpty) { + batch = new BatchJoinIterator(rows, parameters, resultRows, transforms, joinOutput, cache, + inputRemains = () => !inputExhausted, reader = reader) + } + inputExhausted = !hasInput + } + // No later batch reads the cache, so neither it nor the drained batch is kept. + if (inputExhausted && !batch.hasNext) { + batch = Iterator.empty + cache = None + reader.close() + } + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // When a request holds one parameter row because of a selected range, a batch takes the stream + // rows of one key rather than one stream row. It ends before the first row with another key, + // which starts the next batch. A row that cannot match has no key, and any batch takes it. + private var heldRow: UnsafeRow = null + + private def hasInput: Boolean = heldRow != null || input.hasNext + + private def nextRow(): UnsafeRow = if (heldRow != null) { + val row = heldRow + heldRow = null + row + } else { + input.next() match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).copy() + } + } + + /** The request row of a stream row that can match, in a reused row, or null. */ + private def requestRowOf(row: InternalRow): UnsafeRow = + if (!joinOutput.canMatch(row)) null else { + val requestRow = parameters.requestRow(row) + if (parameters.matchesNothing(requestRow)) null else requestRow + } + + // An array, because a batch's rows are read by position for every key, match and output row. + // The batch holds its rows until its request is read, so it stops once their copies reach + // maxBatchBytes, keeping the row that reaches it, as well as at maxParameterRowsPerRequest + // rows, or at another key with one key per batch. It always takes one row. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + var batchKey: UnsafeRow = null + var keyChanged = false + while (!keyChanged && (oneKeyPerBatch || rows.length < maxParameterRowsPerRequest) && + bytes < maxBatchBytes && hasInput) { + val row = nextRow() + val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null + if (requestRow != null && batchKey != null && requestRow != batchKey) { + heldRow = row + keyChanged = true + } else { + if (requestRow != null && batchKey == null) batchKey = requestRow.copy() + bytes += row.getSizeInBytes + rows += row + } + } + rows.toArray + } + } + + /** The stream rows that share a key, and the one request row sent for them. */ + private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: mutable.ArrayBuffer[Int]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: mutable.ArrayBuffer[Int]) + + /** + * Joins one batch of stream rows. Rows whose parameters are equal under Spark equality share + * one request row, and every result row for a request row that satisfies the selected lookup + * predicates joins all the stream rows sharing it. A stream row is finished, which may emit its + * unmatched output row, once no more result rows can match it. + * + * Output rows are projected into a reused row on `next()`, so the consumer copies the rows it + * retains, as with other join iterators. + */ + private class BatchJoinIterator( + rows: Array[InternalRow], + parameters: LookupParameters, + resultRows: LookupResultRows, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + inputRemains: () => Boolean, + reader: LookupReader) extends Iterator[InternalRow] { + metrics.inputRows += rows.length + metrics.inputBatches += 1 + + private val matched = Array.fill(rows.length)(false) + private val finished = mutable.BitSet.empty + // Output rows not yet returned: a stream row index and the lookup row it is joined with. + private val pending = mutable.Queue.empty[(Int, InternalRow)] + + // One entry for each distinct request row that can match and is not cached, in the order of + // first occurrence. A row that can never match, because it fails the stream condition or has a + // null parameter, is finished right away, and its parameters are not requested. The stream + // condition is checked before the parameters are evaluated, so that it can guard their + // expressions. A request row is classified once, on its first occurrence, as a cache hit or a + // row to request: every path fans out to all the rows sharing it, so it must not be both, e.g. + // across a TTL boundary. + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + private val keyEntries = { + val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + lazy val requestRow = parameters.requestRow(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(requestRow)) { + finish(index) + } else { + entries.get(requestRow).map(_.rowIndexes) + .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => + val retained = requestRow.copy() + cache.flatMap(_.get(retained)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(retained, CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + } + entries.values.toArray + } + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [e8fcf1b7ad7](https://github.com/apache/spark/commit/e8fcf1b7ad728f342ba8d9e22005a97c65d26c46): cache hits now produce their output rows lazily, as the batch is read, so they don't pile up on the heap before the first row. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,861 @@ +/* + * 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.util.concurrent.{ConcurrentHashMap, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder, Weigher} + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, + JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform} +import org.apache.spark.sql.catalyst.util.ArrayData +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReader, ExternalLookupReaderFactory, + ExternalLookupResultCursor} +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric} +import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, MapType, + StructType} +import org.apache.spark.util.Utils + +/** + * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The factory is sent to the + * tasks, so it holds only what they need; the plan node and its scan stay on the driver. + * + * An evaluator joins its partition one batch of up to `maxParameterRowsPerRequest` stream rows at + * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each batch it sends one + * request with the distinct parameters that can match and are not cached, and streams the + * connector's result rows into output rows. Parameters are deduplicated within a batch. With the + * cache enabled, a key whose complete result an earlier request of the same input partition + * returned is served from the cache, within the cache's bounds; otherwise a key repeated in a + * later batch is requested again. + * + * Spark does not trust the connector with the selected lookup predicates: it evaluates + * `lookupKeyCheck` on every row that the connector returns, against the request row that the row + * answers, and drops a row that fails it, before it joins the row. The stream rows that share a + * request row have Spark-equal parameters, so one check serves all of them. + * + * The join condition comes in two parts: `streamCondition` reads only stream columns and is + * evaluated on each stream row before the request, and `residualCondition` is evaluated on the + * joined rows. A stream row that fails `streamCondition` cannot match, so its parameters are not + * sent. + */ +class ExternalLookupJoinEvaluatorFactory( + tableName: String, + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + lookupKeyCheck: Option[Expression], + streamOutput: Seq[Attribute], + lookupInput: Seq[Attribute], + lookupTransforms: Seq[ExternalLookupTransform], + transformedLookup: Seq[Attribute], + output: Seq[Attribute], + joinType: JoinType, + streamCondition: Option[Expression], + residualCondition: Option[Expression], + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + oneKeyPerBatch: Boolean, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + cacheTicker: Ticker, + metrics: ExternalLookupJoinMetrics, + readerMetrics: ExternalLookupReaderMetrics) + extends PartitionEvaluatorFactory[InternalRow, InternalRow] { + + require(lookupParameters.length == nullSafeParameters.length, + "Every external lookup parameter must define its null semantics") + + override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] = + new ExternalLookupJoinEvaluator + + private class ExternalLookupJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] { + override def eval( + partitionIndex: Int, + inputs: Iterator[InternalRow]*): Iterator[InternalRow] = { + assert(inputs.length == 1) + new PartitionJoinIterator(inputs.head, partitionIndex) + } + } + + /** Joins one partition batch by batch, and closes its reader after the last batch. */ + private class PartitionJoinIterator(input: Iterator[InternalRow], partitionIndex: Int) + extends Iterator[InternalRow] { + private val reader = new LookupReader + private val parameters = new LookupParameters(partitionIndex) + private val resultRows = new LookupResultRows + private val transforms = new LookupTransforms(partitionIndex) + private val joinOutput = new JoinOutput(partitionIndex) + private var cache = if (cacheOptions.enabled) Some(new LookupCache) else None + private var batch: Iterator[InternalRow] = Iterator.empty + private var inputExhausted = false + + override def hasNext: Boolean = { + tryAdvance() + batch.hasNext + } + + override def next(): InternalRow = { + tryAdvance() + if (!batch.hasNext) { + throw new SparkIllegalStateException( + errorClass = "INTERNAL_ERROR", + messageParameters = Map("message" -> "External lookup join exhausted")) + } + batch.next() + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryAdvance(): Unit = { + while (!batch.hasNext && !inputExhausted) { + val rows = readBatch() + if (rows.nonEmpty) { + batch = new BatchJoinIterator(rows, parameters, resultRows, transforms, joinOutput, cache, + inputRemains = () => !inputExhausted, reader = reader) + } + inputExhausted = !hasInput + } + // No later batch reads the cache, so neither it nor the drained batch is kept. + if (inputExhausted && !batch.hasNext) { + batch = Iterator.empty + cache = None + reader.close() + } + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // When a request holds one parameter row because of a selected range, a batch takes the stream + // rows of one key rather than one stream row. It ends before the first row with another key, + // which starts the next batch. A row that cannot match has no key, and any batch takes it. + private var heldRow: UnsafeRow = null + + private def hasInput: Boolean = heldRow != null || input.hasNext + + private def nextRow(): UnsafeRow = if (heldRow != null) { + val row = heldRow + heldRow = null + row + } else { + input.next() match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).copy() + } + } + + /** The request row of a stream row that can match, in a reused row, or null. */ + private def requestRowOf(row: InternalRow): UnsafeRow = + if (!joinOutput.canMatch(row)) null else { + val requestRow = parameters.requestRow(row) + if (parameters.matchesNothing(requestRow)) null else requestRow + } + + // An array, because a batch's rows are read by position for every key, match and output row. + // The batch holds its rows until its request is read, so it stops once their copies reach + // maxBatchBytes, keeping the row that reaches it, as well as at maxParameterRowsPerRequest + // rows, or at another key with one key per batch. It always takes one row. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + var batchKey: UnsafeRow = null + var keyChanged = false + while (!keyChanged && (oneKeyPerBatch || rows.length < maxParameterRowsPerRequest) && + bytes < maxBatchBytes && hasInput) { + val row = nextRow() + val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null + if (requestRow != null && batchKey != null && requestRow != batchKey) { + heldRow = row + keyChanged = true + } else { + if (requestRow != null && batchKey == null) batchKey = requestRow.copy() + bytes += row.getSizeInBytes + rows += row + } + } + rows.toArray + } + } + + /** The stream rows that share a key, and the one request row sent for them. */ + private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: mutable.ArrayBuffer[Int]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: mutable.ArrayBuffer[Int]) + + /** + * Joins one batch of stream rows. Rows whose parameters are equal under Spark equality share + * one request row, and every result row for a request row that satisfies the selected lookup + * predicates joins all the stream rows sharing it. A stream row is finished, which may emit its + * unmatched output row, once no more result rows can match it. + * + * Output rows are projected into a reused row on `next()`, so the consumer copies the rows it + * retains, as with other join iterators. + */ + private class BatchJoinIterator( + rows: Array[InternalRow], + parameters: LookupParameters, + resultRows: LookupResultRows, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + inputRemains: () => Boolean, + reader: LookupReader) extends Iterator[InternalRow] { + metrics.inputRows += rows.length + metrics.inputBatches += 1 + + private val matched = Array.fill(rows.length)(false) + private val finished = mutable.BitSet.empty + // Output rows not yet returned: a stream row index and the lookup row it is joined with. + private val pending = mutable.Queue.empty[(Int, InternalRow)] + + // One entry for each distinct request row that can match and is not cached, in the order of + // first occurrence. A row that can never match, because it fails the stream condition or has a + // null parameter, is finished right away, and its parameters are not requested. The stream + // condition is checked before the parameters are evaluated, so that it can guard their + // expressions. A request row is classified once, on its first occurrence, as a cache hit or a + // row to request: every path fans out to all the rows sharing it, so it must not be both, e.g. + // across a TTL boundary. + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + private val keyEntries = { + val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + lazy val requestRow = parameters.requestRow(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(requestRow)) { + finish(index) + } else { + entries.get(requestRow).map(_.rowIndexes) + .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => + val retained = requestRow.copy() + cache.flatMap(_.get(retained)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(retained, CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + } + entries.values.toArray + } + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) + finish(index) + } + } + + // Only a later batch of the partition reads what this one caches, so the last batch caches + // nothing. The partition knows whether input remains once the request is sent, before its + // results are read. + private lazy val cacheWriter = if (!inputRemains()) None else { + cache.map(new CacheWriter(_, keyEntries.map(_.requestRow))) + } + + // No connector request, and no reader, when no key can match. + private var cursor: ExternalLookupResultCursor = + if (keyEntries.isEmpty) EmptyLookupCursor + else connectorCall(reader.lookup(keyEntries.map(_.requestRow))) + + override def hasNext: Boolean = { + tryFillPending() + pending.nonEmpty + } + + override def next(): InternalRow = { + tryFillPending() + if (pending.isEmpty) throw new NoSuchElementException("external lookup result") + val (index, lookupRow) = pending.dequeue() + joinOutput.project(rows(index), lookupRow) + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryFillPending(): Unit = { + try { + while (pending.isEmpty && advanceCursor()) { + reader.resultRowRead() + // The join checks for a close() before each connector call, so it makes none after it + // has seen one. + val start = System.nanoTime() + reader.ensureOpen() + val ordinal = cursor.inputOrdinal() + reader.ensureOpen() + val connectorRow = cursor.get() + metrics.lookupTime += System.nanoTime() - start + if (connectorRow == null) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> "ExternalLookupResultCursor.get()")) + } + val entry = requestedEntry(ordinal) + reader.ensureOpen() + val resultRow = resultRows.validatedCopy(connectorRow) + if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) { + transforms(resultRow).foreach { lookupRow => + cacheWriter.foreach(_.add(entry.requestRow, lookupRow)) + entry.rowIndexes.foreach(joinMatch(_, lookupRow)) + } + } + } + if (pending.isEmpty) finishCursor(completed = true) + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor(completed = false) + } + } + } + + /** + * Advances the connector's cursor, unless the reader was closed meanwhile. A close() while + * next() ran fails the read once next() returns: Spark then reads no row from the closed + * cursor, and does not take a missing row for a complete result. + */ + private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && { + reader.ensureOpen() + val advanced = connectorCall(cursor.next()) + reader.ensureOpen() + advanced + } + + /** + * Runs a connector call and adds its time to the lookup time metric, which counts only the + * time in the connector, not that of the work above the join while a cursor is open. + */ + private def connectorCall[T](call: => T): T = { + val start = System.nanoTime() + try call finally metrics.lookupTime += System.nanoTime() - start + } + + private def requestedEntry(ordinal: Int): KeyEntry = { + if (ordinal < 0 || ordinal >= keyEntries.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> keyEntries.length.toString)) + } + keyEntries(ordinal) + } + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + // A semi or anti join knows a stream row's answer at its first match, so it evaluates the + // residual condition no further for that row, as the other join operators do. It still + // reads the whole result, for the other stream rows of the key. + if (!(joinOutput.answeredByFirstMatch && matched(index)) && + joinOutput.matches(rows(index), lookupRow)) { + val firstMatch = !matched(index) + matched(index) = true + joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _)) + } + } + + /** + * Closes the cursor once. After a complete read, caches the results and finishes every stream + * row that was waiting for them. After a failure or a close, the results may be partial, so it + * caches nothing and finishes no row: a row without a match could be a row whose match was + * never read. A failure fails the task, which discards the cache, and the join never retries a + * request. Once the reader is closed, its close owns the cursor and the reader's metrics, so + * the join makes no further connector call. + */ + private def finishCursor(completed: Boolean): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + if (!reader.isClosed) { + try { + connectorCall(reader.closeCursor()) + } finally { + reader.updateMetrics() + } + } + if (completed) { + cacheWriter.foreach(_.write()) + keyEntries.foreach(_.rowIndexes.foreach(finish)) + } + } + + private def finish(index: Int): Unit = if (!finished.contains(index)) { + finished += index + if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _)) + } + + private def emit(index: Int, lookupRow: InternalRow): Unit = { + pending.enqueue(index -> lookupRow) + metrics.outputRows += 1 + } + } + + /** + * The lookup results by key, within a task, per input partition (a task that reads several input + * partitions, e.g. after coalesce, has one cache per partition). Once its entries take more than + * `maxBytes`, the least recently used ones are evicted; an entry expires once it is older than + * the TTL, by `cacheTicker`. An entry takes the bytes of its key and of its rows, with the + * objects that hold each row, plus a fixed overhead, so that a key without a result counts too. + * Its keys and rows are the batches' own copies, which are never changed. + */ + private class LookupCache { + // One segment, so that eviction is exactly least recently used, and bounded by `maxBytes`. + private val entries: Cache[UnsafeRow, Array[UnsafeRow]] = { + val builder = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumWeight(cacheOptions.maxBytes) + .weigher(new Weigher[UnsafeRow, Array[UnsafeRow]] { + override def weigh(key: UnsafeRow, rows: Array[UnsafeRow]): Int = { + val bytes = ExternalLookupJoinEvaluatorFactory.CACHE_ENTRY_OVERHEAD_BYTES + + key.getSizeInBytes + + rows.iterator.map(ExternalLookupJoinEvaluatorFactory.cachedBytes).sum + math.min(bytes, Int.MaxValue).toInt + } + }) + .ticker(cacheTicker) + val expiring = if (cacheOptions.ttlMillis > 0) { + builder.expireAfterWrite(cacheOptions.ttlMillis, TimeUnit.MILLISECONDS) + } else { + builder + } + expiring.build[UnsafeRow, Array[UnsafeRow]]() + } + + def get(key: UnsafeRow): Option[Array[UnsafeRow]] = Option(entries.getIfPresent(key)) + + def put(key: UnsafeRow, values: Array[UnsafeRow]): Unit = entries.put(key, values) + } + + /** + * Collects the result rows of one request by key, and caches them once the cursor is done. It + * receives only the rows that satisfy the selected lookup predicates, so the cache never holds a + * row that Spark's check dropped. A key whose rows take more than a + * [[ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE]]th of `maxBytes` is not cached, so that + * one large result cannot evict most of the cache, and the request holds at most `maxBytes` of + * rows for the cache, which could keep no more; a key whose rows would pass that is not cached + * either. Such a key is still joined in full. The rows are the batch's own copies, which are + * never changed. + */ + private class CacheWriter(cache: LookupCache, keys: Array[UnsafeRow]) { + private class KeyResults(val rows: mutable.ArrayBuffer[UnsafeRow], var bytes: Long) + private val maxKeyBytes = + cacheOptions.maxBytes / ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE + private val resultsByKey = + mutable.HashMap.from(keys.map(_ -> new KeyResults(mutable.ArrayBuffer.empty, 0L))) + private val uncacheable = mutable.HashSet.empty[UnsafeRow] + private var bufferedBytes = 0L + + def add(key: UnsafeRow, lookupRow: UnsafeRow): Unit = if (!uncacheable.contains(key)) { + val results = resultsByKey(key) + val rowBytes = ExternalLookupJoinEvaluatorFactory.cachedBytes(lookupRow) + if (results.bytes + rowBytes > maxKeyBytes || + bufferedBytes + rowBytes > cacheOptions.maxBytes) { + uncacheable += key + bufferedBytes -= results.bytes + results.rows.clear() + } else { + results.rows += lookupRow + results.bytes += rowBytes + bufferedBytes += rowBytes + } + } + + def write(): Unit = keys.foreach { key => + if (!uncacheable.contains(key)) cache.put(key, resultsByKey(key).rows.toArray) + } + } + + /** The cursor of a batch that sends no request, or whose cursor is finished. */ + private object EmptyLookupCursor extends ExternalLookupResultCursor { + override def next(): Boolean = false + override def inputOrdinal(): Int = throw new NoSuchElementException("external lookup result") + override def get(): InternalRow = throw new NoSuchElementException("external lookup result") + override def close(): Unit = {} + } + + /** A check of one value slot: a field of a row, or an element of an array. */ + private type SlotCheck = (SpecializedGetters, Int) => Unit + + /** + * Validates each row that the connector returns, and copies it once into Spark's own row before + * Spark checks, joins or keeps it. A connector may reuse its row and its buffers, byte arrays + * included, so a row that Spark still holds must not share them. A value that breaks its type + * fails the task, at any nested level: a null in a field, array element or map value that the + * table or the read schema declares NOT NULL, or a decimal that does not fit its precision and + * scale. Spark already relied on them while it optimized the query. The checks are built once + * from the read schema, and a field whose type has nothing to check costs nothing per row. + */ + private class LookupResultRows { + private val copy = UnsafeProjection.create(lookupInput, lookupInput) + private val fieldChecks = lookupInput.zipWithIndex.flatMap { case (field, ordinal) => + slotCheck(field.dataType, field.nullable, Seq(field.name)).map(ordinal -> _) + } + + /** The row, validated and copied into a row that Spark owns. */ + def validatedCopy(resultRow: InternalRow): UnsafeRow = { + fieldChecks.foreach { case (ordinal, check) => check(resultRow, ordinal) } + copy(resultRow).copy() + } + + /** The check of a slot of this type, at this field path, or None if it has nothing to check. */ + private def slotCheck( + dataType: DataType, + nullable: Boolean, + path: Seq[String]): Option[SlotCheck] = { + val valueCheck = nonNullValueCheck(dataType, path) + if (nullable && valueCheck.isEmpty) { + None + } else { + Some { (values, ordinal) => + if (!values.isNullAt(ordinal)) { + valueCheck.foreach(_(values, ordinal)) + } else if (!nullable) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "NULL_IN_NOT_NULL_FIELD", + Map("field" -> QueryExecutionErrors.toSQLId(path))) + } + } + } + } + + /** The check of a value that is not null, or None if its type has nothing to check. */ + private def nonNullValueCheck(dataType: DataType, path: Seq[String]): Option[SlotCheck] = + dataType match { + case decimalType: DecimalType => Some { (values, ordinal) => + val value = values.getDecimal(ordinal, decimalType.precision, decimalType.scale) + if (!fits(value, decimalType)) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "DECIMAL_OUT_OF_RANGE", + Map( + "field" -> QueryExecutionErrors.toSQLId(path), + "type" -> QueryExecutionErrors.toSQLType(decimalType))) + } + } + case structType: StructType => + val checks = structType.fields.toSeq.zipWithIndex.flatMap { case (field, ordinal) => + slotCheck(field.dataType, field.nullable, path :+ field.name).map(ordinal -> _) + } + Option.when(checks.nonEmpty) { (values, ordinal) => + val struct = values.getStruct(ordinal, structType.length) + checks.foreach { case (fieldOrdinal, check) => check(struct, fieldOrdinal) } + } + case arrayType: ArrayType => + slotCheck(arrayType.elementType, arrayType.containsNull, path :+ "element").map { + check => (values, ordinal) => eachElement(values.getArray(ordinal), check) + } + case mapType: MapType => + // A map key is never null, whatever the value's nullability. + val keyCheck = slotCheck(mapType.keyType, nullable = false, path :+ "key") + val valueCheck = + slotCheck(mapType.valueType, mapType.valueContainsNull, path :+ "value") + Option.when(keyCheck.nonEmpty || valueCheck.nonEmpty) { (values, ordinal) => + val map = values.getMap(ordinal) + keyCheck.foreach(eachElement(map.keyArray(), _)) + valueCheck.foreach(eachElement(map.valueArray(), _)) + } + case _ => None + } + + private def eachElement(array: ArrayData, check: SlotCheck): Unit = { + var index = 0 + while (index < array.numElements()) { + check(array, index) + index += 1 + } + } + + /** Whether the decimal has its type's precision and scale without rounding. */ + private def fits(value: Decimal, decimalType: DecimalType): Boolean = { + val rescaled = value.clone() + rescaled.changePrecision(decimalType.precision, decimalType.scale) && rescaled == value + } + } + + /** + * Evaluates the lookup parameters of stream rows into the request rows that are sent to the + * connector. Spark offers lookup keys only on types whose values are equal under Spark equality + * exactly when their binary forms are (see ExternalLookupKeyTypes), so equal request rows have + * equal bytes. Also checks the rows that the connector returns against the selected lookup + * predicates. + */ + private class LookupParameters(partitionIndex: Int) { + private val requestProjection = UnsafeProjection.create(lookupParameters, streamOutput) + private val keyCheck = lookupKeyCheck.map(Predicate.create(_)) + private val requestAndResult = new JoinedRow() + requestProjection.initialize(partitionIndex) + keyCheck.foreach(_.initialize(partitionIndex)) + + /** The request row of a stream row, in a reused row: copy it to retain it. */ + def requestRow(streamRow: InternalRow): UnsafeRow = requestProjection(streamRow) + + /** Whether a row that the connector returns satisfies the selected lookup predicates. */ + def selectedPredicatesHold(requestRow: UnsafeRow, resultRow: InternalRow): Boolean = + keyCheck.forall(_.eval(requestAndResult(requestRow, resultRow))) + + /** A null parameter that is not null-safe matches no lookup row, so it is not requested. */ + def matchesNothing(requestRow: InternalRow): Boolean = + nullSafeParameters.indices.exists { index => + !nullSafeParameters(index) && requestRow.isNullAt(index) + } + } + + /** + * Applies the optimized lookup-side projections and filters to a result row, in evaluation + * order. A row that a filter rejects joins no stream row. Several stream rows can join the + * result, so it is retained: a projection reuses its output row, which is copied, and a result + * row that no projection changed is already a copy. + */ + private class LookupTransforms(partitionIndex: Int) { + private val stages = lookupTransforms.map { + case ExternalLookupProject(projectList, input) => + Left(UnsafeProjection.create(projectList, input)) + case ExternalLookupFilter(condition, input) => + Right(Predicate.create(condition, input)) + } + stages.foreach { + case Left(projection) => projection.initialize(partitionIndex) + case Right(predicate) => predicate.initialize(partitionIndex) + } + + private val projects = stages.exists(_.isLeft) + + def apply(resultRow: UnsafeRow): Option[UnsafeRow] = + stages.foldLeft(Option(resultRow)) { + case (Some(row), Left(projection)) => Some(projection(row)) + case (Some(row), Right(predicate)) if predicate.eval(row) => Some(row) + case _ => None + }.map(row => if (projects) row.copy() else row) + } + + /** + * Evaluates the stream condition on stream rows and the residual condition on joined rows, and + * builds output rows per join type. + */ + private class JoinOutput(partitionIndex: Int) { + // Lookup rows follow the last lookup-side stage, or the read schema without one, and the + // residual and output are bound to their fields. + private val joinedLookupInput = if (joinType == LeftOuter) { + transformedLookup.map(_.withNullability(true)) + } else { + transformedLookup + } + private val joinedInput = streamOutput ++ joinedLookupInput + private val joinedRow = new JoinedRow() + private val streamPredicate = streamCondition.map(Predicate.create(_, streamOutput)) + private val residual = residualCondition.map(Predicate.create(_, joinedInput)) + private val projection = UnsafeProjection.create(output, joinedInput) + private val nullLookupRow = new GenericInternalRow(transformedLookup.length) + streamPredicate.foreach(_.initialize(partitionIndex)) + residual.foreach(_.initialize(partitionIndex)) + projection.initialize(partitionIndex) + + /** Whether a stream row passes the stream condition; a row that fails it matches nothing. */ + def canMatch(streamRow: InternalRow): Boolean = streamPredicate.forall(_.eval(streamRow)) + + /** Whether the first match decides a stream row's output, as in a semi or anti join. */ + val answeredByFirstMatch: Boolean = joinType == LeftSemi || joinType == LeftAnti + + def matches(streamRow: InternalRow, lookupRow: InternalRow): Boolean = + residual.forall(_.eval(joinedRow(streamRow, lookupRow))) + + /** + * The lookup row that the output for a match joins, if the join type emits one; a semi join + * emits only its first match. + */ + def matched(lookupRow: InternalRow, firstMatch: Boolean): Option[InternalRow] = + joinType match { + case Inner | LeftOuter => Some(lookupRow) + case LeftSemi if firstMatch => Some(nullLookupRow) + case _ => None + } + + /** The lookup row that the output for a stream row without a match joins, if any. */ + def unmatched: Option[InternalRow] = joinType match { + case LeftOuter | LeftAnti => Some(nullLookupRow) + case _ => None + } + + /** The output row, projected into a reused row. */ + def project(streamRow: InternalRow, lookupRow: InternalRow): InternalRow = + projection(joinedRow(streamRow, lookupRow)) + } + + /** + * The connector reader of one partition and its active cursor. The reader is opened by the + * first request, and closed once, after the last batch or when the task completes, as + * `DataSourceRDD` closes its readers. A thread other than the task's may still drive the join + * then, and the close may overlap the one connector call that it is making, which the close does + * not wait for. That thread checks for the close before each connector call, so it makes no + * further one. A cursor that a request returns after the close is not closed: closing the + * reader releases it. + */ + private class LookupReader { + private val taskReaders = readerMetrics.forCurrentTask() + private val closed = new AtomicBoolean(false) + // Each is taken by exactly one of the join and close(), so it is closed once. + private val openReader = new AtomicReference[ExternalLookupReader]() + private val activeCursor = new AtomicReference[ExternalLookupResultCursor]() + private var resultRowsSinceMetricsUpdate = 0 + Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => close())) + + /** Sends one request and returns the cursor over its result rows. */ + def lookup(requestRows: Array[UnsafeRow]): ExternalLookupResultCursor = { + ensureOpen() + metrics.requests += 1 + metrics.parameterRows += requestRows.length + val reader = Option(openReader.get()).getOrElse(createReader()) + ensureOpen() + val cursor = Option(reader.lookupBatch(requestRows.asInstanceOf[Array[InternalRow]])) + .getOrElse { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> "ExternalLookupReader.lookupBatch()")) + } + activeCursor.set(cursor) + ensureOpen() + cursor + } + + private def createReader(): ExternalLookupReader = { + val reader = Option(readerFactory.createReader()).getOrElse { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> "ExternalLookupReaderFactory.createReader()")) + } + taskReaders.opened(reader) + openReader.set(reader) + // A close() while the reader was created did not find it, so it is closed here. + if (closed.get() && openReader.compareAndSet(reader, null)) { + ExternalLookupJoinExec.closeResources((), taskReaders.closing(reader), reader.close()) + } + reader + } + + /** Fails once the reader is closed, before any further connector call. */ + def ensureOpen(): Unit = if (closed.get()) { + throw SparkException.internalError("External lookup reader used after it was closed") + } + + def isClosed: Boolean = closed.get() + + /** Samples the connector metrics every [[CustomMetrics.NUM_ROWS_PER_UPDATE]] result rows. */ + def resultRowRead(): Unit = { + resultRowsSinceMetricsUpdate += 1 + if (resultRowsSinceMetricsUpdate >= CustomMetrics.NUM_ROWS_PER_UPDATE) updateMetrics() + } + + /** Samples the connector metrics, unless the reader is closed, whose close keeps them. */ + def updateMetrics(): Unit = { + if (!closed.get() && openReader.get() != null) taskReaders.report() + resultRowsSinceMetricsUpdate = 0 + } + + def closeCursor(): Unit = Option(activeCursor.getAndSet(null)).foreach(_.close()) + + def close(): Unit = if (closed.compareAndSet(false, true)) { + val cursor = activeCursor.getAndSet(null) + val reader = openReader.getAndSet(null) + ExternalLookupJoinExec.closeResources( + Option(cursor).foreach(_.close()), + if (reader != null) taskReaders.closing(reader), + if (reader != null) reader.close()) + } + } +} + +private object ExternalLookupJoinEvaluatorFactory { + /** The bytes that a cache entry takes besides its key and rows, as an estimate. */ + val CACHE_ENTRY_OVERHEAD_BYTES = 64L Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [e8fcf1b7ad7](https://github.com/apache/spark/commit/e8fcf1b7ad728f342ba8d9e22005a97c65d26c46). The per-entry overhead is now 168 bytes, taken from the objects each entry holds: - Guava's entry with its links: 64 bytes, or 48 without a TTL; - the weighted value reference: 24; - the hash-table slot and spare room: 8; - the key's UnsafeRow, 40, and its array header, 16; - the header of the rows array: 16. JOL on JDK 21 measures Guava's objects at 88 to 90 bytes per entry with a TTL, which this covers. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,861 @@ +/* + * 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.util.concurrent.{ConcurrentHashMap, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder, Weigher} + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, + JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform} +import org.apache.spark.sql.catalyst.util.ArrayData +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReader, ExternalLookupReaderFactory, + ExternalLookupResultCursor} +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric} +import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, MapType, + StructType} +import org.apache.spark.util.Utils + +/** + * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The factory is sent to the + * tasks, so it holds only what they need; the plan node and its scan stay on the driver. + * + * An evaluator joins its partition one batch of up to `maxParameterRowsPerRequest` stream rows at + * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each batch it sends one + * request with the distinct parameters that can match and are not cached, and streams the + * connector's result rows into output rows. Parameters are deduplicated within a batch. With the + * cache enabled, a key whose complete result an earlier request of the same input partition + * returned is served from the cache, within the cache's bounds; otherwise a key repeated in a + * later batch is requested again. + * + * Spark does not trust the connector with the selected lookup predicates: it evaluates + * `lookupKeyCheck` on every row that the connector returns, against the request row that the row + * answers, and drops a row that fails it, before it joins the row. The stream rows that share a + * request row have Spark-equal parameters, so one check serves all of them. + * + * The join condition comes in two parts: `streamCondition` reads only stream columns and is + * evaluated on each stream row before the request, and `residualCondition` is evaluated on the + * joined rows. A stream row that fails `streamCondition` cannot match, so its parameters are not + * sent. + */ +class ExternalLookupJoinEvaluatorFactory( + tableName: String, + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + lookupKeyCheck: Option[Expression], + streamOutput: Seq[Attribute], + lookupInput: Seq[Attribute], + lookupTransforms: Seq[ExternalLookupTransform], + transformedLookup: Seq[Attribute], + output: Seq[Attribute], + joinType: JoinType, + streamCondition: Option[Expression], + residualCondition: Option[Expression], + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + oneKeyPerBatch: Boolean, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + cacheTicker: Ticker, + metrics: ExternalLookupJoinMetrics, + readerMetrics: ExternalLookupReaderMetrics) + extends PartitionEvaluatorFactory[InternalRow, InternalRow] { + + require(lookupParameters.length == nullSafeParameters.length, + "Every external lookup parameter must define its null semantics") + + override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] = + new ExternalLookupJoinEvaluator + + private class ExternalLookupJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] { + override def eval( + partitionIndex: Int, + inputs: Iterator[InternalRow]*): Iterator[InternalRow] = { + assert(inputs.length == 1) + new PartitionJoinIterator(inputs.head, partitionIndex) + } + } + + /** Joins one partition batch by batch, and closes its reader after the last batch. */ + private class PartitionJoinIterator(input: Iterator[InternalRow], partitionIndex: Int) + extends Iterator[InternalRow] { + private val reader = new LookupReader + private val parameters = new LookupParameters(partitionIndex) + private val resultRows = new LookupResultRows + private val transforms = new LookupTransforms(partitionIndex) + private val joinOutput = new JoinOutput(partitionIndex) + private var cache = if (cacheOptions.enabled) Some(new LookupCache) else None + private var batch: Iterator[InternalRow] = Iterator.empty + private var inputExhausted = false + + override def hasNext: Boolean = { + tryAdvance() + batch.hasNext + } + + override def next(): InternalRow = { + tryAdvance() + if (!batch.hasNext) { + throw new SparkIllegalStateException( + errorClass = "INTERNAL_ERROR", + messageParameters = Map("message" -> "External lookup join exhausted")) + } + batch.next() + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryAdvance(): Unit = { + while (!batch.hasNext && !inputExhausted) { + val rows = readBatch() + if (rows.nonEmpty) { + batch = new BatchJoinIterator(rows, parameters, resultRows, transforms, joinOutput, cache, + inputRemains = () => !inputExhausted, reader = reader) + } + inputExhausted = !hasInput + } + // No later batch reads the cache, so neither it nor the drained batch is kept. + if (inputExhausted && !batch.hasNext) { + batch = Iterator.empty + cache = None + reader.close() + } + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // When a request holds one parameter row because of a selected range, a batch takes the stream + // rows of one key rather than one stream row. It ends before the first row with another key, + // which starts the next batch. A row that cannot match has no key, and any batch takes it. + private var heldRow: UnsafeRow = null + + private def hasInput: Boolean = heldRow != null || input.hasNext + + private def nextRow(): UnsafeRow = if (heldRow != null) { + val row = heldRow + heldRow = null + row + } else { + input.next() match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).copy() + } + } + + /** The request row of a stream row that can match, in a reused row, or null. */ + private def requestRowOf(row: InternalRow): UnsafeRow = + if (!joinOutput.canMatch(row)) null else { + val requestRow = parameters.requestRow(row) + if (parameters.matchesNothing(requestRow)) null else requestRow + } + + // An array, because a batch's rows are read by position for every key, match and output row. + // The batch holds its rows until its request is read, so it stops once their copies reach + // maxBatchBytes, keeping the row that reaches it, as well as at maxParameterRowsPerRequest + // rows, or at another key with one key per batch. It always takes one row. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + var batchKey: UnsafeRow = null + var keyChanged = false + while (!keyChanged && (oneKeyPerBatch || rows.length < maxParameterRowsPerRequest) && + bytes < maxBatchBytes && hasInput) { + val row = nextRow() + val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null + if (requestRow != null && batchKey != null && requestRow != batchKey) { + heldRow = row + keyChanged = true + } else { + if (requestRow != null && batchKey == null) batchKey = requestRow.copy() + bytes += row.getSizeInBytes + rows += row + } + } + rows.toArray + } + } + + /** The stream rows that share a key, and the one request row sent for them. */ + private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: mutable.ArrayBuffer[Int]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: mutable.ArrayBuffer[Int]) + + /** + * Joins one batch of stream rows. Rows whose parameters are equal under Spark equality share + * one request row, and every result row for a request row that satisfies the selected lookup + * predicates joins all the stream rows sharing it. A stream row is finished, which may emit its + * unmatched output row, once no more result rows can match it. + * + * Output rows are projected into a reused row on `next()`, so the consumer copies the rows it + * retains, as with other join iterators. + */ + private class BatchJoinIterator( + rows: Array[InternalRow], + parameters: LookupParameters, + resultRows: LookupResultRows, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + inputRemains: () => Boolean, + reader: LookupReader) extends Iterator[InternalRow] { + metrics.inputRows += rows.length + metrics.inputBatches += 1 + + private val matched = Array.fill(rows.length)(false) + private val finished = mutable.BitSet.empty + // Output rows not yet returned: a stream row index and the lookup row it is joined with. + private val pending = mutable.Queue.empty[(Int, InternalRow)] + + // One entry for each distinct request row that can match and is not cached, in the order of + // first occurrence. A row that can never match, because it fails the stream condition or has a + // null parameter, is finished right away, and its parameters are not requested. The stream + // condition is checked before the parameters are evaluated, so that it can guard their + // expressions. A request row is classified once, on its first occurrence, as a cache hit or a + // row to request: every path fans out to all the rows sharing it, so it must not be both, e.g. + // across a TTL boundary. + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + private val keyEntries = { + val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + lazy val requestRow = parameters.requestRow(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(requestRow)) { + finish(index) + } else { + entries.get(requestRow).map(_.rowIndexes) + .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => + val retained = requestRow.copy() + cache.flatMap(_.get(retained)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(retained, CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + } + entries.values.toArray + } + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) + finish(index) + } + } + + // Only a later batch of the partition reads what this one caches, so the last batch caches + // nothing. The partition knows whether input remains once the request is sent, before its + // results are read. + private lazy val cacheWriter = if (!inputRemains()) None else { + cache.map(new CacheWriter(_, keyEntries.map(_.requestRow))) + } + + // No connector request, and no reader, when no key can match. + private var cursor: ExternalLookupResultCursor = + if (keyEntries.isEmpty) EmptyLookupCursor + else connectorCall(reader.lookup(keyEntries.map(_.requestRow))) + + override def hasNext: Boolean = { + tryFillPending() + pending.nonEmpty + } + + override def next(): InternalRow = { + tryFillPending() + if (pending.isEmpty) throw new NoSuchElementException("external lookup result") + val (index, lookupRow) = pending.dequeue() + joinOutput.project(rows(index), lookupRow) + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryFillPending(): Unit = { + try { + while (pending.isEmpty && advanceCursor()) { + reader.resultRowRead() + // The join checks for a close() before each connector call, so it makes none after it + // has seen one. + val start = System.nanoTime() + reader.ensureOpen() + val ordinal = cursor.inputOrdinal() + reader.ensureOpen() + val connectorRow = cursor.get() + metrics.lookupTime += System.nanoTime() - start + if (connectorRow == null) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> "ExternalLookupResultCursor.get()")) + } + val entry = requestedEntry(ordinal) + reader.ensureOpen() + val resultRow = resultRows.validatedCopy(connectorRow) + if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) { + transforms(resultRow).foreach { lookupRow => + cacheWriter.foreach(_.add(entry.requestRow, lookupRow)) + entry.rowIndexes.foreach(joinMatch(_, lookupRow)) + } + } + } + if (pending.isEmpty) finishCursor(completed = true) + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor(completed = false) + } + } + } + + /** + * Advances the connector's cursor, unless the reader was closed meanwhile. A close() while + * next() ran fails the read once next() returns: Spark then reads no row from the closed + * cursor, and does not take a missing row for a complete result. + */ + private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && { + reader.ensureOpen() + val advanced = connectorCall(cursor.next()) + reader.ensureOpen() + advanced + } + + /** + * Runs a connector call and adds its time to the lookup time metric, which counts only the + * time in the connector, not that of the work above the join while a cursor is open. + */ + private def connectorCall[T](call: => T): T = { + val start = System.nanoTime() + try call finally metrics.lookupTime += System.nanoTime() - start + } + + private def requestedEntry(ordinal: Int): KeyEntry = { + if (ordinal < 0 || ordinal >= keyEntries.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> keyEntries.length.toString)) + } + keyEntries(ordinal) + } + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + // A semi or anti join knows a stream row's answer at its first match, so it evaluates the + // residual condition no further for that row, as the other join operators do. It still + // reads the whole result, for the other stream rows of the key. + if (!(joinOutput.answeredByFirstMatch && matched(index)) && + joinOutput.matches(rows(index), lookupRow)) { + val firstMatch = !matched(index) + matched(index) = true + joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _)) + } + } + + /** + * Closes the cursor once. After a complete read, caches the results and finishes every stream + * row that was waiting for them. After a failure or a close, the results may be partial, so it + * caches nothing and finishes no row: a row without a match could be a row whose match was + * never read. A failure fails the task, which discards the cache, and the join never retries a + * request. Once the reader is closed, its close owns the cursor and the reader's metrics, so + * the join makes no further connector call. + */ + private def finishCursor(completed: Boolean): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + if (!reader.isClosed) { + try { + connectorCall(reader.closeCursor()) + } finally { + reader.updateMetrics() + } + } + if (completed) { + cacheWriter.foreach(_.write()) + keyEntries.foreach(_.rowIndexes.foreach(finish)) + } + } + + private def finish(index: Int): Unit = if (!finished.contains(index)) { + finished += index + if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _)) + } + + private def emit(index: Int, lookupRow: InternalRow): Unit = { + pending.enqueue(index -> lookupRow) + metrics.outputRows += 1 + } + } + + /** + * The lookup results by key, within a task, per input partition (a task that reads several input + * partitions, e.g. after coalesce, has one cache per partition). Once its entries take more than + * `maxBytes`, the least recently used ones are evicted; an entry expires once it is older than + * the TTL, by `cacheTicker`. An entry takes the bytes of its key and of its rows, with the + * objects that hold each row, plus a fixed overhead, so that a key without a result counts too. + * Its keys and rows are the batches' own copies, which are never changed. + */ + private class LookupCache { + // One segment, so that eviction is exactly least recently used, and bounded by `maxBytes`. + private val entries: Cache[UnsafeRow, Array[UnsafeRow]] = { + val builder = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumWeight(cacheOptions.maxBytes) + .weigher(new Weigher[UnsafeRow, Array[UnsafeRow]] { + override def weigh(key: UnsafeRow, rows: Array[UnsafeRow]): Int = { + val bytes = ExternalLookupJoinEvaluatorFactory.CACHE_ENTRY_OVERHEAD_BYTES + + key.getSizeInBytes + + rows.iterator.map(ExternalLookupJoinEvaluatorFactory.cachedBytes).sum + math.min(bytes, Int.MaxValue).toInt + } + }) + .ticker(cacheTicker) + val expiring = if (cacheOptions.ttlMillis > 0) { + builder.expireAfterWrite(cacheOptions.ttlMillis, TimeUnit.MILLISECONDS) + } else { + builder + } + expiring.build[UnsafeRow, Array[UnsafeRow]]() + } + + def get(key: UnsafeRow): Option[Array[UnsafeRow]] = Option(entries.getIfPresent(key)) + + def put(key: UnsafeRow, values: Array[UnsafeRow]): Unit = entries.put(key, values) + } + + /** + * Collects the result rows of one request by key, and caches them once the cursor is done. It + * receives only the rows that satisfy the selected lookup predicates, so the cache never holds a + * row that Spark's check dropped. A key whose rows take more than a + * [[ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE]]th of `maxBytes` is not cached, so that + * one large result cannot evict most of the cache, and the request holds at most `maxBytes` of + * rows for the cache, which could keep no more; a key whose rows would pass that is not cached + * either. Such a key is still joined in full. The rows are the batch's own copies, which are + * never changed. + */ + private class CacheWriter(cache: LookupCache, keys: Array[UnsafeRow]) { + private class KeyResults(val rows: mutable.ArrayBuffer[UnsafeRow], var bytes: Long) + private val maxKeyBytes = + cacheOptions.maxBytes / ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE + private val resultsByKey = + mutable.HashMap.from(keys.map(_ -> new KeyResults(mutable.ArrayBuffer.empty, 0L))) + private val uncacheable = mutable.HashSet.empty[UnsafeRow] + private var bufferedBytes = 0L + + def add(key: UnsafeRow, lookupRow: UnsafeRow): Unit = if (!uncacheable.contains(key)) { + val results = resultsByKey(key) + val rowBytes = ExternalLookupJoinEvaluatorFactory.cachedBytes(lookupRow) + if (results.bytes + rowBytes > maxKeyBytes || + bufferedBytes + rowBytes > cacheOptions.maxBytes) { Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Added in [e8fcf1b7ad7](https://github.com/apache/spark/commit/e8fcf1b7ad728f342ba8d9e22005a97c65d26c46): a test where the per-request buffer bound decides. A mutation run fails it. -- 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]
