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


##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Agreed. Fixed in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa):
 Spark now offers `=` on a VARCHAR lookup column, except under 
`spark.sql.charVarchar.standardSemantics.enabled`, where the read side trims 
trailing blanks. CHAR stays excluded. `ExternalLookupKeyTypes.supportsEquality` 
now takes the lookup column, so it can read the declared type. #60055, which 
adds `<=>`, offers it on VARCHAR too 
([bd66301acae](https://github.com/apache/spark/commit/bd66301acae7ff882d172c3ea4d9218d7c4ec153)),
 and #59910 adds a run test in which a VARCHAR key matches each key exactly 
([ff67010628f](https://github.com/apache/spark/commit/ff67010628ff2215bc180eb23c1d60ae7e4181cc)).
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Added in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa):
 "an equality within one side of the join is never a lookup candidate" covers 
`t.value = t.alt` in both orders and `s.label = s.code`, and asserts that none 
of them is offered.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Done in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa):
 `stringArgs` is now `Iterator(joinType, lookupParameters, residualCondition, 
child)`, so only the scan and the reader factory stay hidden. A new test checks 
the plan string.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Collapsed in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa).
 A planning method that returns null now fails with 
`DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT`, which names the method. A 
null element in the selected predicates fails with 
`UNOFFERED_SELECTED_PREDICATE`, as any other element that Spark did not offer 
does. #59910 does the same for the read path: `createReader()`, `lookupBatch()` 
and the cursor's `get()` 
([ff67010628f](https://github.com/apache/spark/commit/ff67010628ff2215bc180eb23c1d60ae7e4181cc)).
   
   I kept the check rather than dropping it. Without it, a null from a 
connector surfaces later as a `NullPointerException`, with no hint of which 
connector method returned it.
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Shortened in 
[e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa).
 The message now states the required shape and the reason, and points to the 
Javadoc of `selectLookupPredicates()` for the types. #60055 adds the range 
comparisons to it in one sentence, instead of rewriting it 
([bd66301acae](https://github.com/apache/spark/commit/bd66301acae7ff882d172c3ea4d9218d7c4ec153)).
   



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