viirya commented on code in PR #60055:
URL: https://github.com/apache/spark/pull/60055#discussion_r4515407521


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinExec.scala:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.SparkException
+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, GreaterThan, 
GreaterThanOrEqual,
+  LessThan, LessThanOrEqual, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.{JoinType, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.ExternalLookupTransform
+import org.apache.spark.sql.catalyst.plans.physical.Partitioning
+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.sql.internal.SQLConf
+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],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    lookupKeyPredicates: Seq[String],
+    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, and the
+  // lookup-side stages turn them into rows of `transformedLookup`. The lookup 
columns keep their
+  // analyzed order, and take the types and nullability of those rows. In 
`lookupInput`, the
+  // 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 transformedLookup = 
lookupTransforms.lastOption.map(_.output)
+    .getOrElse(lookupInput)
+  private lazy val inputByLookupOutput =
+    AttributeMap(transformedLookup.map(attr => attr -> attr))
+  private lazy val lookupColumns = lookupOutput.map(inputByLookupOutput)
+
+  override def output: Seq[Attribute] = joinType match {
+    case LeftOuter => child.output ++ 
lookupColumns.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => child.output
+    case _ => child.output ++ lookupColumns
+  }
+
+  // Each task joins its input rows where they are, so the stream side's 
partitioning holds.
+  override def outputPartitioning: Partitioning = child.outputPartitioning
+
+  // The conjuncts of the residual condition that read only stream columns, 
and the rest. A stream
+  // row that fails the first cannot match, so the join checks them on each 
stream row before the
+  // lookup, and does not request the row's key. The join then evaluates them 
for rows without a
+  // match too, and before the conjuncts written ahead of them, so only 
conjuncts that can never
+  // fail are checked early: those that ExprUtils.canEvaluateUnconditionally 
accepts, as for the
+  // streamed side of other joins. `Expression.throwable` is not enough, 
because most expressions
+  // that can fail, such as an ANSI cast, do not report it. A conjunct that 
reads no column stays
+  // with the rest: the optimizer has already folded it if it could.
+  private def splitResidualCondition: (Option[Expression], Option[Expression]) 
= {
+    val (streamConjuncts, joinedConjuncts) =
+      residualCondition.toSeq.flatMap(splitConjunctivePredicates).partition { 
conjunct =>
+        conjunct.references.nonEmpty && 
conjunct.references.subsetOf(child.outputSet) &&
+          ExprUtils.canEvaluateUnconditionally(conjunct)
+      }
+    (streamConjuncts.reduceOption(And), joinedConjuncts.reduceOption(And))
+  }
+
+  // Spark does not trust the connector to evaluate the selected lookup 
predicates as Spark does,
+  // so it checks them itself on each row that the connector returns. The 
check reads that row
+  // after the parameter row of its request, and compares lookup key i with 
parameter i as its
+  // selected predicate does.
+  private def lookupKeyCheck: Option[Expression] = 
lookupParameters.indices.map { index =>
+    val parameter = lookupParameters(index)
+    val parameterValue = BoundReference(index, parameter.dataType, 
parameter.nullable)
+    val keyOrdinal = lookupInput.indexWhere(_.exprId == 
lookupKeys(index).exprId)
+    val key = lookupInput(keyOrdinal)
+    val keyValue = BoundReference(lookupParameters.length + keyOrdinal, 
key.dataType, key.nullable)
+    lookupKeyPredicates(index) match {
+      case "=" => EqualTo(keyValue, parameterValue)
+      case "<=>" => EqualNullSafe(keyValue, parameterValue)
+      case "<" => LessThan(keyValue, parameterValue)

Review Comment:
   The test connectors apply ranges exactly, so nothing exercises this 
re-check. Could you add a connector that returns rows outside the selected 
range, covering all four operators and the swapped form?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinExec.scala:
##########
@@ -0,0 +1,232 @@
+/*
+ * 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.SparkException
+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, GreaterThan, 
GreaterThanOrEqual,
+  LessThan, LessThanOrEqual, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.{JoinType, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.ExternalLookupTransform
+import org.apache.spark.sql.catalyst.plans.physical.Partitioning
+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.sql.internal.SQLConf
+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],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    lookupKeyPredicates: Seq[String],
+    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, and the
+  // lookup-side stages turn them into rows of `transformedLookup`. The lookup 
columns keep their
+  // analyzed order, and take the types and nullability of those rows. In 
`lookupInput`, the
+  // 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 transformedLookup = 
lookupTransforms.lastOption.map(_.output)
+    .getOrElse(lookupInput)
+  private lazy val inputByLookupOutput =
+    AttributeMap(transformedLookup.map(attr => attr -> attr))
+  private lazy val lookupColumns = lookupOutput.map(inputByLookupOutput)
+
+  override def output: Seq[Attribute] = joinType match {
+    case LeftOuter => child.output ++ 
lookupColumns.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => child.output
+    case _ => child.output ++ lookupColumns
+  }
+
+  // Each task joins its input rows where they are, so the stream side's 
partitioning holds.
+  override def outputPartitioning: Partitioning = child.outputPartitioning
+
+  // The conjuncts of the residual condition that read only stream columns, 
and the rest. A stream
+  // row that fails the first cannot match, so the join checks them on each 
stream row before the
+  // lookup, and does not request the row's key. The join then evaluates them 
for rows without a
+  // match too, and before the conjuncts written ahead of them, so only 
conjuncts that can never
+  // fail are checked early: those that ExprUtils.canEvaluateUnconditionally 
accepts, as for the
+  // streamed side of other joins. `Expression.throwable` is not enough, 
because most expressions
+  // that can fail, such as an ANSI cast, do not report it. A conjunct that 
reads no column stays
+  // with the rest: the optimizer has already folded it if it could.
+  private def splitResidualCondition: (Option[Expression], Option[Expression]) 
= {
+    val (streamConjuncts, joinedConjuncts) =
+      residualCondition.toSeq.flatMap(splitConjunctivePredicates).partition { 
conjunct =>
+        conjunct.references.nonEmpty && 
conjunct.references.subsetOf(child.outputSet) &&
+          ExprUtils.canEvaluateUnconditionally(conjunct)
+      }
+    (streamConjuncts.reduceOption(And), joinedConjuncts.reduceOption(And))
+  }
+
+  // Spark does not trust the connector to evaluate the selected lookup 
predicates as Spark does,
+  // so it checks them itself on each row that the connector returns. The 
check reads that row
+  // after the parameter row of its request, and compares lookup key i with 
parameter i as its
+  // selected predicate does.
+  private def lookupKeyCheck: Option[Expression] = 
lookupParameters.indices.map { index =>
+    val parameter = lookupParameters(index)
+    val parameterValue = BoundReference(index, parameter.dataType, 
parameter.nullable)
+    val keyOrdinal = lookupInput.indexWhere(_.exprId == 
lookupKeys(index).exprId)
+    val key = lookupInput(keyOrdinal)
+    val keyValue = BoundReference(lookupParameters.length + keyOrdinal, 
key.dataType, key.nullable)
+    lookupKeyPredicates(index) match {
+      case "=" => EqualTo(keyValue, parameterValue)
+      case "<=>" => EqualNullSafe(keyValue, parameterValue)
+      case "<" => LessThan(keyValue, parameterValue)
+      case "<=" => LessThanOrEqual(keyValue, parameterValue)
+      case ">" => GreaterThan(keyValue, parameterValue)
+      case ">=" => GreaterThanOrEqual(keyValue, parameterValue)
+      case other => throw SparkException.internalError(s"Unexpected lookup 
predicate $other")
+    }
+  }.reduceOption(And)
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      
residualCondition.map(_.references.intersect(child.outputSet)).getOrElse(AttributeSet.empty)
+
+  // A connector's custom metrics are registered under prefixed keys, so that 
they never collide
+  // with the operator's own metrics; the UI shows the connector's 
descriptions.
+  override lazy val customMetrics: Map[String, SQLMetric] =
+    scan.supportedCustomMetrics().map { metric =>
+      ExternalLookupJoinExec.sourceMetricKey(metric.name()) ->
+        SQLMetrics.createV2CustomMetric(sparkContext, metric)
+    }.toMap
+
+  override protected lazy val sparkMetrics: Map[String, SQLMetric] =
+    ExternalLookupJoinExec.OPERATOR_METRICS.map { metric =>
+      val sqlMetric = if (metric.isTiming) {
+        SQLMetrics.createNanoTimingMetric(sparkContext, metric.description)
+      } else {
+        SQLMetrics.createMetric(sparkContext, metric.description)
+      }
+      metric.name -> sqlMetric
+    }.toMap
+
+  override protected def doExecute(): RDD[InternalRow] = {
+    postDriverMetrics(scan.reportDriverMetrics().map { metric =>
+      new CustomTaskMetric {
+        override def name(): String = 
ExternalLookupJoinExec.sourceMetricKey(metric.name())
+        override def value(): Long = metric.value()
+      }
+    })
+    val (streamCondition, joinedCondition) = splitResidualCondition
+    val evaluatorFactory = new ExternalLookupJoinEvaluatorFactory(
+      tableName,
+      lookupParameters,
+      nullSafeParameters,
+      lookupKeyCheck,
+      child.output,
+      lookupInput,
+      lookupTransforms,
+      transformedLookup,
+      output,
+      joinType,
+      streamCondition,
+      joinedCondition.map(_.transform {
+        case attr: Attribute => inputByLookupOutput.getOrElse(attr, attr)
+      }),
+      readerFactory,
+      math.min(ExternalLookupJoinExec.MAX_PARAMETER_ROWS_PER_REQUEST, 
maxParameterRowsPerRequest),
+      conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES),
+      ExternalLookupJoinMetrics(
+        outputRows = longMetric("numOutputRows"),
+        inputRows = longMetric("numInputRows"),
+        inputBatches = longMetric("numInputBatches"),
+        requests = longMetric("numLookupRequests"),
+        parameterRows = longMetric("numLookupParameterRows"),
+        lookupTime = longMetric("lookupTime")),
+      new ExternalLookupReaderMetrics(customMetrics))
+    if (conf.usePartitionEvaluator) {
+      child.execute().mapPartitionsWithEvaluator(evaluatorFactory)
+    } else {
+      child.execute().mapPartitionsWithIndexInternal { (index, input) =>
+        evaluatorFactory.createEvaluator().eval(index, input)
+      }
+    }
+  }
+
+  override protected def withNewChildInternal(newChild: SparkPlan): 
ExternalLookupJoinExec =
+    copy(child = newChild)
+
+  override def simpleString(maxFields: Int): String = {

Review Comment:
   `explain` shows only the scan description here. Could the physical node also 
show the join type, selected predicates, lookup stages and residual, keeping 
the redaction?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,498 @@
+/*
+ * 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 scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap,
+  AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, 
PythonUDF}
+import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupJoin,
+  ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, 
Filter, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, 
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,
+  SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+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.
+    if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+      prepared.foreach { node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+      }
+    }
+    prepared
+  }
+
+  // The optimizer folds `WHERE false` on the lookup side into an empty 
relation, and a condition
+  // such as `s.id = r.id AND false` into `false`. Such a join needs no 
connector call.
+  private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+    join.right.maxRows.contains(0L) || (join.condition match {
+      case Some(Literal(value, BooleanType)) => value == null || value == false
+      case _ => false
+    })
+
+  private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+    val nullLookupColumns = join.right.output.map { attr =>
+      Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+    }
+    val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+    join.joinType match {
+      case LeftOuter => unmatched
+      case LeftAnti => join.left
+      // The stream side is kept under a false filter rather than replaced by 
an empty relation,
+      // so that its sources, watermarks and stateful operators still run in 
every micro-batch.
+      // PruneFilters decides whether a streaming subplan may be pruned.
+      case LeftSemi => Filter(Literal.FalseLiteral, join.left)
+      case _ => Filter(Literal.FalseLiteral, unmatched)
+    }
+  }
+
+  private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+    // Analysis already rejects a lookup side with a stage that cannot be 
evaluated, or with another
+    // operator; this is a fallback.
+    val hasUnevaluableStage = join.right.exists {
+      case node @ (_: Project | _: Filter) =>
+        
!node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage)
+      case _ => false
+    }
+    // The lookup-side stages are built here, and no later rule reaches them. 
withField and
+    // dropFields values cannot be evaluated until 
ReplaceUpdateFieldsExpression, in the
+    // optimizer's last batch, lowers them, so the same rule lowers them now.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(join.right))
+    }).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val relation = lookupPlan.relation
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    // A Python or external UDF over lookup columns cannot run in the 
residual. The rules that move
+    // one out of a join condition match only Join and run later, so this rule 
does it: an inner
+    // join evaluates the conjunct in a filter above the join, and other join 
types are rejected.
+    if (join.joinType != Inner) {
+      conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+        case _: ExternalUserDefinedFunction =>
+          throw 
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+        case _ =>
+          throw 
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+      }
+    }
+    val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, 
index) =>
+      ExternalLookupJoinShapes.lookupComparison(
+        conjunct, join.left.outputSet, join.right.outputSet).flatMap { 
comparison =>
+        tableColumn(comparison.lookupField, lookupPlan).map { column =>
+          OfferedLookupPredicate(
+            comparison.parameter, column, index, comparison.predicateName, 
comparison.nullSafe)
+        }
+      }
+    }
+    if (offeredCandidates.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName)))
+    }
+
+    val scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+    // A column is offered under the table's name for it. Under 
case-insensitive analysis, the
+    // condition may spell it in another case, as `ID` for `id`, with the same 
exprId; filter
+    // pushdown renames it the same way, with 
DataSourceStrategy.normalizeExprs.
+    val columnNames = AttributeMap(relation.output.map(attr => attr -> 
attr.name))
+    // Filters are pushed before the lookup predicates are selected, as
+    // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the 
columns of a scan.
+    // Unlike a batch scan, Spark evaluates every pushed filter again on the 
returned rows, not only
+    // the ones that the source rejects, so a source that accepts a filter but 
applies it in another
+    // way, or not at all, cannot change the result.
+    PushDownUtils.pushFilters(
+      scanBuilder,
+      DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, 
relation.output),
+      partitionFields = None)
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition(lookupSideUDF(join, _).isEmpty)
+    val (residualFirst, residualRest) = residualConjuncts.partition { conjunct 
=>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    // A conjunction evaluates its next conjunct after a NULL, so a NULL in 
the first group reads
+    // as false: a hash join never matches a NULL key either. A row matches 
only when the whole
+    // condition is true, so this changes no result.
+    val residual = if (residualRest.isEmpty) residualFirst else {
+      residualFirst.map { conjunct =>
+        if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) 
else conjunct
+      } ++ residualRest
+    }
+
+    // The prepared join replaces the analyzed one, so it keeps the analyzed 
lookup attributes in
+    // their analyzed order; execution projects the lookup results into them. 
It keeps only those
+    // required above the join: the ones that a parent projection reads, to 
which ColumnPruning has
+    // narrowed `requiredLookupOutput` during operator optimization, and the 
ones that `joinFilter`
+    // reads. `joinFilter` holds the conjuncts with a Python or external UDF 
over lookup columns,
+    // which an inner join evaluates in a filter above it; other join types 
reject them above.
+    val requiredAbove = join.joinType match {
+      case LeftSemi | LeftAnti => AttributeSet.empty
+      case _ => AttributeSet(join.requiredLookupOutput ++ 
joinFilter.flatMap(_.references))
+    }
+    val lookupOutput = join.right.output.filter(requiredAbove.contains)
+    val residualLookupReferences =
+      residual.flatMap(_.references).filter(join.right.outputSet.contains)
+    // The columns are pruned only now, once the lookup predicates are 
selected. A column that a
+    // selected lookup predicate reads is kept, because Spark checks the 
predicate itself on every
+    // row that the connector returns. V2ScanRelationPushDown.pruneColumns 
prunes a scan the same
+    // way, through PushDownUtils.pruneColumns, which this rule cannot call: 
it can pass
+    // nested-pruned columns, while a lookup scan receives only whole 
top-level columns, and it
+    // binds the read schema by the resolver, while a lookup scan binds it by 
exact name.
+    val (prunedUpperStages, requiredBySegment) =
+      pruneLookupTransforms(lookupOutput ++ residualLookupReferences, 
lookupPlan.upperStages)
+    val segmentFields =
+      lookupPlan.fields.filter(field => 
requiredBySegment.contains(field.toAttribute))
+    val segmentFilter =
+      (lookupPlan.filtersPushDown ++ 
lookupPlan.filtersStayUp).reduceOption(And)
+    val requiredColumns = relation.output.filter(
+      (AttributeSet(segmentFields.flatMap(_.references)) ++
+        segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++
+        AttributeSet(selectedPredicates.map(_.projectedField))).contains)
+    // As V2ScanRelationPushDown does above a scan: the filters, then a 
projection when it computes
+    // more than the columns it selects. Execution reads a selected column by 
its id.
+    val segmentStages = segmentFilter.map(ExternalLookupFilter(_, 
relation.output)).toSeq ++
+      Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) {
+        ExternalLookupProject(segmentFields, relation.output)
+      }
+    scanBuilder match {
+      case builder: SupportsPushDownRequiredColumns =>
+        builder.pruneColumns(requiredColumns.toStructType)
+      case _ =>
+    }
+
+    def nonNull[T](value: T, method: String): T = Option(value).getOrElse {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "NULL_RESULT", Map("method" -> method))
+    }
+    val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type, 
where a column, nested
+    // field, array element or map value is nullable only when both the table 
and the read schema
+    // allow nulls: the join fails the task on a null that either rules out, 
because Spark relied
+    // on the table's nullability while it optimized the query.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "Scan.readSchema()"))
+    val columnsByName = relation.output.groupBy(_.name)
+    val lookupInput = readSchema.fields.map { field =>
+      columnsByName.getOrElse(field.name, Nil).find { attr =>
+        DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      }.map { attr =>
+        attr.withDataType(withStricterNullability(attr.dataType, 
field.dataType))
+          .withNullability(attr.nullable && field.nullable)
+      }.getOrElse {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    val readExprIds = lookupInput.map(_.exprId).toSet
+    requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { 
attr =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "MISSING_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(attr.name))))
+    }
+    val externalLookup = nonNull(scan.toExternalLookup(), 
"Scan.toExternalLookup()")
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory =
+      nonNull(externalLookup.createReaderFactory(), 
"ExternalLookup.createReaderFactory()")
+    // With a range selected, one stored row can match several parameter rows 
of one request, and
+    // the source would have to return it once for each of them, with each 
ordinal. Spark cannot
+    // detect a missing one, so it sends one parameter row per request then.
+    val selectsRange = selectedPredicates.exists { predicate =>
+      Set("<", "<=", ">", ">=").contains(predicate.predicateName)
+    }
+    val parameterRowsPerRequest = if (selectsRange) 1 else 
maxParameterRowsPerRequest

Review Comment:
   This caps stream rows rather than distinct parameter rows, so equal stream 
rows each send a request: three identical rows give request sizes 1, 1, 1. 
#60087 also disables the cache for ranges. Could a batch end at the second 
distinct key instead? Each request would still hold exactly one parameter row, 
so the connector contract would not change.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,498 @@
+/*
+ * 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 scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap,
+  AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, 
PythonUDF}
+import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupJoin,
+  ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, 
Filter, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, 
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,
+  SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+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.
+    if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+      prepared.foreach { node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+      }
+    }
+    prepared
+  }
+
+  // The optimizer folds `WHERE false` on the lookup side into an empty 
relation, and a condition
+  // such as `s.id = r.id AND false` into `false`. Such a join needs no 
connector call.
+  private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+    join.right.maxRows.contains(0L) || (join.condition match {
+      case Some(Literal(value, BooleanType)) => value == null || value == false
+      case _ => false
+    })
+
+  private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+    val nullLookupColumns = join.right.output.map { attr =>
+      Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+    }
+    val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+    join.joinType match {
+      case LeftOuter => unmatched
+      case LeftAnti => join.left
+      // The stream side is kept under a false filter rather than replaced by 
an empty relation,
+      // so that its sources, watermarks and stateful operators still run in 
every micro-batch.
+      // PruneFilters decides whether a streaming subplan may be pruned.
+      case LeftSemi => Filter(Literal.FalseLiteral, join.left)
+      case _ => Filter(Literal.FalseLiteral, unmatched)
+    }
+  }
+
+  private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+    // Analysis already rejects a lookup side with a stage that cannot be 
evaluated, or with another
+    // operator; this is a fallback.
+    val hasUnevaluableStage = join.right.exists {
+      case node @ (_: Project | _: Filter) =>
+        
!node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage)
+      case _ => false
+    }
+    // The lookup-side stages are built here, and no later rule reaches them. 
withField and
+    // dropFields values cannot be evaluated until 
ReplaceUpdateFieldsExpression, in the
+    // optimizer's last batch, lowers them, so the same rule lowers them now.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(join.right))
+    }).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val relation = lookupPlan.relation
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    // A Python or external UDF over lookup columns cannot run in the 
residual. The rules that move
+    // one out of a join condition match only Join and run later, so this rule 
does it: an inner
+    // join evaluates the conjunct in a filter above the join, and other join 
types are rejected.
+    if (join.joinType != Inner) {
+      conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+        case _: ExternalUserDefinedFunction =>
+          throw 
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+        case _ =>
+          throw 
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+      }
+    }
+    val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, 
index) =>
+      ExternalLookupJoinShapes.lookupComparison(
+        conjunct, join.left.outputSet, join.right.outputSet).flatMap { 
comparison =>
+        tableColumn(comparison.lookupField, lookupPlan).map { column =>
+          OfferedLookupPredicate(
+            comparison.parameter, column, index, comparison.predicateName, 
comparison.nullSafe)
+        }
+      }
+    }
+    if (offeredCandidates.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName)))
+    }
+
+    val scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+    // A column is offered under the table's name for it. Under 
case-insensitive analysis, the
+    // condition may spell it in another case, as `ID` for `id`, with the same 
exprId; filter
+    // pushdown renames it the same way, with 
DataSourceStrategy.normalizeExprs.
+    val columnNames = AttributeMap(relation.output.map(attr => attr -> 
attr.name))
+    // Filters are pushed before the lookup predicates are selected, as
+    // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the 
columns of a scan.
+    // Unlike a batch scan, Spark evaluates every pushed filter again on the 
returned rows, not only
+    // the ones that the source rejects, so a source that accepts a filter but 
applies it in another
+    // way, or not at all, cannot change the result.
+    PushDownUtils.pushFilters(
+      scanBuilder,
+      DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, 
relation.output),
+      partitionFields = None)
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition(lookupSideUDF(join, _).isEmpty)
+    val (residualFirst, residualRest) = residualConjuncts.partition { conjunct 
=>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    // A conjunction evaluates its next conjunct after a NULL, so a NULL in 
the first group reads
+    // as false: a hash join never matches a NULL key either. A row matches 
only when the whole
+    // condition is true, so this changes no result.
+    val residual = if (residualRest.isEmpty) residualFirst else {
+      residualFirst.map { conjunct =>
+        if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) 
else conjunct
+      } ++ residualRest
+    }
+
+    // The prepared join replaces the analyzed one, so it keeps the analyzed 
lookup attributes in
+    // their analyzed order; execution projects the lookup results into them. 
It keeps only those
+    // required above the join: the ones that a parent projection reads, to 
which ColumnPruning has
+    // narrowed `requiredLookupOutput` during operator optimization, and the 
ones that `joinFilter`
+    // reads. `joinFilter` holds the conjuncts with a Python or external UDF 
over lookup columns,
+    // which an inner join evaluates in a filter above it; other join types 
reject them above.
+    val requiredAbove = join.joinType match {
+      case LeftSemi | LeftAnti => AttributeSet.empty
+      case _ => AttributeSet(join.requiredLookupOutput ++ 
joinFilter.flatMap(_.references))
+    }
+    val lookupOutput = join.right.output.filter(requiredAbove.contains)
+    val residualLookupReferences =
+      residual.flatMap(_.references).filter(join.right.outputSet.contains)
+    // The columns are pruned only now, once the lookup predicates are 
selected. A column that a
+    // selected lookup predicate reads is kept, because Spark checks the 
predicate itself on every
+    // row that the connector returns. V2ScanRelationPushDown.pruneColumns 
prunes a scan the same
+    // way, through PushDownUtils.pruneColumns, which this rule cannot call: 
it can pass
+    // nested-pruned columns, while a lookup scan receives only whole 
top-level columns, and it
+    // binds the read schema by the resolver, while a lookup scan binds it by 
exact name.
+    val (prunedUpperStages, requiredBySegment) =
+      pruneLookupTransforms(lookupOutput ++ residualLookupReferences, 
lookupPlan.upperStages)
+    val segmentFields =
+      lookupPlan.fields.filter(field => 
requiredBySegment.contains(field.toAttribute))
+    val segmentFilter =
+      (lookupPlan.filtersPushDown ++ 
lookupPlan.filtersStayUp).reduceOption(And)
+    val requiredColumns = relation.output.filter(
+      (AttributeSet(segmentFields.flatMap(_.references)) ++
+        segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++
+        AttributeSet(selectedPredicates.map(_.projectedField))).contains)
+    // As V2ScanRelationPushDown does above a scan: the filters, then a 
projection when it computes
+    // more than the columns it selects. Execution reads a selected column by 
its id.
+    val segmentStages = segmentFilter.map(ExternalLookupFilter(_, 
relation.output)).toSeq ++
+      Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) {
+        ExternalLookupProject(segmentFields, relation.output)
+      }
+    scanBuilder match {
+      case builder: SupportsPushDownRequiredColumns =>
+        builder.pruneColumns(requiredColumns.toStructType)
+      case _ =>
+    }
+
+    def nonNull[T](value: T, method: String): T = Option(value).getOrElse {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "NULL_RESULT", Map("method" -> method))
+    }
+    val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type, 
where a column, nested
+    // field, array element or map value is nullable only when both the table 
and the read schema
+    // allow nulls: the join fails the task on a null that either rules out, 
because Spark relied
+    // on the table's nullability while it optimized the query.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "Scan.readSchema()"))
+    val columnsByName = relation.output.groupBy(_.name)
+    val lookupInput = readSchema.fields.map { field =>
+      columnsByName.getOrElse(field.name, Nil).find { attr =>
+        DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      }.map { attr =>
+        attr.withDataType(withStricterNullability(attr.dataType, 
field.dataType))
+          .withNullability(attr.nullable && field.nullable)
+      }.getOrElse {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    val readExprIds = lookupInput.map(_.exprId).toSet
+    requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { 
attr =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "MISSING_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(attr.name))))
+    }
+    val externalLookup = nonNull(scan.toExternalLookup(), 
"Scan.toExternalLookup()")
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory =
+      nonNull(externalLookup.createReaderFactory(), 
"ExternalLookup.createReaderFactory()")
+    // With a range selected, one stored row can match several parameter rows 
of one request, and
+    // the source would have to return it once for each of them, with each 
ordinal. Spark cannot
+    // detect a missing one, so it sends one parameter row per request then.
+    val selectsRange = selectedPredicates.exists { predicate =>
+      Set("<", "<=", ">", ">=").contains(predicate.predicateName)
+    }
+    val parameterRowsPerRequest = if (selectsRange) 1 else 
maxParameterRowsPerRequest
+
+    val prepared = PreparedExternalLookupJoin(
+      join.left,
+      tableName,
+      scan,
+      readerFactory,
+      parameterRowsPerRequest,
+      lookupInput,
+      lookupOutput,
+      rebindLookupTransforms(segmentStages ++ prunedUpperStages, lookupInput),
+      selectedPredicates.map(_.parameter),
+      selectedPredicates.map(_.nullSafe),
+      selectedPredicates.map(_.projectedField),
+      selectedPredicates.map(_.predicateName),
+      join.joinType,
+      residual.reduceOption(And))
+    joinFilter.reduceOption(And).map(Filter(_, prepared)).getOrElse(prepared)
+  }
+
+  /**
+   * The read schema's type of a column, where a nested field, array element 
or map value is
+   * nullable only when the table's type allows nulls there too. The two types 
differ only in
+   * nullability.
+   */
+  private def withStricterNullability(tableType: DataType, readType: 
DataType): DataType =
+    (tableType, readType) match {
+      case (table: StructType, read: StructType) =>
+        StructType(table.fields.zip(read.fields).map { case (tableField, 
readField) =>
+          readField.copy(
+            dataType = withStricterNullability(tableField.dataType, 
readField.dataType),
+            nullable = tableField.nullable && readField.nullable)
+        })
+      case (table: ArrayType, read: ArrayType) =>
+        ArrayType(
+          withStricterNullability(table.elementType, read.elementType),
+          table.containsNull && read.containsNull)
+      case (table: MapType, read: MapType) =>
+        MapType(
+          withStricterNullability(table.keyType, read.keyType),
+          withStricterNullability(table.valueType, read.valueType),
+          table.valueContainsNull && read.valueContainsNull)
+      case _ => readType
+    }
+
+  /** A Python or external UDF in the conjunct that reads lookup columns. */
+  private def lookupSideUDF(join: ExternalLookupJoin, conjunct: Expression): 
Option[Expression] =
+    conjunct.find { e =>
+      (PythonUDF.isScalarPythonUDF(e) || 
e.isInstanceOf[ExternalUserDefinedFunction]) &&
+        !e.references.subsetOf(join.left.outputSet)
+    }
+
+  /**
+   * An equality between an expression over the stream side and one over the 
lookup side, each
+   * reading a column, which a hash join would use as a join key.
+   */
+  private def isJoinKeyEquality(join: ExternalLookupJoin, conjunct: 
Expression): Boolean = {
+    def readsOnly(expression: Expression, plan: LogicalPlan): Boolean =
+      expression.references.nonEmpty && 
expression.references.subsetOf(plan.outputSet)
+    def betweenSides(first: Expression, second: Expression): Boolean =
+      (readsOnly(first, join.left) && readsOnly(second, join.right)) ||
+        (readsOnly(first, join.right) && readsOnly(second, join.left))
+    conjunct match {
+      case EqualTo(first, second) => betweenSides(first, second)
+      case EqualNullSafe(first, second) => betweenSides(first, second)
+      case _ => false
+    }
+  }
+
+  /**
+   * Maps the connector's selection back to the offered candidates, in the 
connector's order, which
+   * defines the fields of each request parameter row. Selections are matched 
by object identity
+   * rather than by equality, so two candidates of the same shape, for example 
the same lookup field
+   * compared with two different join-side values, remain distinguishable.
+   */
+  private def selectedCandidates(
+      tableName: String,
+      offered: Array[V2Predicate],
+      candidates: Seq[OfferedLookupPredicate],
+      selected: Array[V2Predicate]): Seq[OfferedLookupPredicate] = {
+    if (selected == null) {
+      throw 
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, 
"NULL_RESULT",
+        Map("method" -> "SupportsExternalLookup.selectLookupPredicates()"))
+    }
+    if (selected.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_PREDICATE", Map("table" -> toSQLId(tableName)))
+    }
+    val candidateByPredicate = new IdentityHashMap[V2Predicate, 
OfferedLookupPredicate]()
+    offered.zip(candidates).foreach { case (predicate, candidate) =>
+      candidateByPredicate.put(predicate, candidate)
+    }
+    val seen = Collections.newSetFromMap(new IdentityHashMap[V2Predicate, 
java.lang.Boolean]())
+    selected.toSeq.map { predicate =>
+      // A null element is not an offered instance either.
+      val candidate = Option(predicate).map(candidateByPredicate.get).orNull
+      if (candidate == null) {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNOFFERED_SELECTED_PREDICATE",
+          Map("predicate" -> 
Option(predicate).map(_.describe()).getOrElse("null")))
+      }
+      if (!seen.add(predicate)) {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "DUPLICATE_SELECTED_PREDICATE", Map("predicate" -> 
predicate.describe()))
+      }
+      candidate
+    }
+  }
+
+  private case class OfferedLookupPredicate(
+      parameter: Expression,
+      projectedField: Attribute,
+      conjunctIndex: Int,
+      predicateName: String,
+      nullSafe: Boolean)
+
+  /**
+   * A lookup side, split the way V2ScanRelationPushDown.pruneColumns splits a 
scan. The segment
+   * over the relation is what ScanOperation collapses into one projection and 
its filters, with
+   * aliases substituted. The stages above it are the projections and filters 
that ScanOperation
+   * cannot collapse, such as a projection whose costly expression a stage 
above reads more than
+   * once, in evaluation order.
+   */
+  private case class LookupPlan(
+      relation: DataSourceV2Relation,
+      fields: Seq[NamedExpression],
+      filtersStayUp: Seq[Expression],
+      filtersPushDown: Seq[Expression],
+      upperStages: Seq[ExternalLookupTransform])
+
+  /** The lookup side below its topmost operator at which ScanOperation 
reaches the relation. */
+  @tailrec
+  private def extractLookupPlan(
+      plan: LogicalPlan,
+      upperStages: List[ExternalLookupTransform] = Nil): Option[LookupPlan] = 
plan match {
+    case ScanOperation(fields, filtersStayUp, filtersPushDown, 
LookupRelation(relation)) =>
+      Some(LookupPlan(relation, fields, filtersStayUp, filtersPushDown, 
upperStages))
+    // The walk goes down from the join, so each stage is evaluated before 
those found earlier.
+    case Project(projectList, child) =>
+      extractLookupPlan(child, ExternalLookupProject(projectList, 
child.output) :: upperStages)

Review Comment:
   No test reaches this branch, as the existing plans all collapse into the 
`ScanOperation` segment. Please cover stages that cannot collapse, e.g. 
`.select($"id".as("k"), upper($"department").as("d")).select($"k", concat($"d", 
lit("-"), $"d").as("dd"))`, including key resolution through the alias and 
pruning across stages.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
BinaryComparison,
+  Cast, EqualNullSafe, EqualTo, Expression, ExprUtils, 
ExternalUserDefinedFunction, GreaterThan,
+  GreaterThanOrEqual, LessThan, LessThanOrEqual, NamedExpression, PythonUDF, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_HINT, 
EXTERNAL_LOOKUP_JOIN,
+  TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, IntegralType, LongType, ShortType, 
StringType,
+  TimestampNTZType, TimestampType, VarcharType}
+
+/**
+ * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint 
asks an external
+ * lookup join to read. The external lookup join rules consume it when they 
form the join.
+ *
+ * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. 
This hint is not,
+ * because that representation cannot keep two of its guarantees:
+ *  - A strategy hint that conflicts with it must fail the query. [[HintInfo]] 
holds one strategy,
+ *    and `ResolveJoinStrategyHints` merges a strategy hint on an already 
hinted relation into the
+ *    existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one 
strategy and only warns.
+ *  - It selects how the lookup side is read, not a physical join. 
`EliminateResolvedHint` moves
+ *    every [[ResolvedHint]] it can attach into `Join.hint`, for physical join 
selection.
+ */
+case class ExternalLookupHint(child: LogicalPlan) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
ExternalLookupHint =
+    copy(child = newChild)
+}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Lookup-side attributes still required above 
this join. They are
+ *   part of this node's references, so column pruning keeps them on the 
lookup side.
+ *   `ColumnPruning` narrows them to what the parent reads, and 
`PrepareExternalLookupJoin` prunes
+ *   the lookup scan to them.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => left.output
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  // As an ordinary join's: a semi or anti join returns at most its stream 
rows, and the other join
+  // types get the product of both sides' sizes.
+  override def stats: Statistics = joinType match {
+    case LeftSemi | LeftAnti => left.stats
+    case _ => super.stats
+  }
+
+  override def maxRows: Option[Long] = joinType match {
+    case LeftSemi | LeftAnti => left.maxRows
+    case _ => None
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/**
+ * The join-condition and lookup-side shapes that an external lookup join can 
run. Analysis,
+ * lookup planning and the optimizer rules for lookup joins share them.
+ */
+object ExternalLookupJoinShapes {
+  /**
+   * A lookup candidate: a comparison of a lookup column with a value, written 
with the lookup
+   * column on the left. `predicateName` is the name of the DSv2 `Predicate` 
that is offered to the
+   * connector for it: the SQL operator of the comparison, as 
`V2ExpressionBuilder` names it.
+   */
+  case class LookupComparison(
+      lookupField: Attribute,
+      parameter: Expression,
+      predicateName: String,
+      nullSafe: Boolean)
+
+  /**
+   * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, 
`<=>`, `<`, `<=`, `>`
+   * or `>=` between a bare lookup column and a value, in either operand 
order. When the lookup
+   * column is written on the right, the comparison is rebuilt with it on the 
left, so
+   * `s.ts < t.event_time` is offered as `event_time > ?`.
+   *
+   * The value is the other operand, which Spark evaluates for each stream row 
to fill the
+   * comparison's parameter. It may read only stream columns, and it may read 
none, as a literal
+   * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a 
parameter.
+   *
+   * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets 
Spark offer the
+   * comparison. A comparison on another column is an ordinary conjunct.
+   *
+   * @param streamOutput The output of the join's left side, the stream side.
+   * @param lookupOutput The output of the join's right side, the lookup side.
+   */
+  def lookupComparison(
+      conjunct: Expression,
+      streamOutput: AttributeSet,
+      lookupOutput: AttributeSet): Option[LookupComparison] = {
+    def isLookupComparison(lookupField: Attribute, parameter: Expression): 
Boolean =
+      lookupOutput.contains(lookupField) && 
parameter.references.subsetOf(streamOutput)
+    conjunct match {
+      case comparison: BinaryComparison if isLookupOperator(comparison) =>
+        val nullSafe = comparison.isInstanceOf[EqualNullSafe]
+        Seq(comparison, withOperandsSwapped(comparison)).collectFirst {
+          case candidate @ BinaryComparison(lookupField: Attribute, parameter)
+              if isLookupComparison(lookupField, parameter) &&
+                isOfferedOn(comparison, lookupField, parameter) =>
+            LookupComparison(lookupField, parameter, candidate.sqlOperator, 
nullSafe)
+        }
+      case _ => None
+    }
+  }
+
+  private def isLookupOperator(comparison: BinaryComparison): Boolean = 
comparison match {
+    case _: EqualTo | _: EqualNullSafe | _: LessThan | _: LessThanOrEqual | _: 
GreaterThan |
+        _: GreaterThanOrEqual => true
+    case _ => false
+  }
+
+  /**
+   * Whether Spark offers the comparison on this lookup column, with this 
parameter.
+   *
+   * Spark evaluates every parameter on every stream row, before the other 
join conditions. That
+   * is safe for an equality, as a hash join evaluates its keys on every row 
too. A range is a
+   * join condition, which a join evaluates only after its keys match, so its 
parameter must be
+   * one that cannot fail, as `cannotFail` decides.
+   */
+  private def isOfferedOn(
+      comparison: BinaryComparison,
+      lookupField: Attribute,
+      parameter: Expression): Boolean = comparison match {
+    case _: EqualTo | _: EqualNullSafe => 
ExternalLookupKeyTypes.supportsEquality(lookupField)
+    case _ =>
+      ExternalLookupKeyTypes.supportsRange(lookupField.dataType) && 
cannotFail(parameter)
+  }
+
+  /**
+   * Whether a range parameter cannot fail: 
ExprUtils.canEvaluateUnconditionally accepts it, or it
+   * is a widening numeric cast of such a value. Analysis adds such a cast 
when the stream side has
+   * a narrower type than the lookup column, as an INT column compared with a 
BIGINT key.
+   */
+  private def cannotFail(parameter: Expression): Boolean = parameter match {
+    case cast: Cast =>
+      isTotalNumericWidening(cast.child.dataType, cast.dataType) &&
+        ExprUtils.canEvaluateUnconditionally(cast.child)
+    case _ => ExprUtils.canEvaluateUnconditionally(parameter)
+  }
+
+  /**
+   * Whether a cast converts every value of its source type: an integral type 
to a wider one, or
+   * an integral type or DECIMAL to a DECIMAL with room for all of its digits. 
`Cast.canUpCast`
+   * is not enough: it also accepts casts that fail on some values, as a 
far-future DATE overflows
+   * a TIMESTAMP, and 9999999999999999999 as DECIMAL(19, 0) exceeds BIGINT 
under ANSI.
+   */
+  private def isTotalNumericWidening(from: DataType, to: DataType): Boolean = 
(from, to) match {
+    case (from: IntegralType, to: IntegralType) => from.defaultSize < 
to.defaultSize
+    case (from: IntegralType, to: DecimalType) => to.isWiderThan(from)
+    case (from: DecimalType, to: DecimalType) => to.isWiderThan(from)
+    case _ => false
+  }
+
+  /** The same comparison with its operands swapped, so that `a < b` becomes 
`b > a`. */
+  private def withOperandsSwapped(comparison: BinaryComparison): 
BinaryComparison =
+    comparison match {
+      case EqualTo(left, right) => EqualTo(right, left)
+      case EqualNullSafe(left, right) => EqualNullSafe(right, left)
+      case LessThan(left, right) => GreaterThan(right, left)
+      case LessThanOrEqual(left, right) => GreaterThanOrEqual(right, left)
+      case GreaterThan(left, right) => LessThan(right, left)
+      case GreaterThanOrEqual(left, right) => LessThanOrEqual(right, left)
+    }
+
+  /**
+   * Whether a lookup-side projection or filter can evaluate `expression` on 
the lookup results,
+   * inside the join. Python and external UDFs and subqueries are planned as 
separate operators,
+   * which a lookup-side stage cannot contain. A non-deterministic expression 
is not allowed
+   * either: the join evaluates a stage on each returned row, so one stored 
row could get
+   * different values for different stream rows, which a read of the table 
never does.
+   */
+  def canEvaluateInLookupStage(expression: Expression): Boolean =

Review Comment:
   `current_date()` / `current_timestamp()` on the lookup side, e.g. 
`.where($"valid_to" > current_timestamp())`, fails with `LOOKUP_PLAN` on the 
first micro-batch. `MicroBatchExecution` rewrites them to 
`CurrentBatchTimestamp`, which stays `Nondeterministic` until 
`IncrementalExecution` lowers it after the optimizer, so this check rejects a 
value that is constant within the batch. The same filter works on the static 
side of a stream-static join, and the startup check misses this because it 
optimizes the original expressions.
   
   Could the check accept `CurrentBatchTimestamp`, with 
`PrepareExternalLookupJoin` lowering it via `toLiteral` next to 
`ReplaceUpdateFieldsExpression`? `IncrementalExecution`'s rewrite cannot reach 
the stages. If this is not meant to be supported, it should be rejected at 
analysis with an accurate error. Either way it needs a test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
BinaryComparison,
+  Cast, EqualNullSafe, EqualTo, Expression, ExprUtils, 
ExternalUserDefinedFunction, GreaterThan,
+  GreaterThanOrEqual, LessThan, LessThanOrEqual, NamedExpression, PythonUDF, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_HINT, 
EXTERNAL_LOOKUP_JOIN,
+  TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, IntegralType, LongType, ShortType, 
StringType,
+  TimestampNTZType, TimestampType, VarcharType}
+
+/**
+ * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint 
asks an external
+ * lookup join to read. The external lookup join rules consume it when they 
form the join.
+ *
+ * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. 
This hint is not,
+ * because that representation cannot keep two of its guarantees:
+ *  - A strategy hint that conflicts with it must fail the query. [[HintInfo]] 
holds one strategy,
+ *    and `ResolveJoinStrategyHints` merges a strategy hint on an already 
hinted relation into the
+ *    existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one 
strategy and only warns.
+ *  - It selects how the lookup side is read, not a physical join. 
`EliminateResolvedHint` moves
+ *    every [[ResolvedHint]] it can attach into `Join.hint`, for physical join 
selection.
+ */
+case class ExternalLookupHint(child: LogicalPlan) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
ExternalLookupHint =
+    copy(child = newChild)
+}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Lookup-side attributes still required above 
this join. They are
+ *   part of this node's references, so column pruning keeps them on the 
lookup side.
+ *   `ColumnPruning` narrows them to what the parent reads, and 
`PrepareExternalLookupJoin` prunes
+ *   the lookup scan to them.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => left.output
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  // As an ordinary join's: a semi or anti join returns at most its stream 
rows, and the other join
+  // types get the product of both sides' sizes.
+  override def stats: Statistics = joinType match {
+    case LeftSemi | LeftAnti => left.stats
+    case _ => super.stats
+  }
+
+  override def maxRows: Option[Long] = joinType match {
+    case LeftSemi | LeftAnti => left.maxRows
+    case _ => None
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/**
+ * The join-condition and lookup-side shapes that an external lookup join can 
run. Analysis,
+ * lookup planning and the optimizer rules for lookup joins share them.
+ */
+object ExternalLookupJoinShapes {
+  /**
+   * A lookup candidate: a comparison of a lookup column with a value, written 
with the lookup
+   * column on the left. `predicateName` is the name of the DSv2 `Predicate` 
that is offered to the
+   * connector for it: the SQL operator of the comparison, as 
`V2ExpressionBuilder` names it.
+   */
+  case class LookupComparison(
+      lookupField: Attribute,
+      parameter: Expression,
+      predicateName: String,
+      nullSafe: Boolean)
+
+  /**
+   * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, 
`<=>`, `<`, `<=`, `>`
+   * or `>=` between a bare lookup column and a value, in either operand 
order. When the lookup
+   * column is written on the right, the comparison is rebuilt with it on the 
left, so
+   * `s.ts < t.event_time` is offered as `event_time > ?`.
+   *
+   * The value is the other operand, which Spark evaluates for each stream row 
to fill the
+   * comparison's parameter. It may read only stream columns, and it may read 
none, as a literal
+   * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a 
parameter.
+   *
+   * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets 
Spark offer the
+   * comparison. A comparison on another column is an ordinary conjunct.
+   *
+   * @param streamOutput The output of the join's left side, the stream side.
+   * @param lookupOutput The output of the join's right side, the lookup side.
+   */
+  def lookupComparison(
+      conjunct: Expression,
+      streamOutput: AttributeSet,
+      lookupOutput: AttributeSet): Option[LookupComparison] = {
+    def isLookupComparison(lookupField: Attribute, parameter: Expression): 
Boolean =
+      lookupOutput.contains(lookupField) && 
parameter.references.subsetOf(streamOutput)
+    conjunct match {
+      case comparison: BinaryComparison if isLookupOperator(comparison) =>
+        val nullSafe = comparison.isInstanceOf[EqualNullSafe]
+        Seq(comparison, withOperandsSwapped(comparison)).collectFirst {
+          case candidate @ BinaryComparison(lookupField: Attribute, parameter)
+              if isLookupComparison(lookupField, parameter) &&
+                isOfferedOn(comparison, lookupField, parameter) =>
+            LookupComparison(lookupField, parameter, candidate.sqlOperator, 
nullSafe)
+        }
+      case _ => None
+    }
+  }
+
+  private def isLookupOperator(comparison: BinaryComparison): Boolean = 
comparison match {
+    case _: EqualTo | _: EqualNullSafe | _: LessThan | _: LessThanOrEqual | _: 
GreaterThan |
+        _: GreaterThanOrEqual => true
+    case _ => false
+  }
+
+  /**
+   * Whether Spark offers the comparison on this lookup column, with this 
parameter.
+   *
+   * Spark evaluates every parameter on every stream row, before the other 
join conditions. That
+   * is safe for an equality, as a hash join evaluates its keys on every row 
too. A range is a
+   * join condition, which a join evaluates only after its keys match, so its 
parameter must be
+   * one that cannot fail, as `cannotFail` decides.
+   */
+  private def isOfferedOn(
+      comparison: BinaryComparison,
+      lookupField: Attribute,
+      parameter: Expression): Boolean = comparison match {
+    case _: EqualTo | _: EqualNullSafe => 
ExternalLookupKeyTypes.supportsEquality(lookupField)
+    case _ =>
+      ExternalLookupKeyTypes.supportsRange(lookupField.dataType) && 
cannotFail(parameter)
+  }
+
+  /**
+   * Whether a range parameter cannot fail: 
ExprUtils.canEvaluateUnconditionally accepts it, or it
+   * is a widening numeric cast of such a value. Analysis adds such a cast 
when the stream side has
+   * a narrower type than the lookup column, as an INT column compared with a 
BIGINT key.
+   */
+  private def cannotFail(parameter: Expression): Boolean = parameter match {
+    case cast: Cast =>
+      isTotalNumericWidening(cast.child.dataType, cast.dataType) &&
+        ExprUtils.canEvaluateUnconditionally(cast.child)
+    case _ => ExprUtils.canEvaluateUnconditionally(parameter)
+  }
+
+  /**
+   * Whether a cast converts every value of its source type: an integral type 
to a wider one, or
+   * an integral type or DECIMAL to a DECIMAL with room for all of its digits. 
`Cast.canUpCast`
+   * is not enough: it also accepts casts that fail on some values, as a 
far-future DATE overflows
+   * a TIMESTAMP, and 9999999999999999999 as DECIMAL(19, 0) exceeds BIGINT 
under ANSI.
+   */
+  private def isTotalNumericWidening(from: DataType, to: DataType): Boolean = 
(from, to) match {
+    case (from: IntegralType, to: IntegralType) => from.defaultSize < 
to.defaultSize
+    case (from: IntegralType, to: DecimalType) => to.isWiderThan(from)
+    case (from: DecimalType, to: DecimalType) => to.isWiderThan(from)
+    case _ => false
+  }
+
+  /** The same comparison with its operands swapped, so that `a < b` becomes 
`b > a`. */
+  private def withOperandsSwapped(comparison: BinaryComparison): 
BinaryComparison =
+    comparison match {
+      case EqualTo(left, right) => EqualTo(right, left)
+      case EqualNullSafe(left, right) => EqualNullSafe(right, left)
+      case LessThan(left, right) => GreaterThan(right, left)
+      case LessThanOrEqual(left, right) => GreaterThanOrEqual(right, left)
+      case GreaterThan(left, right) => LessThan(right, left)
+      case GreaterThanOrEqual(left, right) => LessThanOrEqual(right, left)
+    }
+
+  /**
+   * Whether a lookup-side projection or filter can evaluate `expression` on 
the lookup results,
+   * inside the join. Python and external UDFs and subqueries are planned as 
separate operators,
+   * which a lookup-side stage cannot contain. A non-deterministic expression 
is not allowed
+   * either: the join evaluates a stage on each returned row, so one stored 
row could get
+   * different values for different stream rows, which a read of the table 
never does.
+   */
+  def canEvaluateInLookupStage(expression: Expression): Boolean =
+    expression.deterministic && !expression.exists {
+      case _: PythonUDF | _: ExternalUserDefinedFunction | _: 
SubqueryExpression => true
+      case _ => false
+    }
+}
+
+/** One optimized lookup-side operation, retained in evaluation order. */
+sealed trait ExternalLookupTransform {
+  def input: Seq[Attribute]
+  def output: Seq[Attribute]
+}
+
+case class ExternalLookupProject(
+    projectList: Seq[NamedExpression],
+    input: Seq[Attribute]) extends ExternalLookupTransform {
+  override def output: Seq[Attribute] = projectList.map(_.toAttribute)
+}
+
+case class ExternalLookupFilter(
+    condition: Expression,
+    input: Seq[Attribute]) extends ExternalLookupTransform {
+  override def output: Seq[Attribute] = input
+}
+
+/**
+ * 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.
+ * @param lookupKeyPredicates The name of each selected lookup predicate, such 
as `=` or `<`,
+ *   with the lookup column on the left. It tells how Spark checks the key.
+ */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    tableName: String,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],

Review Comment:
   `nullSafeParameters` can now be derived from `lookupKeyPredicates`, and the 
operators are matched as strings in `selectsRange` and `lookupKeyCheck`. One 
small case class per selected predicate would replace the parallel `Seq`s and 
the `internalError` fallback.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,498 @@
+/*
+ * 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 scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap,
+  AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, 
PythonUDF}
+import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupJoin,
+  ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, 
Filter, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, 
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,
+  SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+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.
+    if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+      prepared.foreach { node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+      }
+    }
+    prepared
+  }
+
+  // The optimizer folds `WHERE false` on the lookup side into an empty 
relation, and a condition
+  // such as `s.id = r.id AND false` into `false`. Such a join needs no 
connector call.
+  private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+    join.right.maxRows.contains(0L) || (join.condition match {
+      case Some(Literal(value, BooleanType)) => value == null || value == false
+      case _ => false
+    })
+
+  private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+    val nullLookupColumns = join.right.output.map { attr =>
+      Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+    }
+    val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+    join.joinType match {
+      case LeftOuter => unmatched
+      case LeftAnti => join.left
+      // The stream side is kept under a false filter rather than replaced by 
an empty relation,
+      // so that its sources, watermarks and stateful operators still run in 
every micro-batch.
+      // PruneFilters decides whether a streaming subplan may be pruned.
+      case LeftSemi => Filter(Literal.FalseLiteral, join.left)
+      case _ => Filter(Literal.FalseLiteral, unmatched)
+    }
+  }
+
+  private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+    // Analysis already rejects a lookup side with a stage that cannot be 
evaluated, or with another
+    // operator; this is a fallback.
+    val hasUnevaluableStage = join.right.exists {
+      case node @ (_: Project | _: Filter) =>
+        
!node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage)
+      case _ => false
+    }
+    // The lookup-side stages are built here, and no later rule reaches them. 
withField and
+    // dropFields values cannot be evaluated until 
ReplaceUpdateFieldsExpression, in the
+    // optimizer's last batch, lowers them, so the same rule lowers them now.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(join.right))
+    }).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val relation = lookupPlan.relation
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    // A Python or external UDF over lookup columns cannot run in the 
residual. The rules that move
+    // one out of a join condition match only Join and run later, so this rule 
does it: an inner
+    // join evaluates the conjunct in a filter above the join, and other join 
types are rejected.
+    if (join.joinType != Inner) {
+      conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+        case _: ExternalUserDefinedFunction =>
+          throw 
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+        case _ =>
+          throw 
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+      }
+    }
+    val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, 
index) =>
+      ExternalLookupJoinShapes.lookupComparison(
+        conjunct, join.left.outputSet, join.right.outputSet).flatMap { 
comparison =>
+        tableColumn(comparison.lookupField, lookupPlan).map { column =>
+          OfferedLookupPredicate(
+            comparison.parameter, column, index, comparison.predicateName, 
comparison.nullSafe)
+        }
+      }
+    }
+    if (offeredCandidates.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName)))
+    }
+
+    val scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+    // A column is offered under the table's name for it. Under 
case-insensitive analysis, the
+    // condition may spell it in another case, as `ID` for `id`, with the same 
exprId; filter
+    // pushdown renames it the same way, with 
DataSourceStrategy.normalizeExprs.
+    val columnNames = AttributeMap(relation.output.map(attr => attr -> 
attr.name))
+    // Filters are pushed before the lookup predicates are selected, as
+    // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the 
columns of a scan.
+    // Unlike a batch scan, Spark evaluates every pushed filter again on the 
returned rows, not only
+    // the ones that the source rejects, so a source that accepts a filter but 
applies it in another
+    // way, or not at all, cannot change the result.
+    PushDownUtils.pushFilters(
+      scanBuilder,
+      DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, 
relation.output),
+      partitionFields = None)
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition(lookupSideUDF(join, _).isEmpty)
+    val (residualFirst, residualRest) = residualConjuncts.partition { conjunct 
=>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    // A conjunction evaluates its next conjunct after a NULL, so a NULL in 
the first group reads
+    // as false: a hash join never matches a NULL key either. A row matches 
only when the whole
+    // condition is true, so this changes no result.
+    val residual = if (residualRest.isEmpty) residualFirst else {
+      residualFirst.map { conjunct =>
+        if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) 
else conjunct
+      } ++ residualRest
+    }
+
+    // The prepared join replaces the analyzed one, so it keeps the analyzed 
lookup attributes in
+    // their analyzed order; execution projects the lookup results into them. 
It keeps only those
+    // required above the join: the ones that a parent projection reads, to 
which ColumnPruning has
+    // narrowed `requiredLookupOutput` during operator optimization, and the 
ones that `joinFilter`
+    // reads. `joinFilter` holds the conjuncts with a Python or external UDF 
over lookup columns,
+    // which an inner join evaluates in a filter above it; other join types 
reject them above.
+    val requiredAbove = join.joinType match {
+      case LeftSemi | LeftAnti => AttributeSet.empty
+      case _ => AttributeSet(join.requiredLookupOutput ++ 
joinFilter.flatMap(_.references))
+    }
+    val lookupOutput = join.right.output.filter(requiredAbove.contains)
+    val residualLookupReferences =
+      residual.flatMap(_.references).filter(join.right.outputSet.contains)
+    // The columns are pruned only now, once the lookup predicates are 
selected. A column that a
+    // selected lookup predicate reads is kept, because Spark checks the 
predicate itself on every
+    // row that the connector returns. V2ScanRelationPushDown.pruneColumns 
prunes a scan the same
+    // way, through PushDownUtils.pruneColumns, which this rule cannot call: 
it can pass
+    // nested-pruned columns, while a lookup scan receives only whole 
top-level columns, and it
+    // binds the read schema by the resolver, while a lookup scan binds it by 
exact name.
+    val (prunedUpperStages, requiredBySegment) =
+      pruneLookupTransforms(lookupOutput ++ residualLookupReferences, 
lookupPlan.upperStages)
+    val segmentFields =
+      lookupPlan.fields.filter(field => 
requiredBySegment.contains(field.toAttribute))
+    val segmentFilter =
+      (lookupPlan.filtersPushDown ++ 
lookupPlan.filtersStayUp).reduceOption(And)
+    val requiredColumns = relation.output.filter(
+      (AttributeSet(segmentFields.flatMap(_.references)) ++
+        segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++
+        AttributeSet(selectedPredicates.map(_.projectedField))).contains)
+    // As V2ScanRelationPushDown does above a scan: the filters, then a 
projection when it computes
+    // more than the columns it selects. Execution reads a selected column by 
its id.
+    val segmentStages = segmentFilter.map(ExternalLookupFilter(_, 
relation.output)).toSeq ++
+      Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) {
+        ExternalLookupProject(segmentFields, relation.output)
+      }
+    scanBuilder match {
+      case builder: SupportsPushDownRequiredColumns =>
+        builder.pruneColumns(requiredColumns.toStructType)
+      case _ =>
+    }
+
+    def nonNull[T](value: T, method: String): T = Option(value).getOrElse {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "NULL_RESULT", Map("method" -> method))
+    }
+    val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type, 
where a column, nested
+    // field, array element or map value is nullable only when both the table 
and the read schema
+    // allow nulls: the join fails the task on a null that either rules out, 
because Spark relied
+    // on the table's nullability while it optimized the query.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "Scan.readSchema()"))
+    val columnsByName = relation.output.groupBy(_.name)
+    val lookupInput = readSchema.fields.map { field =>
+      columnsByName.getOrElse(field.name, Nil).find { attr =>
+        DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      }.map { attr =>
+        attr.withDataType(withStricterNullability(attr.dataType, 
field.dataType))
+          .withNullability(attr.nullable && field.nullable)
+      }.getOrElse {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    val readExprIds = lookupInput.map(_.exprId).toSet
+    requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { 
attr =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "MISSING_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(attr.name))))
+    }
+    val externalLookup = nonNull(scan.toExternalLookup(), 
"Scan.toExternalLookup()")
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory =
+      nonNull(externalLookup.createReaderFactory(), 
"ExternalLookup.createReaderFactory()")
+    // With a range selected, one stored row can match several parameter rows 
of one request, and
+    // the source would have to return it once for each of them, with each 
ordinal. Spark cannot
+    // detect a missing one, so it sends one parameter row per request then.
+    val selectsRange = selectedPredicates.exists { predicate =>

Review Comment:
   `id = s.id AND id > 0` also lands here. With a constant bound, a stored row 
cannot match several parameter rows, so the reason above does not apply, yet a 
connector selecting both predicates drops to one row per request. Should this 
consider only ranges whose parameter reads the stream?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,681 @@
+/*
+ * 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.connector
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, AttributeSet,
+  BindReferences, Cast, Coalesce, Expression, ExternalUserDefinedFunction, 
Literal,
+  Predicate => CatalystPredicate}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi,
+  PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExecuteExternalUDF, 
ExternalLookupJoin,
+  Filter, Join, JoinHint, LocalRelation, LogicalPlan, 
PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.read.{ExternalLookup, 
ExternalLookupReader,
+  ExternalLookupReaderFactory, Scan, ScanBuilder, SupportsExternalLookup}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation, PrepareExternalLookupJoin}
+import org.apache.spark.sql.execution.externalUDF.PlanExternalUDFs
+import org.apache.spark.sql.internal.{SQLConf, StaticSQLConf}
+import org.apache.spark.sql.types.{ArrayType, BooleanType, IntegerType, 
LongType, MapType,
+  StringType, StructType, TimestampNTZType, TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.udf.worker.UDFWorkerSpecification
+import org.apache.spark.unsafe.types.UTF8String
+
+class PrepareExternalLookupJoinSuite extends PlanTest {
+  private val stream =
+    LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = 
true)
+  private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`"
+
+  private def lookupRelation(table: PlanningExternalLookupTable): 
ExternalLookupRelation =
+    ExternalLookupRelation(
+      DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty))
+
+  private def lookupJoin(
+      lookup: LogicalPlan,
+      condition: Expression,
+      joinType: JoinType = Inner,
+      left: LogicalPlan = stream): LogicalPlan =
+    FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), 
JoinHint.NONE))
+
+  private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan =
+    lookupJoin(lookup, stream.output.head === lookup.output.head)
+
+  private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin =
+    PrepareExternalLookupJoin(plan) match {
+      case lookup: PreparedExternalLookupJoin => lookup
+      case other => fail(s"Expected a prepared external lookup join: $other")
+    }
+
+  private def prepareError(plan: LogicalPlan): AnalysisException =
+    intercept[AnalysisException] { PrepareExternalLookupJoin(plan) }
+
+  // A conjunct of the residual's first group, read as false when it is NULL.
+  private def orFalse(conjunct: Expression): Expression =
+    Coalesce(Seq(conjunct, Literal.FalseLiteral))
+
+  /**
+   * Whether Spark offers `code = ?` on a lookup column `code` of the given 
type. The connector
+   * selects only `id = ?`, so Spark evaluates the code equality either way.
+   */
+  private def offeredCodeCandidate(codeType: String): Boolean = {
+    var offeredCandidates = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType", select = {
+      candidates =>
+        offeredCandidates = candidates.map(_.toString).toSeq
+        candidates.take(1)
+    }))
+    val Seq(lookupId, lookupCode) = lookup.output
+    val streamId = stream.output.head
+    val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+    val codesEqual = streamCode === lookupCode
+    val prepared = prepare(lookupJoin(lookup, streamId === lookupId && 
codesEqual,
+      left = LocalRelation(Seq(streamId, streamCode), isStreaming = true)))
+    assert(prepared.residualCondition === Some(codesEqual), codeType)
+    offeredCandidates match {
+      case Seq("id = ?") => false
+      case Seq("id = ?", "code = ?") => true
+      case other => fail(s"Unexpected candidates for $codeType: $other")
+    }
+  }
+
+  test("a lookup-only relation that no lookup join reads is rejected") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    prepare(lookupJoinOnId(lookup))
+    checkError(
+      exception = prepareError(Project(lookup.output, lookup)),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch 
scan"))
+  }
+
+  test("an equality is a lookup candidate only on a type that stores compare 
as Spark does") {
+    val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", 
"DECIMAL(10, 2)",
+      "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING 
COLLATE UTF8_BINARY",
+      "VARCHAR(3)")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)",
+      "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE 
UTF8_BINARY_RTRIM",
+      "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND")
+    for ((codeType, offered) <- offeredTypes.map(_ -> true) ++ 
notOfferedTypes.map(_ -> false)) {
+      assert(offeredCodeCandidate(codeType) === offered, codeType)
+    }
+    // Standard CHAR/VARCHAR semantics trims trailing blanks from a VARCHAR 
value on read, so a
+    // store that compares the stored value could miss a row.
+    withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+      assert(offeredCodeCandidate("VARCHAR(3)") === false)
+      assert(offeredCodeCandidate("STRING"))
+    }
+
+    // Without another candidate, the join cannot run.
+    Seq("DOUBLE", "STRING COLLATE UTF8_LCASE", "CHAR(3)").foreach { codeType =>
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType"))
+      val lookupCode = lookup.output(1)
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      checkError(
+        exception = prepareError(lookupJoin(lookup, streamCode === lookupCode,
+          left = LocalRelation(Seq(streamCode), isStreaming = true))),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+        parameters = Map("table" -> QUOTED_TABLE_NAME))
+    }
+  }
+
+  test("an equality within one side of the join is never a lookup candidate") {
+    var offered = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, value 
STRING, alt STRING",
+      select = { candidates =>
+        offered = candidates.map(_.toString).toSeq
+        candidates.take(1)
+      }))
+    val Seq(id, value, alt) = lookup.output
+    val streamCode = AttributeReference("streamCode", value.dataType)()
+    val left = LocalRelation(stream.output :+ streamCode, isStreaming = true)
+    val Seq(streamId, streamLabel) = stream.output
+    // `t.value = t.alt` would offer a parameter over a lookup column, and 
`s.label = s.code` a
+    // candidate on a column that the lookup side does not have.
+    val withinSides = Seq(value === alt, alt === value, streamLabel === 
streamCode)
+    val prepared = prepare(
+      lookupJoin(lookup, ((streamId === id) +: withinSides).reduce(_ && _), 
left = left))
+    assert(offered === Seq("id = ?"))
+    assert(prepared.lookupParameters === Seq(streamId))
+    assert(prepared.residualCondition === Some(withinSides.reduce(_ && _)))
+  }
+
+  test("the residual evaluates key equalities and conjuncts that cannot fail 
first") {
+    // With ANSI mode on, a cast of a string to INT fails on a string that is 
not a number. Without
+    // it, ExprUtils.canEvaluateUnconditionally may take the cast as unable to 
fail.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING, value STRING"))
+      val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+      val Seq(streamId, streamLabel) = stream.output
+      // The cast can fail, so it runs after the equality and the comparison 
written after it,
+      // which keep their written order. The connector selects only `id = ?`.
+      val mayFail = streamLabel.cast(IntegerType) > 0
+      val conjuncts =
+        Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel, 
lookupValue > "a")
+      val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _)))
+      assert(prepared.residualCondition ===
+        Some(orFalse(streamLabel === lookupLabel) && orFalse(lookupValue > 
"a") && mayFail))
+
+      // Equalities between the sides go first even when they can fail, as a 
hash join's keys: `=`
+      // and `<=>`, each comparing a lookup column with a cast of a stream 
column, written after a
+      // conjunct that can fail. A `<=>` is never NULL.
+      val codes = lookupRelation(PlanningExternalLookupTable("id INT, code 
INT, alt INT"))
+      val Seq(codeId, code, alt) = codes.output
+      val codeEqual = code === streamLabel.cast(IntegerType)
+      val altEqual = alt <=> streamLabel.cast(IntegerType)
+      val keyed = prepare(
+        lookupJoin(codes, Seq(codeId === streamId, mayFail, codeEqual, 
altEqual).reduce(_ && _)))
+      assert(keyed.residualCondition === Some(orFalse(codeEqual) && altEqual 
&& mayFail))
+    }
+  }
+
+  test("a NULL key equality in the residual stops the conjuncts that can 
fail") {
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING"))
+    val Seq(lookupId, lookupLabel) = lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // Under ANSI mode, the cast fails on a label that is not a number.
+      val mayFail = streamLabel.cast(IntegerType) > 0
+      val keyEqual = streamLabel === lookupLabel
+      val prepared = prepare(lookupJoin(lookup, lookupId === streamId && 
keyEqual && mayFail))
+      val joinedOutput = stream.output ++ lookup.output
+      val residual = prepared.residualCondition.get
+      val conjunction = keyEqual && mayFail
+      def row(label: String, lookupLabelValue: String): InternalRow = 
InternalRow(
+        1, UTF8String.fromString(label), 1, 
UTF8String.fromString(lookupLabelValue))
+      def matches(condition: Expression, input: InternalRow): Boolean = {
+        val interpreted = BindReferences.bindReference(condition, 
joinedOutput).eval(input)
+        val generated = CatalystPredicate.create(condition, 
joinedOutput).eval(input)
+        assert(generated === (interpreted == true))
+        generated
+      }
+
+      // A hash join never matches a NULL key, so it does not reach the cast. 
Neither does the
+      // residual.
+      assert(matches(residual, row("x", null)) === false)
+      val error = intercept[Exception](matches(conjunction, row("x", null)))
+      // The catalyst DSL turns a String operand of `===` into an expression.
+      assert(error.asInstanceOf[SparkThrowable].getCondition == 
"CAST_INVALID_INPUT")
+      // Otherwise the residual matches the rows that the conjunction matches.
+      Seq(row("2", "2"), row("-2", "-2"), row("2", "3")).foreach { input =>
+        assert(matches(residual, input) === matches(conjunction, input))
+      }
+    }
+  }
+
+  test("selected predicates bind in the connector's order, and the residual in 
written order") {
+    val Seq(streamId, streamLabel) = stream.output
+    def prepared(select: Array[Predicate] => Array[Predicate])
+        : (PreparedExternalLookupJoin, Seq[Attribute], Seq[Expression]) = {
+      val lookup = lookupRelation(
+        PlanningExternalLookupTable("id INT, label STRING, value STRING", 
select = select))
+      val Seq(id, label, value) = lookup.output
+      // `value = 'a'` is offered as well; `streamId > 0` is not.
+      val conjuncts =
+        Seq(id === streamId, streamLabel === label, streamId > 0, value === 
Literal("a"))
+      val join = lookupJoin(lookup, conjuncts.reduce(_ && _), LeftOuter)
+      (prepare(join), join.output, conjuncts)
+    }
+
+    val (reversed, joinOutput, conjuncts) =
+      prepared(candidates => Array(candidates(1), candidates(0)))
+    assert(reversed.lookupParameters === Seq(streamLabel, streamId))
+    assert(reversed.nullSafeParameters === Seq(false, false))
+    assert(reversed.lookupKeys.map(_.name) === Seq("label", "id"))
+    assert(reversed.residualCondition === Some(conjuncts(2) && conjuncts(3)))
+    assert(reversed.output === joinOutput)
+    assert(PrepareExternalLookupJoin(reversed) === reversed)
+
+    // An unselected equality stays ahead of the conjuncts written after it.
+    val (idOnly, _, idOnlyConjuncts) = prepared(candidates => 
Array(candidates(0)))
+    assert(idOnly.lookupParameters === Seq(streamId))
+    assert(idOnly.residualCondition === Some(idOnlyConjuncts.drop(1).reduce(_ 
&& _)))
+  }
+
+  test("a candidate is offered with the lookup column first, also for a 
literal value") {
+    var offered = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, value 
STRING", select = {
+      candidates =>
+        offered = candidates.map(_.toString).toSeq
+        candidates
+    }))
+    val Seq(id, value) = lookup.output
+    val streamId = stream.output.head
+    // A value that reads no column, such as a literal, is a parameter as well.
+    val conjuncts = Seq(streamId === id, Literal("a") === value, Literal(0) < 
id, id <= streamId)
+    val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _)))
+    assert(offered === Seq("id = ?", "value = ?", "id > ?", "id <= ?"))
+    assert(prepared.lookupParameters === Seq(streamId, Literal("a"), 
Literal(0), streamId))
+    assert(prepared.residualCondition.isEmpty)
+  }
+
+  test("a null-safe equality and a range are lookup candidates only on types 
they are safe on") {
+    // `<=>` has the allowlist of `=`. A range is offered only on integral, 
DECIMAL and datetime
+    // types: Spark orders strings by code point and BINARY by unsigned byte, 
and stores often do
+    // not.
+    val rangeTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "DECIMAL(10, 
2)", "DATE",
+      "TIMESTAMP", "TIMESTAMP_NTZ")
+    val equalityOnlyTypes =
+      Seq("BOOLEAN", "BINARY", "STRING", "STRING COLLATE UTF8_BINARY", 
"VARCHAR(3)")
+    val neitherTypes =
+      Seq("FLOAT", "DOUBLE", "CHAR(3)", "STRING COLLATE UTF8_LCASE", 
"STRUCT<a: INT>")
+    def offeredFor(codeType: String): Seq[String] = {
+      var offered = Seq.empty[String]
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType", select = {
+        candidates =>
+          offered = candidates.map(_.toString).toSeq
+          candidates.take(1)
+      }))
+      val Seq(lookupId, lookupCode) = lookup.output
+      val streamId = stream.output.head
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      val conjuncts =
+        Seq(streamId === lookupId, streamCode <=> lookupCode, streamCode < 
lookupCode,
+          lookupCode <= streamCode)
+      prepare(lookupJoin(lookup, conjuncts.reduce(_ && _),
+        left = LocalRelation(Seq(streamId, streamCode), isStreaming = true)))
+      offered
+    }
+    rangeTypes.foreach { codeType =>
+      assert(offeredFor(codeType) === Seq("id = ?", "code <=> ?", "code > ?", 
"code <= ?"),
+        codeType)
+    }
+    equalityOnlyTypes.foreach { codeType =>
+      assert(offeredFor(codeType) === Seq("id = ?", "code <=> ?"), codeType)
+    }
+    neitherTypes.foreach { codeType =>
+      assert(offeredFor(codeType) === Seq("id = ?"), codeType)
+    }
+    // Neither on VARCHAR under standard CHAR/VARCHAR semantics, as `=`.
+    withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+      assert(offeredFor("VARCHAR(3)") === Seq("id = ?"))
+    }
+
+    // A string or BINARY range alone leaves no candidate.
+    Seq("STRING", "BINARY").foreach { codeType =>
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType"))
+      val lookupCode = lookup.output(1)
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      checkError(
+        exception = prepareError(lookupJoin(lookup, lookupCode < streamCode,
+          left = LocalRelation(Seq(streamCode), isStreaming = true))),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+        parameters = Map("table" -> QUOTED_TABLE_NAME))
+    }
+  }
+
+  test("a range is a lookup candidate only when its parameter cannot fail") {
+    var offered = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable(
+      "id INT, value INT, total BIGINT, localTime TIMESTAMP_NTZ, time 
TIMESTAMP",
+      select = { candidates =>
+        offered = candidates.map(_.toString).toSeq
+        candidates.take(1)
+      }))
+    val Seq(lookupId, lookupValue, lookupTotal, lookupLocalTime, lookupTime) = 
lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    val (streamDay, streamLocalTime, streamAmount) =
+      ($"streamDay".date, $"streamLocalTime".timestampNTZ, 
$"streamAmount".decimal(19, 0))
+    // Spark evaluates every parameter on every stream row, but a join 
evaluates a range only after
+    // its keys match. A widening numeric cast, as of the INT `streamId` to 
BIGINT, cannot fail, so
+    // a range with one is offered. Other casts stay in the residual, as each 
can fail on some
+    // values: a string that is not a number, a far-future DATE or a 
TIMESTAMP_NTZ near the limits
+    // as a timestamp, and DECIMAL(19, 0) as BIGINT under ANSI. An equality 
with a cast that can
+    // fail is still offered, as a hash join evaluates its keys on every row 
too.
+    val labelNumber = streamLabel.cast(IntegerType)
+    val conjuncts = Seq(
+      lookupId === labelNumber,
+      lookupValue >= streamId,
+      lookupValue < labelNumber,
+      lookupTotal >= streamId.cast(LongType),
+      lookupLocalTime >= Cast(streamDay, TimestampNTZType),
+      lookupTime >= Cast(streamDay, TimestampType, Some("UTC")),
+      lookupTime >= Cast(streamLocalTime, TimestampType, Some("UTC")),
+      lookupTotal >= streamAmount.cast(LongType))
+    val left = LocalRelation(
+      Seq(streamId, streamLabel, streamDay, streamLocalTime, streamAmount), 
isStreaming = true)
+    val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _), left = 
left))
+    assert(offered === Seq("id = ?", "value >= ?", "total >= ?"))
+    assert(prepared.lookupParameters === Seq(labelNumber))
+    // The other conjuncts stay in the residual, those that go first under a 
NULL guard. Which ones
+    // go first depends on what ExprUtils.canEvaluateUnconditionally takes as 
unable to fail, which
+    // another test covers.
+    val residual = 
prepared.residualCondition.toSeq.flatMap(splitConjunctivePredicates).map {
+      case Coalesce(Seq(conjunct, Literal(false, BooleanType))) => conjunct
+      case conjunct => conjunct
+    }
+    assert(residual.length === conjuncts.length - 1)
+    assert(residual.toSet === conjuncts.drop(1).toSet)
+  }
+
+  test("the read schema binds to the analyzed lookup attributes by exact 
name") {
+    val lookup = lookupRelation(PlanningExternalLookupTable(
+      "id INT NOT NULL, value VARCHAR(8) NOT NULL, s STRUCT<a: INT NOT NULL>",
+      readSchemaDDL = Some("s STRUCT<a: INT>, value VARCHAR(8), id INT NOT 
NULL")))
+    val join = lookupJoinOnId(lookup)
+    val prepared = prepare(join)
+    assert(prepared.lookupOutput === lookup.output)
+    assert(prepared.output === join.output)
+    // The value-row attributes follow the read schema, with its types. A 
column or nested field
+    // is nullable only when both the table and the read schema allow nulls: 
the join fails the
+    // task on a null that either rules out, so `value` and `s.a` stay NOT 
NULL.
+    val relationAttrs = lookup.output.map(attr => attr.name -> attr).toMap
+    assert(prepared.lookupInput.map(_.name) === Seq("s", "value", "id"))
+    assert(prepared.lookupInput.map(_.nullable) === Seq(true, false, false))
+    assert(prepared.lookupInput.head.dataType === StructType.fromDDL("a INT 
NOT NULL"))
+    prepared.lookupInput.foreach { attr =>
+      assert(attr.exprId === relationAttrs(attr.name).exprId)
+      assert(attr.metadata === relationAttrs(attr.name).metadata)
+    }
+
+    withSQLConf(SQLConf.CASE_SENSITIVE.key -> "false") {
+      val caseVariant = lookupRelation(PlanningExternalLookupTable(
+        "id INT, a INT, A INT", readSchemaDDL = Some("A INT, id INT, a INT")))
+      val Seq(id, a, upperA) = caseVariant.output
+      val prepared = prepare(lookupJoinOnId(caseVariant))
+      assert(prepared.lookupInput.map(_.exprId) === Seq(upperA, id, 
a).map(_.exprId))
+    }
+  }
+
+  test("a read schema may declare NOT NULL where the table allows nulls") {
+    // A connector that never returns a null may say so, at the top level and 
in nested fields.
+    val lookup = lookupRelation(PlanningExternalLookupTable(
+      "id INT, value STRING, s STRUCT<a: INT>",
+      readSchemaDDL = Some("id INT, value STRING NOT NULL, s STRUCT<a: INT NOT 
NULL>")))
+    val join = lookupJoinOnId(lookup)
+    val prepared = prepare(join)
+    assert(prepared.output === join.output)
+    assert(prepared.lookupInput.map(_.nullable) === Seq(true, false, true))
+    assert(prepared.lookupInput(2).dataType === StructType.fromDDL("a INT NOT 
NULL"))
+  }
+
+  test("a candidate names the lookup column as the table schema spells it") {
+    var offered = Seq.empty[String]
+    val lookup = lookupRelation(PlanningExternalLookupTable(select = { 
candidates =>
+      offered = candidates.map(_.toString).toSeq
+      candidates.filter(_.children()(0) == FieldReference.column("id"))
+    }))
+    // Under case-insensitive analysis, a condition that writes `ID` resolves 
to the column `id`,
+    // with the same exprId and the query's spelling.
+    val idAsWritten = lookup.output.head.withName("ID")
+    val prepared = prepare(lookupJoin(lookup, stream.output.head === 
idAsWritten))
+    assert(offered === Seq("id = ?"))
+    assert(prepared.lookupParameters === Seq(stream.output.head))
+  }
+
+  test("nullability merges at every nested level, in arrays and maps too") {
+    // The table rules out nulls in `tags` elements and `scores` values, and 
the read schema rules
+    // them out in `labels` elements. Each value-row attribute keeps the 
stricter of the two.
+    def schemaWith(tagsNull: Boolean, scoresNull: Boolean, labelsNull: 
Boolean): StructType =
+      new StructType()
+        .add("id", IntegerType)
+        .add("tags", ArrayType(IntegerType, tagsNull))
+        .add("scores", MapType(StringType, IntegerType, scoresNull))
+        .add("labels", ArrayType(StringType, labelsNull))
+    val lookup = lookupRelation(PlanningExternalLookupTable(
+      tableSchema = Some(schemaWith(tagsNull = false, scoresNull = false, 
labelsNull = true)),
+      lookupReadSchema = Some(schemaWith(tagsNull = true, scoresNull = true, 
labelsNull = false))))
+    val prepared = prepare(lookupJoinOnId(lookup))
+    assert(prepared.lookupInput.map(_.dataType) ===
+      schemaWith(tagsNull = false, scoresNull = false, labelsNull = 
false).map(_.dataType))
+  }
+
+  test("the read schema must cover every lookup column with its data type") {
+    Seq(
+      ("id INT", "MISSING_SCAN_FIELD"),
+      ("id INT, value INT", "UNKNOWN_SCAN_FIELD")).foreach { case (readSchema, 
subClass) =>
+      val lookup = lookupRelation(PlanningExternalLookupTable(readSchemaDDL = 
Some(readSchema)))
+      checkError(
+        exception = prepareError(lookupJoinOnId(lookup)),
+        condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+        parameters = Map("table" -> QUOTED_TABLE_NAME, "field" -> "`value`"))
+    }
+  }
+
+  test("a failed predicate selection blames Spark or the connector, whichever 
caused it") {
+    // A wider stream key casts the lookup column, so Spark has no candidate 
to offer.
+    val longStream = LocalRelation(Seq($"id".long), isStreaming = true)
+    val unreachable = lookupRelation(PlanningExternalLookupTable(
+      select = _ => fail("Spark must not ask the connector to select from no 
candidates")))
+    checkError(
+      exception = prepareError(lookupJoin(unreachable,
+        longStream.output.head === unreachable.output.head.cast(LongType), 
left = longStream)),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> QUOTED_TABLE_NAME))
+
+    Seq[(Array[Predicate] => Array[Predicate], String, Map[String, String])](
+      (_ => Array.empty, 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE", Map.empty),
+      (_ => null, "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT",
+        Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")),
+      // A null element is not one of the offered instances.
+      (_ :+ null, 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.UNOFFERED_SELECTED_PREDICATE",
+        Map("predicate" -> "null"))).foreach {
+      case (select, condition, parameters) =>
+        checkError(
+          exception = prepareError(lookupJoinOnId(
+            lookupRelation(PlanningExternalLookupTable(select = select)))),
+          condition = condition,
+          parameters = Map("table" -> QUOTED_TABLE_NAME) ++ parameters)
+    }
+  }
+
+  test("a left outer join makes NOT NULL lookup columns nullable") {
+    val lookup =
+      lookupRelation(PlanningExternalLookupTable("id INT NOT NULL, value 
STRING NOT NULL"))
+    assert(lookup.output.forall(_.nullable === false))
+    val join = lookupJoin(lookup, stream.output.head === lookup.output.head, 
LeftOuter)
+    val prepared = prepare(join)
+    assert(prepared.output === join.output)
+    assert(prepared.output.drop(stream.output.length).forall(_.nullable))
+    assert(prepared.copy(joinType = Inner).output.drop(stream.output.length)
+      .forall(_.nullable === false))
+  }
+
+  test("a prepared lookup join reads its parameters and the residual's stream 
columns") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    val Seq(streamId, streamLabel) = stream.output
+    val Seq(id, value) = lookup.output
+    // The connector selects only `id = ?`, so the residual reads 
`streamLabel` and `value`.
+    val prepared = prepare(lookupJoin(lookup, streamId === id && streamLabel 
=== value))
+    assert(prepared.residualCondition === Some(streamLabel === value))
+    // It produces `value` itself, so it reads only stream columns.
+    assert(prepared.references === AttributeSet(Seq(streamId, streamLabel)))
+    assert(prepared.missingInput.isEmpty)
+  }
+
+  test("a prepared lookup join keeps its scan and reader factory out of its 
plan string") {
+    val prepared = 
prepare(lookupJoinOnId(lookupRelation(PlanningExternalLookupTable())))
+    assert(prepared.scan.toString.contains("secret-scan"))
+    assert(prepared.readerFactory.toString.contains("secret-factory"))
+    Seq(prepared.toString, prepared.simpleString(100), 
prepared.verboseString(100)).foreach {
+      rendered => assert(rendered.contains("secret") === false, rendered)
+    }
+  }
+
+  test("a prepared lookup join shows its join type, parameters and residual in 
its plan string") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    val Seq(streamId, streamLabel) = stream.output
+    val Seq(id, value) = lookup.output
+    val residual = streamLabel === value
+    val prepared = prepare(lookupJoin(lookup, streamId === id && residual, 
LeftOuter))
+    Seq(prepared.toString, prepared.simpleString(100)).foreach { rendered =>
+      Seq(LeftOuter.toString, streamId.toString, residual.toString).foreach { 
arg =>
+        assert(rendered.contains(arg), rendered)
+      }
+    }
+  }
+
+  test("a connector that reorders the offered array in place selects the 
predicate it returns") {
+    val Seq(streamId, streamLabel) = stream.output
+    // The connector swaps the two candidates in the array it receives, and 
returns the one now
+    // first, `value = ?`. Spark keeps its own copy, so it binds that 
predicate to `streamLabel`.
+    val lookup = lookupRelation(PlanningExternalLookupTable(select = { 
candidates =>
+      val first = candidates(0)
+      candidates(0) = candidates(1)
+      candidates(1) = first
+      Array(candidates(0))
+    }))
+    val Seq(id, value) = lookup.output
+    val prepared = prepare(lookupJoin(lookup, streamId === id && streamLabel 
=== value))
+    assert(prepared.lookupParameters === Seq(streamLabel))
+    assert(prepared.residualCondition === Some(streamId === id))
+  }
+
+  test("a connector method that returns null fails with a named error") {
+    Seq(
+      "build" -> "ScanBuilder.build()",
+      "readSchema" -> "Scan.readSchema()",
+      "toExternalLookup" -> "Scan.toExternalLookup()",
+      "createReaderFactory" -> "ExternalLookup.createReaderFactory()").foreach 
{
+      case (nullFrom, method) =>
+        val lookup = lookupRelation(PlanningExternalLookupTable(nullFrom = 
nullFrom))
+        checkError(
+          exception = prepareError(lookupJoinOnId(lookup)),
+          condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT",
+          parameters = Map("table" -> QUOTED_TABLE_NAME, "method" -> method))
+    }
+  }
+
+  test("a prepared lookup join keeps the size estimate of the join it 
replaces") {
+    // Two stream rows, and a lookup side of Spark's default size.
+    withSQLConf(SQLConf.DEFAULT_SIZE_IN_BYTES.key -> "1000") {
+      val rows = Seq(1, 2).map(id => InternalRow(id, 
UTF8String.fromString("a")))
+      val sizedStream = LocalRelation(stream.output, rows, isStreaming = true)
+      assert(sizedStream.stats.sizeInBytes > 0)
+      // Inner and left outer joins get the product of both sides' sizes. Semi 
and anti joins, as
+      // ordinary ones, get the stream side's size.
+      Seq(Inner -> 1000, LeftOuter -> 1000, LeftSemi -> 1, LeftAnti -> 
1).foreach {
+        case (joinType, lookupFactor) =>
+          val lookup = lookupRelation(PlanningExternalLookupTable())
+          val join = lookupJoin(lookup, sizedStream.output.head === 
lookup.output.head, joinType,
+            left = sizedStream)
+          val prepared = prepare(join)
+          assert(prepared.stats.sizeInBytes === sizedStream.stats.sizeInBytes 
* lookupFactor,
+            joinType)
+          assert(prepared.stats.sizeInBytes === join.stats.sizeInBytes, 
joinType)
+      }
+    }
+  }
+
+  test("an external UDF over lookup columns in the join condition") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    val lookupId = lookup.output.head
+    val lookupUDF = ExternalUserDefinedFunction(
+      name = Some("lookup_udf"),
+      workerSpec = UDFWorkerSpecification.getDefaultInstance,
+      payload = Array.emptyByteArray,
+      dataType = BooleanType,
+      children = Seq(lookupId),
+      udfDeterministic = true,
+      udfNullable = false)
+    val condition = stream.output.head === lookupId && lookupUDF
+
+    // An inner join evaluates it above the lookup join, where 
PlanExternalUDFs extracts it.
+    val prepared = PrepareExternalLookupJoin(lookupJoin(lookup, condition))
+    prepared match {
+      case Filter(filterCondition, join: PreparedExternalLookupJoin) =>
+        assert(filterCondition == lookupUDF)
+        assert(join.residualCondition.isEmpty)
+      case other => fail(s"Expected a filter above a prepared external lookup 
join: $other")
+    }
+    val conf = SQLConf.get
+    val unifiedUDFExecution = 
conf.getConf(StaticSQLConf.UNIFIED_UDF_EXECUTION_ENABLED)
+    conf.setConf(StaticSQLConf.UNIFIED_UDF_EXECUTION_ENABLED, true)
+    try {
+      val planned = PlanExternalUDFs(prepared)
+      assert(planned.exists(_.isInstanceOf[ExecuteExternalUDF]))
+      assert(planned.exists {
+        case _: ExecuteExternalUDF => false
+        case node => 
node.expressions.exists(_.exists(_.isInstanceOf[ExternalUserDefinedFunction]))
+      } === false)
+    } finally {
+      conf.setConf(StaticSQLConf.UNIFIED_UDF_EXECUTION_ENABLED, 
unifiedUDFExecution)
+    }
+    // A left outer join cannot.
+    checkError(
+      exception = prepareError(lookupJoin(lookup, condition, LeftOuter)),
+      condition = "UNSUPPORTED_FEATURE.EXTERNAL_UDF_IN_ON_CLAUSE",
+      parameters = Map("joinType" -> "LEFT OUTER"))
+  }
+
+  test("column pruning never projects the lookup relation under a lookup 
join") {

Review Comment:
   nit: the title no longer holds, since the comment below says a later pass 
does project. `RewriteWithExpression.scala:111` ("reads its lookup side 
directly") is stale for the same reason.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,731 @@
+/*
+ * 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 java.util.concurrent.locks.LockSupport
+
+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, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupProject,
+  ExternalLookupTransform}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time. For each batch it sends one request with the distinct parameters 
that can match, and
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    maxBatchBytes: Long,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val transforms = new LookupTransforms(partitionIndex)
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(
+            rows, parameters, resultRows, transforms, joinOutput, reader)
+        }
+        inputExhausted = !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,
+      transforms: LookupTransforms,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct 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
+
+    // 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 
connectorCall(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 start = System.nanoTime()
+          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 key = requestedKey(ordinal)
+          val resultRow = 
reader.copyRow(resultRows.validatedCopy(connectorRow))
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {
+            // The lookup-side stages reuse their output row, and several 
stream rows can join it.
+            transforms(resultRow).foreach(lookupRow => joinResultRow(key, 
lookupRow.copy()))

Review Comment:
   `validatedCopy` has already copied this row, and only a Project stage reuses 
its output. Could the copy happen only after a Project, so plans without one 
skip the second copy?



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