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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupJoin.scala:
##########
@@ -0,0 +1,100 @@
+/*
+ * 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, 
JoinHint,
+  JoinStrategyHint, LogicalPlan}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
+
+/**
+ * Replaces an eligible join with a lookup join holder.
+ *
+ * A join is planned as 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 ResolveExternalLookupJoin extends Rule[LogicalPlan] with 
QueryErrorsBase {
+  private val SupportedJoinTypes = Seq(Inner, LeftOuter)
+
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    plan.resolveOperatorsUpWithPruning(_.containsPattern(JOIN), ruleId) {
+      case join: Join if join.left.resolved && join.right.resolved => 
resolveLookupJoin(join)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[73b62b7c559](https://github.com/apache/spark/pull/59909/commits/73b62b7c559b90caf5ac9088417679591118c5d5)
 by moving the conversion (see the review reply). The join stays a `Join` 
through analysis, so `DeduplicateRelations` and CheckAnalysis's join checks 
apply to it as to any join. The new analysis-time check, 
`CheckExternalLookupJoin`, considers only resolved joins (`Join.resolved`). A 
non-boolean condition or conflicting attributes are therefore reported by the 
analyzer's usual errors, not by a lookup-join reason. The test "validation 
leaves a join that is not resolved to the analyzer's join checks" covers an INT 
condition and a right side that shares attribute IDs with the left side. Both 
would otherwise fail with `JOIN_TYPE`.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, EqualTo, 
Expression,
+  PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
Filter, Join, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+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.internal.SQLConf
+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. Pre-order visits a join before the 
relation it reads.
+    prepared.foreach {
+      // Classic Dataset.join(right, usingColumns) first analyzes Join(left, 
right, joinType, None),
+      // including CheckAnalysis, to disambiguate a self-join, and only then 
builds the USING join.
+      // That plan cannot be told apart from a join without a condition, so 
analysis keeps it, and
+      // a missing condition is reported here, on the final plan.
+      case Join(_, right, _, None, _) if readsLookupOnlyTable(right) =>
+        throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("MISSING_JOIN_CONDITION")
+      case node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+    }
+    prepared
+  }
+
+  private def readsLookupOnlyTable(plan: LogicalPlan): Boolean = plan match {
+    case node @ (_: Project | _: Filter) => 
readsLookupOnlyTable(node.children.head)
+    case node => ExternalLookupRelations.lookupOnlyTable(node).isDefined
+  }
+
+  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 scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    val offeredCandidates = mutable.ArrayBuffer.empty[OfferedLookupPredicate]
+    val residual = mutable.ArrayBuffer.empty[Expression]
+    conjuncts.foreach {
+      case equality @ EqualTo(leftExpr, rightAttr: Attribute)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case equality @ EqualTo(rightAttr: Attribute, leftExpr)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case other => residual += other
+    }
+
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(candidate.projectedField.name),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val (selectedPredicates, unselectedPredicates) = 
selectedCandidates(tableName,
+      offeredPredicates, offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    residual ++= unselectedPredicates.map(_.condition)
+
+    val scan = scanBuilder.build()
+    val resolver = SQLConf.get.resolver
+    // Fields match the way ordinary V2 scans match them 
(`PushDownUtils.toOutputAttrs`): CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count.
+    val readSchema = 
CharVarcharUtils.replaceCharVarcharWithStringInSchema(scan.readSchema())
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>
+        resolver(attr.name, field.name) &&
+          DataType.equalsIgnoreNullability(attr.dataType, field.dataType)
+      }.getOrElse {
+        throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+          tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> 
toSQLId(Seq(field.name))))
+      }
+    }.toSeq
+    lookupInput.groupBy(_.name).collectFirst {
+      case (name, fields) if fields.size > 1 => name
+    }.foreach { name =>
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name))))
+    }
+    val externalLookup = scan.toExternalLookup()
+    val maxParameterRowsPerRequest = 
externalLookup.maxParameterRowsPerRequest()
+    if (maxParameterRowsPerRequest <= 0) {
+      throw QueryCompilationErrors.invalidDataSourceExternalLookupError(
+        tableName,
+        "NON_POSITIVE_MAX_PARAMETER_ROWS",
+        Map("value" -> maxParameterRowsPerRequest.toString))
+    }
+    val readerFactory = externalLookup.createReaderFactory()
+    // TODO: prune lookup output to the columns required above the join.
+    val lookupOutput = lookupInput

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[73b62b7c559](https://github.com/apache/spark/pull/59909/commits/73b62b7c559b90caf5ac9088417679591118c5d5).
 `lookupOutput` is now the analyzed lookup attributes (`join.right.output`) in 
analyzed order, so `PreparedExternalLookupJoin.output` equals the output of the 
`ExternalLookupJoin` it replaces, whatever order the read schema uses. The read 
schema may list the columns in any order, but it must contain every table 
column, because the lookup builder is not pruned yet. A missing column fails 
with the new `DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.MISSING_SCAN_FIELD`, which 
names it. That also covers lookup columns that the residual uses, so a dangling 
reference can no longer reach binding. `lookupInput` keeps the read-schema 
order, so execution can project the value rows into `lookupOutput`. Tests: "the 
read schema binds to the analyzed lookup attributes by exact name" checks a 
reordered read schema, and "the read schema must cover every lookup column with 
its data type" checks
  a missing one.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, EqualTo, 
Expression,
+  PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
Filter, Join, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+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.internal.SQLConf
+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. Pre-order visits a join before the 
relation it reads.
+    prepared.foreach {
+      // Classic Dataset.join(right, usingColumns) first analyzes Join(left, 
right, joinType, None),
+      // including CheckAnalysis, to disambiguate a self-join, and only then 
builds the USING join.
+      // That plan cannot be told apart from a join without a condition, so 
analysis keeps it, and
+      // a missing condition is reported here, on the final plan.
+      case Join(_, right, _, None, _) if readsLookupOnlyTable(right) =>

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[73b62b7c559](https://github.com/apache/spark/pull/59909/commits/73b62b7c559b90caf5ac9088417679591118c5d5),
 as you recommended. `FormExternalLookupJoin` runs at the start of 
optimization, before `PushPredicateThroughJoin`. It raises 
`MISSING_JOIN_CONDITION` for a join without a condition whose right side is a 
lookup-only relation, so `s.join(t).where(...)` and `s.crossJoin(t).where(...)` 
now report it. Analysis still doesn't raise it, because the classic Dataset API 
first analyzes a USING join as a join without a condition. By the start of 
optimization, a USING join has its condition. The final-plan case in 
`PrepareExternalLookupJoin` is removed. Its rejection of a lookup-only relation 
read outside a lookup join is unchanged, so a lookup side beneath an alias 
still fails as a batch scan. The message now says to write the condition in the 
join rather than in a later `WHERE` clause or filter. In the tests, a join 
without a condition, the same join followed by `where()`, and
  a cross join followed by `where()` all pass the analysis-time check and fail 
at conversion.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, EqualTo, 
Expression,
+  PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
Filter, Join, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+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.internal.SQLConf
+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. Pre-order visits a join before the 
relation it reads.
+    prepared.foreach {
+      // Classic Dataset.join(right, usingColumns) first analyzes Join(left, 
right, joinType, None),
+      // including CheckAnalysis, to disambiguate a self-join, and only then 
builds the USING join.
+      // That plan cannot be told apart from a join without a condition, so 
analysis keeps it, and
+      // a missing condition is reported here, on the final plan.
+      case Join(_, right, _, None, _) if readsLookupOnlyTable(right) =>
+        throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("MISSING_JOIN_CONDITION")
+      case node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+    }
+    prepared
+  }
+
+  private def readsLookupOnlyTable(plan: LogicalPlan): Boolean = plan match {
+    case node @ (_: Project | _: Filter) => 
readsLookupOnlyTable(node.children.head)
+    case node => ExternalLookupRelations.lookupOnlyTable(node).isDefined
+  }
+
+  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 scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    val offeredCandidates = mutable.ArrayBuffer.empty[OfferedLookupPredicate]
+    val residual = mutable.ArrayBuffer.empty[Expression]
+    conjuncts.foreach {
+      case equality @ EqualTo(leftExpr, rightAttr: Attribute)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case equality @ EqualTo(rightAttr: Attribute, leftExpr)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case other => residual += other
+    }
+
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(candidate.projectedField.name),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val (selectedPredicates, unselectedPredicates) = 
selectedCandidates(tableName,
+      offeredPredicates, offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    residual ++= unselectedPredicates.map(_.condition)
+
+    val scan = scanBuilder.build()
+    val resolver = SQLConf.get.resolver
+    // Fields match the way ordinary V2 scans match them 
(`PushDownUtils.toOutputAttrs`): CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count.
+    val readSchema = 
CharVarcharUtils.replaceCharVarcharWithStringInSchema(scan.readSchema())
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>
+        resolver(attr.name, field.name) &&

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[73b62b7c559](https://github.com/apache/spark/pull/59909/commits/73b62b7c559b90caf5ac9088417679591118c5d5).
 Read-schema fields now bind to the relation attribute with exactly the same 
name, as `PushDownUtils.toOutputAttrs` does. For a table `(id, a, A)`, each 
field binds to its own column, and `DUPLICATE_SCAN_FIELD` fires only when a 
field is listed twice. The test uses a table `(id INT, a INT, A INT)` with the 
read schema `(A, id, a)` under `spark.sql.caseSensitive=false` and checks that 
each field gets its own column's exprId. The comment no longer claims resolver 
matching.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{And, Attribute, EqualTo, 
Expression,
+  PredicateHelper}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
Filter, Join, LogicalPlan,
+  PreparedExternalLookupJoin, Project}
+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.internal.SQLConf
+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. Pre-order visits a join before the 
relation it reads.
+    prepared.foreach {
+      // Classic Dataset.join(right, usingColumns) first analyzes Join(left, 
right, joinType, None),
+      // including CheckAnalysis, to disambiguate a self-join, and only then 
builds the USING join.
+      // That plan cannot be told apart from a join without a condition, so 
analysis keeps it, and
+      // a missing condition is reported here, on the final plan.
+      case Join(_, right, _, None, _) if readsLookupOnlyTable(right) =>
+        throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("MISSING_JOIN_CONDITION")
+      case node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+    }
+    prepared
+  }
+
+  private def readsLookupOnlyTable(plan: LogicalPlan): Boolean = plan match {
+    case node @ (_: Project | _: Filter) => 
readsLookupOnlyTable(node.children.head)
+    case node => ExternalLookupRelations.lookupOnlyTable(node).isDefined
+  }
+
+  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 scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    val offeredCandidates = mutable.ArrayBuffer.empty[OfferedLookupPredicate]
+    val residual = mutable.ArrayBuffer.empty[Expression]
+    conjuncts.foreach {
+      case equality @ EqualTo(leftExpr, rightAttr: Attribute)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case equality @ EqualTo(rightAttr: Attribute, leftExpr)
+          if leftExpr.references.subsetOf(join.left.outputSet) &&
+            join.right.outputSet.contains(rightAttr) =>
+        offeredCandidates += OfferedLookupPredicate(leftExpr, rightAttr, 
equality, "=", false)
+      case other => residual += other
+    }
+
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(candidate.projectedField.name),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    // A copy, so a connector that reorders the array in place cannot break 
the identity mapping.
+    val (selectedPredicates, unselectedPredicates) = 
selectedCandidates(tableName,
+      offeredPredicates, offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates.clone()))
+    residual ++= unselectedPredicates.map(_.condition)
+
+    val scan = scanBuilder.build()
+    val resolver = SQLConf.get.resolver
+    // Fields match the way ordinary V2 scans match them 
(`PushDownUtils.toOutputAttrs`): CHAR and
+    // VARCHAR are read as STRING, and nullability, including nested 
nullability, does not count.
+    val readSchema = 
CharVarcharUtils.replaceCharVarcharWithStringInSchema(scan.readSchema())
+    val lookupInput = readSchema.fields.map { field =>
+      relation.output.find { attr =>

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[73b62b7c559](https://github.com/apache/spark/pull/59909/commits/73b62b7c559b90caf5ac9088417679591118c5d5),
 along the lines you suggested. Each `lookupInput` attribute takes the 
read-schema field's type and nullability, including nested nullability, and 
keeps the relation attribute's exprId and metadata, including the CHAR/VARCHAR 
type string. `lookupOutput` keeps the analyzed attributes and their 
nullability, and the left outer widening is unchanged. Read schemas whose 
nullability is weaker than the table's are still accepted. The test uses the 
read schema `s STRUCT<a: INT>, value VARCHAR(8), id INT NOT NULL` for a table 
`id INT NOT NULL, value VARCHAR(8) NOT NULL, s STRUCT<a: INT NOT NULL>`. It 
checks `lookupInput`'s order, nullability, nested type, exprIds and metadata, 
and that `lookupOutput` and the node's output are unchanged.
   



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