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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TableCapabilityCheck.scala:
##########
@@ -97,4 +119,43 @@ object TableCapabilityCheck extends (LogicalPlan => Unit) {
       }
     }
   }
+
+  /**
+   * Fails on a lookup-only table that `plan` reads outside a lookup join, 
including in the plans
+   * that a node holds outside its children, as a V1 write command holds its 
query, and in
+   * subqueries. A join over a lookup-only table is classified as for a lookup 
join, so a join that
+   * cannot run fails with its named reason, and the lookup side of one that 
can is not a scan. The
+   * walk enters only the plans that can read a DSv2 table, or hold a subquery 
that can.
+   */
+  private def rejectLookupOnlyReads(plan: LogicalPlan): Unit = {
+    if (plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, PLAN_EXPRESSION)) {
+      plan match {
+        case join: Join =>
+          ExternalLookupJoinEligibility(join) match {
+            case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+            // The query is analyzed in full, so the condition cannot be added 
later.
+            case ExternalLookupJoinEligibility.MissingCondition =>
+              throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+                "MISSING_JOIN_CONDITION")
+            case ExternalLookupJoinEligibility.NotLookupJoin =>
+              join.children.foreach(rejectLookupOnlyReads)

Review Comment:
   **Non-blocking (P2):** This descent is the only analysis-time check that 
reaches a lookup-only read under a join that the classifier leaves ordinary, 
such as `batch.join(lookup.select("id", "department"), cond)` written with 
`mode("overwrite")` to a V1 source. `CheckExternalLookupJoin` accepts that 
join, the first capability pass lets `EXTERNAL_LOOKUP` tables through, and 
`PrepareExternalLookupJoin`'s final check runs only when the command optimizes 
its query, after a source such as JDBC would already have truncated or dropped 
its target. No command test takes this branch: they read the table directly or 
through a `NOT IN` subquery, and the commands over joins take the `Eligible` 
and `MissingCondition` branches. A refactor that stopped descending here would 
reopen the data loss that the earlier overwrite fix closed, with every test 
still passing. Suggested fix: add a V1 overwrite `save()` into the recording 
write source whose query joins a batch DataFrame with a projection of the 
 lookup-only table, and assert the batch-scan error with no write recorded.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59910#discussion_r4501893223).
   
   **Verification:**
   - **Regression:** A command that holds its query outside its children and 
reads the lookup-only table only through a projection under an ordinary join 
fails during analysis with the batch-scan error before its source receives any 
write, and the test fails if the command check stops descending into the sides 
of such a join.



##########
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:
   Thanks. At the current head this can happen again: the latest commit moved 
the closed check from before `createReader()` to after it. If the task-end 
close lands after the request's first check and before it reads the open 
reader, the request finds the slot empty and the factory creates a second 
reader for the partition, which `createReader()` then closes. Checking for the 
close again after finding no open reader, before `createReader()`, restores the 
guarantee, because `close()` marks the reader closed before it clears the slot.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4501893235","thread_id":"inline:4501893235","verdict_sha256":"f46a3db6288279e359667855c7be777194dd4518bcc6c37a7523490b4619c1a8"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/ExternalLookupJoinStartupCheck.scala:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.streaming.runtime
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility
+import 
org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility.NotLookupJoin
+import org.apache.spark.sql.catalyst.plans.logical.{Join, LogicalPlan}
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.streaming.checkpointing.OffsetSeqMetadata
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Plans the external lookup joins of a streaming query when it starts, in the 
thread that starts
+ * it, so that a join that cannot be planned fails `start()` instead of the 
first micro-batch that
+ * runs, which may come much later. Whether a join has a lookup predicate, and 
which ones the
+ * connector selects, depend on the condition as the optimizer leaves it, for 
example after it
+ * simplifies the condition. So the query is optimized once here, with the 
optimizer of its
+ * micro-batches and with their configuration, and the result is discarded.
+ *
+ * Only the lookup sides are planned. The other subtrees without a streaming 
relation, and the
+ * subtrees of subquery plans without an outer reference, become placeholders 
of their outputs, as
+ * in the optimization for the column pruning of streaming scans (see
+ * `StreamingV2ScanPushDown.forStartup`), so that their scans are neither 
built nor planned at the
+ * start, as for a query without a lookup join.
+ *
+ * Only the planning errors of the lookup join and of its connector contract 
fail the start. Any
+ * other error, such as one that an ordinary join raises too, is left to the 
micro-batch, which
+ * plans the query as before.
+ */
+private[sql] object ExternalLookupJoinStartupCheck extends Logging {
+  private val lookupErrorClasses = Set(
+    "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED",
+    "INVALID_EXTERNAL_LOOKUP_HINT",
+    "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP",
+    // The default Scan.toExternalLookup() of a scan that does not override it.
+    "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED")
+
+  def apply(session: SparkSession, write: WriteToStream): Unit = {
+    val plan = write.inputQuery
+    if 
(!session.sessionState.conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED)
 ||
+        lookupSidePlans(plan).isEmpty) {
+      return
+    }
+    session.withActive {
+      try {
+        SQLConf.withExistingConf(startupConf(session, write)) {
+          val normalized = QueryExecution.normalize(session, plan)
+          // The values that depend on when they are evaluated fold as in the 
first micro-batch.
+          session.sessionState.optimizer.execute(
+            StreamingV2ScanPushDown.forStartup(normalized, withStartupValues = 
false))
+        }
+      } catch {
+        case e: SparkThrowable if lookupErrorClasses.contains(errorClass(e)) 
=> throw e

Review Comment:
   **Nit (P3):** Neither this guard nor the `withStartupValues = false` choice 
above it has a test. Reverting the call to `forStartup(normalized)`, whose 
default masks date and timestamp conversions, would make `start()` reject `s.id 
= t.id OR CAST('1999-01-01' AS DATE) > CAST('2000-01-01' AS DATE)` with 
`NO_LOOKUP_CANDIDATE`, although every micro-batch folds the casts and plans the 
join; the one optimizer-dependent startup case uses `|| lit(false)`, which 
folds the same either way. Replacing this guard with `case e: SparkThrowable => 
throw e` would make `start()` fail on a connector's own `SparkException`, for 
example from `newScanBuilder()`; the only deferred-error case throws an 
`IllegalStateException`, which never reaches it. Every current test would pass 
after either change. Suggested fix: add a startup-check case whose condition 
becomes a lookup equality only once date conversions fold, and one whose test 
connector throws a `SparkThrowable` outside the lookup error classes whil
 e Spark plans its scan.
   
   **Verification:**
   - **Regression:** Turning the startup values back on in the startup 
optimization makes a startup-check test fail, because the lookup join whose 
condition only folds to an equality through date conversions then fails start() 
with the no-lookup-candidate error.
   - **Regression:** Rethrowing every SparkThrowable from the startup 
optimization makes a startup-check test fail, because a connector's own 
SparkThrowable raised while its scan is planned then fails start() instead of 
the first micro-batch.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,633 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, 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,
+    maxBatchBytes: Long,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val 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()
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes 
&& input.hasNext) {
+        val row = input.next() match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+        bytes += row.getSizeInBytes
+        rows += row
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * 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 request row that can match, in the order of 
first occurrence.
+    // A row that can never match, because it fails the stream condition or 
has a null parameter,
+    // is finished right away, and its parameters are not requested. The 
stream condition is
+    // checked before the parameters are evaluated, so that it can guard their 
expressions.
+    private val keyEntries = {
+      val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+      rows.indices.foreach { index =>
+        lazy val requestRow = parameters.requestRow(rows(index))
+        if (!joinOutput.canMatch(rows(index)) || 
parameters.matchesNothing(requestRow)) {
+          finish(index)
+        } else {
+          entries.get(requestRow) match {
+            case Some(entry) => entry.rowIndexes += index
+            case None =>
+              val retained = requestRow.copy()
+              entries.put(retained, KeyEntry(retained, 
mutable.ArrayBuffer(index)))
+          }
+        }
+      }
+      entries.values.toArray
+    }
+
+    // No connector request, and no reader, when no key can match.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else connectorCall(reader.lookup(keyEntries.map(_.requestRow)))
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // The join checks for a close() before each connector call, so it 
makes none after it
+          // has seen one.
+          val start = System.nanoTime()
+          reader.ensureOpen()
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          metrics.lookupTime += System.nanoTime() - start
+          if (connectorRow == null) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName, "NULL_RESULT", Map("method" -> 
"ExternalLookupResultCursor.get()"))
+          }
+          val entry = requestedEntry(ordinal)
+          reader.ensureOpen()
+          val resultRow = resultRows.validatedCopy(connectorRow)
+          if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) {
+            entry.rowIndexes.foreach(joinMatch(_, 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 = connectorCall(cursor.next())
+      reader.ensureOpen()
+      advanced
+    }
+
+    /**
+     * Runs a connector call and adds its time to the lookup time metric, 
which counts only the
+     * time in the connector, not that of the work above the join while a 
cursor is open.
+     */
+    private def connectorCall[T](call: => T): T = {
+      val start = System.nanoTime()
+      try call finally metrics.lookupTime += System.nanoTime() - start
+    }
+
+    private def requestedEntry(ordinal: Int): KeyEntry = {
+      if (ordinal < 0 || ordinal >= keyEntries.length) {
+        throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+          tableName,
+          "INVALID_INPUT_ORDINAL",
+          Map("ordinal" -> ordinal.toString, "numParameterRows" -> 
keyEntries.length.toString))
+      }
+      keyEntries(ordinal)
+    }
+
+    private def joinMatch(index: Int, lookupRow: InternalRow): Unit = {
+      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. Once 
the reader is closed,
+     * its close owns the cursor and the reader's metrics, so the join makes 
no further connector
+     * call.
+     */
+    private def finishCursor(completed: Boolean): Unit = if (cursor ne 
EmptyLookupCursor) {
+      cursor = EmptyLookupCursor
+      if (!reader.isClosed) {
+        try {
+          connectorCall(reader.closeCursor())
+        } finally {
+          reader.updateMetrics()
+        }
+      }
+      if (completed) keyEntries.foreach(_.rowIndexes.foreach(finish))
+    }
+
+    private def finish(index: Int): Unit = if (!finished.contains(index)) {
+      finished += index
+      if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _))
+    }
+
+    private def emit(index: Int, lookupRow: InternalRow): Unit = {
+      pending.enqueue(index -> lookupRow)
+      metrics.outputRows += 1
+    }
+  }
+
+  /** The cursor of a batch that sends no request, or whose cursor is 
finished. */
+  private object EmptyLookupCursor extends ExternalLookupResultCursor {
+    override def next(): Boolean = false
+    override def inputOrdinal(): Int = throw new 
NoSuchElementException("external lookup result")
+    override def get(): InternalRow = throw new 
NoSuchElementException("external lookup result")
+    override def close(): Unit = {}
+  }
+
+  /** A check of one value slot: a field of a row, or an element of an array. 
*/
+  private type SlotCheck = (SpecializedGetters, Int) => Unit
+
+  /**
+   * Validates each row that the connector returns, and copies it once into 
Spark's own row before
+   * Spark checks, joins or keeps it. A connector may reuse its row and its 
buffers, byte arrays
+   * included, so a row that Spark still holds must not share them. A value 
that breaks its type
+   * fails the task, at any nested level: a null in a field, array element or 
map value that the
+   * table or the read schema declares NOT NULL, or a decimal that does not 
fit its precision and
+   * scale. Spark already relied on them while it optimized the query. The 
checks are built once
+   * from the read schema, and a field whose type has nothing to check costs 
nothing per row.
+   */
+  private class LookupResultRows {
+    private val copy = UnsafeProjection.create(lookupInput, lookupInput)
+    private val fieldChecks = lookupInput.zipWithIndex.flatMap { case (field, 
ordinal) =>
+      slotCheck(field.dataType, field.nullable, Seq(field.name)).map(ordinal 
-> _)
+    }
+
+    /** The row, validated and copied into a row that Spark owns. */
+    def validatedCopy(resultRow: InternalRow): UnsafeRow = {
+      fieldChecks.foreach { case (ordinal, check) => check(resultRow, ordinal) 
}
+      copy(resultRow).copy()
+    }
+
+    /** The check of a slot of this type, at this field path, or None if it 
has nothing to check. */
+    private def slotCheck(
+        dataType: DataType,
+        nullable: Boolean,
+        path: Seq[String]): Option[SlotCheck] = {
+      val valueCheck = nonNullValueCheck(dataType, path)
+      if (nullable && valueCheck.isEmpty) {
+        None
+      } else {
+        Some { (values, ordinal) =>
+          if (!values.isNullAt(ordinal)) {
+            valueCheck.foreach(_(values, ordinal))
+          } else if (!nullable) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName,
+              "NULL_IN_NOT_NULL_FIELD",
+              Map("field" -> QueryExecutionErrors.toSQLId(path)))
+          }
+        }
+      }
+    }
+
+    /** The check of a value that is not null, or None if its type has nothing 
to check. */
+    private def nonNullValueCheck(dataType: DataType, path: Seq[String]): 
Option[SlotCheck] =
+      dataType match {
+        case decimalType: DecimalType => Some { (values, ordinal) =>
+          val value = values.getDecimal(ordinal, decimalType.precision, 
decimalType.scale)
+          if (!fits(value, decimalType)) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName,
+              "DECIMAL_OUT_OF_RANGE",
+              Map(
+                "field" -> QueryExecutionErrors.toSQLId(path),
+                "type" -> QueryExecutionErrors.toSQLType(decimalType)))
+          }
+        }
+        case structType: StructType =>
+          val checks = structType.fields.toSeq.zipWithIndex.flatMap { case 
(field, ordinal) =>
+            slotCheck(field.dataType, field.nullable, path :+ 
field.name).map(ordinal -> _)
+          }
+          Option.when(checks.nonEmpty) { (values, ordinal) =>
+            val struct = values.getStruct(ordinal, structType.length)
+            checks.foreach { case (fieldOrdinal, check) => check(struct, 
fieldOrdinal) }
+          }
+        case arrayType: ArrayType =>
+          slotCheck(arrayType.elementType, arrayType.containsNull, path :+ 
"element").map {
+            check => (values, ordinal) => 
eachElement(values.getArray(ordinal), check)
+          }
+        case mapType: MapType =>
+          // A map key is never null, whatever the value's nullability.
+          val keyCheck = slotCheck(mapType.keyType, nullable = false, path :+ 
"key")
+          val valueCheck =
+            slotCheck(mapType.valueType, mapType.valueContainsNull, path :+ 
"value")
+          Option.when(keyCheck.nonEmpty || valueCheck.nonEmpty) { (values, 
ordinal) =>
+            val map = values.getMap(ordinal)
+            keyCheck.foreach(eachElement(map.keyArray(), _))
+            valueCheck.foreach(eachElement(map.valueArray(), _))
+          }
+        case _ => None
+      }
+
+    private def eachElement(array: ArrayData, check: SlotCheck): Unit = {
+      var index = 0
+      while (index < array.numElements()) {
+        check(array, index)
+        index += 1
+      }
+    }
+
+    /** Whether the decimal has its type's precision and scale without 
rounding. */
+    private def fits(value: Decimal, decimalType: DecimalType): Boolean = {
+      val rescaled = value.clone()
+      rescaled.changePrecision(decimalType.precision, decimalType.scale) && 
rescaled == value

Review Comment:
   **Non-blocking (P2):** `changePrecision` returns `true` on its fast path 
whenever the value's recorded precision and scale already equal the target, and 
`getDecimal` on an `UnsafeRow`, on a struct nested in one, or on a columnar row 
or array builds a compact decimal (precision up to 18) with 
`Decimal.createUnsafe`, which records the declared precision without checking 
the stored digits. So for a `DECIMAL(5,2)` field into which a connector wrote 
12345678.90 with `UnsafeRow.setDecimal(i, value, 5)`, this check would accept 
the value and the join would emit it, where the cursor contract says the task 
fails. Wider decimals in an `UnsafeRow` still fail, though with 
`NUMERIC_VALUE_OUT_OF_RANGE` rather than the named error. Every decimal test 
returns `GenericInternalRow` values built from `BigDecimal`, whose recorded 
precision is accurate, so none can see this. Suggested fix: when a compact 
value's recorded precision and scale already equal its type's, check that its 
unscaled value has a
 t most the type's precision in digits, and keep the current check for every 
other value.
   
   **Verification:**
   - **Regression:** A connector whose cursor returns UnsafeRows with 
12345678.90 written into a DECIMAL(5,2) field makes an inner and a left outer 
lookup join fail with the named out-of-range decimal error instead of emitting 
the value.
   - **Regression:** The same out-of-range compact decimal fails the task with 
the same error when it is a field of a struct nested in an UnsafeRow and when 
the connector returns it in a columnar row.
   - **Behavior:** In-range compact decimals returned in UnsafeRows, in nested 
structs and in columnar rows are joined with their values unchanged, and the 
existing value-check cases keep their results and errors.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/ExternalLookupJoinStartupCheck.scala:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.streaming.runtime
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility
+import 
org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility.NotLookupJoin
+import org.apache.spark.sql.catalyst.plans.logical.{Join, LogicalPlan}
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.streaming.checkpointing.OffsetSeqMetadata
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Plans the external lookup joins of a streaming query when it starts, in the 
thread that starts
+ * it, so that a join that cannot be planned fails `start()` instead of the 
first micro-batch that
+ * runs, which may come much later. Whether a join has a lookup predicate, and 
which ones the
+ * connector selects, depend on the condition as the optimizer leaves it, for 
example after it
+ * simplifies the condition. So the query is optimized once here, with the 
optimizer of its
+ * micro-batches and with their configuration, and the result is discarded.
+ *
+ * Only the lookup sides are planned. The other subtrees without a streaming 
relation, and the
+ * subtrees of subquery plans without an outer reference, become placeholders 
of their outputs, as
+ * in the optimization for the column pruning of streaming scans (see
+ * `StreamingV2ScanPushDown.forStartup`), so that their scans are neither 
built nor planned at the
+ * start, as for a query without a lookup join.
+ *
+ * Only the planning errors of the lookup join and of its connector contract 
fail the start. Any
+ * other error, such as one that an ordinary join raises too, is left to the 
micro-batch, which
+ * plans the query as before.
+ */
+private[sql] object ExternalLookupJoinStartupCheck extends Logging {
+  private val lookupErrorClasses = Set(
+    "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED",
+    "INVALID_EXTERNAL_LOOKUP_HINT",
+    "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP",
+    // The default Scan.toExternalLookup() of a scan that does not override it.
+    "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED")
+
+  def apply(session: SparkSession, write: WriteToStream): Unit = {
+    val plan = write.inputQuery
+    if 
(!session.sessionState.conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED)
 ||
+        lookupSidePlans(plan).isEmpty) {
+      return
+    }
+    session.withActive {
+      try {
+        SQLConf.withExistingConf(startupConf(session, write)) {
+          val normalized = QueryExecution.normalize(session, plan)
+          // The values that depend on when they are evaluated fold as in the 
first micro-batch.

Review Comment:
   **Nit (P3):** This holds for date and timestamp conversions, but not for 
`current_timestamp()`, `current_date()` and `localtimestamp()`: here 
`ComputeCurrentTime` folds them to the time of `start()`, while each 
micro-batch replaces them with `CurrentBatchTimestamp` before it analyzes and 
optimizes its plan, and that expression becomes a literal only after 
optimization. For `s.id = t.id OR current_date() < DATE'2000-01-01'`, this 
optimization simplifies the condition to `s.id = t.id`, while a micro-batch 
keeps the `OR`. From the code, that rarely changes what `start()` reports: a 
micro-batch re-analyzes its plan, and `CheckAnalysis` would reject a join 
condition holding the nondeterministic `CurrentBatchTimestamp` with 
`INVALID_NON_DETERMINISTIC_EXPRESSIONS`, as it does for an ordinary 
stream-static join. The one exception found is a filter over a lookup join that 
folds to false here under the internal 
`spark.sql.optimizer.pruneFiltersCanPruneStreamingSubplan`, where the join is pr
 uned before it is planned. Suggested fix: say in this comment that date and 
timestamp conversions fold as in the micro-batches, while current-time 
functions fold to the time of `start()`, unlike in the micro-batches, which use 
their batch timestamp.
   
   **Verification:**
   - **Inspection:** The comment above the startup optimization matches what 
the optimizer folds there without startup values and what MicroBatchExecution 
replaces before each micro-batch is analyzed and optimized, both for date and 
timestamp conversions and for current_timestamp(), current_date() and 
localtimestamp().



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupResultCursor.java:
##########
@@ -29,8 +29,11 @@
  * ordinal is a miss. If the read schema has no columns, each match is still 
one (empty) row.
  * <p>
  * {@link #inputOrdinal()} and {@link #get()} are valid after {@link #next()} 
returns
- * {@code true}, until the next {@code next} or {@link #close()}. The row may 
be reused; Spark
- * copies the rows it keeps. Spark closes every cursor, which may be before 
its end.
+ * {@code true}, until the next {@code next} or {@link #close()}. The row and 
its buffers, byte
+ * arrays included, may be reused: Spark copies each row before it calls 
{@code next} again.
+ * Each value, nested values included, must fit its type: a null only where 
both the table and
+ * the read schema allow one, and a decimal within its precision and scale. 
Otherwise the task
+ * fails. Spark closes every cursor, which may be before its end.

Review Comment:
   **Nit (P3):** Since the close was narrowed, this sentence and the last 
paragraph of `lookupBatch` each draw a task-end boundary that the code does 
not. `close()` sets the closed flag and only then takes the cursor slot, 
`lookup()` publishes a cursor only after `lookupBatch` returns, and 
`finishCursor()` takes a finished cursor before it closes it. So, from the 
code: (1) a cursor that `lookupBatch` returns after the close started is closed 
when it is published before the close takes the slot; (2) a cursor obtained 
before the close is never closed when it is published after the close took the 
empty slot; (3) a request that passed its last check can reach `lookupBatch` 
after `close()` returned, so closing the reader cannot release that cursor; and 
(4) a finished cursor that the consuming thread took first is closed after its 
reader. All four need another thread consuming the join at task end. A 
connector that relies on Spark to close each cursor would leak one in (2) and 
(3), and one
  that releases late cursors in `reader.close()` without tracking which ones 
Spark closed could release one twice in (1). The task-end test's comment that 
every reader and cursor is closed has the same mismatch, since that test 
expects only the reader to be closed when the task ends during a request.
   
   **Recommended change:** Write one task-end rule in the ExternalLookupReader 
Javadoc, and replace the closing sentence of the cursor Javadoc and the last 
paragraph of lookupBatch with references to it. The rule: apart from the end of 
a task, Spark closes each cursor it obtains, including one read to its end, 
before its next call and before it closes the reader. If another thread is 
still consuming the join when the task ends, Spark closes the reader once 
without waiting for that thread; the thread makes no call after it has seen the 
close, but the one call that has already passed its check for the close may 
still run during or after close(), so Spark may close that thread's cursor 
before the reader, after it, or not at all. Closing a reader must therefore 
release every cursor of it that is still open and tolerate one that Spark has 
closed, a cursor's close() must work after its reader is closed, and a request 
on a closed reader must fail. Two of these statements were in the Javadoc
  before: commit 0860f7fec59 added that a call Spark checked just before the 
close can still reach the source during or after close(), and commit 
33f5e55b6a2 that closing a cursor must work after its reader is closed. Commit 
4bc87c4843a removed both when it moved the close to the DataSourceRDD model, 
and its message gives no reason beyond that move, although the code it kept 
still allows both cases; start from those two sentences. Also correct the 
LookupReader comment, which says that a cursor returned after the close is 
never closed, and the comment in the task-end test that says every reader and 
cursor is closed, and add a task-end test in which the task ends while the 
consuming thread is closing a finished cursor.
   
   **Why this works:** Every outcome that the code allows becomes one the 
published rule permits: a cursor that close() takes is closed before the 
reader; a cursor that lookup() publishes after close() took the empty slot, or 
that a request obtains after close() returned, is left to the reader's close; 
and a finished cursor that the consuming thread took first may be closed after 
the reader. A connector that implements the rule as written therefore neither 
leaks a cursor nor releases one twice in any of these interleavings, and the 
code needs no lock or wait.
   
   **Scope:** State the connector API's task-end close rule once, matching the 
lock-free close, align the LookupReader and task-end test comments with it, and 
pin the case of a cursor closed after its reader with a test.
   
   **Compatibility:** The order in which Spark closes cursors and readers at 
the end of a task stays as it is; only the published rule, the comments and the 
tests change.
   
   **Risks:** A connector written to the current sentences, which relies on 
Spark to close every cursor, leaks a cursor at task end unless its reader's 
close releases the open ones; the rule makes that duty explicit, and the API is 
marked Evolving, so it can still state it. The duty that a request on a closed 
reader must fail is new: a connector that instead returns a cursor holding 
resources from a closed reader leaks it, because neither Spark nor the reader's 
close, which has already run, releases it.
   
   **Constraints:** Keep the close lock-free and free of waits, as the narrowed 
close model requires. Leave the cursor Javadoc's sentences about returned 
values as they are: for an out-of-range decimal the code, not the text, is what 
changes. Keep the reader factory's promise of at most one reader per input 
partition, which holds once lookup() checks for the close again before it 
creates a reader.
   
   **Exclusions:**
   - Changing when, or by which thread, a cursor or a reader is closed at the 
end of a task.
   
   **Success:** The ExternalLookupReader Javadoc states one task-end rule, and 
the cursor Javadoc and lookupBatch refer to it instead of stating their own. 
The rule permits every task-end outcome that the code allows: a cursor closed 
before the reader, a cursor closed after it, a cursor that Spark never closes, 
and a request that reaches the connector after close() returned. The 
LookupReader comment and the comments of the task-end tests describe the same 
rule. A task-end test shows the reader closed before a finished cursor that the 
consuming thread is closing, each of them closed once.
   
   **Verification:**
   - **Inspection:** Read side by side, the reader Javadoc, lookupBatch, the 
cursor Javadoc, the LookupReader comment and the task-end test comments state 
the same rule, and every way the task-end close can interleave with lookup() 
and with the close of a finished cursor ends in an outcome that rule permits.
   - **Behavior:** When the task ends on another thread while the consuming 
thread is closing a finished cursor, the reader is closed before that cursor 
and each is closed once; when the task ends during a request, only the reader 
is closed; and when the close finds an open cursor, it closes that cursor 
before the reader.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_JOIN, 
TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Every output attribute of the lookup side. They 
are all part of this
+ *   node's references, so column pruning never puts a projection over the 
lookup relation, which
+ *   preparation needs directly under the join. A narrower list would let it 
do so.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/**
+ * A lookup join after its optimized lookup side has been converted to an 
external operation.
+ *
+ * @param lookupKeys The table column that each selected lookup predicate 
compares with the
+ *   parameter at the same position. Spark checks each row that the connector 
returns against
+ *   them, so the read schema must hold these columns.
+ */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    tableName: String,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    joinType: JoinType,
+    residualCondition: Option[Expression]) extends UnaryNode {
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => child.output ++ lookupOutput
+    case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      residualCondition.map(_.references.intersect(child.outputSet))
+        .getOrElse(AttributeSet.empty)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
PreparedExternalLookupJoin =
+    copy(child = newChild)
+
+  // Connector descriptions may contain secrets, so the scan and the reader 
factory are not shown.
+  // The physical node renders a redacted description of them.
+  override protected def stringArgs: Iterator[Any] =
+    Iterator(joinType, lookupParameters, residualCondition, child)
+
+  // The join keeps the size estimate it had before preparation, as an 
ordinary join's: the product
+  // of the stream side's size and the lookup side's, Spark's default size for 
a table it cannot
+  // scan. The stream side's size alone would ignore the lookup columns and 
the rows that a stream
+  // row can match.
+  override def stats: Statistics = statsCache.getOrElse {
+    statsCache = Some(Statistics(sizeInBytes =
+      Seq(child.stats.sizeInBytes, BigInt(conf.defaultSizeInBytes)).filter(_ > 
0L).product))
+    statsCache.get
+  }
+}
+
+/**
+ * The types of lookup columns on which Spark offers a comparison to the 
connector as a lookup
+ * candidate. The connector evaluates a selected candidate in its store, so 
Spark offers only types
+ * whose values a store compares as Spark does. A comparison on any other type 
stays in Spark's
+ * residual condition.
+ */
+object ExternalLookupKeyTypes {
+  /**
+   * Whether Spark offers `=` on the lookup column `column`, by its declared 
type: integral types,
+   * BOOLEAN, DECIMAL, DATE, TIMESTAMP, TIMESTAMP_NTZ, BINARY, and STRING and 
VARCHAR whose
+   * collation compares bytes, such as UTF8_BINARY. FLOAT and DOUBLE are not 
offered, because
+   * stores treat NaN and -0.0 in different ways, nor CHAR, which Spark pads 
on read, nor strings
+   * with another collation, nor complex types, nor any other type. VARCHAR is 
not offered under
+   * `spark.sql.charVarchar.standardSemantics.enabled` either, because Spark 
then trims trailing
+   * blanks on read, so a store that compares the stored value could miss a 
row.
+   *
+   * Analysis reads a CHAR or VARCHAR column as a STRING and keeps its 
declared type in the
+   * metadata, so the column's data type alone does not tell.
+   */
+  def supportsEquality(column: Attribute): Boolean =
+    
supportsEquality(CharVarcharUtils.getRawType(column.metadata).getOrElse(column.dataType))
+
+  private def supportsEquality(dataType: DataType): Boolean = dataType match {
+    case ByteType | ShortType | IntegerType | LongType | BooleanType | 
DateType | TimestampType |
+        TimestampNTZType | BinaryType | _: DecimalType => true
+    case _: CharType => false
+    case varchar: VarcharType =>
+      !SQLConf.get.charVarcharStandardSemantics && 
varchar.supportsBinaryEquality

Review Comment:
   **Nit (P3):** The key-type matrix tests `VARCHAR(3)` only with the default 
`UTF8_BINARY` collation; `UTF8_LCASE`, `UNICODE` and `UTF8_BINARY_RTRIM` appear 
only on `STRING`, which takes the `StringType` case. Dropping `&& 
varchar.supportsBinaryEquality` would make Spark offer `code = ?` on a 
`VARCHAR(3) COLLATE UTF8_LCASE` column, whose collation the column metadata 
keeps, and a store that compares bytes would then miss rows that Spark treats 
as equal, which the re-check of returned rows cannot recover; no test would 
fail. Suggested fix: add `VARCHAR(3)` with those three collations to the types 
that the matrix expects not to be offered, as for `STRING`.
   
   **Verification:**
   - **Regression:** Dropping the binary-equality condition from the VARCHAR 
case of the lookup key-type rule makes the key-type matrix fail for a VARCHAR 
column collated with UTF8_LCASE, which Spark must not offer as a lookup key.



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