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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,492 @@
+/*
+ * 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,
+  LookupKeyComparison, 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, 
and the current time
+    // of a micro-batch takes its value now too.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(
+        ExternalLookupJoinShapes.withBatchTimestampValues(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.comparison)
+        }
+      }
+    }
+    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

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.
   
   Corrected in 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb):
 the comment now says that evaluating the pushed filters again only drops rows 
that should not be there.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,492 @@
+/*
+ * 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,
+  LookupKeyComparison, 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, 
and the current time
+    // of a micro-batch takes its value now too.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(
+        ExternalLookupJoinShapes.withBatchTimestampValues(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.comparison)
+        }
+      }
+    }
+    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.comparison.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates))
+    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.

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.
   
   Corrected in 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb):
 the comment now says how `PushDownUtils` binds the read schema.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,427 @@
+/*
+ * 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, CurrentBatchTimestamp, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, GreaterThan, GreaterThanOrEqual, LessThan, 
LessThanOrEqual, Literal,
+  NamedExpression, PythonUDF, SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
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.
+   */
+  case class LookupComparison(
+      lookupField: Attribute,
+      parameter: Expression,
+      comparison: LookupKeyComparison)
+
+  /**
+   * `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 written: BinaryComparison =>
+        LookupKeyComparison.of(written).flatMap { comparison =>
+          Seq(
+            (written.left, written.right, comparison),
+            (written.right, written.left, comparison.swapped)).collectFirst {
+            case (lookupField: Attribute, parameter, comparison)
+                if isLookupComparison(lookupField, parameter) &&
+                  isOfferedOn(comparison, lookupField, parameter) =>
+              LookupComparison(lookupField, parameter, comparison)
+          }
+        }
+      case _ => None
+    }
+  }
+
+  /**
+   * 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: LookupKeyComparison,
+      lookupField: Attribute,
+      parameter: Expression): Boolean =
+    if (comparison.isRange) {
+      ExternalLookupKeyTypes.supportsRange(lookupField.dataType) && 
cannotFail(parameter)
+    } else {
+      ExternalLookupKeyTypes.supportsEquality(lookupField)
+    }
+
+  /**
+   * 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
+  }
+
+  /**
+   * 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. The current
+   * time of a micro-batch is allowed, as on a static side: 
MicroBatchExecution writes
+   * `current_timestamp()` and `current_date()` as a `CurrentBatchTimestamp`, 
which is constant
+   * within the batch, and [[withBatchTimestampValues]] replaces it with its 
value.
+   */
+  def canEvaluateInLookupStage(expression: Expression): Boolean =
+    expression.transform {
+      case batchTimestamp: CurrentBatchTimestamp => Literal(null, 
batchTimestamp.dataType)
+    }.deterministic && !expression.exists {
+      case _: PythonUDF | _: ExternalUserDefinedFunction | _: 
SubqueryExpression => true
+      case _ => false
+    }
+
+  /**
+   * Whether a request holds one parameter row: one of the selected 
comparisons is a range whose
+   * parameter reads a stream column. One stored row can then match several 
parameter rows of a
+   * request, and the source would have to return it once for each of them, 
with each ordinal.
+   * Spark cannot detect a missing one. A range whose parameter reads no 
stream column has the
+   * same value in every parameter row, so a stored row that satisfies it 
matches only the
+   * parameter rows that the other comparisons select.
+   */
+  def oneParameterRowPerRequest(
+      parameters: Seq[Expression],
+      comparisons: Seq[LookupKeyComparison]): Boolean =
+    parameters.zip(comparisons).exists { case (parameter, comparison) =>
+      comparison.isRange && parameter.references.nonEmpty
+    }
+
+  /**
+   * `plan` with the current time of the micro-batch replaced by its value. 
IncrementalExecution
+   * replaces it after optimization, which does not reach the lookup-side 
stages of a prepared
+   * lookup join.
+   */
+  def withBatchTimestampValues(plan: LogicalPlan): LogicalPlan =
+    plan.transformAllExpressionsWithPruning(_.containsPattern(CURRENT_LIKE)) {
+      case batchTimestamp: CurrentBatchTimestamp => batchTimestamp.toLiteral
+    }
+}
+
+/**
+ * The comparison that a lookup predicate makes between a lookup column, on 
the left, and its
+ * parameter. `predicateName` is the name of the DSv2 `Predicate` that is 
offered for it: the SQL
+ * operator, as `V2ExpressionBuilder` names it.
+ */
+sealed abstract class LookupKeyComparison(val predicateName: String) extends 
Serializable {
+  /** The comparison of `key` with `parameter`, as Spark evaluates it. */
+  def apply(key: Expression, parameter: Expression): Expression
+
+  /** The same comparison with the operands swapped, so that `<` becomes `>`. 
*/
+  def swapped: LookupKeyComparison
+
+  /** Whether one lookup column value can satisfy the comparison with several 
parameter values. */
+  def isRange: Boolean = true
+
+  /** Whether a NULL parameter can match, as with `<=>`. */
+  def nullSafe: Boolean = false
+}
+
+object LookupKeyComparison {
+  case object Equal extends LookupKeyComparison("=") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      EqualTo(key, parameter)
+    override def swapped: LookupKeyComparison = this
+    override def isRange: Boolean = false
+  }
+
+  case object NullSafeEqual extends LookupKeyComparison("<=>") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      EqualNullSafe(key, parameter)
+    override def swapped: LookupKeyComparison = this
+    override def isRange: Boolean = false
+    override def nullSafe: Boolean = true
+  }
+
+  case object Less extends LookupKeyComparison("<") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      LessThan(key, parameter)
+    override def swapped: LookupKeyComparison = Greater
+  }
+
+  case object LessOrEqual extends LookupKeyComparison("<=") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      LessThanOrEqual(key, parameter)
+    override def swapped: LookupKeyComparison = GreaterOrEqual
+  }
+
+  case object Greater extends LookupKeyComparison(">") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      GreaterThan(key, parameter)
+    override def swapped: LookupKeyComparison = Less
+  }
+
+  case object GreaterOrEqual extends LookupKeyComparison(">=") {
+    override def apply(key: Expression, parameter: Expression): Expression =
+      GreaterThanOrEqual(key, parameter)
+    override def swapped: LookupKeyComparison = LessOrEqual
+  }
+
+  /** The comparison that `comparison` makes, if it is one that Spark can 
offer. */
+  def of(comparison: BinaryComparison): Option[LookupKeyComparison] = 
comparison match {
+    case _: EqualTo => Some(Equal)
+    case _: EqualNullSafe => Some(NullSafeEqual)
+    case _: LessThan => Some(Less)
+    case _: LessThanOrEqual => Some(LessOrEqual)
+    case _: GreaterThan => Some(Greater)
+    case _: GreaterThanOrEqual => Some(GreaterOrEqual)
+    case _ => None
+  }
+}
+
+/** 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 lookupKeyComparisons The comparison that each selected lookup 
predicate makes, 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],
+    lookupKeys: Seq[Attribute],
+    lookupKeyComparisons: Seq[LookupKeyComparison],
+    joinType: JoinType,
+    residualCondition: Option[Expression]) extends UnaryNode {
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => child.output ++ lookupOutput
+    case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => child.output
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      residualCondition.map(_.references.intersect(child.outputSet))
+        .getOrElse(AttributeSet.empty)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
PreparedExternalLookupJoin =
+    copy(child = newChild)
+
+  // Connector descriptions may contain secrets, so the scan and the reader 
factory are not shown.
+  // The physical node renders a redacted description of them.
+  override protected def stringArgs: Iterator[Any] =
+    Iterator(joinType, lookupParameters, residualCondition, child)
+
+  // The join keeps the size estimate it had before preparation, as an 
ordinary join's: the product

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.
   
   Corrected in 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb):
 the comment now covers a lookup side that column pruning narrows with a 
projection.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,4504 @@
+/*
+ * 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 java.nio.charset.StandardCharsets
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, 
AtomicReference}
+
+import scala.collection.mutable
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import org.apache.spark.{SparkException, SparkIllegalArgumentException, 
SparkRuntimeException,
+  SparkThrowable, SparkUnsupportedOperationException, TaskContext}
+import org.apache.spark.rdd.DeterministicLevel
+import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Encoders, 
Row, SaveMode,
+  SQLContext}
+import org.apache.spark.sql.IntegratedUDFTestUtils.{shouldTestPythonUDFs, 
TestPythonUDF}
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.{ExternalLookupJoinEligibility,
+  FormExternalLookupJoin, NoSuchTableException}
+import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, 
AttributeReference, Cast,
+  EqualTo, GenericInternalRow, LessThan, Literal, Rand}
+import org.apache.spark.sql.catalyst.plans.QueryPlan
+import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, 
ExternalLookupProject, LeafNode,
+  LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.classic.Dataset
+import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable,
+  InMemoryTableCatalog, MetadataColumn, SupportsMetadataColumns, SupportsRead, 
Table,
+  TableCapability, TableCatalog, TableChange,
+  TableProvider}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.connector.expressions.{NamedReference, Transform}
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.metric.{CustomMetric, CustomSumMetric, 
CustomTaskMetric}
+import org.apache.spark.sql.connector.read.{Batch, ExternalLookup, 
ExternalLookupReader,
+  ExternalLookupReaderFactory, ExternalLookupResultCursor, InputPartition, 
LookupParameter,
+  PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, 
SupportsExternalLookup,
+  SupportsPushDownRequiredColumns, SupportsPushDownV2Filters}
+import org.apache.spark.sql.execution.{CoalesceExec, LocalTableScanExec}
+import org.apache.spark.sql.execution.datasources.{FileFormat, 
SaveIntoDataSourceCommand}
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
ExternalLookupRelation,
+  FileDataSourceV2, TableCapabilityCheck}
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+import org.apache.spark.sql.execution.joins.ExternalLookupJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.StreamingDeduplicateExec
+import org.apache.spark.sql.execution.streaming.runtime.{IncrementalExecution, 
MemoryStream,
+  StreamingQueryWrapper}
+import org.apache.spark.sql.execution.streaming.sources.LowLatencyMemoryStream
+import org.apache.spark.sql.functions.{broadcast, coalesce, col, concat, 
current_date,
+  current_timestamp, date_from_unix_date, expr, length, lit, max, raise_error, 
rand, struct,
+  to_json, upper, when}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, 
InsertableRelation,
+  RelationProvider, SchemaRelationProvider}
+import org.apache.spark.sql.streaming.{StreamingQueryException, 
StreamRealTimeModeE2ESuiteBase}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DoubleType, 
IntegerType,
+  MapType, StringType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
+
+class ExternalLookupJoinSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  private val EXTERNAL_LOOKUP_CATALOG_NAME = "external_lookup_cat"
+  // The supportedJoinTypes parameter of a JOIN_TYPE error.
+  private val SUPPORTED_JOIN_TYPES = "INNER, LEFT OUTER, LEFT SEMI, LEFT ANTI"
+
+  private val streamRunCount = new AtomicInteger()
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    SimpleExternalLookupDataSource.resetCounters()
+    SemanticKeyExternalLookupDataSource.requestSizes.clear()
+  }
+
+  /** The rows of `df` as a streaming DataFrame: one micro-batch, in 
`numPartitions` partitions. */
+  private def streamOf(df: DataFrame, numPartitions: Int = 1): DataFrame = {
+    val input = MemoryStream[Row](numPartitions)(Encoders.row(df.schema), 
spark.sqlContext)
+    input.addData(df.collect().toSeq)
+    input.toDF()
+  }
+
+  private case class StreamRun(rows: Seq[Row], execution: 
IncrementalExecution) {
+    def plan: LogicalPlan = execution.optimizedPlan
+    def lookupJoin: ExternalLookupJoinExec = 
execution.executedPlan.collectFirst {
+      case exec: ExternalLookupJoinExec => exec
+    }.get
+  }
+
+  /** Runs the streaming `df` on a memory sink until it has processed all of 
its input. */
+  private def runStream(df: DataFrame, outputMode: String = "append"): 
StreamRun = {
+    val queryName = 
s"external_lookup_stream_${streamRunCount.incrementAndGet()}"
+    val query =
+      
df.writeStream.format("memory").outputMode(outputMode).queryName(queryName).start()
+    try {
+      query.processAllAvailable()
+      StreamRun(
+        spark.table(queryName).collect().toSeq,
+        query.asInstanceOf[StreamingQueryWrapper].streamingQuery.lastExecution)
+    } finally {
+      query.stop()
+      spark.catalog.dropTempView(queryName)
+    }
+  }
+
+  private def checkStream(df: DataFrame, expected: Seq[Row]): Unit =
+    QueryTest.sameRows(expected, runStream(df).rows).foreach(fail(_))
+
+  /** The error that the streaming `df` fails with, when it starts or in a 
micro-batch. */
+  private def streamFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val cause = try {
+      runStream(df)
+      fail("The streaming query did not fail")
+    } catch {
+      case e: StreamingQueryException => e.getCause
+      case e: Throwable with SparkThrowable => e
+    }
+    assert(classTag[T].runtimeClass.isInstance(cause), cause)
+    cause.asInstanceOf[T]
+  }
+
+  test("a stream whose scan is pruned at the start reads the columns of its 
lookup joins") {
+    withSQLConf(
+        "spark.sql.catalog.stream_cat" -> 
classOf[InMemoryTableCatalog].getName,
+        SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "true") {
+      withTable("stream_cat.ns.badge_swipes") {
+        sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door 
STRING, minute INT) " +
+          s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_COLUMN_PRUNING}' = 
'true')")
+        sql("INSERT INTO stream_cat.ns.badge_swipes VALUES (1, 'lobby', 10), 
(3, 'garage', 20)")
+        val swipes = spark.readStream.table("stream_cat.ns.badge_swipes")
+        val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+        checkStream(
+          swipes.join(lookup, swipes("employee") === lookup("id"))
+            .select(swipes("door"), lookup("department")),
+          Seq(Row("lobby", "engineering"), Row("lobby", "research")))
+        // An aggregate that reads only stream columns and ignores duplicates 
does not need a left
+        // outer join, so the optimizer removes an ordinary one. A lookup join 
stays.
+        val latestByDoor = swipes.join(lookup, swipes("employee") === 
lookup("id"), "left_outer")
+          .groupBy(swipes("door")).agg(max(swipes("minute")))
+        QueryTest.sameRows(
+          Seq(Row("lobby", 10), Row("garage", 20)),
+          runStream(latestByDoor, "complete").rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("external lookup capability produces a unary external lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val joined = left.join(lookup, left("id") === lookup("id"), "inner")
+
+    val plan = runStream(joined).plan
+    assert(plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    assert(!plan.toString.contains("SimpleExternalLookupScan"))
+  }
+
+  test("a dual-capability source keeps an ordinary join unless the hint opts 
in") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))
+
+    assert(lookup.queryExecution.analyzed.isInstanceOf[DataSourceV2Relation])
+    assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation] 
=== false)
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(lookup, left("id") === lookup("id"), "inner")
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, expected)
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+    SimpleExternalLookupDataSource.resetCounters()
+    val hinted = lookup.hint("external_lookup")
+    val lookupJoin = left.join(hinted, left("id") === hinted("id"), "inner")
+    
assert(runStream(lookupJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(lookupJoin, expected)
+    assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+  }
+
+  test("a hinted or aliased lookup side follows the stream-static contract") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // Without the hint, a dual-capability table keeps an ordinary batch join.
+    checkAnswer(
+      batch.join(dual, batch("id") === dual("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    // With it, the batch join fails: a hint the user wrote is never silently 
dropped.
+    Seq(
+      dual -> "`DualCapabilityExternalLookupTable`",
+      lookupOnly -> "`SimpleExternalLookupTable`").foreach { case (table, 
relation) =>
+      val hinted = table.hint("external_lookup")
+      checkError(
+        exception = intercept[AnalysisException] {
+          batch.join(hinted, batch("id") === hinted("id"))
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+        parameters = Map("relation" -> relation))
+    }
+    // A lookup-only table on the left side is found beneath an alias too.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookupOnly.as("l").join(stream, $"l.id" === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("a physical join strategy hint conflicts with the external lookup 
hint") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val lookupSide = dual.hint("external_lookup").hint("broadcast")
+    val streamSide = left.hint("broadcast")
+    val hinted = dual.hint("external_lookup")
+    Seq(
+      () => left.join(lookupSide, left("id") === lookupSide("id")),
+      () => streamSide.join(hinted, streamSide("id") === 
hinted("id"))).foreach { query =>
+      checkError(
+        exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+        condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+        parameters = Map(
+          "strategy" -> "BROADCAST",
+          "relation" -> "`DualCapabilityExternalLookupTable`"))
+    }
+    // Both hints may name the same relation, in either order. A strategy hint 
is never merged
+    // into the lookup hint, so the conflict is still reported.
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      dual.createOrReplaceTempView("external_lookup_right")
+      Seq("EXTERNAL_LOOKUP(r), MERGE(r)", "MERGE(r), 
EXTERNAL_LOOKUP(r)").foreach { hints =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"SELECT /*+ $hints */ * FROM external_lookup_left l " +
+              "JOIN external_lookup_right r ON l.id = r.id")
+          },
+          condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map(
+            "strategy" -> "MERGE",
+            "relation" -> "`DualCapabilityExternalLookupTable`"))
+      }
+    }
+
+    // Without the lookup hint, the strategy hint plans the ordinary join it 
asks for.
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(dual.hint("merge"), left("id") === dual("id"))
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+  }
+
+  test("a hinted dual-capability source fails when no lookup access path 
exists") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val invoices = streamOf(Seq((1, "sales")).toDF("invoice", "costCenter"))
+
+    checkStream(
+      invoices.join(lookup, invoices("costCenter") === lookup("department")),
+      Seq(Row(1, "sales", 2, "sales")))
+    val hinted = lookup.hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](
+        invoices.join(hinted, invoices("costCenter") === 
hinted("department"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`DualCapabilityExternalLookupTable`"))
+  }
+
+  test("a physical strategy hint on a lookup-only join is rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val withLookupHint = lookup.hint("external_lookup").hint("shuffle_hash")
+    Seq(
+      "BROADCAST" ->
+        (() => left.join(lookup.hint("broadcast"), left("id") === 
lookup("id"), "left_outer")),
+      "BROADCAST" ->
+        (() => left.join(broadcast(lookup), left("id") === lookup("id"), 
"left_outer")),
+      "MERGE" -> (() => left.hint("merge").join(lookup, left("id") === 
lookup("id"))),
+      "SHUFFLE_HASH" ->
+        (() => left.join(withLookupHint, left("id") === 
withLookupHint("id")))).foreach {
+      case (strategy, query) =>
+        checkError(
+          exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+          condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map("strategy" -> strategy, "relation" -> 
"`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("an ordinary join over an enriched lookup join result stays ordinary") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val events = streamOf(Seq(1, 2).toDF("id"))
+    val enriched = events.join(lookup, events("id") === lookup("id"))
+      .select(events("id").as("event_id"), lookup("department"))
+    val base = Seq((1, "a"), (2, "b")).toDF("id", "tag")
+    val expected = Seq(
+      Row(1, "a", 1, "engineering"), Row(1, "a", 1, "research"), Row(2, "b", 
2, "sales"))
+    def lookupJoinCount(df: DataFrame): Int =
+      runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j 
}.size
+
+    val joined = base.join(enriched, base("id") === enriched("event_id"))
+    assert(lookupJoinCount(joined) === 1)
+    checkStream(joined, expected)
+
+    withTempView("external_lookup_base", "external_lookup_events", 
"external_lookup_right") {
+      base.createOrReplaceTempView("external_lookup_base")
+      events.createOrReplaceTempView("external_lookup_events")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      val sqlJoined = sql(
+        """
+          |SELECT b.id, b.tag, e.event_id, e.department
+          |FROM external_lookup_base b JOIN (
+          |  SELECT v.id AS event_id, r.department
+          |  FROM external_lookup_events v JOIN external_lookup_right r ON 
v.id = r.id) e
+          |ON b.id = e.event_id
+          |""".stripMargin)
+      assert(lookupJoinCount(sqlJoined) === 1)
+      checkStream(sqlJoined, expected)
+    }
+  }
+
+  test("an external lookup hint outside any join is ignored") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales"))
+
+    checkAnswer(dual.hint("external_lookup"), expected)
+    assert(dual.hint("external_lookup").count() === 3)
+    withTempView("external_lookup_right") {
+      dual.createOrReplaceTempView("external_lookup_right")
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP */ * FROM 
external_lookup_right"), expected)
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ * FROM 
external_lookup_right r"), expected)
+      checkAnswer(
+        sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ id, count(*) FROM 
external_lookup_right r " +
+          "GROUP BY id"),
+        Seq(Row(1, 2), Row(2, 1)))
+    }
+  }
+
+  test("a query without a lookup-only table or the hint is not searched for 
lookup joins") {
+    // Classifying the joins of a plan inlines its CTE references, so a plan 
that can have no lookup
+    // join is left alone, such as this self-join of a CTE over a table that 
supports batch reads.
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    withTempView("employee_directory", "lookup_directory", "badge_swipes") {
+      dual.createOrReplaceTempView("employee_directory")
+      lookupOnly.createOrReplaceTempView("lookup_directory")
+      streamOf(Seq((1, "lobby")).toDF("employee", 
"door")).createOrReplaceTempView("badge_swipes")
+      val ordinary = sql(
+        """
+          |WITH d AS (TABLE employee_directory)
+          |SELECT a.id, a.department, b.department FROM d a JOIN d b ON a.id = 
b.id
+          |""".stripMargin)
+      val analyzed = ordinary.queryExecution.analyzed
+      assert(ExternalLookupJoinEligibility.mayHaveLookupJoin(analyzed) === 
false)
+      assert(ExternalLookupJoinEligibility.lookupSidePlans(analyzed).isEmpty)
+      assert(FormExternalLookupJoin(analyzed) eq analyzed)
+      checkAnswer(ordinary, Seq(
+        Row(1, "engineering", "engineering"), Row(1, "engineering", 
"research"),
+        Row(1, "research", "engineering"), Row(1, "research", "research"),
+        Row(2, "sales", "sales")))
+      // The hint or a lookup-only table makes a lookup join possible, so the 
joins are classified.
+      Seq("/*+ EXTERNAL_LOOKUP(d) */" -> "employee_directory", "" -> 
"lookup_directory").foreach {
+        case (hint, table) =>
+          val query = sql(
+            s"""
+              |WITH d AS (TABLE $table)
+              |SELECT $hint s.door, d.department FROM badge_swipes s JOIN d ON 
s.employee = d.id
+              |""".stripMargin)
+          
assert(ExternalLookupJoinEligibility.mayHaveLookupJoin(query.queryExecution.analyzed))
+          checkStream(query, Seq(Row("lobby", "engineering"), Row("lobby", 
"research")))
+      }
+    }
+  }
+
+  test("a lookup side may be hinted more than once") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val swipes = streamOf(Seq((1, "door-a")).toDF("employee", "door"))
+    val expected = Seq(Row(1, "door-a", "engineering"), Row(1, "door-a", 
"research"))
+    def lookupJoinCount(df: DataFrame): Int =
+      runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j 
}.size
+
+    val twice = dual.hint("external_lookup").hint("external_lookup")
+    val joined = swipes.join(twice, swipes("employee") === twice("id"))
+      .select(swipes("employee"), swipes("door"), twice("department"))
+    assert(lookupJoinCount(joined) === 1)
+    checkStream(joined, expected)
+    withTempView("badge_swipes", "hinted_directory", "employee_directory") {
+      swipes.createOrReplaceTempView("badge_swipes")
+      dual.hint("external_lookup").createOrReplaceTempView("hinted_directory")
+      dual.createOrReplaceTempView("employee_directory")
+      // A view over a hinted table that the hint names too, and a name given 
twice in any case.
+      Seq(
+        "EXTERNAL_LOOKUP(d)" -> "hinted_directory",
+        "EXTERNAL_LOOKUP(d, d)" -> "employee_directory",
+        "EXTERNAL_LOOKUP(d, D)" -> "employee_directory").foreach { case (hint, 
directory) =>
+        val df = sql(
+          s"""
+            |SELECT /*+ $hint */ s.employee, s.door, d.department
+            |FROM badge_swipes s JOIN $directory d ON s.employee = d.id
+            |""".stripMargin)
+        assert(lookupJoinCount(df) === 1, hint)
+        checkStream(df, expected)
+      }
+    }
+  }
+
+  test("an external lookup hint in a subquery without a join is ignored like a 
strategy hint") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    withTempView("badge_swipes", "employee_directory") {
+      Seq((1, "door-a"), (3, "door-b")).toDF("employee", "door")
+        .createOrReplaceTempView("badge_swipes")
+      dual.createOrReplaceTempView("employee_directory")
+      Seq("BROADCAST", "EXTERNAL_LOOKUP").foreach { hint =>
+        checkAnswer(
+          sql(
+            s"""
+              |SELECT door FROM badge_swipes s WHERE EXISTS (
+              |  SELECT /*+ $hint */ * FROM employee_directory d WHERE d.id = 
s.employee)
+              |""".stripMargin),
+          Seq(Row("door-a")))
+        checkAnswer(
+          sql(
+            s"""
+              |SELECT door, (
+              |  SELECT /*+ $hint */ max(d.department) FROM employee_directory 
d
+              |  WHERE d.id = s.employee)
+              |FROM badge_swipes s
+              |""".stripMargin),
+          Seq(Row("door-a", "research"), Row("door-b", null)))
+      }
+    }
+  }
+
+  test("an empty lookup side does not call the connector") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    withTempView("empty_side_lookup", "empty_side_left") {
+      lookup.createOrReplaceTempView("empty_side_lookup")
+      left.createOrReplaceTempView("empty_side_left")
+      Seq("inner" -> "INNER", "left_outer" -> "LEFT OUTER").foreach { case 
(joinType, sqlJoin) =>
+        val expected =
+          if (joinType == "inner") Seq.empty[Row] else Seq(Row(1, null, null), 
Row(3, null, null))
+        val empty = lookup.where(lit(false))
+        Seq(
+          () => left.join(empty, left("id") === empty("id"), joinType),
+          () => sql(s"SELECT * FROM empty_side_left l $sqlJoin JOIN " +
+            "(SELECT * FROM empty_side_lookup WHERE 1 = 0) r ON l.id = 
r.id")).foreach { query =>
+          SimpleExternalLookupDataSource.resetCounters()
+          val joined = query()
+          assert(
+            
runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === 
false)
+          checkStream(joined, expected)
+          assert(SimpleExternalLookupDataSource.lookupCandidates.get() === 
Seq.empty)
+          assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+          assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+        }
+      }
+    }
+  }
+
+  test("a lookup side with another operator above the table fails when the 
DataFrame is built") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val values = Seq(1).toDF("v")
+    // A lookup-only table, which no other join can read, and a hinted table 
that supports batch
+    // reads too. The join fails even where the optimizer would remove the 
operator. A subquery is
+    // planned apart from the lookup results, so a projection or filter with 
one cannot run either.
+    Seq(
+      lookup.limit(1),
+      lookup.distinct(),
+      dual.limit(1).hint("external_lookup"),
+      lookup.filter($"id".isin(values)),
+      lookup.filter(values.where(col("v") === 1).exists()),
+      lookup.filter($"id" < 
spark.range(2).select(max($"id")).scalar())).foreach { right =>
+      checkError(
+        exception = intercept[AnalysisException] {
+          left.join(right, left("id") === right("id"), "left_outer")
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+        parameters = Map.empty)
+    }
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+  }
+
+  test("a USING join with the EXTERNAL_LOOKUP hint runs as an external lookup 
join") {
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    Seq[Class[_]](
+      classOf[DualCapabilityExternalLookupDataSource],
+      classOf[SimpleExternalLookupDataSource]).foreach { source =>
+      val lookup = 
spark.read.format(source.getName).load().hint("external_lookup")
+      val joined = left.join(lookup, Seq("id"), "left_outer")
+      
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+      checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), 
Row(3, null)))
+    }
+
+    // Without a condition the hinted join still fails, on the final plan.
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](left.join(dual)),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+  }
+
+  test("an external lookup hint is found beneath an alias on either join 
side") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    val aliased = dual.hint("external_lookup").as("r")
+    val joined = left.join(aliased, left("id") === $"r.id")
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").as("l").join(dual, $"l.id" === dual("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("a strategy hint on a nested join does not disable an outer lookup 
join") {
+    val left = streamOf(Seq((1, 10), (2, 20)).toDF("id", "k"))
+    val other = Seq((10, "a"), (20, "b")).toDF("k", "v")
+    val nested = left.join(other.hint("merge"), "k")
+    def usesLookup(df: DataFrame): Boolean =
+      runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val dualJoin = nested.join(dual, nested("id") === dual("id"))
+    assert(usesLookup(dualJoin))
+    checkStream(dualJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+
+    // A lookup-only table on the outer join becomes a lookup join too, 
despite the nested join's
+    // MERGE hint.
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookupOnlyJoin = nested.join(lookupOnly, nested("id") === 
lookupOnly("id"))
+    assert(usesLookup(lookupOnlyJoin))
+    checkStream(lookupOnlyJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+  }
+
+  test("an explicit external lookup option marker rejects unsupported join 
shapes") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(
+          lookup.hint("external_lookup"),
+          left("id") === lookup("id"),
+          "right_outer").queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE",
+      parameters = Map(
+        "joinType" -> "RIGHT OUTER",
+        "relation" -> "`DualCapabilityExternalLookupTable`",
+        "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+
+    // A cross join fails with its join type while it is analyzed, before its 
missing condition.
+    checkError(
+      exception = 
intercept[AnalysisException](left.crossJoin(lookup.hint("external_lookup"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE",
+      parameters = Map(
+        "joinType" -> "CROSS",
+        "relation" -> "`DualCapabilityExternalLookupTable`",
+        "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+
+    // A strategy hint on the same join conflicts before the join type is 
checked.
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(
+          lookup.hint("external_lookup").hint("merge"),
+          left("id") === lookup("id"),
+          "right_outer").queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+      parameters = Map("strategy" -> "MERGE", "relation" -> 
"`DualCapabilityExternalLookupTable`"))
+  }
+
+  test("external lookup predicate negotiation includes type and null 
semantics") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id"))
+
+    runStream(left.join(lookup, left("id") <=> lookup("id"), "inner"))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("<=>", "id", IntegerType)))
+  }
+
+  test("an external lookup hint on an ineligible join is rejected") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val left = streamOf(Seq(1).toDF("id"))
+
+    // A cross join fails with its join type too, although it has no condition.
+    Seq[(() => DataFrame, String)](
+      (() => left.join(dual, left("id") === dual("id"), "right_outer"), "RIGHT 
OUTER"),
+      (() => left.crossJoin(dual), "CROSS")).foreach { case (joined, joinType) 
=>
+      val error = intercept[AnalysisException](joined())
+      assert(error.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+      assert(error.getMessageParameters.get("joinType") === joinType)
+      assert(error.getMessageParameters.get("relation") === 
"`DualCapabilityExternalLookupTable`")
+    }
+  }
+
+  test("an external lookup join is a stream-static join with the lookup-only 
table on the right") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // The left side must be a streaming query.
+    checkError(
+      exception = intercept[AnalysisException] {
+        batch.join(lookup, batch("id") === lookup("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+    // The sides are never swapped.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookup.join(stream, lookup("id") === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup validates connector planning and request contracts") {
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      ("nullKeySelection", "true", "NULL_RESULT",
+        Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")),
+      ("selectionMode", "nullElement", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "null")),
+      ("selectionMode", "duplicate", "DUPLICATE_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("selectionMode", "copy", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("maxBatchSize", "0", "NON_POSITIVE_MAX_PARAMETER_ROWS", Map("value" -> 
"0"))).foreach {
+      case (option, value, subClass, parameters) =>
+        val lookup = spark.read
+          .format(classOf[SimpleExternalLookupDataSource].getName)
+          .option(option, value)
+          .load()
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = Map("table" -> "`SimpleExternalLookupTable`") ++ 
parameters)
+    }
+
+    def misconfigured(kind: String): DataFrame = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", kind)
+      .load()
+    val table = Map("table" -> "`MisconfiguredExternalLookupTable`")
+    Seq(
+      ("unknownField", "UNKNOWN_SCAN_FIELD", Map("field" -> "`unknown`")),
+      ("duplicateField", "DUPLICATE_SCAN_FIELD", Map("field" -> 
"`id`"))).foreach {
+      case (kind, subClass, parameters) =>
+        val lookup = misconfigured(kind)
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = table ++ parameters)
+    }
+
+    val noExternalLookup = misconfigured("noExternalLookup")
+    checkError(
+      exception = streamFailure[SparkUnsupportedOperationException](
+        left.join(noExternalLookup, left("id") === noExternalLookup("id"))),
+      condition = "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED",
+      parameters = Map("description" -> "NoExternalLookupScan"))
+
+    // Violations found while the join runs are reported the same way, by the 
tasks.
+    val nullCursor = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("nullCursor", "true")
+      .load()
+    Seq(
+      (nullCursor, "NULL_RESULT", Map("table" -> "`SimpleExternalLookupTable`",
+        "method" -> "ExternalLookupReader.lookupBatch()")),
+      (misconfigured("nullReader"), "NULL_RESULT",
+        table ++ Map("method" -> 
"ExternalLookupReaderFactory.createReader()")),
+      (misconfigured("invalidOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "5", "numParameterRows" -> "1")),
+      // The ordinals just outside the request's parameter rows.
+      (misconfigured("negativeOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "-1", "numParameterRows" -> "1")),
+      (misconfigured("ordinalAtCount"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "1", "numParameterRows" -> "1")),
+      (misconfigured("nullRow"), "NULL_RESULT",
+        table ++ Map("method" -> "ExternalLookupResultCursor.get()")),
+      // A value that breaks its column's type, which Spark relied on while it 
optimized.
+      (misconfigured("nullValue"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("nullUnderNotNullReadSchema"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("decimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")),
+      // The same checks reach nested values: a decimal array element with too 
many digits, and
+      // a decimal map value that would need rounding.
+      (misconfigured("nestedDecimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amounts`.`element`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      (misconfigured("nestedDecimalRounding"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`rates`.`value`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      // A map key is never null, whether it is a primitive or a struct.
+      (misconfigured("nullMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`labels`.`key`")),
+      (misconfigured("nullComplexMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`parts`.`key`"))).foreach {
+      case (lookup, subClass, parameters) =>
+        // A left outer join binds the lookup columns as nullable for its 
output, but checks the
+        // returned values against the table and the read schema, as an inner 
join does.
+        Seq("inner", "left_outer").foreach { joinType =>
+          checkError(
+            exception = streamFailure[SparkRuntimeException](
+              left.join(lookup, left("id") === lookup("id"), joinType)),
+            condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+            parameters = parameters)
+        }
+    }
+
+    // Planning failures that need no hint. A catalog can serve a table 
without SupportsRead.
+    val noLookupBuilder = misconfigured("noLookupBuilder")
+    val nonReadable = Dataset.ofRows(spark, DataSourceV2Relation.create(
+      NonReadableExternalLookupTable, None, None, 
CaseInsensitiveStringMap.empty))
+    val simple = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    Seq(
+      (noLookupBuilder, left("id") === noLookupBuilder("id"), "SCAN_BUILDER",
+        "MisconfiguredExternalLookupTable"),
+      (nonReadable, left("id") === nonReadable("id"), "TABLE", 
"NonReadableExternalLookupTable"),
+      (simple, simple("department") === "sales", "NO_LOOKUP_PREDICATE",
+        "SimpleExternalLookupTable")).foreach { case (lookup, condition, 
subClass, name) =>
+      checkError(
+        exception = streamFailure[AnalysisException](left.join(lookup, 
condition)),
+        condition = s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass",
+        parameters = Map("table" -> s"`$name`"))
+    }
+    // A BIGINT stream key casts the INT lookup column, so Spark has no 
candidate to offer.
+    val bigintLeft = streamOf(Seq(1L).toDF("id"))
+    checkError(
+      exception = streamFailure[AnalysisException](
+        bigintLeft.join(simple, bigintLeft("id") === simple("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("an external lookup hinted DataFrame can be reused by multiple joins") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+
+    val first = streamOf(Seq(1).toDF("id"))
+    val second = streamOf(Seq(2).toDF("id"))
+    checkStream(first.join(lookup, first("id") === lookup("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    checkStream(second.join(lookup, second("id") === lookup("id")),
+      Seq(Row(2, 2, "sales")))
+  }
+
+  test("external lookup finalizes expressions on the stream side after 
analysis") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id"))
+
+    checkStream(
+      left.join(
+        lookup,
+        coalesce(left("id"), lit(0)) === lookup("id"),
+        "inner"),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+  }
+
+  test("external lookup prunes unused throwable lookup expressions") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookup = rawLookup.select($"id", 
expr("raise_error('unused')").as("unused"))
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_semi"),
+      Seq(Row(1)))
+
+    val projected = left.as("left").join(
+      lookup.as("lookup"),
+      $"left.id" === $"lookup.id",
+      "inner").select($"left.id")
+    checkStream(projected, Seq(Row(1), Row(1)))
+  }
+
+  test("external lookup rejects a non-deterministic lookup-side projection or 
filter") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 1, 2).toDF("id"))
+    // The join evaluates the lookup-side stages on each returned row, so a 
random value could
+    // differ between two stream rows that join the same stored row.
+    Seq(
+      rawLookup.select($"id", $"department", rand(3).as("sample")),
+      rawLookup.filter(rand(3) >= 0.5)).foreach { lookup =>
+      checkError(
+        exception = intercept[AnalysisException] {
+          left.join(lookup, left("id") === lookup("id"), "inner")
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+        parameters = Map.empty)
+    }
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+  }
+
+  test("external lookup hint rejects invalid placement and relation targets") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").join(lookup, left("id") === lookup("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      def query(hint: String): DataFrame = sql(
+        s"""
+          |SELECT /*+ $hint */ l.id, r.department
+          |FROM external_lookup_left l JOIN external_lookup_right r ON l.id = 
r.id
+          |""".stripMargin)
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(missing)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+        parameters = Map("relations" -> "`missing`"))
+      // A name that is repeated is reported once.
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(missing, missing)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+        parameters = Map("relations" -> "`missing`"))
+    }
+
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(stream.hint("external_lookup"), left("id") === stream("id"))
+          .queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STREAMING_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("external lookup reports lookup sides and conditions it cannot plan") {
+    val claims = streamOf(Seq((1, "sales")).toDF("id", "costCenter"))
+    def planningError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      streamFailure[AnalysisException](claims.join(lookup, condition))
+    def analysisError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      intercept[AnalysisException](claims.join(lookup, condition))
+
+    // A hinted lookup side fails when the DataFrame is built: with 
LOOKUP_PLAN when it reads no
+    // DSv2 table, as a local relation does, and with TABLE for a DSv2 table 
that does not support
+    // external lookup.
+    val local = Seq(1).toDF("id").hint("external_lookup")
+    checkError(
+      exception = analysisError(local, claims("id") === local("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+      parameters = Map.empty)
+
+    val batchOnly = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "batchOnly")
+      .load()
+      .hint("external_lookup")
+    checkError(
+      exception = analysisError(batchOnly, claims("id") === batchOnly("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.TABLE",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val noLookupBuilder = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "noLookupBuilder")
+      .load()
+    checkError(
+      exception = planningError(noLookupBuilder, claims("id") === 
noLookupBuilder("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SCAN_BUILDER",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    checkError(
+      exception = planningError(lookup, claims("costCenter") === 
lookup("department")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup maps a selected predicate to its own occurrence") {
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "last")
+      .load()
+    val left = streamOf(Seq((1, 2), (2, 2), (2, 1)).toDF("a", "b"))
+
+    // Both candidates have the shape `id = ?`; only the second one, bound to 
`b`, is selected.
+    val joined =
+      left.join(lookup, lookup("id") === left("a") && lookup("id") === 
left("b"), "left_outer")
+    assert(runStream(joined).rows.toSet ===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("=", "id", IntegerType), ("=", "id", IntegerType)))
+    assert(SimpleExternalLookupDataSource.lookupCandidateDescriptions.get() ===
+      Seq("id = ?", "id = ?"))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 1))
+
+    // Selected in reverse order, each parameter row is `(b, a)`.
+    SimpleExternalLookupDataSource.resetCounters()
+    val reversed = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "reversed")
+      .load()
+    val condition = reversed("id") === left("a") && reversed("id") === 
left("b")
+    assert(runStream(left.join(reversed, condition, "left_outer")).rows.toSet 
===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 2, 1))
+  }
+
+  test("a parent projection of some lookup columns still plans an external 
lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    // Generic column pruning must not project the lookup relation, which 
would hide it from

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.
   
   Corrected in 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb).
 The search you suggested found no other comment or test that assumes the 
lookup side reaches lookup planning as the bare table.
   



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