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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TableCapabilityCheck.scala:
##########
@@ -38,7 +38,14 @@ object TableCapabilityCheck extends (LogicalPlan => Unit) {
 
   override def apply(plan: LogicalPlan): Unit = {
     plan foreach {
-      case r: DataSourceV2Relation if !r.table.supports(BATCH_READ) =>
+      // A table that supports external lookup may be read by a lookup join 
formed later, e.g.
+      // when a DataFrame over it is joined. PrepareExternalLookupJoin rejects 
it when it remains
+      // a plain scan after lookup joins are prepared.
+      case r: DataSourceV2Relation

Review Comment:
   **Blocking (P1):** This arm now lets a lookup-only relation, either the 
`spark.read` placeholder or a catalog reference, pass analysis in any plan, so 
a read outside an eligible lookup join is rejected only when the reading query 
is optimized. Some commands optimize their query only after a destructive side 
effect. With `kv` a lookup-only table and `jdbc.db.t` an existing table in a 
`JDBCTableCatalog`, 
`spark.read.format("kv").load().write.mode("overwrite").saveAsTable("jdbc.db.t")`
 builds a `ReplaceTableAsSelect` that passes analysis and is planned as the 
non-atomic `ReplaceTableAsSelectExec`. Its `run()` drops `jdbc.db.t` and 
creates the new table before `writeToTable` optimizes the query, where 
`PrepareExternalLookupJoin` throws `UNSUPPORTED_FEATURE.TABLE_OPERATION` 
('batch scan'), and the failure handler drops the new table too. The statement 
fails, and the original table and its rows are gone. V1 overwrites have the 
same order: `SaveIntoDataSourceCommand` passes an unoptimize
 d Dataset to `JdbcRelationProvider`, which truncates, or drops and recreates, 
the table before `saveTable` runs the query. On the base branch, `load()` 
failed before any write, and this check rejected a catalog-resolved lookup-only 
table during analysis. (Traced from source, not executed.)
   
   **Recommended change:** Make TableCapabilityCheck reject, during analysis 
and with the batch-scan error that the base branch raised, any command whose 
query reads a table that reports EXTERNAL_LOOKUP without BATCH_READ, either as 
the spark.read placeholder or through a catalog reference, outside a join that 
can become a lookup join, and keep deferring the rejection to 
PrepareExternalLookupJoin for plans that are not commands. Update the comment 
above the relaxed arms to say which plans keep the deferral, and add 
capability-check and lookup join tests showing that overwrite saves, REPLACE 
TABLE AS SELECT and V1 inserts over such a table fail during analysis without 
touching their target.
   
   **Why this works:** TableCapabilityCheck already runs during analysis before 
any command runs, including before HandleSpecialCommand moves an analysis-only 
command's query out of its children. For each command, it would also walk the 
command's query, including a query held as an inner child, as 
SaveIntoDataSourceCommand, InsertIntoDataSourceCommand and analyzed view 
commands hold theirs, and plans inside subquery expressions. A lookup-only 
relation that is a direct child of a join goes through the shared eligibility 
classification, which raises the named lookup join error for a join that cannot 
run and accepts one that can become a lookup join; any other lookup-only 
relation fails with the batch-scan error. Because each traced statement drops, 
truncates or recreates its target only after its command is analyzed, the error 
again precedes the side effect, while spark.read, DataFrames composed into a 
stream-static join and streaming queries keep reaching the optimizer's final 
check u
 nchanged.
   
   **Scope:** An analysis-time rejection of lookup-only reads in commands, 
built into the existing capability check and reusing the lookup join 
eligibility classification, with tests for the destructive statements and for 
the plans that keep the deferred check.
   
   **Compatibility:** spark.read of a lookup-only table still returns a 
DataFrame that a stream-static lookup join can use, and commands and queries 
that read no lookup-only table behave as before.
   
   **Risks:** Commands that this change lets pass analysis over a lookup-only 
table outside a lookup join, including a view defined over a spark.read 
placeholder or a CACHE TABLE statement over such a table, fail during analysis, 
as every such statement failed on the base branch; support for wrapped lookup 
sides would later have to relax the rule for view definitions. The change can 
be rolled back by removing the command walk, which restores the deferred check 
for commands. A command defined outside Spark, for example by a session 
extension, that kept its query outside both its children and its inner children 
would bypass the walk and still fail only when its query is optimized; the 
write commands in Spark that hold a query all expose it to the walk.
   
   **Constraints:** Named lookup join errors keep their precedence: a 
lookup-only relation that is a direct child of a join is judged by the shared 
eligibility classification rather than rejected with the batch-scan error, so 
that a view or other command over a whole stream-static lookup join keeps 
working. The walk must be pruned by the DSv2 relation tree pattern of each plan 
it enters, so that commands that read no DSv2 table pay no extra traversal. The 
final check in PrepareExternalLookupJoin stays as defense in depth for plans 
that are not commands.
   
   **Exclusions:**
   - Plans that are not commands, including DataFrames whose lookup side is 
wrapped in an alias, hint, projection or filter and batch actions over the bare 
table, keep failing when they are optimized; whether they should fail during 
analysis is the open question about wrapped lookup sides.
   - CREATE TEMPORARY VIEW ... USING over a lookup-only table keeps succeeding, 
because it loads the table only when it runs; commands that later read the view 
are rejected during analysis.
   
   **Success:** An overwrite saveAsTable, REPLACE TABLE AS SELECT, or V1 
overwrite save or insert whose query reads a lookup-only table outside a lookup 
join fails during analysis with the batch-scan error, and its target table and 
rows are unchanged. A command whose query reads a lookup-only table through a 
catalog reference or a subquery expression, or that defines a view over one, 
fails during analysis, as on the base branch. spark.read of a lookup-only table 
still returns a DataFrame, a stream-static lookup join over it still runs, and 
a batch action over the bare table still fails when it is optimized.
   
   **Verification:**
   - **Regression:** An overwrite save into an existing table of a V2 catalog 
that does not stage writes, from a query that reads a lookup-only table, fails 
during analysis and leaves the existing table and its rows in place.
   - **Regression:** A V1 overwrite save and a V1 insert overwrite from such a 
query fail before the data source truncates, drops or recreates its target.
   - **Behavior:** A command that reads a lookup-only table only through a 
catalog reference, a subquery expression or a query held outside its children 
fails during analysis with the batch-scan error, and a command over a lookup 
join that cannot run still fails with that join's named error.
   - **Compatibility:** A stream-static lookup join over a spark.read 
lookup-only table still runs, including when a temporary view is defined over 
the whole join, and a batch action over the bare table still fails only when it 
is optimized.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 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, LeftOuter}
+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
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    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 joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      while (rows.length < maxParameterRowsPerRequest && input.hasNext) {
+        rows += input.next().copy()
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    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) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    private val lookupStartNanos = System.nanoTime()
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          reader.ensureOpen()
+          val key = requestedKey(ordinal)
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {
+            joinResultRow(key, resultRow)
+          }
+        }
+        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 = cursor.next()
+      reader.ensureOpen()
+      advanced
+    }
+
+    private def requestedKey(ordinal: Int): UnsafeRow = {
+      if (ordinal < 0 || ordinal >= requestedKeys.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
requestedKeys.length.toString))
+      }
+      requestedKeys(ordinal)
+    }
+
+    private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit =
+      keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow))
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      if (joinOutput.matches(rows(index), lookupRow)) {
+        matched(index) = true
+        joinOutput.matched(lookupRow).foreach(emit(index, _))
+      }
+    }
+
+    /**
+     * Closes the cursor once. After a complete read, finishes every stream 
row that was waiting for
+     * its results. After a failure or a close, the results may be partial, so 
it finishes none:
+     * a row without a match could be a row whose match was never read.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      try {
+        reader.closeCursor()
+      } finally {
+        metrics.lookupTime += System.nanoTime() - lookupStartNanos
+        reader.updateMetrics()
+      }
+      if (completed) keyEntries.values.foreach(_.rowIndexes.foreach(finish))
+    }
+
+    private def finish(index: Int): Unit = if (!finished.contains(index)) {
+      finished += index
+      if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _))
+    }
+
+    private def emit(index: Int, lookupRow: InternalRow): Unit = {
+      pending.enqueue(index -> lookupRow)
+      metrics.outputRows += 1
+    }
+  }
+
+  /** The 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: the request row that is 
sent to the
+   * connector, and the key that identifies equal parameters under Spark 
equality, which
+   * normalizes floating-point values and collations. 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 keyProjection = UnsafeProjection.create(lookupParameters.map { 
parameter =>
+      
NormalizeFloatingNumbers.normalize(CollationKey.injectCollationKey(parameter))
+    }, streamOutput)
+    private val keyCheck = lookupKeyCheck.map(Predicate.create(_))
+    private val requestAndResult = new JoinedRow()
+    requestProjection.initialize(partitionIndex)
+    keyProjection.initialize(partitionIndex)
+    keyCheck.foreach(_.initialize(partitionIndex))
+
+    def requestRow(streamRow: InternalRow): UnsafeRow = 
requestProjection(streamRow).copy()
+
+    /** The key of a stream row, in a reused row: copy it to retain it. */
+    def key(streamRow: InternalRow): UnsafeRow = keyProjection(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.
+     * The key has the request row's nulls.
+     */
+    def matchesNothing(key: InternalRow): Boolean =
+      nullSafeParameters.indices.exists { index =>
+        !nullSafeParameters(index) && key.isNullAt(index)
+      }
+  }
+
+  /**
+   * 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) {
+    // Value rows follow the read schema, and the residual and output are 
bound to its fields.
+    private val joinedLookupInput =
+      if (joinType == LeftOuter) lookupInput.map(_.withNullability(true)) else 
lookupInput
+    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(lookupInput.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))
+
+    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. */
+    def matched(lookupRow: InternalRow): Option[InternalRow] = joinType match {
+      case Inner | LeftOuter => Some(lookupRow)
+      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 => 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. A thread
+   * other than the task's may still drive the join then: closing may overlap 
the one connector
+   * call in progress, but no request, cursor advance, row read or new reader 
follows it. Requests
+   * and cursor calls take no lock, so closing does not wait for them. Metrics 
reads do: closing
+   * keeps the reader's final metrics under the lock of the task's 
`TaskLookupReaders`, so it can
+   * wait for a metrics read in progress, which calls `currentMetricsValues()` 
on the task's
+   * readers.
+   */
+  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())
+      val cursor = 
Option(reader.lookupBatch(requestRows.asInstanceOf[Array[InternalRow]]))
+        .getOrElse {
+          throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+            tableName, "NULL_RESULT_CURSOR")
+        }
+      activeCursor.set(cursor)
+      // A close() while the request ran did not find this cursor, so it is 
closed here.
+      if (closed.get()) {
+        closeCursor()
+        ensureOpen()
+      }
+      cursor
+    }
+
+    private def createReader(): ExternalLookupReader = {
+      val reader = Option(readerFactory.createReader()).getOrElse {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName, "NULL_LOOKUP_READER")
+      }
+      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())
+      }
+      ensureOpen()
+      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")
+    }
+
+    /** 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()
+    }
+
+    def updateMetrics(): Unit = {
+      if (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 reader = openReader.getAndSet(null)
+      ExternalLookupJoinExec.closeResources(
+        closeCursor(),
+        if (reader != null) taskReaders.closing(reader),

Review Comment:
   **Non-blocking (P2):** `close()` runs from the task-completion listener, 
which can fire while another thread, such as a script transformation's writer 
thread, is still consuming the join. Here it calls 
`taskReaders.closing(reader)`, and `closing()` and `report()` call 
`currentMetricsValues()` on this reader and the task's other open readers, 
unordered against that thread's in-progress `lookupBatch()`, `next()` or 
`get()`. The `ExternalLookupReader` contract lets only `close()` overlap a call 
in progress, so a connector that keeps its metrics in plain fields updated by 
`next()` can return torn values or throw from the listener, failing a task that 
already produced its output, and a connector that serializes the metrics read 
with its calls makes task completion wait for a stuck request, because 
`reader.close()` runs only after the metrics read. Separately, the consumer 
copies the row from `get()` after its last `ensureOpen()`, so a close in 
between closes the cursor while Spark read
 s the row; a connector that releases pooled or off-heap row buffers in 
`close()`, as the cursor contract allows, then has them read after release. The 
tests inject closes only inside connector calls, with on-heap rows that 
`close()` never frees.
   
   **Recommended change:** Extend the threading paragraph of 
ExternalLookupReader to say that, when the task ends, Spark may also call 
currentMetricsValues() on this reader and on the task's other open readers from 
the closing thread while a call is in progress on another thread, so that 
method must be safe to call concurrently and must not wait for that call. 
Extend ExternalLookupResultCursor to say that Spark may still be reading the 
row get() returned, and its buffers, while close() runs on another thread at 
the end of the task, so close() must leave that row safe to read, for example 
by deferring the release of its memory. Correct the LookupReader comment, which 
says no row read follows the close, and add a lookup join test that ends the 
task while a request is in progress and checks that task completion reports 
metrics and closes the reader without waiting for that request.
   
   **Why this works:** The close stays lock-free, as chosen in this change so 
that task completion never waits for a hung connector call. Stating every 
operation that can overlap a call in progress, the close itself, the metrics 
read and Spark's read of the current row, makes the contract match what the 
close path does, so a connector built to it keeps its metrics and row memory 
safe under that overlap instead of relying on a sequential-call promise that 
the close path does not keep.
   
   **Scope:** A correction of the connector reader and cursor threading 
contract, and of the matching LookupReader comment, to describe the metrics 
read and the row read that overlap the task-end close, with a test of the 
documented behavior.
   
   **Compatibility:** Spark still starts no request or cursor advance after it 
has seen the close, and every reader and cursor that it obtains is still closed.
   
   **Risks:** Connectors written to the current text must make 
currentMetricsValues() safe to call concurrently and keep row memory readable 
while close() runs; the interfaces are marked Evolving, and the change only 
retracts promises that the close path does not keep.
   
   **Constraints:** The task-end close must not wait for a connector call in 
progress.
   
   **Exclusions:**
   - Stopping a consumer from opening a new reader after the close is left to a 
separate fix in the request path.
   
   **Success:** The reader contract says that, at task end, 
currentMetricsValues() may be called on another thread while a call is in 
progress, and must be safe to call then and must not wait for that call. The 
cursor contract says that Spark may still read the current row and its buffers 
while close() runs at task end. The LookupReader comment lists the metrics read 
and the row read among what may overlap the close.
   
   **Verification:**
   - **Inspection:** The connector reader and cursor contracts list every 
operation that the task-end close can overlap with a call in progress: closing 
the reader and its cursor, reading reader metrics, and reading the current row.
   - **Behavior:** When the task ends while another thread is inside a lookup 
request, task completion reports the readers' metrics and closes the reader 
without waiting for the request, and the cursor that the request later returns 
is closed too.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java:
##########
@@ -53,14 +56,27 @@ public interface ExternalLookupReader extends Closeable {
    * Spark guarantees that {@code uniqueParameters} is non-null and holds 
between 1 and
    * {@link ExternalLookup#maxParameterRowsPerRequest()} rows, none of them 
null. Field {@code i}
    * of each row is the value for the {@code i}-th selected predicate, in 
Spark's internal
-   * representation.
-   * Rows are distinct under Spark SQL equality (NaN equals NaN, {@code -0.0} 
equals {@code 0.0},
-   * strings compare by collation). Only {@code <=>} parameters may be null at 
the top level.
+   * representation: an integral or BOOLEAN value as its Java primitive; 
DECIMAL as a
+   * {@code Decimal} at the column's precision and scale; DATE as days since 
1970-01-01 in the
+   * proleptic Gregorian calendar; TIMESTAMP as microseconds since 1970-01-01 
00:00:00 UTC;
+   * TIMESTAMP_NTZ as microseconds of the local date and time, with no time 
zone; BINARY as its
+   * bytes; and STRING as UTF-8 bytes, compared byte by byte. A conversion 
that loses precision,
+   * such as to milliseconds, can lose matches.
+   * No two rows are equal; a null {@code <=>} parameter equals a null. Only 
{@code <=>} parameters
+   * may be null at the top level.
    * <p>
-   * The cursor must be non-null. Each row's results must be complete and 
depend only on the row;
-   * Spark may reuse them for equal rows. The input is read-only and must not 
be kept after the
-   * cursor closes. Spark closes every cursor it obtains, including one it has 
read to the end,
-   * before the next call and before closing this reader.
+   * The cursor must be non-null. Each row's results must be complete, with no 
cap and no row lost
+   * to paging, and depend only on the row; Spark may reuse them for equal 
rows. Under Spark
+   * semantics, a stored row matches at most one parameter row of a request. 
If the source matches

Review Comment:
   **Non-blocking (P2):** This holds only for the `=` candidates offered today. 
`SupportsExternalLookup` documents range candidates and notes that a field may 
appear in several predicates, so with the selection `[event_time >= ?, tenant = 
?]` the distinct parameter rows `(10, 'a')` and `(20, 'a')` both match a stored 
row with `event_time = 25` and `tenant = 'a'`, and Spark needs that row under 
each ordinal. A connector written to this sentence returns it once, under one 
ordinal, and since Spark cannot detect a missing row, inner joins drop the 
other stream rows' matches and left outer joins null-pad them once range 
candidates are offered. Suggested fix: state the rule instead, that a stored 
row matching several parameter rows is returned once with each of their 
ordinals, and keep the allowance that a looser source may return extra pairs 
that Spark drops.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,160 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinStrategyHint,
+  LogicalPlan}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN
+import org.apache.spark.sql.connector.catalog.Table
+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 a join that passes analysis is exactly a join that the 
optimizer converts.

Review Comment:
   **Nit (P3):** This says a join that passes analysis is exactly a join the 
optimizer converts, but `CheckExternalLookupJoin` accepts `MissingCondition` 
and `FormExternalLookupJoin` then throws `MISSING_JOIN_CONDITION`, as 
`FormExternalLookupJoinSuite` pins. Two other comments have the same problem: 
`NotLookupJoin` is documented as reading no lookup-only table, yet a 
lookup-only relation under an alias, hint, projection or filter is classified 
`NotLookupJoin`, and `ExternalLookupJoinStrategy` says it plans resolved 
external lookup joins but matches only `PreparedExternalLookupJoin`. 
Maintainers who extend the classification, for example with the planned 
look-through of aliases, are told invariants that do not hold. Suggested fix: 
say that sharing the classification makes analysis reject the joins the 
optimizer cannot convert, except a join without a condition; say that 
`NotLookupJoin` means neither child is a lookup-only relation, so wrapped ones 
are not recognized yet; and say that
  the strategy plans prepared external lookup joins.
   
   **Verification:**
   - **Inspection:** Each corrected comment matches the code: the one 
difference between analysis and conversion in the shared classification, the 
ordinary-join classification of wrapped lookup-only relations, and the 
strategy's match on prepared lookup joins only.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinExec.scala:
##########
@@ -0,0 +1,209 @@
+/*
+ * 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 org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, AttributeSet,
+  BoundReference, EqualNullSafe, EqualTo, Expression, ExprUtils, 
PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.{JoinType, LeftOuter}
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode}
+import 
org.apache.spark.sql.execution.datasources.v2.SupportsCustomDriverMetrics
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.util.Utils
+
+/**
+ * Executes synchronous, parameterized external lookup joins without a 
shuffle. Each task joins
+ * its input rows in batches, through an 
[[ExternalLookupJoinEvaluatorFactory]].
+ */
+case class ExternalLookupJoinExec(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    joinType: JoinType,
+    residualCondition: Option[Expression],
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    child: SparkPlan) extends UnaryExecNode with SupportsCustomDriverMetrics 
with PredicateHelper {
+
+  // The connector's value rows follow the read schema, which `lookupInput` 
describes. The lookup
+  // columns keep their analyzed order and take the read schema's types. Their 
nullability, at
+  // every nested level, combines the table's and the read schema's: a field 
is NOT NULL when
+  // either says so.
+  private lazy val inputByLookupOutput = AttributeMap(lookupInput.map(attr => 
attr -> attr))
+  private lazy val lookupColumns = lookupOutput.map(inputByLookupOutput)
+
+  override def output: Seq[Attribute] = joinType match {

Review Comment:
   **Non-blocking (P2):** The operator keeps every row in its stream partition 
and outputs `child.output` unchanged ahead of the lookup columns, but without 
an `outputPartitioning` override it reports `SparkPlan`'s 
`UnknownPartitioning(0)`. In `events.dropDuplicates("customerId")` joined to a 
lookup-only table on `customerId` and then grouped by `customerId`, the stream 
side is already hash-partitioned on `customerId`, yet `EnsureRequirements` 
inserts a `ShuffleExchangeExec` of every enriched row before the aggregation in 
each micro-batch, and AQE is not applied to stateful streaming plans. 
Row-preserving peers such as `FilterExec` and `GenerateExec`, and the broadcast 
stream-static join, keep the child's partitioning. Suggested fix: override 
`outputPartitioning` to return `child.outputPartitioning`, and leave 
`outputOrdering` empty because rows follow the cursor's order.
   
   **Verification:**
   - **Regression:** A streaming query that deduplicates its stream on a key, 
joins a lookup-only table on that key and then aggregates on the same key plans 
no exchange between the lookup join and the aggregation, and returns the same 
results.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java:
##########
@@ -30,11 +30,14 @@
  *   <li>Calls to a reader and its cursors are sequential, but may come from 
different threads.
  *   The one exception is the end of the task: if another thread is still 
consuming the join,
  *   Spark may call {@link #close()} on the reader, and {@code close()} on its 
open cursor, while
- *   one call from that thread is in progress. Spark starts no new call after 
the close, so
- *   implementations must tolerate {@code close()} during an in-progress call, 
for example by
- *   cancelling or failing that call.</li>
+ *   one call from that thread is in progress. Implementations must tolerate 
{@code close()}
+ *   during an in-progress call, for example by cancelling or failing that 
call. Spark starts no
+ *   new call once it has seen the close. A call that Spark checked just 
before the close can
+ *   still reach the source during or after {@code close()}. It must tolerate 
the close too, for
+ *   example by failing.</li>
  *   <li>Requests are not snapshot boundaries: results may mix source 
versions.</li>
- *   <li>Retried or speculative tasks may repeat a request; duplicates must be 
tolerated.</li>
+ *   <li>Retried or speculative tasks may send the same request again, so a 
source must
+ *   tolerate repeated requests. This does not allow repeated result rows.</li>

Review Comment:
   **Nit (P3):** Read literally, this forbids a value row from appearing twice 
in a response. Join results have bag semantics, so a store that holds two equal 
rows for a key must return both, and `lookupBatch` itself lets a loosely 
matching source return a stored row once per matching parameter row. A 
connector that follows the literal reading returns one row where the table 
holds two, and Spark cannot tell that a row is missing. Suggested fix: say what 
is meant, for example that a repeated request must not make the source return 
the same match more than once, while equal stored rows are each still returned.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 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, LeftOuter}
+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
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    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 joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      while (rows.length < maxParameterRowsPerRequest && input.hasNext) {
+        rows += input.next().copy()
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    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) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    private val lookupStartNanos = System.nanoTime()
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()

Review Comment:
   **Nit (P3):** If a connector's cursor returns true from `next()` and then 
null from `get()`, `validatedCopy` dereferences the null row in a field check 
or the `UnsafeProjection`, and the task fails with a `NullPointerException` 
that names neither the connector nor the table. The evaluator already reports 
the sibling violations, a null cursor, a null reader and an out-of-range 
ordinal, as named `DATA_SOURCE_INVALID_EXTERNAL_LOOKUP` errors. Suggested fix: 
after the open check that follows `get()`, fail with a new 
`DATA_SOURCE_INVALID_EXTERNAL_LOOKUP` subclass for a null result row that names 
the table, and state in `ExternalLookupResultCursor` that `get()` returns a 
non-null row.
   
   **Verification:**
   - **Regression:** A connector cursor that returns null from get() after a 
successful advance fails the query with the named external lookup contract 
error for a null result row, naming the table, rather than with a 
NullPointerException.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 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, LeftOuter}
+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
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    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 joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      while (rows.length < maxParameterRowsPerRequest && input.hasNext) {
+        rows += input.next().copy()
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    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) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    private val lookupStartNanos = System.nanoTime()
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          reader.ensureOpen()
+          val key = requestedKey(ordinal)
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {
+            joinResultRow(key, resultRow)
+          }
+        }
+        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 = cursor.next()
+      reader.ensureOpen()
+      advanced
+    }
+
+    private def requestedKey(ordinal: Int): UnsafeRow = {
+      if (ordinal < 0 || ordinal >= requestedKeys.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
requestedKeys.length.toString))
+      }
+      requestedKeys(ordinal)
+    }
+
+    private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit =
+      keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow))
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      if (joinOutput.matches(rows(index), lookupRow)) {
+        matched(index) = true
+        joinOutput.matched(lookupRow).foreach(emit(index, _))
+      }
+    }
+
+    /**
+     * Closes the cursor once. After a complete read, finishes every stream 
row that was waiting for
+     * its results. After a failure or a close, the results may be partial, so 
it finishes none:
+     * a row without a match could be a row whose match was never read.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      try {
+        reader.closeCursor()
+      } finally {
+        metrics.lookupTime += System.nanoTime() - lookupStartNanos
+        reader.updateMetrics()
+      }
+      if (completed) keyEntries.values.foreach(_.rowIndexes.foreach(finish))
+    }
+
+    private def finish(index: Int): Unit = if (!finished.contains(index)) {
+      finished += index
+      if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _))
+    }
+
+    private def emit(index: Int, lookupRow: InternalRow): Unit = {
+      pending.enqueue(index -> lookupRow)
+      metrics.outputRows += 1
+    }
+  }
+
+  /** The 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: the request row that is 
sent to the
+   * connector, and the key that identifies equal parameters under Spark 
equality, which
+   * normalizes floating-point values and collations. 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 keyProjection = UnsafeProjection.create(lookupParameters.map { 
parameter =>
+      
NormalizeFloatingNumbers.normalize(CollationKey.injectCollationKey(parameter))
+    }, streamOutput)
+    private val keyCheck = lookupKeyCheck.map(Predicate.create(_))
+    private val requestAndResult = new JoinedRow()
+    requestProjection.initialize(partitionIndex)
+    keyProjection.initialize(partitionIndex)
+    keyCheck.foreach(_.initialize(partitionIndex))
+
+    def requestRow(streamRow: InternalRow): UnsafeRow = 
requestProjection(streamRow).copy()
+
+    /** The key of a stream row, in a reused row: copy it to retain it. */
+    def key(streamRow: InternalRow): UnsafeRow = keyProjection(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.
+     * The key has the request row's nulls.
+     */
+    def matchesNothing(key: InternalRow): Boolean =
+      nullSafeParameters.indices.exists { index =>
+        !nullSafeParameters(index) && key.isNullAt(index)
+      }
+  }
+
+  /**
+   * 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) {
+    // Value rows follow the read schema, and the residual and output are 
bound to its fields.
+    private val joinedLookupInput =
+      if (joinType == LeftOuter) lookupInput.map(_.withNullability(true)) else 
lookupInput
+    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(lookupInput.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))
+
+    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. */
+    def matched(lookupRow: InternalRow): Option[InternalRow] = joinType match {
+      case Inner | LeftOuter => Some(lookupRow)
+      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 => 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. A thread
+   * other than the task's may still drive the join then: closing may overlap 
the one connector
+   * call in progress, but no request, cursor advance, row read or new reader 
follows it. Requests
+   * and cursor calls take no lock, so closing does not wait for them. Metrics 
reads do: closing
+   * keeps the reader's final metrics under the lock of the task's 
`TaskLookupReaders`, so it can
+   * wait for a metrics read in progress, which calls `currentMetricsValues()` 
on the task's
+   * readers.
+   */
+  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())

Review Comment:
   **Nit (P3):** If the task-end close lands after this request's 
`ensureOpen()` but before `openReader.get()`, `close()` has already set 
`closed` and taken the partition's reader, so this line sees null and calls 
`createReader()`. The factory then opens a second reader for the same 
partition, and `createReader()` only afterwards notices the close and closes it 
before failing. A connector that opens a connection or session per reader sees 
one it was promised would not be created: `ExternalLookupReaderFactory` says at 
most one reader per input partition, and the `LookupReader` comment says that 
no new reader follows the close. Suggested fix: re-check `closed` after finding 
no open reader and before `createReader()`; `close()` sets the flag before it 
clears `openReader`, so a consumer that finds the reader cleared always sees it.
   
   **Verification:**
   - **Regression:** When the task ends after a consumer on another thread has 
passed the open check of its next request but before it reads the open reader, 
that request fails as a request on a closed reader does, and the connector 
factory creates no second reader for the partition.
   - **Behavior:** A first request in a partition still creates exactly one 
reader, and a close that lands while that reader is being created still closes 
it before any request is sent.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 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, LeftOuter}
+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
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    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 joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      while (rows.length < maxParameterRowsPerRequest && input.hasNext) {
+        rows += input.next().copy()
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    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) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    private val lookupStartNanos = System.nanoTime()
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          reader.ensureOpen()
+          val key = requestedKey(ordinal)
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {

Review Comment:
   **Nit (P3):** `keyEntries(key)` here and again in `joinResultRow` each 
recompute the key's Murmur3 hash and compare its bytes for every returned row, 
although `requestedKey(ordinal)` has just mapped the ordinal to that key, and 
`keyEntries` is fixed after construction and iterates in request order. For 
each new distinct key the constructor also runs `requestProjection` after 
copying the `keyProjection` result, but for every type `supportsEquality` 
admits, `CollationKey.injectCollationKey` and 
`NormalizeFloatingNumbers.normalize` leave the parameter unchanged, so both 
rows have the same bytes; for unique-key enrichment that is one extra 
projection and copy per stream row. Suggested fix: keep the batch's entries in 
an array in request order and take a returned row's entry by its validated 
ordinal, and reuse the copied key as the request row when the normalized key 
expressions equal the parameter expressions.
   
   **Verification:**
   - **Compatibility:** Join results, the request rows the connector receives, 
the re-check of selected predicates and the error for an out-of-range input 
ordinal are unchanged for every key type the lookup join offers.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,313 @@
+/*
+ * 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.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
EqualNullSafe, EqualTo,
+  Expression, ExprUtils, ExternalUserDefinedFunction, Literal, 
PredicateHelper, PythonUDF}
+import org.apache.spark.sql.catalyst.plans.LeftOuter
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  Filter, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.EXTERNAL_LOOKUP_JOIN
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, 
StructType}
+
+/** Finalizes an optimized external lookup side immediately before ordinary V2 
scan preparation. */
+object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper
+  with QueryErrorsBase {
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val prepared = 
plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) {
+      case join: ExternalLookupJoin if provablyEmpty(join) => 
emptyJoinResult(join)
+      case join: ExternalLookupJoin => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    prepared.foreach { node =>

Review Comment:
   **Non-blocking (P2):** This `foreach` visits every node of every optimized 
plan on every optimizer run, including each optimized subquery and each 
streaming micro-batch, and `CheckExternalLookupJoin` likewise walks every 
analyzed plan that contains a join. Only a `DataSourceV2Relation` or 
`ExternalLookupRelation` can make either pass throw or classify anything, and 
both declare `DATA_SOURCE_V2_RELATION`, so a plan without a DSv2 relation, such 
as a V1 file-source join, pays the traversals for nothing. Each pass is cheap, 
but it is always on. Suggested fix: run this `foreach` only when 
`prepared.containsPattern(DATA_SOURCE_V2_RELATION)`, and gate 
`CheckExternalLookupJoin` on `containsAllPatterns(JOIN, 
DATA_SOURCE_V2_RELATION)`.
   
   **Verification:**
   - **Inspection:** Both lookup validation passes return without traversing a 
plan that contains no DSv2 relation.
   - **Regression:** Lookup-only reads outside a lookup join still fail the 
optimizer's final check, and lookup joins that cannot run still receive their 
named analysis errors, for both the spark.read placeholder and a bare DSv2 
relation.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,605 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 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, LeftOuter}
+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
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    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 joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      while (rows.length < maxParameterRowsPerRequest && input.hasNext) {
+        rows += input.next().copy()
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    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) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    private val lookupStartNanos = System.nanoTime()
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray)
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          reader.ensureOpen()
+          val key = requestedKey(ordinal)
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {
+            joinResultRow(key, resultRow)
+          }
+        }
+        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 = cursor.next()
+      reader.ensureOpen()
+      advanced
+    }
+
+    private def requestedKey(ordinal: Int): UnsafeRow = {
+      if (ordinal < 0 || ordinal >= requestedKeys.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
requestedKeys.length.toString))
+      }
+      requestedKeys(ordinal)
+    }
+
+    private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit =
+      keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow))
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      if (joinOutput.matches(rows(index), lookupRow)) {
+        matched(index) = true
+        joinOutput.matched(lookupRow).foreach(emit(index, _))
+      }
+    }
+
+    /**
+     * Closes the cursor once. After a complete read, finishes every stream 
row that was waiting for
+     * its results. After a failure or a close, the results may be partial, so 
it finishes none:
+     * a row without a match could be a row whose match was never read.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      try {
+        reader.closeCursor()
+      } finally {
+        metrics.lookupTime += System.nanoTime() - lookupStartNanos

Review Comment:
   **Nit (P3):** `lookupStartNanos` is taken when the batch iterator is 
constructed, and this line adds the elapsed time only after the consumer has 
pulled every joined row of the batch. Each joined row goes to the consumer 
while the cursor is still open, so with a slow sink, a Python UDF or costly 
expressions above the join, up to 1000 output rows' worth of downstream work 
per batch is reported as external lookup time, and so is the upstream 
`input.hasNext()` call that `tryAdvance` makes right after building the batch. 
The SQL UI then points latency tuning at the connector. Suggested fix: 
accumulate the metric only around the connector calls a batch makes: the 
`lookupBatch()` request, the cursor calls that read each result row, and the 
cursor close.
   
   **Verification:**
   - **Regression:** With slow processing downstream of the lookup join and a 
connector that answers quickly, the external lookup time metric stays near the 
connector's own call time and does not grow with the downstream work.



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