HeartSaVioR commented on code in PR #60055: URL: https://github.com/apache/spark/pull/60055#discussion_r4524183784
########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,721 @@ +/* + * 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 +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +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.{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 streams the connector's result rows + * into output rows. Parameters are deduplicated per request, that is within one batch: 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, + 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 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, reader) + } + inputExhausted = !hasInput + } + if (inputExhausted && !batch.hasNext) 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) && 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 [3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb): a range batch again stops at the request's row cap, 1000 or the source's lower limit, and at `maxBatchBytes`, as the docs say. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,721 @@ +/* + * 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 +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +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.{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 streams the connector's result rows + * into output rows. Parameters are deduplicated per request, that is within one batch: 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, + 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 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, reader) + } + inputExhausted = !hasInput + } + if (inputExhausted && !batch.hasNext) 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]) + + /** + * 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, + 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, 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. + 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) match { + case Some(entry) => entry.rowIndexes += index + case None => + val retained = requestRow.copy() + entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + entries.values.toArray + } + + // 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 => + 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)) && 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 [3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb): a semi or anti join closes the cursor once every requested row of the batch is decided. Tests cover an equality key that matches several rows, and an open range. From #60087 there's one exception: a batch that fills the cache still reads its keys to the end, because the cache keeps only complete results. The last batch, and range lookups, which cache nothing, still close early. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,721 @@ +/* + * 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 +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +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.{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 streams the connector's result rows + * into output rows. Parameters are deduplicated per request, that is within one batch: 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, + 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 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, reader) + } + inputExhausted = !hasInput + } + if (inputExhausted && !batch.hasNext) 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]) + + /** + * 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, + 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, 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. + 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) match { + case Some(entry) => entry.rowIndexes += index + case None => + val retained = requestRow.copy() + entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + entries.values.toArray + } + + // 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 => + 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, finishes every stream row that was waiting for + * its results. After a failure or a close, the results may be partial, so it finishes none: + * a row without a match could be a row whose match was never read. 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) 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 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: InternalRow): Option[InternalRow] = + 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) 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 [3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb): a returned row is now copied once, after the stages. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala: ########## @@ -0,0 +1,427 @@ +/* + * 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.plans.logical + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, BinaryComparison, + Cast, CurrentBatchTimestamp, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Literal, + NamedExpression, PythonUDF, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, EXTERNAL_LOOKUP_HINT, + EXTERNAL_LOOKUP_JOIN, TreePattern} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, CharType, DataType, + DateType, DecimalType, IntegerType, IntegralType, LongType, ShortType, StringType, + TimestampNTZType, TimestampType, VarcharType} + +/** + * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint asks an external + * lookup join to read. The external lookup join rules consume it when they form the join. + * + * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. This hint is not, + * because that representation cannot keep two of its guarantees: + * - A strategy hint that conflicts with it must fail the query. [[HintInfo]] holds one strategy, + * and `ResolveJoinStrategyHints` merges a strategy hint on an already hinted relation into the + * existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one strategy and only warns. + * - It selects how the lookup side is read, not a physical join. `EliminateResolvedHint` moves + * every [[ResolvedHint]] it can attach into `Join.hint`, for physical join selection. + */ +case class ExternalLookupHint(child: LogicalPlan) extends UnaryNode { + override def output: Seq[Attribute] = child.output + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT) + + override protected def withNewChildInternal(newChild: LogicalPlan): ExternalLookupHint = + copy(child = newChild) +} + +/** + * A lookup join retained through ordinary expression and operator optimization. + * + * @param requiredLookupOutput Lookup-side attributes still required above this join. They are + * part of this node's references, so column pruning keeps them on the lookup side. + * `ColumnPruning` narrows them to what the parent reads, and `PrepareExternalLookupJoin` prunes + * the lookup scan to them. + */ +case class ExternalLookupJoin( + left: LogicalPlan, + right: LogicalPlan, + joinType: JoinType, + condition: Option[Expression], + requiredLookupOutput: Seq[Attribute]) extends BinaryNode { + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN) + + override def output: Seq[Attribute] = joinType match { + case Inner => left.output ++ right.output + case LeftOuter => left.output ++ right.output.map(_.withNullability(true)) + case LeftSemi | LeftAnti => left.output + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + // As an ordinary join's: a semi or anti join returns at most its stream rows, and the other join + // types get the product of both sides' sizes. + override def stats: Statistics = joinType match { + case LeftSemi | LeftAnti => left.stats + case _ => super.stats + } + + override def maxRows: Option[Long] = joinType match { + case LeftSemi | LeftAnti => left.maxRows + case _ => None + } + + override protected def withNewChildrenInternal( + newLeft: LogicalPlan, + newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right = newRight) +} + +/** + * The join-condition and lookup-side shapes that an external lookup join can run. Analysis, + * lookup planning and the optimizer rules for lookup joins share them. + */ +object ExternalLookupJoinShapes { + /** + * A lookup candidate: a comparison of a lookup column with a value, written with the lookup + * column on the left. + */ + case class LookupComparison( + lookupField: Attribute, + parameter: Expression, + comparison: LookupKeyComparison) + + /** + * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, `<=>`, `<`, `<=`, `>` + * or `>=` between a bare lookup column and a value, in either operand order. When the lookup + * column is written on the right, the comparison is rebuilt with it on the left, so + * `s.ts < t.event_time` is offered as `event_time > ?`. + * + * The value is the other operand, which Spark evaluates for each stream row to fill the + * comparison's parameter. It may read only stream columns, and it may read none, as a literal + * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a parameter. + * + * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets Spark offer the + * comparison. A comparison on another column is an ordinary conjunct. + * + * @param streamOutput The output of the join's left side, the stream side. + * @param lookupOutput The output of the join's right side, the lookup side. + */ + def lookupComparison( + conjunct: Expression, + streamOutput: AttributeSet, + lookupOutput: AttributeSet): Option[LookupComparison] = { + def isLookupComparison(lookupField: Attribute, parameter: Expression): Boolean = + lookupOutput.contains(lookupField) && parameter.references.subsetOf(streamOutput) + conjunct match { + case written: BinaryComparison => + LookupKeyComparison.of(written).flatMap { comparison => + Seq( + (written.left, written.right, comparison), + (written.right, written.left, comparison.swapped)).collectFirst { + case (lookupField: Attribute, parameter, comparison) + if isLookupComparison(lookupField, parameter) && + isOfferedOn(comparison, lookupField, parameter) => + LookupComparison(lookupField, parameter, comparison) + } + } + case _ => None + } + } + + /** + * Whether Spark offers the comparison on this lookup column, with this parameter. + * + * Spark evaluates every parameter on every stream row, before the other join conditions. That 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. Corrected in [3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb): the doc now says that the parameters are evaluated only for the stream rows that pass the checks before the lookup. -- 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]
