HeartSaVioR commented on code in PR #60087:
URL: https://github.com/apache/spark/pull/60087#discussion_r4532152598


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,917 @@
+/*
+ * 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, and with `oneKeyPerBatch`, of stream rows that share 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)
+
+    // An inner or left semi join emits nothing for a stream row that cannot 
match, because it
+    // fails the stream condition or has a null parameter that is not 
null-safe, as an ordinary
+    // inner join filters such a row out before it joins. So the row takes no 
place in a batch and
+    // is not copied: it counts only as an input row. A left outer or left 
anti join emits it, so a
+    // batch keeps it.
+    private val keepsRowsThatCannotMatch = joinType != Inner && joinType != 
LeftSemi
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes stream
+    // rows of one key. 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 that keeps it takes 
it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    /** The next row that a batch keeps, copied, or null after a row that it 
leaves out. */
+    private def nextKeptRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      val next = input.next()
+      if (keepsRowsThatCannotMatch || requestRowOf(next) != null) {
+        next match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+      } else {
+        metrics.inputRows += 1
+        null
+      }
+    }
+
+    /** 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, and at 
maxParameterRowsPerRequest rows, also
+    // with one key per batch, where it stops at another key too. It always 
keeps one row, when one
+    // remains.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && rows.length < maxParameterRowsPerRequest &&
+          bytes < maxBatchBytes && hasInput) {
+        val row = nextKeptRow()
+        if (row != null) {
+          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
+    }
+    // The cache hits are joined as the output is read, before the connector's 
rows: one cached row
+    // at a time, with every stream row of its key, so that their output rows 
do not pile up while
+    // the batch is built. A key's stream rows are finished after its last 
cached row.
+    private val cacheHits: Iterator[(CachedKey, Option[UnsafeRow])] =
+      cachedKeys.valuesIterator.flatMap { cached =>
+        (cached.lookupRows.iterator.map(Some(_)) ++ 
Iterator.single(None)).map(cached -> _)
+      }
+
+    // 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)))
+
+    // A semi or anti join decides a stream row at its first match. Once every 
requested row has
+    // matched, no later result row can change the output, so the join reads 
no further, unless it
+    // fills the cache, which keeps only complete results for later batches.
+    private var undecidedRows = 
keyEntries.iterator.map(_.rowIndexes.length).sum
+
+    private def decided: Boolean =
+      joinOutput.answeredByFirstMatch && undecidedRows == 0 && 
cacheWriter.isEmpty

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 
[2cac5728327](https://github.com/apache/spark/commit/2cac5728327094a89511a974a0da305f98a4a9fc),
 in two steps.
   - **Most of these joins now cache one row per key.** A left semi or left 
anti join whose residual reads no lookup column keeps at most one passing row 
per key (see the decision below). So it closes its cursor as soon as every 
stream row has matched, cache on or off.
   - **For the case that remains, your fix:** a residual that reads a lookup 
column, with every key past its share. `CacheWriter` tracks the keys whose 
entry a later row can still change, and `decided` accepts a writer with none 
left.
   - **Tests:**
     - an employee with five rows and a small cache, where the first batch 
stops after the row that takes the key past its share, and the next batch 
requests the key again;
     - one cached row when the residual reads no lookup column, and the whole 
result when it reads one.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,917 @@
+/*
+ * 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, and with `oneKeyPerBatch`, of stream rows that share 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)
+
+    // An inner or left semi join emits nothing for a stream row that cannot 
match, because it
+    // fails the stream condition or has a null parameter that is not 
null-safe, as an ordinary
+    // inner join filters such a row out before it joins. So the row takes no 
place in a batch and
+    // is not copied: it counts only as an input row. A left outer or left 
anti join emits it, so a
+    // batch keeps it.
+    private val keepsRowsThatCannotMatch = joinType != Inner && joinType != 
LeftSemi
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes stream
+    // rows of one key. 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 that keeps it takes 
it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    /** The next row that a batch keeps, copied, or null after a row that it 
leaves out. */
+    private def nextKeptRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      val next = input.next()
+      if (keepsRowsThatCannotMatch || requestRowOf(next) != null) {
+        next match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+      } else {
+        metrics.inputRows += 1
+        null
+      }
+    }
+
+    /** 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, and at 
maxParameterRowsPerRequest rows, also
+    // with one key per batch, where it stops at another key too. It always 
keeps one row, when one
+    // remains.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && rows.length < maxParameterRowsPerRequest &&
+          bytes < maxBatchBytes && hasInput) {
+        val row = nextKeptRow()
+        if (row != null) {
+          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
+    }
+    // The cache hits are joined as the output is read, before the connector's 
rows: one cached row
+    // at a time, with every stream row of its key, so that their output rows 
do not pile up while
+    // the batch is built. A key's stream rows are finished after its last 
cached row.
+    private val cacheHits: Iterator[(CachedKey, Option[UnsafeRow])] =
+      cachedKeys.valuesIterator.flatMap { cached =>
+        (cached.lookupRows.iterator.map(Some(_)) ++ 
Iterator.single(None)).map(cached -> _)
+      }
+
+    // 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)))
+
+    // A semi or anti join decides a stream row at its first match. Once every 
requested row has
+    // matched, no later result row can change the output, so the join reads 
no further, unless it
+    // fills the cache, which keeps only complete results for later batches.
+    private var undecidedRows = 
keyEntries.iterator.map(_.rowIndexes.length).sum
+
+    private def decided: Boolean =
+      joinOutput.answeredByFirstMatch && undecidedRows == 0 && 
cacheWriter.isEmpty
+
+    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 && cacheHits.hasNext) {
+          cacheHits.next() match {
+            case (cached, Some(lookupRow)) => 
cached.rowIndexes.foreach(joinMatch(_, lookupRow))
+            case (cached, None) => cached.rowIndexes.foreach(finish)
+          }
+        }
+        while (pending.isEmpty && !decided && 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.validated(connectorRow)
+          if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) {
+            transforms(resultRow).foreach { lookupRow =>
+              cacheWriter.foreach(_.add(entry.requestRow, lookupRow))
+              entry.rowIndexes.foreach { index =>
+                if (joinMatch(index, lookupRow)) undecidedRows -= 1
+              }
+            }
+          }
+        }
+        // A decided batch closes its cursor before the end. Its rows have all 
matched, so none is
+        // waiting for its results.
+        if (pending.isEmpty) finishCursor(completed = !decided)
+      } 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)
+    }
+
+    /** Joins a lookup row with a stream row, and returns whether it is the 
row's first match. */
+    private def joinMatch(index: Int, lookupRow: InternalRow): Boolean = {
+      // 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 reads on
+      // while another stream row of the batch has not matched.
+      if (!(joinOutput.answeredByFirstMatch && matched(index)) &&
+          joinOutput.matches(rows(index), lookupRow)) {
+        val firstMatch = !matched(index)
+        matched(index) = true
+        joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _))
+        firstMatch
+      } else {
+        false
+      }
+    }
+
+    /**
+     * 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. Nor does a semi or anti join that closes the cursor once 
every stream row has
+     * matched. 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())

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 
[2cac5728327](https://github.com/apache/spark/commit/2cac5728327094a89511a974a0da305f98a4a9fc):
 the test connector can return each key's rows in turn. A later batch serves 
both keys from the cache with every row, in inner, left outer, left semi and 
left anti joins. The semi and anti residual holds only for each key's second 
row, which arrives after the other key's first.
   



-- 
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]

Reply via email to