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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, EqualNullSafe,
+  EqualTo, Expression, ExprUtils, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.EXTERNAL_LOOKUP_JOIN
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.DataType
+
+/** 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 => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    prepared.foreach { node =>
+      ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+        throw QueryCompilationErrors.unsupportedBatchReadError(table)
+      }
+    }
+    prepared
+  }
+
+  private def prepare(join: ExternalLookupJoin): PreparedExternalLookupJoin = {
+    val relation = extractLookupPlan(join.right).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    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)
+    val offeredCandidates = conjuncts.zipWithIndex.collect {
+      case (EqualTo(leftExpr, rightAttr: Attribute), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+      case (EqualTo(rightAttr: Attribute, leftExpr), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+    }
+    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))
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualFirst, residualRest) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition { conjunct =>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    val residual = residualFirst ++ residualRest
+
+    def nonNull[T](value: T, subClass: String): T = Option(value).getOrElse {
+      throw 
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, subClass)
+    }
+    val scan = nonNull(scanBuilder.build(), "NULL_SCAN")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type and 
nullability, so they
+    // describe every value the connector may return.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "NULL_READ_SCHEMA"))
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>
+        attr.name == field.name && 
DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      
}.map(_.withDataType(field.dataType).withNullability(field.nullable)).getOrElse 
{
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    // The prepared join replaces the analyzed one, so it keeps the analyzed 
lookup attributes in
+    // their analyzed order; execution projects the value rows into them.
+    // TODO: prune lookup output to the columns required above the join.
+    val lookupOutput = join.right.output
+    val readExprIds = lookupInput.map(_.exprId).toSet
+    lookupOutput.find(attr => !readExprIds.contains(attr.exprId)).foreach { 
attr =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "MISSING_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(attr.name))))
+    }
+    val externalLookup = nonNull(scan.toExternalLookup(), 
"NULL_EXTERNAL_LOOKUP")
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory = nonNull(externalLookup.createReaderFactory(), 
"NULL_READER_FACTORY")
+
+    PreparedExternalLookupJoin(
+      join.left,
+      scan,
+      readerFactory,
+      maxParameterRowsPerRequest,
+      lookupInput,
+      lookupOutput,
+      selectedPredicates.map(_.parameter),
+      selectedPredicates.map(_.nullSafe),
+      join.joinType,
+      residual.reduceOption(And))
+  }
+
+  /**
+   * An equality between a bare lookup column and an expression over the 
stream side, on a type
+   * that Spark offers as a lookup key.
+   */
+  private def isLookupEquality(
+      join: ExternalLookupJoin,
+      leftExpr: Expression,
+      rightAttr: Attribute): Boolean =
+    leftExpr.references.subsetOf(join.left.outputSet) && 
join.right.outputSet.contains(rightAttr) &&
+      ExternalLookupKeyTypes.supportsEquality(rightAttr.dataType) &&
+      !ExternalLookupKeyTypes.isCharOrVarchar(rightAttr)

Review Comment:
   Why exclude VARCHAR? Without 
`spark.sql.charVarchar.standardSemantics.enabled` it has no read-side padding 
and compares like STRING, so a PAD SPACE or case-insensitive store can only 
return extra rows, which the re-check in #59910 removes. The same store is 
already accepted for STRING keys. The one under-match I can find is standard 
semantics, where the read side trims trailing blanks.
   
   Meanwhile a join keyed only on VARCHAR fails with `NO_LOOKUP_CANDIDATE` and 
has no workaround, since a cast on the lookup column is no longer a bare 
attribute. Could this exclude only CHAR, plus VARCHAR under standard semantics?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_JOIN, 
TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Every output attribute of the lookup side. They 
are all part of this
+ *   node's references, so column pruning never puts a projection over the 
lookup relation, which
+ *   preparation needs directly under the join. A narrower list would let it 
do so.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/** A lookup join after its optimized lookup side has been converted to an 
external operation. */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    joinType: JoinType,
+    residualCondition: Option[Expression]) extends UnaryNode {
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => child.output ++ lookupOutput
+    case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      residualCondition.map(_.references.intersect(child.outputSet))
+        .getOrElse(AttributeSet.empty)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
PreparedExternalLookupJoin =
+    copy(child = newChild)
+
+  // Connector descriptions may contain secrets. The physical node renders a 
redacted description.
+  override protected def stringArgs: Iterator[Any] = Iterator(child)

Review Comment:
   This prints as a bare `PreparedExternalLookupJoin`, losing what 
`ExternalLookupJoin` shows. Only `scan` and `readerFactory` need hiding, so how 
about `Iterator(joinType, lookupParameters, residualCondition, child)`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, EqualNullSafe,
+  EqualTo, Expression, ExprUtils, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.EXTERNAL_LOOKUP_JOIN
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.DataType
+
+/** 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 => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    prepared.foreach { node =>
+      ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+        throw QueryCompilationErrors.unsupportedBatchReadError(table)
+      }
+    }
+    prepared
+  }
+
+  private def prepare(join: ExternalLookupJoin): PreparedExternalLookupJoin = {
+    val relation = extractLookupPlan(join.right).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    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)
+    val offeredCandidates = conjuncts.zipWithIndex.collect {
+      case (EqualTo(leftExpr, rightAttr: Attribute), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+      case (EqualTo(rightAttr: Attribute, leftExpr), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+    }
+    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))
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualFirst, residualRest) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition { conjunct =>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    val residual = residualFirst ++ residualRest
+
+    def nonNull[T](value: T, subClass: String): T = Option(value).getOrElse {
+      throw 
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, subClass)
+    }
+    val scan = nonNull(scanBuilder.build(), "NULL_SCAN")
+    // Fields bind to table columns by exact name, as in 
`PushDownUtils.toOutputAttrs`. CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count
+    // for the match. The value-row attributes take the read schema's type and 
nullability, so they
+    // describe every value the connector may return.
+    val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      nonNull(scan.readSchema(), "NULL_READ_SCHEMA"))
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>
+        attr.name == field.name && 
DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      
}.map(_.withDataType(field.dataType).withNullability(field.nullable)).getOrElse 
{
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    // The prepared join replaces the analyzed one, so it keeps the analyzed 
lookup attributes in
+    // their analyzed order; execution projects the value rows into them.
+    // TODO: prune lookup output to the columns required above the join.
+    val lookupOutput = join.right.output
+    val readExprIds = lookupInput.map(_.exprId).toSet
+    lookupOutput.find(attr => !readExprIds.contains(attr.exprId)).foreach { 
attr =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "MISSING_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(attr.name))))
+    }
+    val externalLookup = nonNull(scan.toExternalLookup(), 
"NULL_EXTERNAL_LOOKUP")
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory = nonNull(externalLookup.createReaderFactory(), 
"NULL_READER_FACTORY")
+
+    PreparedExternalLookupJoin(
+      join.left,
+      scan,
+      readerFactory,
+      maxParameterRowsPerRequest,
+      lookupInput,
+      lookupOutput,
+      selectedPredicates.map(_.parameter),
+      selectedPredicates.map(_.nullSafe),
+      join.joinType,
+      residual.reduceOption(And))
+  }
+
+  /**
+   * An equality between a bare lookup column and an expression over the 
stream side, on a type
+   * that Spark offers as a lookup key.
+   */
+  private def isLookupEquality(
+      join: ExternalLookupJoin,
+      leftExpr: Expression,
+      rightAttr: Attribute): Boolean =
+    leftExpr.references.subsetOf(join.left.outputSet) && 
join.right.outputSet.contains(rightAttr) &&

Review Comment:
   Removing either side check on this line, on its own, still passes all of 
`PrepareExternalLookupJoinSuite`. Without them `t.a = t.b` is offered with a 
parameter over a lookup column, and `s.a = s.b` throws `NoSuchElementException` 
in `columnNames`. Please add a case asserting that neither is offered.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -2855,6 +2918,64 @@
     ],
     "sqlState" : "42822"
   },
+  "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED" : {
+    "message" : [
+      "The join cannot be executed as an external lookup join:"
+    ],
+    "subClass" : {
+      "CONFLICTING_JOIN_STRATEGY" : {
+        "message" : [
+          "The join strategy hint <strategy> cannot be honored by an external 
lookup join over <relation>. Remove the <strategy> hint."
+        ]
+      },
+      "JOIN_TYPE" : {
+        "message" : [
+          "The join type <joinType> is not supported by an external lookup 
join over <relation>. Supported join types are <supportedJoinTypes>."
+        ]
+      },
+      "LOOKUP_PLAN" : {
+        "message" : [
+          "The lookup side must be a DSv2 table, with no other operator 
between the table and the join."
+        ]
+      },
+      "LOOKUP_TABLE_ON_LEFT" : {
+        "message" : [
+          "The lookup-only table <relation> must be on the right side of the 
join."
+        ]
+      },
+      "MISSING_JOIN_CONDITION" : {
+        "message" : [
+          "The join has no join condition. Write the lookup condition in the 
join itself, such as in its `ON` clause or the condition argument of `join()`, 
rather than in a later `WHERE` clause or filter."
+        ]
+      },
+      "NO_LOOKUP_CANDIDATE" : {

Review Comment:
   This message is over 900 characters, and "Spark offers it" lost its 
antecedent once the cast sentences were inserted. Could it state only the 
required shape and the reason, leaving the type list to the Javadoc? That also 
saves rewriting it in #60055.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, EqualNullSafe,
+  EqualTo, Expression, ExprUtils, PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.EXTERNAL_LOOKUP_JOIN
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.DataType
+
+/** 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 => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    prepared.foreach { node =>
+      ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+        throw QueryCompilationErrors.unsupportedBatchReadError(table)
+      }
+    }
+    prepared
+  }
+
+  private def prepare(join: ExternalLookupJoin): PreparedExternalLookupJoin = {
+    val relation = extractLookupPlan(join.right).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    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)
+    val offeredCandidates = conjuncts.zipWithIndex.collect {
+      case (EqualTo(leftExpr, rightAttr: Attribute), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+      case (EqualTo(rightAttr: Attribute, leftExpr), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+    }
+    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))
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualFirst, residualRest) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition { conjunct =>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)
+    }
+    val residual = residualFirst ++ residualRest
+
+    def nonNull[T](value: T, subClass: String): T = Option(value).getOrElse {
+      throw 
QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, subClass)
+    }
+    val scan = nonNull(scanBuilder.build(), "NULL_SCAN")

Review Comment:
   The five `NULL_*` subclasses differ only by method name, and 
`V2ScanRelationPushDown` / `PushDownUtils` have no such checks. Could they 
collapse into one `NULL_RESULT` with a `<method>` parameter, or be dropped?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinStrategyHint,
+  LogicalPlan, ResolvedHint}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN
+import org.apache.spark.sql.connector.catalog.Table
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
+
+/**
+ * Classifies a join for external lookup. [[CheckExternalLookupJoin]] and 
[[FormExternalLookupJoin]]
+ * share it, so analysis rejects every join that the optimizer cannot convert, 
except one without
+ * a condition: see [[CheckExternalLookupJoin]].
+ *
+ * A join is an external lookup join when its right side reads a table that 
supports external
+ * lookup but not batch read. It must be a stream-static join: the left side 
is a streaming query,
+ * whose micro-batches tolerate lookup results that change between requests, 
and the lookup-only
+ * table is on the right side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+  sealed trait Eligibility
+  /**
+   * The join stays an ordinary join: the classifier recognizes no lookup-only 
relation as either
+   * of its sides. A lookup-only relation under another operator, such as a 
projection or an
+   * alias, is not recognized yet, and fails later as a batch scan.
+   */
+  case object NotLookupJoin extends Eligibility
+  /** The join runs as an external lookup join. */
+  case object Eligible extends Eligibility
+  /** The join reads a lookup-only table, with a supported join type, but has 
no condition. */
+  case object MissingCondition extends Eligibility
+  /** The join reads a lookup-only table, which no other join can read, but 
cannot run. */
+  case class Ineligible(error: Throwable) extends Eligibility
+
+  private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter)
+
+  def apply(join: Join): Eligibility = {
+    // The lookup-only table must be on the right side; the sides are never 
swapped.
+    // TODO: look through projections, filters and aliases above the lookup 
relation.
+    // TODO: allow the EXTERNAL_LOOKUP hint once it is introduced, and 
classify the joins it opts
+    //   in.
+    (ExternalLookupRelations.lookupOnlyTable(join.left), 
lookupOnlyTableOnRight(join)) match {
+      case (Some(table), _) => ineligible("LOOKUP_TABLE_ON_LEFT", table)
+      case (None, Some(table)) => lookupJoinEligibility(join, table)
+      case (None, None) => NotLookupJoin
+    }
+  }
+
+  /**
+   * The lookup-only table on the join's right side, also under a strategy 
hint, which is where a
+   * broadcast hint usually goes in a stream-static join. The hint is then 
reported as conflicting.
+   */
+  private def lookupOnlyTableOnRight(join: Join): Option[Table] = {
+    def underStrategyHints(plan: LogicalPlan): LogicalPlan = plan match {
+      case ResolvedHint(child, hint) if hint.strategy.isDefined => 
underStrategyHints(child)
+      case other => other
+    }
+    ExternalLookupRelations.lookupOnlyTable(underStrategyHints(join.right))
+  }
+
+  private def lookupJoinEligibility(join: Join, table: Table): Eligibility = {
+    if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", table)
+    // A join hint the user wrote is never silently dropped: an external 
lookup join cannot run a
+    // physical join strategy, and a lookup-only table has no batch scan for 
one.
+    joinStrategyHint(join) match {
+      case Some(strategy) =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", table,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      // Checked before the condition, so that a cross join fails while it is 
analyzed.
+      case None if !SUPPORTED_JOIN_TYPES.contains(join.joinType) =>
+        ineligible("JOIN_TYPE", table, Map(
+          "joinType" -> toSQLStmt(join.joinType.sql),
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => 
toSQLStmt(t.sql)).mkString(", ")))
+      case None if join.condition.isEmpty => MissingCondition
+      case None => Eligible
+    }
+  }
+
+  private def ineligible(
+      subClass: String,
+      table: Table,
+      parameters: Map[String, String] = Map.empty): Ineligible =
+    Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+      subClass, parameters + ("relation" -> toSQLId(table.name()))))
+
+  private def joinStrategyHint(join: Join): Option[JoinStrategyHint] = {
+    // Only the hints that EliminateResolvedHint will attach to this join 
count; a strategy hint
+    // on a nested join belongs to that join.
+    val attached = join.hint.leftHint.toSeq ++ join.hint.rightHint.toSeq ++
+      Seq(join.left, 
join.right).flatMap(EliminateResolvedHint.extractHintsFromPlan(_)._2)
+    attached.flatMap(_.strategy).headOption
+  }
+}
+
+/**
+ * Reports, while a query is analyzed, why a join over a lookup-only table 
cannot run as an
+ * external lookup join. It does not change the plan: the join stays a 
[[Join]] until
+ * [[FormExternalLookupJoin]] converts it, so the APIs and rules that expect 
an analyzed join keep
+ * working. A join that is not resolved, for example one whose condition is 
not boolean, is left to
+ * the analyzer's own join checks.
+ *
+ * A missing join condition is not reported here, because the classic Dataset 
API analyzes a USING
+ * join first as a join without a condition.
+ */
+object CheckExternalLookupJoin extends (LogicalPlan => Unit) {
+  override def apply(plan: LogicalPlan): Unit = {
+    if (plan.containsPattern(JOIN)) {
+      plan.foreachUp {
+        case join: Join if join.resolved =>
+          ExternalLookupJoinEligibility(join) match {
+            case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+            case _ =>
+          }
+        case _ =>
+      }
+    }
+  }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an 
[[ExternalLookupJoin]].
+ *
+ * It must run at the start of optimization, before Finish Analysis and 
operator optimization, so
+ * that it sees the join and its lookup side as analysis left them: no hint or 
alias eliminated,
+ * no predicate pushed into the join and no column pruned. These are the 
shapes that
+ * [[CheckExternalLookupJoin]] validated.
+ */
+object FormExternalLookupJoin extends Rule[LogicalPlan] {
+  import ExternalLookupJoinEligibility._
+
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    plan.transformUpWithPruning(_.containsPattern(JOIN), ruleId) {

Review Comment:
   This rule runs in a `Once` batch in #59910, so `ruleId` has little to prune, 
while rule ids are a bounded space. Could we drop it and the `RuleIdCollection` 
entry?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,398 @@
+/*
+ * 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.SparkException
+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,
+  Expression, Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, 
LeftOuter, PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 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.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+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) }
+
+  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")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(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)) {
+      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)))
+      val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+      assert(offeredCandidates === expected, codeType)
+      // The connector selects only `id = ?`, so Spark evaluates the code 
equality either way.
+      assert(prepared.residualCondition === Some(codesEqual), codeType)
+    }
+
+    // Without another candidate, the join cannot run.
+    Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").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("the residual evaluates key equalities and conjuncts that cannot fail 
first") {
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING, value STRING"))
+    val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    // A 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(streamLabel === lookupLabel && 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.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      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(codeEqual && altEqual && 
mayFail))
+    }
+  }
+
+  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.residualCondition === Some(conjuncts(2) && conjuncts(3)))
+    assert(reversed.output === joinOutput)
+    assert(PrepareExternalLookupJoin(reversed) === reversed)
+    checkError(
+      exception = intercept[SparkException] { reversed.copy(joinType = 
FullOuter).output },

Review Comment:
   Same internal-error check as `FormExternalLookupJoinSuite`; one copy is 
enough.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.QueryPlanningTracker
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.dsl.plans._
+import org.apache.spark.sql.catalyst.plans.{Cross, FullOuter, Inner, 
LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinHint,
+  LocalRelation, LogicalPlan, Project}
+import org.apache.spark.sql.connector.catalog.{Table, TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation}
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class FormExternalLookupJoinSuite extends AnalysisTest {
+  // The stream side of a stream-static join.
+  private val stream = LocalRelation(Seq($"streamTenant".int, 
$"streamId".int), isStreaming = true)
+  // A lookup-only table has no batch scan, so it reaches the join as this 
placeholder.
+  private val lookupOnly = ExternalLookupRelation(tableWith(EXTERNAL_LOOKUP))
+  private val idsEqual = stream.output(1) === lookupOnly.output(1)
+
+  private def tableWith(capabilities: TableCapability*): DataSourceV2Relation =
+    DataSourceV2Relation.create(
+      LookupCapabilityTable(capabilities.toSet), None, None, 
CaseInsensitiveStringMap.empty)
+
+  // An inner join of the stream with `right`, on the id column of each.
+  private def innerJoinOnId(right: LogicalPlan): Join =
+    Join(stream, right, Inner, Some(stream.output(1) === right.output(1)), 
JoinHint.NONE)
+
+  // Hints become ResolvedHint nodes, which only Finish Analysis moves into 
the join.
+  private def analyze(plan: LogicalPlan): LogicalPlan =
+    getAnalyzer.executeAndCheck(plan, new QueryPlanningTracker)
+
+  test("an eligible join stays a Join in analysis and is converted when 
optimization starts") {
+    val Seq(tenant, id) = stream.output
+    val compositeKey = tenant === lookupOnly.output(0) && idsEqual
+    for (condition <- Seq(idsEqual, compositeKey); joinType <- Seq(Inner, 
LeftOuter)) {
+      val analyzed = analyze(stream.join(lookupOnly, joinType, 
Some(condition)))
+      assert(analyzed.isInstanceOf[Join])
+      CheckExternalLookupJoin(analyzed)
+      FormExternalLookupJoin(analyzed) match {
+        case lookupJoin: ExternalLookupJoin =>
+          assert(lookupJoin.joinType == joinType && lookupJoin.condition == 
Some(condition))
+          assert(lookupJoin.requiredLookupOutput == lookupOnly.output)
+          assert(lookupJoin.output == analyzed.output)
+          assert(lookupJoin.output.drop(2).forall(_.nullable) == (joinType == 
LeftOuter))
+          assert(lookupJoin.missingInput.isEmpty)
+          assert(FormExternalLookupJoin(lookupJoin) == lookupJoin)
+        case other => fail(s"Expected an external lookup join: $other")
+      }
+    }
+  }
+
+  test("keep ordinary joins that cannot become external lookup joins") {
+    val other = LocalRelation($"k".int, $"k2".int)
+    Seq(
+      innerJoinOnId(tableWith(BATCH_READ, EXTERNAL_LOOKUP)),
+      innerJoinOnId(tableWith(BATCH_READ)),
+      innerJoinOnId(other),
+      innerJoinOnId(Project(lookupOnly.output, lookupOnly))).foreach { join =>
+      CheckExternalLookupJoin(join)
+      assert(FormExternalLookupJoin(join) == join)
+    }
+  }
+
+  test("validation and conversion reject a lookup-only join with the same 
reason") {
+    Seq(
+      // Only a stream-static join, with the lookup-only table on the right 
side.
+      (stream.copy(isStreaming = false).join(lookupOnly, Inner, 
Some(idsEqual)),
+        "STATIC_LEFT_SIDE", Map.empty[String, String]),
+      (lookupOnly.join(stream, Inner, Some(idsEqual)), "LOOKUP_TABLE_ON_LEFT",
+        Map.empty[String, String]),
+      (stream.join(lookupOnly, RightOuter, Some(idsEqual)), "JOIN_TYPE",
+        Map("joinType" -> "RIGHT OUTER")),
+      // A cross join fails with its join type, with or without a later filter.
+      (stream.join(lookupOnly, Cross), "JOIN_TYPE", Map("joinType" -> 
"CROSS")),
+      (stream.join(lookupOnly, Cross).where(idsEqual), "JOIN_TYPE", 
Map("joinType" -> "CROSS")),
+      // No join strategy hint applies to an external lookup join; sort merge 
is named MERGE.
+      (stream.hint("broadcast").join(lookupOnly, Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")),
+      (stream.hint("merge").join(lookupOnly, Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")),
+      (stream.hint("shuffle_hash").join(lookupOnly, Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")),
+      (stream.hint("shuffle_replicate_nl").join(lookupOnly, Inner, 
Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> 
"SHUFFLE_REPLICATE_NL")),
+      // The same on the lookup side, where a broadcast hint usually goes in a 
stream-static join.
+      (stream.join(lookupOnly.hint("broadcast"), Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")),
+      (stream.join(lookupOnly.hint("merge"), Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")),
+      (stream.join(lookupOnly.hint("shuffle_hash"), Inner, Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")),
+      (stream.join(lookupOnly.hint("shuffle_replicate_nl"), Inner, 
Some(idsEqual)),
+        "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> 
"SHUFFLE_REPLICATE_NL"))).foreach {
+      case (plan, subClass, parameters) =>
+        val analyzed = analyze(plan)
+        Seq[LogicalPlan => Any](CheckExternalLookupJoin, 
FormExternalLookupJoin(_)).foreach {
+          rule =>
+            val error = intercept[AnalysisException] { rule(analyzed) }
+            assert(error.getCondition == 
s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass")
+            // The list of supported join types grows in a later change.
+            assert(error.getMessageParameters.asScala.toMap - 
"supportedJoinTypes" ==

Review Comment:
   Excluding `supportedJoinTypes` means this parameter is never asserted. 
Please assert it now and update it in #60055, rather than leaving a comment 
about a later change.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,398 @@
+/*
+ * 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.SparkException
+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,
+  Expression, Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, 
LeftOuter, PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 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.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+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) }
+
+  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")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(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)) {
+      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)))
+      val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+      assert(offeredCandidates === expected, codeType)
+      // The connector selects only `id = ?`, so Spark evaluates the code 
equality either way.
+      assert(prepared.residualCondition === Some(codesEqual), codeType)
+    }
+
+    // Without another candidate, the join cannot run.
+    Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").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("the residual evaluates key equalities and conjuncts that cannot fail 
first") {
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING, value STRING"))
+    val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    // A 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(streamLabel === lookupLabel && 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.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {

Review Comment:
   `withSQLConf(ANSI_ENABLED)` has no effect here: `canEvaluateUnconditionally` 
never whitelists `Cast`, regardless of ANSI mode.



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