spark-test commented on code in PR #60087:
URL: https://github.com/apache/spark/pull/60087#discussion_r4521444952


##########
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))

Review Comment:
   Thanks, I verified this at the head: the last batch of a partition creates 
no cache writer, the partition drops its cache and drained batch once its input 
runs out, and the new test shows a partition that fits in one request returning 
the same rows and sending the same request with the cache on and off.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4518337233","thread_id":"inline:4518337233","verdict_sha256":"9215fd188929def83fce370374e2518354a42e8d0b48e16b7cff1ab8ecbae581"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,861 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import com.google.common.base.Ticker
+import com.google.common.cache.{Cache, CacheBuilder, Weigher}
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each 
batch it sends one
+ * request with the distinct parameters that can match and are not cached, and 
streams the
+ * connector's result rows into output rows. Parameters are deduplicated 
within a batch. With the
+ * cache enabled, a key whose complete result an earlier request of the same 
input partition
+ * returned is served from the cache, within the cache's bounds; otherwise a 
key repeated in a
+ * later batch is requested again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    oneKeyPerBatch: Boolean,
+    maxBatchBytes: Long,
+    cacheOptions: ExternalLookupCacheOptions,
+    cacheTicker: Ticker,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val transforms = new LookupTransforms(partitionIndex)
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private var cache = if (cacheOptions.enabled) Some(new LookupCache) else 
None
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
transforms, joinOutput, cache,
+            inputRemains = () => !inputExhausted, reader = reader)
+        }
+        inputExhausted = !hasInput
+      }
+      // No later batch reads the cache, so neither it nor the drained batch 
is kept.
+      if (inputExhausted && !batch.hasNext) {
+        batch = Iterator.empty
+        cache = None
+        reader.close()
+      }
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes the stream
+    // rows of one key rather than one stream row. It ends before the first 
row with another key,
+    // which starts the next batch. A row that cannot match has no key, and 
any batch takes it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    private def nextRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      input.next() match {
+        case unsafe: UnsafeRow => unsafe.copy()
+        case other => toUnsafe(other).copy()
+      }
+    }
+
+    /** The request row of a stream row that can match, in a reused row, or 
null. */
+    private def requestRowOf(row: InternalRow): UnsafeRow =
+      if (!joinOutput.canMatch(row)) null else {
+        val requestRow = parameters.requestRow(row)
+        if (parameters.matchesNothing(requestRow)) null else requestRow
+      }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows, or at another key with one key per batch. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && (oneKeyPerBatch || rows.length < 
maxParameterRowsPerRequest) &&
+          bytes < maxBatchBytes && hasInput) {
+        val row = nextRow()
+        val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null
+        if (requestRow != null && batchKey != null && requestRow != batchKey) {
+          heldRow = row
+          keyChanged = true
+        } else {
+          if (requestRow != null && batchKey == null) batchKey = 
requestRow.copy()
+          bytes += row.getSizeInBytes
+          rows += row
+        }
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /** The stream rows that share a key, and the cached lookup rows that they 
join. */
+  private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      transforms: LookupTransforms,
+      joinOutput: JoinOutput,
+      cache: Option[LookupCache],
+      inputRemains: () => Boolean,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct request row that can match and is not 
cached, in the order of
+    // first occurrence. A row that can never match, because it fails the 
stream condition or has a
+    // null parameter, is finished right away, and its parameters are not 
requested. The stream
+    // condition is checked before the parameters are evaluated, so that it 
can guard their
+    // expressions. A request row is classified once, on its first occurrence, 
as a cache hit or a
+    // row to request: every path fans out to all the rows sharing it, so it 
must not be both, e.g.
+    // across a TTL boundary.
+    private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey]
+    private val keyEntries = {
+      val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+      rows.indices.foreach { index =>
+        lazy val requestRow = parameters.requestRow(rows(index))
+        if (!joinOutput.canMatch(rows(index)) || 
parameters.matchesNothing(requestRow)) {
+          finish(index)
+        } else {
+          entries.get(requestRow).map(_.rowIndexes)
+            .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match {
+            case Some(rowIndexes) => rowIndexes += index
+            case None =>
+              val retained = requestRow.copy()
+              cache.flatMap(_.get(retained)) match {
+                case Some(lookupRows) =>
+                  metrics.cacheHits += 1
+                  cachedKeys.put(retained, CachedKey(lookupRows, 
mutable.ArrayBuffer(index)))
+                case None => entries.put(retained, KeyEntry(retained, 
mutable.ArrayBuffer(index)))
+              }
+          }
+        }
+      }
+      entries.values.toArray
+    }
+    cachedKeys.values.foreach { cached =>
+      cached.rowIndexes.foreach { index =>
+        cached.lookupRows.foreach(joinMatch(index, _))

Review Comment:
   **Non-blocking (P2):** The constructor joins every cache hit up front: for 
each stream row of each cached key it runs `joinMatch` against all of the key's 
cached rows, so every (stream row, cached row) output is queued in `pending` 
before the batch returns its first row and before the request for the uncached 
keys is sent. The cursor path reads the next connector row only when `pending` 
is empty, so it never holds more than one pending row per stream row.
   
   By this review's reading of the code, with the default 16m `maxBytes` a key 
can cache about 11,000 rows of an INT and a short STRING (1 MiB at 92 bytes a 
row), so a later batch of 1,000 stream rows that hits such keys queues about 11 
million tuples, each a `Tuple2`, a boxed index and a queue slot: roughly half a 
gigabyte per task, on the heap and outside both `maxBytes` and the task memory 
manager. A fan-out of 1,000 rows already queues about 45 MB, and neither a 
downstream limit nor a task kill stops the expansion. Results are unchanged.
   
   Draining the hits lazily, the way the cursor path drains connector rows (one 
cached row at a time, joined with every stream row of its key, before the 
cursor advances), keeps the same rows and metrics within the cursor path's 
bound.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60087#discussion_r4515369777), 
[2](https://github.com/apache/spark/pull/60087#pullrequestreview-5829323099).
   
   **Verification:**
   - **Regression:** Under a downstream limit of one row, a later batch whose 
stream row hits a key that an earlier batch cached without a match returns one 
row and never evaluates the residual condition on the key's later cached rows: 
a residual that fails only when that stream row meets a later cached row does 
not fail, while today it fails as the batch is built.
   - **Behavior:** Inner, left outer, left semi and left anti joins over 
batches that mix cache hits, including a hit key repeated within one batch, 
with requested keys return the same rows and the same cache-hit and request 
counts as before.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,861 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import com.google.common.base.Ticker
+import com.google.common.cache.{Cache, CacheBuilder, Weigher}
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each 
batch it sends one
+ * request with the distinct parameters that can match and are not cached, and 
streams the
+ * connector's result rows into output rows. Parameters are deduplicated 
within a batch. With the
+ * cache enabled, a key whose complete result an earlier request of the same 
input partition
+ * returned is served from the cache, within the cache's bounds; otherwise a 
key repeated in a
+ * later batch is requested again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    oneKeyPerBatch: Boolean,
+    maxBatchBytes: Long,
+    cacheOptions: ExternalLookupCacheOptions,
+    cacheTicker: Ticker,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val transforms = new LookupTransforms(partitionIndex)
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private var cache = if (cacheOptions.enabled) Some(new LookupCache) else 
None
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
transforms, joinOutput, cache,
+            inputRemains = () => !inputExhausted, reader = reader)
+        }
+        inputExhausted = !hasInput
+      }
+      // No later batch reads the cache, so neither it nor the drained batch 
is kept.
+      if (inputExhausted && !batch.hasNext) {
+        batch = Iterator.empty
+        cache = None
+        reader.close()
+      }
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes the stream
+    // rows of one key rather than one stream row. It ends before the first 
row with another key,
+    // which starts the next batch. A row that cannot match has no key, and 
any batch takes it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    private def nextRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      input.next() match {
+        case unsafe: UnsafeRow => unsafe.copy()
+        case other => toUnsafe(other).copy()
+      }
+    }
+
+    /** The request row of a stream row that can match, in a reused row, or 
null. */
+    private def requestRowOf(row: InternalRow): UnsafeRow =
+      if (!joinOutput.canMatch(row)) null else {
+        val requestRow = parameters.requestRow(row)
+        if (parameters.matchesNothing(requestRow)) null else requestRow
+      }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows, or at another key with one key per batch. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && (oneKeyPerBatch || rows.length < 
maxParameterRowsPerRequest) &&
+          bytes < maxBatchBytes && hasInput) {
+        val row = nextRow()
+        val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null
+        if (requestRow != null && batchKey != null && requestRow != batchKey) {
+          heldRow = row
+          keyChanged = true
+        } else {
+          if (requestRow != null && batchKey == null) batchKey = 
requestRow.copy()
+          bytes += row.getSizeInBytes
+          rows += row
+        }
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /** The stream rows that share a key, and the cached lookup rows that they 
join. */
+  private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      transforms: LookupTransforms,
+      joinOutput: JoinOutput,
+      cache: Option[LookupCache],
+      inputRemains: () => Boolean,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct request row that can match and is not 
cached, in the order of
+    // first occurrence. A row that can never match, because it fails the 
stream condition or has a
+    // null parameter, is finished right away, and its parameters are not 
requested. The stream
+    // condition is checked before the parameters are evaluated, so that it 
can guard their
+    // expressions. A request row is classified once, on its first occurrence, 
as a cache hit or a
+    // row to request: every path fans out to all the rows sharing it, so it 
must not be both, e.g.
+    // across a TTL boundary.
+    private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey]
+    private val keyEntries = {
+      val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+      rows.indices.foreach { index =>
+        lazy val requestRow = parameters.requestRow(rows(index))
+        if (!joinOutput.canMatch(rows(index)) || 
parameters.matchesNothing(requestRow)) {
+          finish(index)
+        } else {
+          entries.get(requestRow).map(_.rowIndexes)
+            .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match {
+            case Some(rowIndexes) => rowIndexes += index
+            case None =>
+              val retained = requestRow.copy()
+              cache.flatMap(_.get(retained)) match {
+                case Some(lookupRows) =>
+                  metrics.cacheHits += 1
+                  cachedKeys.put(retained, CachedKey(lookupRows, 
mutable.ArrayBuffer(index)))
+                case None => entries.put(retained, KeyEntry(retained, 
mutable.ArrayBuffer(index)))
+              }
+          }
+        }
+      }
+      entries.values.toArray
+    }
+    cachedKeys.values.foreach { cached =>
+      cached.rowIndexes.foreach { index =>
+        cached.lookupRows.foreach(joinMatch(index, _))
+        finish(index)
+      }
+    }
+
+    // Only a later batch of the partition reads what this one caches, so the 
last batch caches
+    // nothing. The partition knows whether input remains once the request is 
sent, before its
+    // results are read.
+    private lazy val cacheWriter = if (!inputRemains()) None else {
+      cache.map(new CacheWriter(_, keyEntries.map(_.requestRow)))
+    }
+
+    // No connector request, and no reader, when no key can match.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else connectorCall(reader.lookup(keyEntries.map(_.requestRow)))
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // The join checks for a close() before each connector call, so it 
makes none after it
+          // has seen one.
+          val start = System.nanoTime()
+          reader.ensureOpen()
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          metrics.lookupTime += System.nanoTime() - start
+          if (connectorRow == null) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName, "NULL_RESULT", Map("method" -> 
"ExternalLookupResultCursor.get()"))
+          }
+          val entry = requestedEntry(ordinal)
+          reader.ensureOpen()
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) {
+            transforms(resultRow).foreach { lookupRow =>
+              cacheWriter.foreach(_.add(entry.requestRow, lookupRow))
+              entry.rowIndexes.foreach(joinMatch(_, lookupRow))
+            }
+          }
+        }
+        if (pending.isEmpty) finishCursor(completed = true)
+      } catch {
+        case error: Throwable =>
+          Utils.tryWithSafeFinally(throw error) {
+            finishCursor(completed = false)
+          }
+      }
+    }
+
+    /**
+     * Advances the connector's cursor, unless the reader was closed 
meanwhile. A close() while
+     * next() ran fails the read once next() returns: Spark then reads no row 
from the closed
+     * cursor, and does not take a missing row for a complete result.
+     */
+    private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && {
+      reader.ensureOpen()
+      val advanced = connectorCall(cursor.next())
+      reader.ensureOpen()
+      advanced
+    }
+
+    /**
+     * Runs a connector call and adds its time to the lookup time metric, 
which counts only the
+     * time in the connector, not that of the work above the join while a 
cursor is open.
+     */
+    private def connectorCall[T](call: => T): T = {
+      val start = System.nanoTime()
+      try call finally metrics.lookupTime += System.nanoTime() - start
+    }
+
+    private def requestedEntry(ordinal: Int): KeyEntry = {
+      if (ordinal < 0 || ordinal >= keyEntries.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
keyEntries.length.toString))
+      }
+      keyEntries(ordinal)
+    }
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      // A semi or anti join knows a stream row's answer at its first match, 
so it evaluates the
+      // residual condition no further for that row, as the other join 
operators do. It still
+      // reads the whole result, for the other stream rows of the key.
+      if (!(joinOutput.answeredByFirstMatch && matched(index)) &&
+          joinOutput.matches(rows(index), lookupRow)) {
+        val firstMatch = !matched(index)
+        matched(index) = true
+        joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _))
+      }
+    }
+
+    /**
+     * Closes the cursor once. After a complete read, caches the results and 
finishes every stream
+     * row that was waiting for them. After a failure or a close, the results 
may be partial, so it
+     * caches nothing and finishes no row: a row without a match could be a 
row whose match was
+     * never read. A failure fails the task, which discards the cache, and the 
join never retries a
+     * request. Once the reader is closed, its close owns the cursor and the 
reader's metrics, so
+     * the join makes no further connector call.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      if (!reader.isClosed) {
+        try {
+          connectorCall(reader.closeCursor())
+        } finally {
+          reader.updateMetrics()
+        }
+      }
+      if (completed) {
+        cacheWriter.foreach(_.write())
+        keyEntries.foreach(_.rowIndexes.foreach(finish))
+      }
+    }
+
+    private def finish(index: Int): Unit = if (!finished.contains(index)) {
+      finished += index
+      if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _))
+    }
+
+    private def emit(index: Int, lookupRow: InternalRow): Unit = {
+      pending.enqueue(index -> lookupRow)
+      metrics.outputRows += 1
+    }
+  }
+
+  /**
+   * The lookup results by key, within a task, per input partition (a task 
that reads several input
+   * partitions, e.g. after coalesce, has one cache per partition). Once its 
entries take more than
+   * `maxBytes`, the least recently used ones are evicted; an entry expires 
once it is older than
+   * the TTL, by `cacheTicker`. An entry takes the bytes of its key and of its 
rows, with the
+   * objects that hold each row, plus a fixed overhead, so that a key without 
a result counts too.
+   * Its keys and rows are the batches' own copies, which are never changed.
+   */
+  private class LookupCache {
+    // One segment, so that eviction is exactly least recently used, and 
bounded by `maxBytes`.
+    private val entries: Cache[UnsafeRow, Array[UnsafeRow]] = {
+      val builder = CacheBuilder.newBuilder()
+        .concurrencyLevel(1)
+        .maximumWeight(cacheOptions.maxBytes)
+        .weigher(new Weigher[UnsafeRow, Array[UnsafeRow]] {
+          override def weigh(key: UnsafeRow, rows: Array[UnsafeRow]): Int = {
+            val bytes = 
ExternalLookupJoinEvaluatorFactory.CACHE_ENTRY_OVERHEAD_BYTES +
+              key.getSizeInBytes +
+              
rows.iterator.map(ExternalLookupJoinEvaluatorFactory.cachedBytes).sum
+            math.min(bytes, Int.MaxValue).toInt
+          }
+        })
+        .ticker(cacheTicker)
+      val expiring = if (cacheOptions.ttlMillis > 0) {
+        builder.expireAfterWrite(cacheOptions.ttlMillis, TimeUnit.MILLISECONDS)
+      } else {
+        builder
+      }
+      expiring.build[UnsafeRow, Array[UnsafeRow]]()
+    }
+
+    def get(key: UnsafeRow): Option[Array[UnsafeRow]] = 
Option(entries.getIfPresent(key))
+
+    def put(key: UnsafeRow, values: Array[UnsafeRow]): Unit = entries.put(key, 
values)
+  }
+
+  /**
+   * Collects the result rows of one request by key, and caches them once the 
cursor is done. It
+   * receives only the rows that satisfy the selected lookup predicates, so 
the cache never holds a
+   * row that Spark's check dropped. A key whose rows take more than a
+   * [[ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE]]th of `maxBytes` is 
not cached, so that
+   * one large result cannot evict most of the cache, and the request holds at 
most `maxBytes` of
+   * rows for the cache, which could keep no more; a key whose rows would pass 
that is not cached
+   * either. Such a key is still joined in full. The rows are the batch's own 
copies, which are
+   * never changed.
+   */
+  private class CacheWriter(cache: LookupCache, keys: Array[UnsafeRow]) {
+    private class KeyResults(val rows: mutable.ArrayBuffer[UnsafeRow], var 
bytes: Long)
+    private val maxKeyBytes =
+      cacheOptions.maxBytes / 
ExternalLookupJoinEvaluatorFactory.CACHE_KEY_SHARE
+    private val resultsByKey =
+      mutable.HashMap.from(keys.map(_ -> new 
KeyResults(mutable.ArrayBuffer.empty, 0L)))
+    private val uncacheable = mutable.HashSet.empty[UnsafeRow]
+    private var bufferedBytes = 0L
+
+    def add(key: UnsafeRow, lookupRow: UnsafeRow): Unit = if 
(!uncacheable.contains(key)) {
+      val results = resultsByKey(key)
+      val rowBytes = ExternalLookupJoinEvaluatorFactory.cachedBytes(lookupRow)
+      if (results.bytes + rowBytes > maxKeyBytes ||
+          bufferedBytes + rowBytes > cacheOptions.maxBytes) {

Review Comment:
   **Non-blocking (P2):** This second condition keeps the rows that one request 
buffers for the cache within `maxBytes`, besides the per-key cutoff of 
`maxBytes/16`, but no test makes it decide. In 'external lookup cache evicts 
least recently used entries at the configured bound' the keys return no rows; 
'a key whose rows take more than a sixteenth of the cache is joined but not 
cached' buffers at most 184 of 1,472 bytes (n = 1) and 552 of 4,416 (n = 3); 
and the other `cache_max_bytes` tests only parse or merge the option.
   
   By this review's reading of the suite, deleting the condition would leave 
every test passing, while one request of up to 1,000 keys could then buffer up 
to 1,000 x `maxBytes/16` of rows, about 62 times `maxBytes` or 1 GiB at the 16m 
default, until its cursor ends, and would cache keys that a later batch should 
request again.
   
   A test with one request that is not the partition's last, whose keys' rows 
each fit `maxBytes/16` but together pass `maxBytes`, asserting that the next 
batch hits the earlier keys and requests the crossing one again, would pin it.
   
   **Verification:**
   - **Regression:** A request whose cacheable keys' rows together exceed 
maxBytes leaves uncached the key whose rows would take the request's buffered 
rows past maxBytes, while the keys before it stay cached, so the next batch 
serves those keys from the cache and requests the crossing key again.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,861 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import com.google.common.base.Ticker
+import com.google.common.cache.{Cache, CacheBuilder, Weigher}
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time, or with `oneKeyPerBatch`, of the stream rows of one key. For each 
batch it sends one
+ * request with the distinct parameters that can match and are not cached, and 
streams the
+ * connector's result rows into output rows. Parameters are deduplicated 
within a batch. With the
+ * cache enabled, a key whose complete result an earlier request of the same 
input partition
+ * returned is served from the cache, within the cache's bounds; otherwise a 
key repeated in a
+ * later batch is requested again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    oneKeyPerBatch: Boolean,
+    maxBatchBytes: Long,
+    cacheOptions: ExternalLookupCacheOptions,
+    cacheTicker: Ticker,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val transforms = new LookupTransforms(partitionIndex)
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private var cache = if (cacheOptions.enabled) Some(new LookupCache) else 
None
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
transforms, joinOutput, cache,
+            inputRemains = () => !inputExhausted, reader = reader)
+        }
+        inputExhausted = !hasInput
+      }
+      // No later batch reads the cache, so neither it nor the drained batch 
is kept.
+      if (inputExhausted && !batch.hasNext) {
+        batch = Iterator.empty
+        cache = None
+        reader.close()
+      }
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes the stream
+    // rows of one key rather than one stream row. It ends before the first 
row with another key,
+    // which starts the next batch. A row that cannot match has no key, and 
any batch takes it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    private def nextRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      input.next() match {
+        case unsafe: UnsafeRow => unsafe.copy()
+        case other => toUnsafe(other).copy()
+      }
+    }
+
+    /** The request row of a stream row that can match, in a reused row, or 
null. */
+    private def requestRowOf(row: InternalRow): UnsafeRow =
+      if (!joinOutput.canMatch(row)) null else {
+        val requestRow = parameters.requestRow(row)
+        if (parameters.matchesNothing(requestRow)) null else requestRow
+      }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows, or at another key with one key per batch. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && (oneKeyPerBatch || rows.length < 
maxParameterRowsPerRequest) &&
+          bytes < maxBatchBytes && hasInput) {
+        val row = nextRow()
+        val requestRow = if (oneKeyPerBatch) requestRowOf(row) else null
+        if (requestRow != null && batchKey != null && requestRow != batchKey) {
+          heldRow = row
+          keyChanged = true
+        } else {
+          if (requestRow != null && batchKey == null) batchKey = 
requestRow.copy()
+          bytes += row.getSizeInBytes
+          rows += row
+        }
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /** The stream rows that share a key, and the cached lookup rows that they 
join. */
+  private case class CachedKey(lookupRows: Array[UnsafeRow], rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      transforms: LookupTransforms,
+      joinOutput: JoinOutput,
+      cache: Option[LookupCache],
+      inputRemains: () => Boolean,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct request row that can match and is not 
cached, in the order of
+    // first occurrence. A row that can never match, because it fails the 
stream condition or has a
+    // null parameter, is finished right away, and its parameters are not 
requested. The stream
+    // condition is checked before the parameters are evaluated, so that it 
can guard their
+    // expressions. A request row is classified once, on its first occurrence, 
as a cache hit or a
+    // row to request: every path fans out to all the rows sharing it, so it 
must not be both, e.g.
+    // across a TTL boundary.
+    private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey]
+    private val keyEntries = {
+      val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+      rows.indices.foreach { index =>
+        lazy val requestRow = parameters.requestRow(rows(index))
+        if (!joinOutput.canMatch(rows(index)) || 
parameters.matchesNothing(requestRow)) {
+          finish(index)
+        } else {
+          entries.get(requestRow).map(_.rowIndexes)
+            .orElse(cachedKeys.get(requestRow).map(_.rowIndexes)) match {
+            case Some(rowIndexes) => rowIndexes += index
+            case None =>
+              val retained = requestRow.copy()
+              cache.flatMap(_.get(retained)) match {
+                case Some(lookupRows) =>
+                  metrics.cacheHits += 1
+                  cachedKeys.put(retained, CachedKey(lookupRows, 
mutable.ArrayBuffer(index)))
+                case None => entries.put(retained, KeyEntry(retained, 
mutable.ArrayBuffer(index)))
+              }
+          }
+        }
+      }
+      entries.values.toArray
+    }
+    cachedKeys.values.foreach { cached =>
+      cached.rowIndexes.foreach { index =>
+        cached.lookupRows.foreach(joinMatch(index, _))
+        finish(index)
+      }
+    }
+
+    // Only a later batch of the partition reads what this one caches, so the 
last batch caches
+    // nothing. The partition knows whether input remains once the request is 
sent, before its
+    // results are read.
+    private lazy val cacheWriter = if (!inputRemains()) None else {
+      cache.map(new CacheWriter(_, keyEntries.map(_.requestRow)))
+    }
+
+    // No connector request, and no reader, when no key can match.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else connectorCall(reader.lookup(keyEntries.map(_.requestRow)))
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // The join checks for a close() before each connector call, so it 
makes none after it
+          // has seen one.
+          val start = System.nanoTime()
+          reader.ensureOpen()
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          metrics.lookupTime += System.nanoTime() - start
+          if (connectorRow == null) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName, "NULL_RESULT", Map("method" -> 
"ExternalLookupResultCursor.get()"))
+          }
+          val entry = requestedEntry(ordinal)
+          reader.ensureOpen()
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) {
+            transforms(resultRow).foreach { lookupRow =>
+              cacheWriter.foreach(_.add(entry.requestRow, lookupRow))
+              entry.rowIndexes.foreach(joinMatch(_, lookupRow))
+            }
+          }
+        }
+        if (pending.isEmpty) finishCursor(completed = true)
+      } catch {
+        case error: Throwable =>
+          Utils.tryWithSafeFinally(throw error) {
+            finishCursor(completed = false)
+          }
+      }
+    }
+
+    /**
+     * Advances the connector's cursor, unless the reader was closed 
meanwhile. A close() while
+     * next() ran fails the read once next() returns: Spark then reads no row 
from the closed
+     * cursor, and does not take a missing row for a complete result.
+     */
+    private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && {
+      reader.ensureOpen()
+      val advanced = connectorCall(cursor.next())
+      reader.ensureOpen()
+      advanced
+    }
+
+    /**
+     * Runs a connector call and adds its time to the lookup time metric, 
which counts only the
+     * time in the connector, not that of the work above the join while a 
cursor is open.
+     */
+    private def connectorCall[T](call: => T): T = {
+      val start = System.nanoTime()
+      try call finally metrics.lookupTime += System.nanoTime() - start
+    }
+
+    private def requestedEntry(ordinal: Int): KeyEntry = {
+      if (ordinal < 0 || ordinal >= keyEntries.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
keyEntries.length.toString))
+      }
+      keyEntries(ordinal)
+    }
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      // A semi or anti join knows a stream row's answer at its first match, 
so it evaluates the
+      // residual condition no further for that row, as the other join 
operators do. It still
+      // reads the whole result, for the other stream rows of the key.
+      if (!(joinOutput.answeredByFirstMatch && matched(index)) &&
+          joinOutput.matches(rows(index), lookupRow)) {
+        val firstMatch = !matched(index)
+        matched(index) = true
+        joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _))
+      }
+    }
+
+    /**
+     * Closes the cursor once. After a complete read, caches the results and 
finishes every stream
+     * row that was waiting for them. After a failure or a close, the results 
may be partial, so it
+     * caches nothing and finishes no row: a row without a match could be a 
row whose match was
+     * never read. A failure fails the task, which discards the cache, and the 
join never retries a
+     * request. Once the reader is closed, its close owns the cursor and the 
reader's metrics, so
+     * the join makes no further connector call.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      if (!reader.isClosed) {
+        try {
+          connectorCall(reader.closeCursor())
+        } finally {
+          reader.updateMetrics()
+        }
+      }
+      if (completed) {
+        cacheWriter.foreach(_.write())
+        keyEntries.foreach(_.rowIndexes.foreach(finish))
+      }
+    }
+
+    private def finish(index: Int): Unit = if (!finished.contains(index)) {
+      finished += index
+      if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _))
+    }
+
+    private def emit(index: Int, lookupRow: InternalRow): Unit = {
+      pending.enqueue(index -> lookupRow)
+      metrics.outputRows += 1
+    }
+  }
+
+  /**
+   * The lookup results by key, within a task, per input partition (a task 
that reads several input
+   * partitions, e.g. after coalesce, has one cache per partition). Once its 
entries take more than
+   * `maxBytes`, the least recently used ones are evicted; an entry expires 
once it is older than
+   * the TTL, by `cacheTicker`. An entry takes the bytes of its key and of its 
rows, with the
+   * objects that hold each row, plus a fixed overhead, so that a key without 
a result counts too.
+   * Its keys and rows are the batches' own copies, which are never changed.
+   */
+  private class LookupCache {
+    // One segment, so that eviction is exactly least recently used, and 
bounded by `maxBytes`.
+    private val entries: Cache[UnsafeRow, Array[UnsafeRow]] = {
+      val builder = CacheBuilder.newBuilder()
+        .concurrencyLevel(1)
+        .maximumWeight(cacheOptions.maxBytes)
+        .weigher(new Weigher[UnsafeRow, Array[UnsafeRow]] {
+          override def weigh(key: UnsafeRow, rows: Array[UnsafeRow]): Int = {
+            val bytes = 
ExternalLookupJoinEvaluatorFactory.CACHE_ENTRY_OVERHEAD_BYTES +
+              key.getSizeInBytes +
+              
rows.iterator.map(ExternalLookupJoinEvaluatorFactory.cachedBytes).sum
+            math.min(bytes, Int.MaxValue).toInt
+          }
+        })
+        .ticker(cacheTicker)
+      val expiring = if (cacheOptions.ttlMillis > 0) {
+        builder.expireAfterWrite(cacheOptions.ttlMillis, TimeUnit.MILLISECONDS)

Review Comment:
   **Nit (P3):** The TTL counts from an entry's write, but by this review's 
reading neither TTL test would fail if this became `expireAfterAccess`. 
'external lookup cache TTL expires entries' writes the entry at t = 0 and 
probes it only after the clock has passed the TTL, and in 'a cache entry 
expiring between duplicate keys in one batch is looked up once' the hit at 
reading 3 is still at t = 0, the write's time.
   
   A change that let a key hit at least once per TTL stay cached for the rest 
of its partition, which defeats the long micro-batches the TTL is kept for, 
would ship with no failing test. Hitting the entry before the TTL passes, then 
probing once the TTL has passed since the write but not since the hit and 
asserting a new request, would pin the write age.
   
   **Verification:**
   - **Regression:** An entry that a batch hits before its TTL passes is still 
requested again by a batch that comes once the TTL has passed since the entry's 
write, although less than the TTL has passed since the hit.



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

Review Comment:
   **Nit (P3):** This is a `timeConf(TimeUnit.MILLISECONDS)`, but neither its 
name nor its doc gives a unit, so `SET 
spark.sql.join.externalLookup.cache.ttl=60`, meant as a minute, is read as a 60 
ms TTL without error, and almost every later probe then finds its entry expired 
and requests the key again: more requests, no wrong result. The hint option 
`cache_ttl` reads a bare number the same way, and its error text gives only 
suffixed examples.
   
   The guideline in `ConfigEntry.scala` asks a new duration config to put its 
unit in its name, as in `featureName.timeoutMs`, which 
`spark.sql.metadataCacheTTLSeconds` and this feature's own `maxBytes` and 
`maxBatchBytes` follow; most SQL time configs that leave the unit out of the 
name state it in their doc instead, as in 'Timeout in seconds ...'. Renaming 
the key with its unit, for example `spark.sql.join.externalLookup.cache.ttlMs`, 
costs only a rename while it is unreleased; at the least, the doc and the hint 
option's expected text should say that a number without a unit is in 
milliseconds.
   
   **Verification:**
   - **Behavior:** Setting the renamed TTL configuration, as a time string or 
as a bare number of milliseconds, gives the join that TTL, and cache_ttl in the 
hint still overrides it.
   - **Inspection:** No reference to the old configuration key remains, and the 
configuration's doc and the hint option's expected-value text state the unit of 
a bare number.



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

Review Comment:
   **Nit (P3):** `LookupCache` weighs an entry as these 64 bytes plus its key's 
and rows' data, and charges each row its data plus `CACHE_ROW_OVERHEAD_BYTES`, 
which counts the objects that hold the row: a 40-byte `UnsafeRow`, the 16-byte 
header of its data array and a 4-byte reference. By the same accounting, the 
key copy's `UnsafeRow` and data-array header take 56 bytes and the entry's 
`Array[UnsafeRow]` header 16 more, 72 bytes before Guava's own per-entry 
objects (its entry with access and write links, the weighted value reference 
and a table slot).
   
   So a cached miss for a one-INT key is weighed at 80 bytes but holds at least 
88 bytes of Spark objects, and, by this review's estimate of Guava's objects, 
about twice its weight. A cache of row-less or one-row entries, as a left outer 
or left anti join against a sparse table builds, can then hold roughly twice 
`maxBytes` on the heap, about 34 MiB at the 16m default, outside the task 
memory manager; entries with many rows are counted accurately.
   
   Counting the key's objects, the rows array header and an estimate of Guava's 
per-entry objects here, with the breakdown documented as it is for 
`CACHE_ROW_OVERHEAD_BYTES`, keeps the bound honest; the LRU test's 200-byte 
bound moves with it.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60087#discussion_r4515369777), 
[2](https://github.com/apache/spark/pull/60087#pullrequestreview-5829323099).
   
   **Verification:**
   - **Inspection:** The entry overhead's documentation lists each object it 
counts, and its value is at least the key's UnsafeRow object, the key's byte 
array header and the rows array header by the same accounting as the row 
overhead, plus an estimate of Guava's per-entry objects.
   - **Regression:** With entries for keys without rows, the cache keeps 
exactly as many of them as the new entry weight fits in its byte bound, and 
evicts the least recently used one when another arrives.



##########
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)
+    } else {
+      // As with join strategy hints, a name marks every relation that it 
matches. `matched` only
+      // tells which names matched nothing.
+      val matched = mutable.HashSet.empty[Seq[String]]
+      def matches(identifier: Seq[String]): Boolean = {
+        val names = relationNames.filter { name =>
+          ResolveHints.matchedIdentifier(name, identifier, conf.resolver)
+        }
+        matched ++= names
+        names.nonEmpty
+      }
+      // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: 
a name matches an
+      // unaliased (possibly multipart) table or an alias, and does not reach 
into a view,
+      // a WITH clause, or an aliased subquery.
+      def applyHint(plan: LogicalPlan): LogicalPlan = plan match {
+        case relation: UnresolvedRelation if 
matches(relation.multipartIdentifier) =>
+          ExternalLookupHint(relation, cacheOptions)
+        case alias: SubqueryAlias
+            if matches(alias.identifier.qualifier :+ alias.identifier.name) =>
+          ExternalLookupHint(alias, cacheOptions)
+        case _: View | _: UnresolvedWith | _: SubqueryAlias => plan
+        case _ => plan.mapChildren(applyHint)
+      }
+      val rewritten = applyHint(child)
+      val missing = relationNames.filterNot(matched.contains)
+      if (missing.nonEmpty) {
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "RELATION_NOT_FOUND", Map("relations" -> 
missing.map(toSQLId).mkString(", ")))
+      }
+      rewritten
+    }
+  }
+
+  private[analysis] def defaultCacheOptions: ExternalLookupCacheOptions = {

Review Comment:
   Thanks, verified: maxBytes and ttl are now set through the session 
configuration in the tests of eviction, the per-key cutoff and expiry, and the 
test where a hint sets only cache_max_bytes shows the unset option following 
the configuration.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4518337247","thread_id":"inline:4518337247","verdict_sha256":"9215fd188929def83fce370374e2518354a42e8d0b48e16b7cff1ab8ecbae581"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2530,6 +2530,76 @@ object SQLConf {
     .bytesConf(ByteUnit.BYTE)
     .createWithDefault(8L << 30)
 
+  val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES =
+    buildConf("spark.sql.join.externalLookup.maxBatchBytes")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("Size in bytes of input rows at which an external lookup join stops 
adding rows to " +
+        "a lookup request. The row that reaches this size stays in the 
request, so a request " +
+        "can exceed it by one row. A request always takes at least one row, 
and never more rows " +
+        "than the source allows, or 1000.")
+      .version("4.4.0")
+      .bytesConf(ByteUnit.BYTE)
+      .checkValue(_ > 0, "External lookup join max batch bytes must be 
positive")
+      .createWithDefaultString("64m")
+
+  val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED =
+    buildConf("spark.sql.join.externalLookup.startupCheck.enabled")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("When true, starting a streaming query plans its external lookup 
joins once, " +
+        "including the planning calls to their connectors, so that a join that 
cannot be " +
+        "planned fails the start instead of the first micro-batch. When false, 
such a join " +
+        "fails the first micro-batch that runs.")
+      .version("4.4.0")
+      .booleanConf
+      .createWithDefault(true)
+
+  val JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED =
+    buildConf("spark.sql.join.externalLookup.cache.enabled")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .doc("When true, external lookup join caches the complete lookup result 
of each key, " +
+        "including a key with no result, within a task, per input partition (a 
task that reads " +
+        "several input partitions, e.g. after coalesce, has one cache per 
partition). A cached " +
+        "result is reused as it was read. At present, a join whose source 
serves a range " +
+        "comparison (<, <=, >, >=) caches nothing. It can be overridden per 
join with the " +

Review Comment:
   Thanks, verified: the doc now names the configuration as what the hint 
option overrides, and says that neither of them turns the cache on for a range 
lookup.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4518337258","thread_id":"inline:4518337258","verdict_sha256":"9215fd188929def83fce370374e2518354a42e8d0b48e16b7cff1ab8ecbae581"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.optimizer.{EliminateResolvedHint, 
InlineCTE}
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupCacheOptions, ExternalLookupHint, ExternalLookupJoin, 
ExternalLookupJoinShapes,
+  Filter, Join, JoinStrategyHint, LogicalPlan, Project, ResolvedHint, 
SubqueryAlias, UnaryNode,
+  View, WithCTE}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CTE, 
DATA_SOURCE_V2_RELATION,
+  EXTERNAL_LOOKUP_HINT, JOIN}
+import org.apache.spark.sql.catalyst.util.MetadataColumnHelper
+import org.apache.spark.sql.connector.catalog.TableCapability
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
+
+/**
+ * Classifies a join for external lookup. [[CheckExternalLookupJoin]] and 
[[FormExternalLookupJoin]]
+ * share it, so analysis rejects every join that the optimizer cannot convert, 
except one without
+ * a condition: see [[CheckExternalLookupJoin]].
+ *
+ * A join is an external lookup join when its right side reads a table that 
supports external
+ * lookup but not batch read, or when the right side carries an 
`EXTERNAL_LOOKUP` hint. A table
+ * that supports both keeps the ordinary join strategies unless the hint opts 
in. It must be a
+ * stream-static join: the left side is a streaming query, whose micro-batches 
tolerate lookup
+ * results that change between requests, and the lookup table is on the right 
side. The join reads
+ * the table directly, or through hints, aliases, views, and projections and 
filters that it can
+ * evaluate on the lookup results, so a join that must be a lookup join either 
runs as one or fails
+ * here, whatever the optimizer later does to its lookup side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+  sealed trait Eligibility
+  /**
+   * The join stays an ordinary join: it has no `EXTERNAL_LOOKUP` hint, and 
neither of its inputs is
+   * a lookup-only relation, directly or below unary operators. A lookup-only 
relation below another
+   * operator, such as a union, is not recognized, and fails later as a batch 
scan.
+   */
+  case object NotLookupJoin extends Eligibility
+  /** The join runs as an external lookup join. */
+  case object Eligible extends Eligibility
+  /**
+   * The join must run as an external lookup join, with a supported join type, 
but has no
+   * condition.
+   */
+  case object MissingCondition extends Eligibility
+  /** The join must run as an external lookup join but cannot. */
+  case class Ineligible(error: Throwable) extends Eligibility
+
+  private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter, LeftSemi, LeftAnti)
+
+  def apply(join: Join): Eligibility = {
+    if (lookupHints(join.left).nonEmpty) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE"))
+    }
+    // The lookup-only table must be on the right side; the sides are never 
swapped.
+    val leftLookupOnlyTable = 
ExternalLookupRelations.lookupOnlyTable(input(join.left))
+    if (leftLookupOnlyTable.isDefined) {
+      return ineligible("LOOKUP_TABLE_ON_LEFT", 
toSQLId(leftLookupOnlyTable.get.name()))
+    }
+    val markers = lookupHints(join.right)
+    val lookupOnly = 
ExternalLookupRelations.lookupOnlyTable(input(join.right)).isDefined
+    // A lookup-only table can be read only by a lookup join, and the hint 
opts a join in. Either
+    // way the join must run as an external lookup join, and the checks below 
apply.
+    if (!lookupOnly && markers.isEmpty) return NotLookupJoin
+    if (markers.length > 1) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("MULTIPLE_HINTS"))
+    }
+    if (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases, 
views, and projections and
+    // filters that the lookup join can evaluate. There is none when another 
operator, or a stage
+    // that it cannot evaluate, stands in between, or the side reads no DSv2 
table.
+    val tableRelation = lookupRelation(join.right)
+    val table = ExternalLookupRelations.table(tableRelation) match {
+      case Some(table) => table
+      case None =>
+        return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN"))
+    }
+    val relation = toSQLId(table.name())
+    if (!table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP)) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "TABLE", Map("table" -> relation)))
+    }
+    // A lookup returns the data columns of the table only. The relation 
outputs a metadata column
+    // only when the query reads one.
+    if (tableRelation.output.exists(_.isMetadataCol)) return 
ineligible("METADATA_COLUMN", relation)
+    if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", relation)
+    // A join hint the user wrote is never silently dropped: an external 
lookup join cannot run a
+    // physical join strategy, and a lookup-only table has no batch scan for 
one. On a table that
+    // also supports batch reads, the strategy hint conflicts with the 
`EXTERNAL_LOOKUP` hint.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) if lookupOnly =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      case Some(strategy) =>
+        Ineligible(QueryCompilationErrors.invalidExternalLookupHintError(
+          "CONFLICTING_JOIN_STRATEGY",
+          Map("strategy" -> toSQLStmt(strategy.displayName), "relation" -> 
relation)))
+      // No physical join was asked for: the join runs as an external lookup 
join unless a check
+      // below fails.
+      // Checked before the condition, so that a cross join fails while it is 
analyzed.
+      case None if !SUPPORTED_JOIN_TYPES.contains(join.joinType) =>
+        ineligible("JOIN_TYPE", relation, Map(
+          "joinType" -> toSQLStmt(join.joinType.sql),
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => 
toSQLStmt(t.sql)).mkString(", ")))
+      case None if join.condition.isEmpty => MissingCondition
+      // The optimizer rewrites a subquery in a join condition only for a 
Join, which a lookup join
+      // no longer is by then.
+      case None if join.condition.exists(SubqueryExpression.hasSubquery) =>
+        ineligible("SUBQUERY_IN_JOIN_CONDITION", relation)
+      case None => Eligible
+    }
+  }
+
+  /** The CTE definitions in `plan` by id, which [[inlineCTEs]] inlines. */
+  def cteDefinitions(plan: LogicalPlan): Map[Long, CTERelationDef] =
+    if (plan.containsPattern(CTE)) {
+      plan.collect { case cteDef: CTERelationDef => cteDef.id -> cteDef }.toMap
+    } else {
+      Map.empty
+    }
+
+  /**
+   * `join` with the CTE references on the paths of unary operators of its 
inputs inlined, as
+   * InlineCTE inlines them for the analysis check. Only these paths decide 
how the join is
+   * classified, and the lookup side of an eligible join is its path alone, so 
it has no other CTE
+   * reference left.
+   */
+  def inlineCTEs(join: Join, cteDefs: Map[Long, CTERelationDef]): Join =
+    if (cteDefs.isEmpty) {
+      join
+    } else {
+      join.copy(
+        left = inlinePathCTEs(join.left, cteDefs),
+        right = inlinePathCTEs(join.right, cteDefs))
+    }
+
+  private def inlinePathCTEs(
+      plan: LogicalPlan,
+      cteDefs: Map[Long, CTERelationDef]): LogicalPlan = plan match {
+    case _ if !plan.containsPattern(CTE) => plan
+    case ref: CTERelationRef if cteDefs.contains(ref.cteId) =>
+      val cteDef = cteDefs(ref.cteId)
+      InlineCTE.inlineReference(ref, cteDef, inlinePathCTEs(cteDef.child, 
cteDefs))
+    case WithCTE(child, _) => inlinePathCTEs(child, cteDefs)
+    case unary: UnaryNode => 
unary.withNewChildren(Seq(inlinePathCTEs(unary.child, cteDefs)))
+    case other => other
+  }
+
+  /**
+   * The plans that external lookup joins in `plan` read by lookups: the 
lookup side of each join
+   * that must run as an external lookup join, and the CTE definitions that 
the side reads,
+   * directly or through other CTE definitions. Subqueries are not searched.
+   */
+  def lookupSidePlans(plan: LogicalPlan): Seq[LogicalPlan] =
+    // As in CheckExternalLookupJoin, other plans have no join that must run 
as a lookup join.
+    if (!plan.containsPattern(JOIN) ||
+        !plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      Nil
+    } else {
+      val cteDefs = cteDefinitions(plan)
+      val lookupSides = plan.collect {
+        case join: Join if apply(inlineCTEs(join, cteDefs)) != NotLookupJoin 
=> join.right
+      }
+      val readCTEs = mutable.LinkedHashMap.empty[Long, CTERelationDef]
+      def addReadCTEs(plan: LogicalPlan): Unit = plan.foreach {
+        case ref: CTERelationRef if !readCTEs.contains(ref.cteId) =>
+          cteDefs.get(ref.cteId).foreach { cteDef =>
+            readCTEs(ref.cteId) = cteDef
+            addReadCTEs(cteDef)
+          }
+        case _ =>
+      }
+      lookupSides.foreach(addReadCTEs)
+      lookupSides ++ readCTEs.values
+    }
+
+  /**
+   * The lookup side of an eligible join, without its `EXTERNAL_LOOKUP` hint. 
The lookup side of an
+   * eligible join is a chain of hints, aliases, views, projections and 
filters over the table, so
+   * every marker in it is the join's own.
+   */
+  def lookupSide(join: Join): LogicalPlan =
+    join.right.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_HINT)) 
{
+      case marker: ExternalLookupHint => marker.child
+    }
+
+  /**
+   * The cache options of an eligible join, with its CTEs inlined by 
[[inlineCTEs]]: its hint's, or
+   * the session defaults.
+   */
+  def cacheOptions(join: Join): ExternalLookupCacheOptions =
+    lookupHints(join.right).headOption.map(_.cacheOptions)
+      .getOrElse(ResolveExternalLookupHint.defaultCacheOptions)
+
+  private def ineligible(
+      subClass: String,
+      relation: String,
+      parameters: Map[String, String] = Map.empty): Ineligible =
+    Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+      subClass, parameters + ("relation" -> relation)))
+
+  /** The relation that a join input reads: the first operator that has no 
single child. */
+  @tailrec
+  private def input(plan: LogicalPlan): LogicalPlan = plan match {
+    case unary: UnaryNode => input(unary.child)
+    case other => other
+  }
+
+  /**
+   * The first operator below a join input that is not a hint, an alias, a 
view, or a projection or
+   * filter that the lookup join can evaluate on the lookup results. A Python 
or external UDF or a
+   * subquery in one cannot be evaluated there, and the optimizer would 
rewrite some of them into
+   * other operators.
+   */
+  @tailrec
+  private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+    case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | 
_: View) =>
+      lookupRelation(node.children.head)
+    case node @ (_: Project | _: Filter)
+        if 
node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) =>
+      lookupRelation(node.children.head)
+    case other => other
+  }
+
+  /**
+   * The `EXTERNAL_LOOKUP` hints on a join input. Like a join strategy hint, 
the hint applies to the
+   * join that the input feeds, through any unary operator.
+   */
+  @tailrec
+  private def lookupHints(
+      plan: LogicalPlan,
+      found: Seq[ExternalLookupHint] = Nil): Seq[ExternalLookupHint] = plan 
match {
+    case marker: ExternalLookupHint => lookupHints(marker.child, found :+ 
marker)
+    case unary: UnaryNode => lookupHints(unary.child, found)
+    case _ => found
+  }
+
+  /**
+   * The physical join strategy hint, such as `BROADCAST` or `MERGE`, that 
EliminateResolvedHint
+   * would attach to the join, or None if there is none. The `EXTERNAL_LOOKUP` 
hint is never
+   * returned: it is an [[ExternalLookupHint]] marker, not a 
[[JoinStrategyHint]]. A `HintInfo`
+   * without a strategy asks for nothing, so it is skipped.
+   */
+  private def joinStrategyHint(join: Join): Option[JoinStrategyHint] = {
+    // Only the hints that EliminateResolvedHint will attach to this join 
count; a strategy hint
+    // on a nested join belongs to that join.
+    val attached = join.hint.leftHint.toSeq ++ join.hint.rightHint.toSeq ++
+      Seq(join.left, 
join.right).flatMap(EliminateResolvedHint.extractHintsFromPlan(_)._2)
+    attached.flatMap(_.strategy).headOption
+  }
+}
+
+/**
+ * Reports, while a query is analyzed, why a join cannot run as the external 
lookup join it must
+ * be. It does not change the plan: the join stays a [[Join]] until 
[[FormExternalLookupJoin]]
+ * converts it, so the APIs and rules that expect an analyzed join keep 
working. A join that is not
+ * resolved, for example one whose condition is not boolean, is left to the 
analyzer's own join
+ * checks.
+ *
+ * A missing join condition is reported only for the query of a streaming 
write, which is analyzed
+ * in full when the query starts, so that `start()` throws it. Other plans can 
still get their
+ * condition: the classic Dataset API analyzes a USING join first as a join 
without a condition.
+ */
+object CheckExternalLookupJoin extends (LogicalPlan => Unit) {
+  override def apply(plan: LogicalPlan): Unit = {
+    // A join must run as a lookup join only over a lookup-only table, which 
is a DSv2 relation, or
+    // under the hint, so other plans need no walk.
+    if (plan.containsPattern(JOIN) &&
+        plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      val complete = plan.isInstanceOf[WriteToStream]
+      plan.foreachUp {
+        case join: Join if join.resolved =>
+          ExternalLookupJoinEligibility(join) match {
+            case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+            case ExternalLookupJoinEligibility.MissingCondition if complete =>
+              throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+                "MISSING_JOIN_CONDITION")
+            case _ =>
+          }
+        case _ =>
+      }
+    }
+  }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an 
[[ExternalLookupJoin]], and
+ * removes the `EXTERNAL_LOOKUP` hints that no join consumed.
+ *
+ * It must run at the start of optimization, before Finish Analysis and 
operator optimization, so
+ * that it sees the join and its lookup side as analysis left them: no hint or 
alias eliminated,
+ * no predicate pushed into the join and no column pruned. These are the 
shapes that
+ * [[CheckExternalLookupJoin]] validated. It also runs before CTEs are 
inlined, so it classifies a
+ * join with the CTEs of its inputs inlined, as the analysis check does, and 
inlines the CTEs of
+ * the lookup side into the lookup join.
+ */
+object FormExternalLookupJoin extends Rule[LogicalPlan] {
+  import ExternalLookupJoinEligibility._
+
+  // As in CheckExternalLookupJoin, a join runs as a lookup join only over a 
lookup-only table,
+  // which is a DSv2 relation, or under the hint, so other plans have no join 
to convert.
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    if (!plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) plan
+    else formLookupJoins(plan)
+
+  private def formLookupJoins(plan: LogicalPlan): LogicalPlan = {
+    val cteDefs = cteDefinitions(plan)
+    val formed = plan.transformUpWithPruning(_.containsPattern(JOIN)) {
+      case join: Join =>
+        val inlined = inlineCTEs(join, cteDefs)

Review Comment:
   Thanks, verified: forming lookup joins, CheckExternalLookupJoin and 
lookupSidePlans now check for the hint or a lookup-only table before they 
collect or inline any CTE, and the new test leaves a CTE self-join over a 
batch-readable table unchanged.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4518337270","thread_id":"inline:4518337270","verdict_sha256":"9215fd188929def83fce370374e2518354a42e8d0b48e16b7cff1ab8ecbae581"}
 -->



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