HeartSaVioR commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4524189587
########## 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) 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 that tells expiry after a write from expiry after idle time. Switching to `expireAfterAccess` fails it. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -2530,6 +2530,72 @@ object SQLConf { .bytesConf(ByteUnit.BYTE) .createWithDefault(8L << 30) + val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES = + buildConf("spark.sql.join.externalLookup.maxBatchBytes") + .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE) + .doc("Size in bytes of input rows at which an external lookup join stops adding rows to " + + "a lookup request. The row that reaches this size stays in the request, so a request " + + "can exceed it by one row. A request always takes at least one row, and never more rows " + + "than the source allows, or 1000.") + .version("4.4.0") + .bytesConf(ByteUnit.BYTE) + .checkValue(_ > 0, "External lookup join max batch bytes must be positive") + .createWithDefaultString("64m") + + val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED = + buildConf("spark.sql.join.externalLookup.startupCheck.enabled") + .internal() + .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE) + .doc("When true, starting a streaming query plans its external lookup joins once, " + + "including the planning calls to their connectors, so that a join that cannot be " + + "planned fails the start instead of the first micro-batch. When false, such a join " + + "fails the first micro-batch that runs.") + .version("4.4.0") + .booleanConf + .createWithDefault(true) + + val JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED = + buildConf("spark.sql.join.externalLookup.cache.enabled") + .withBindingPolicy(ConfigBindingPolicy.SESSION) + .doc("When true, external lookup join caches the complete lookup result of each key, " + + "including a key with no result, within a task, per input partition (a task that reads " + + "several input partitions, e.g. after coalesce, has one cache per partition). A cached " + + "result is reused as it was read. This configuration can be overridden per join with " + + "the EXTERNAL_LOOKUP hint option 'cache_enabled', a string parameter of the form " + + "key=value such as 'cache_enabled=false'. A string parameter of the hint that does not " + + "contain '=' names a relation. At present, a join whose source serves a range " + + "comparison (<, <=, >, >=) with a stream-side value caches nothing, whatever this " + + "configuration or the hint option says.") + .version("4.4.0") + .booleanConf + .createWithDefault(true) + + val JOIN_EXTERNAL_LOOKUP_CACHE_MAX_BYTES = + buildConf("spark.sql.join.externalLookup.cache.maxBytes") + .withBindingPolicy(ConfigBindingPolicy.SESSION) + .doc("Maximum size of one external lookup join cache, that is per input partition of a " + + "task: the binary size of its lookup keys and of their result rows, after lookup-side " + + "projections and filters, plus a fixed overhead per key and per row for the objects " + + "that hold them. Beyond it, the least recently " + + "used keys are evicted. A key whose result rows take more than a sixteenth of it is " + + "returned but not cached. It can be overridden per join with the EXTERNAL_LOOKUP hint " + + "option 'cache_max_bytes'.") + .version("4.4.0") + .bytesConf(ByteUnit.BYTE) + .checkValue(_ > 0, "External lookup join cache max bytes must be positive") + .createWithDefaultString("16m") + + val JOIN_EXTERNAL_LOOKUP_CACHE_TTL = + buildConf("spark.sql.join.externalLookup.cache.ttl") 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 conf doc and the hint option text now say that a bare number is in milliseconds. -- 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]
