HeartSaVioR commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4520079392
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,193 @@ +/* + * 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.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries" + private val CACHE_TTL_OPTION = "cache_ttl" + private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key" + private val SUPPORTED_OPTIONS = Set( + CACHE_ENABLED_OPTION, + CACHE_MAX_ENTRIES_OPTION, + CACHE_TTL_OPTION, + CACHE_MAX_ROWS_PER_KEY_OPTION) + private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 5s, or 10m" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = defaultCacheOptions + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case Literal(value: String, _) => addString(value) + case attr: UnresolvedAttribute => + relationNames += attr.nameParts + case other => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other))) + } + relationNames.diff(relationNames.distinct).headOption.foreach { duplicate => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "DUPLICATE_RELATION", Map("relation" -> toSQLId(duplicate))) + } + + if (relationNames.isEmpty) { + ExternalLookupHint(child, cacheOptions) 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. Agreed. Fixed in [c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62): an option-only hint over a join fails with `NOT_ON_LOOKUP_SIDE`. The marker keeps only the options the user set, so unset ones follow the session conf when the join is planned, and `.hint()` no longer freezes them. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,193 @@ +/* + * 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.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries" + private val CACHE_TTL_OPTION = "cache_ttl" + private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key" + private val SUPPORTED_OPTIONS = Set( + CACHE_ENABLED_OPTION, + CACHE_MAX_ENTRIES_OPTION, + CACHE_TTL_OPTION, + CACHE_MAX_ROWS_PER_KEY_OPTION) + private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 5s, or 10m" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = defaultCacheOptions + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case Literal(value: String, _) => addString(value) 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. Dropped in [c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62). ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,819 @@ +/* + * 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 java.util.concurrent.locks.LockSupport + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder} + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, CollationKey, Expression, + GenericInternalRow, JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.optimizer.NormalizeFloatingNumbers +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. 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, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + 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 val 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, reader) + } + inputExhausted = !input.hasNext + } + if (inputExhausted && !batch.hasNext) reader.close() + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // 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. It always takes one row. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes && input.hasNext) { + val row = input.next() match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).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[InternalRow], 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], + 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 key that can match, 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 key is not requested. The stream condition is checked before + // the key is computed, so that it can guard the parameter expressions. A key is classified + // once, on its first occurrence, as a cache hit or a key to request: every path fans out to + // all the rows sharing the key, so a key must not be both, e.g. across a TTL boundary. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + rows.indices.foreach { index => + lazy val key = parameters.key(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(key)) { + finish(index) + } else { + keyEntries.get(key).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => cache.flatMap(_.get(key)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(key.copy(), CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + } + private val requestedKeys = keyEntries.keys.toArray + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) + finish(index) + } + } + + private val cacheWriter = cache.map(new CacheWriter(_, requestedKeys)) + + // No connector request, and no reader, when no key can match. The connector gets copies of + // the request rows, so that the ones that Spark checks the results against stay its own. + private var cursor: ExternalLookupResultCursor = + if (keyEntries.isEmpty) EmptyLookupCursor + else connectorCall(reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)) + + 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() + // A close() during either call fails the read before Spark copies or joins the row. + val start = System.nanoTime() + 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 key = requestedKey(ordinal) + val resultRow = reader.copyRow(resultRows.validatedCopy(connectorRow)) + if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, resultRow)) { + // The lookup-side stages reuse their output row, and several stream rows can join it. + transforms(resultRow).foreach { transformed => + val lookupRow = transformed.copy() + cacheWriter.foreach(_.add(key, lookupRow)) + joinResultRow(key, 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 requestedKey(ordinal: Int): UnsafeRow = { + if (ordinal < 0 || ordinal >= requestedKeys.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> requestedKeys.length.toString)) + } + requestedKeys(ordinal) + } + + private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit = + keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow)) + + 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.values.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). Beyond `maxEntries` keys, the + * least recently used entry is evicted; an entry expires once it is older than the TTL. + */ + private class LookupCache { + // One segment, so that eviction is exactly least recently used. + private val entries: Cache[UnsafeRow, Array[InternalRow]] = { + val builder = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumSize(cacheOptions.maxEntries) 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. Agreed, done in [c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62), and the cache stays on by default. - `spark.sql.join.externalLookup.cache.maxBytes` (default `16m` per input partition) and the hint option `cache_max_bytes` replace `maxEntries` and `maxRowsPerKey`. - A Guava weigher counts each entry's key and rows, with a fixed overhead per entry and per row, so keys with no rows count too. - A key whose rows take more than a sixteenth of `maxBytes` is joined in full but not cached, and a request buffers at most `maxBytes` of rows for the cache. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,819 @@ +/* + * 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 java.util.concurrent.locks.LockSupport + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder} + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, CollationKey, Expression, + GenericInternalRow, JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.optimizer.NormalizeFloatingNumbers +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. 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, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + 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 val 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, reader) + } + inputExhausted = !input.hasNext + } + if (inputExhausted && !batch.hasNext) reader.close() + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // 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. It always takes one row. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes && input.hasNext) { + val row = input.next() match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).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[InternalRow], 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], + 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 key that can match, 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 key is not requested. The stream condition is checked before + // the key is computed, so that it can guard the parameter expressions. A key is classified + // once, on its first occurrence, as a cache hit or a key to request: every path fans out to + // all the rows sharing the key, so a key must not be both, e.g. across a TTL boundary. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + rows.indices.foreach { index => + lazy val key = parameters.key(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(key)) { + finish(index) + } else { + keyEntries.get(key).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => cache.flatMap(_.get(key)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(key.copy(), CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + } + private val requestedKeys = keyEntries.keys.toArray 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 [c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62), across the join types, asserting `requestSizes`, `requestedKeys` and the hits. -- 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]
