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


##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Done in 
[715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf):
 explain also shows the selected predicates and the lookup-side stages, with 
the scan still redacted.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Done in 
[715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf):
 `LookupKeyComparison` replaces the parallel sequences, the operator strings 
and the `internalError` fallback. Parameters and keys stay expression lists, so 
plan rewrites still reach them.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Done in 
[715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf):
 the second copy now happens only after a `Project` stage.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed both in 
[715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf).
   



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