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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala:
##########
@@ -0,0 +1,193 @@
+/*
+ * 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 java.util.Locale
+
+import scala.collection.mutable
+import scala.util.control.NonFatal
+
+import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, 
StringLiteral}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, 
UnresolvedWith, View}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its 
parameters are
+ * relation names and cache options:
+ *  - A relation name is an identifier, or a string that does not contain `=`. 
As with join
+ *    strategy hints, a hint without relation names marks the plan it is 
attached to, and a hint
+ *    with relation names marks each named relation.
+ *  - A cache option is a string of the form `key=value`, such as 
`'cache_ttl=5s'`. It overrides a
+ *    `spark.sql.join.externalLookup.cache.*` configuration for the joins that 
the hint marks.
+ */
+object ResolveExternalLookupHint extends Rule[LogicalPlan] with 
QueryErrorsBase {
+  private val HINT_NAME = "EXTERNAL_LOOKUP"
+  private val CACHE_ENABLED_OPTION = "cache_enabled"
+  private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries"
+  private val CACHE_TTL_OPTION = "cache_ttl"
+  private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key"
+  private val SUPPORTED_OPTIONS = Set(
+    CACHE_ENABLED_OPTION,
+    CACHE_MAX_ENTRIES_OPTION,
+    CACHE_TTL_OPTION,
+    CACHE_MAX_ROWS_PER_KEY_OPTION)
+  private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 
5s, or 10m"
+
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), 
ruleId) {
+      case UnresolvedHint(name, parameters, child)
+          if name.toUpperCase(Locale.ROOT) == HINT_NAME =>
+        resolveHint(parameters, child)
+    }
+
+  private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): 
LogicalPlan = {
+    val relationNames = mutable.ArrayBuffer.empty[Seq[String]]
+    var cacheOptions = defaultCacheOptions
+    val seenOptions = mutable.HashSet.empty[String]
+    // The Dataset API, PySpark and Spark Connect pass a relation name as a 
string, as they do for
+    // join strategy hints. A relation whose name contains `=` is named with 
an identifier.
+    def addString(value: String): Unit =
+      if (value.contains('=')) {
+        cacheOptions = parseOption(value, cacheOptions, seenOptions)
+      } else {
+        relationNames += UnresolvedAttribute.parseAttributeName(value)
+      }
+    parameters.foreach {
+      case StringLiteral(value) => addString(value)
+      case Literal(value: String, _) => addString(value)
+      case attr: UnresolvedAttribute =>
+        relationNames += attr.nameParts
+      case other =>
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other)))
+    }
+    relationNames.diff(relationNames.distinct).headOption.foreach { duplicate 
=>
+      throw QueryCompilationErrors.invalidExternalLookupHintError(
+        "DUPLICATE_RELATION", Map("relation" -> toSQLId(duplicate)))
+    }
+
+    if (relationNames.isEmpty) {
+      ExternalLookupHint(child, cacheOptions)
+    } else {
+      // As with join strategy hints, a name marks every relation that it 
matches. `matched` only
+      // tells which names matched nothing.
+      val matched = mutable.HashSet.empty[Seq[String]]
+      def matches(identifier: Seq[String]): Boolean = {
+        val names = relationNames.filter { name =>
+          ResolveHints.matchedIdentifier(name, identifier, conf.resolver)
+        }
+        matched ++= names
+        names.nonEmpty
+      }
+      // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: 
a name matches an
+      // unaliased (possibly multipart) table or an alias, and does not reach 
into a view,
+      // a WITH clause, or an aliased subquery.
+      def applyHint(plan: LogicalPlan): LogicalPlan = plan match {
+        case relation: UnresolvedRelation if 
matches(relation.multipartIdentifier) =>
+          ExternalLookupHint(relation, cacheOptions)
+        case alias: SubqueryAlias
+            if matches(alias.identifier.qualifier :+ alias.identifier.name) =>
+          ExternalLookupHint(alias, cacheOptions)
+        case _: View | _: UnresolvedWith | _: SubqueryAlias => plan
+        case _ => plan.mapChildren(applyHint)
+      }
+      val rewritten = applyHint(child)
+      val missing = relationNames.filterNot(matched.contains)
+      if (missing.nonEmpty) {
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "RELATION_NOT_FOUND", Map("relations" -> 
missing.map(toSQLId).mkString(", ")))
+      }
+      rewritten
+    }
+  }
+
+  private[analysis] def defaultCacheOptions: ExternalLookupCacheOptions = {

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 
[c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62):
 `maxBytes` and `ttl` are tested through the session conf, not only through 
hint options.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2530,6 +2530,76 @@ object SQLConf {
     .bytesConf(ByteUnit.BYTE)
     .createWithDefault(8L << 30)
 
+  val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES =
+    buildConf("spark.sql.join.externalLookup.maxBatchBytes")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("Size in bytes of input rows at which an external lookup join stops 
adding rows to " +
+        "a lookup request. The row that reaches this size stays in the 
request, so a request " +
+        "can exceed it by one row. A request always takes at least one row, 
and never more rows " +
+        "than the source allows, or 1000.")
+      .version("4.4.0")
+      .bytesConf(ByteUnit.BYTE)
+      .checkValue(_ > 0, "External lookup join max batch bytes must be 
positive")
+      .createWithDefaultString("64m")
+
+  val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED =
+    buildConf("spark.sql.join.externalLookup.startupCheck.enabled")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("When true, starting a streaming query plans its external lookup 
joins once, " +
+        "including the planning calls to their connectors, so that a join that 
cannot be " +
+        "planned fails the start instead of the first micro-batch. When false, 
such a join " +
+        "fails the first micro-batch that runs.")
+      .version("4.4.0")
+      .booleanConf
+      .createWithDefault(true)
+
+  val JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED =
+    buildConf("spark.sql.join.externalLookup.cache.enabled")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .doc("When true, external lookup join caches the complete lookup result 
of each key, " +
+        "including a key with no result, within a task, per input partition (a 
task that reads " +
+        "several input partitions, e.g. after coalesce, has one cache per 
partition). A cached " +
+        "result is reused as it was read. At present, a join whose source 
serves a range " +
+        "comparison (<, <=, >, >=) caches nothing. It can be overridden per 
join with the " +

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 
[c45ebaea1e7](https://github.com/apache/spark/commit/c45ebaea1e785c3674e8cc06b6872823725f1d62):
 the doc names the conf, and says that no option enables the cache for a range 
lookup.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.optimizer.{EliminateResolvedHint, 
InlineCTE}
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupCacheOptions, ExternalLookupHint, ExternalLookupJoin, 
ExternalLookupJoinShapes,
+  Filter, Join, JoinStrategyHint, LogicalPlan, Project, ResolvedHint, 
SubqueryAlias, UnaryNode,
+  View, WithCTE}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CTE, 
DATA_SOURCE_V2_RELATION,
+  EXTERNAL_LOOKUP_HINT, JOIN}
+import org.apache.spark.sql.catalyst.util.MetadataColumnHelper
+import org.apache.spark.sql.connector.catalog.TableCapability
+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, or when the right side carries an 
`EXTERNAL_LOOKUP` hint. A table
+ * that supports both keeps the ordinary join strategies unless the hint opts 
in. 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 table is on the right 
side. The join reads
+ * the table directly, or through hints, aliases, views, and projections and 
filters that it can
+ * evaluate on the lookup results, so a join that must be a lookup join either 
runs as one or fails
+ * here, whatever the optimizer later does to its lookup side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+  sealed trait Eligibility
+  /**
+   * The join stays an ordinary join: it has no `EXTERNAL_LOOKUP` hint, and 
neither of its inputs is
+   * a lookup-only relation, directly or below unary operators. A lookup-only 
relation below another
+   * operator, such as a union, is not recognized, 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 must run as an external lookup join, with a supported join type, 
but has no
+   * condition.
+   */
+  case object MissingCondition extends Eligibility
+  /** The join must run as an external lookup join but cannot. */
+  case class Ineligible(error: Throwable) extends Eligibility
+
+  private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter, LeftSemi, LeftAnti)
+
+  def apply(join: Join): Eligibility = {
+    if (lookupHints(join.left).nonEmpty) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE"))
+    }
+    // The lookup-only table must be on the right side; the sides are never 
swapped.
+    val leftLookupOnlyTable = 
ExternalLookupRelations.lookupOnlyTable(input(join.left))
+    if (leftLookupOnlyTable.isDefined) {
+      return ineligible("LOOKUP_TABLE_ON_LEFT", 
toSQLId(leftLookupOnlyTable.get.name()))
+    }
+    val markers = lookupHints(join.right)
+    val lookupOnly = 
ExternalLookupRelations.lookupOnlyTable(input(join.right)).isDefined
+    // A lookup-only table can be read only by a lookup join, and the hint 
opts a join in. Either
+    // way the join must run as an external lookup join, and the checks below 
apply.
+    if (!lookupOnly && markers.isEmpty) return NotLookupJoin
+    if (markers.length > 1) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("MULTIPLE_HINTS"))
+    }
+    if (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases, 
views, and projections and
+    // filters that the lookup join can evaluate. There is none when another 
operator, or a stage
+    // that it cannot evaluate, stands in between, or the side reads no DSv2 
table.
+    val tableRelation = lookupRelation(join.right)
+    val table = ExternalLookupRelations.table(tableRelation) match {
+      case Some(table) => table
+      case None =>
+        return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN"))
+    }
+    val relation = toSQLId(table.name())
+    if (!table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP)) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "TABLE", Map("table" -> relation)))
+    }
+    // A lookup returns the data columns of the table only. The relation 
outputs a metadata column
+    // only when the query reads one.
+    if (tableRelation.output.exists(_.isMetadataCol)) return 
ineligible("METADATA_COLUMN", relation)
+    if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", relation)
+    // 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. On a table that
+    // also supports batch reads, the strategy hint conflicts with the 
`EXTERNAL_LOOKUP` hint.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) if lookupOnly =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      case Some(strategy) =>
+        Ineligible(QueryCompilationErrors.invalidExternalLookupHintError(
+          "CONFLICTING_JOIN_STRATEGY",
+          Map("strategy" -> toSQLStmt(strategy.displayName), "relation" -> 
relation)))
+      // No physical join was asked for: the join runs as an external lookup 
join unless a check
+      // below fails.
+      // 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", relation, Map(
+          "joinType" -> toSQLStmt(join.joinType.sql),
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => 
toSQLStmt(t.sql)).mkString(", ")))
+      case None if join.condition.isEmpty => MissingCondition
+      // The optimizer rewrites a subquery in a join condition only for a 
Join, which a lookup join
+      // no longer is by then.
+      case None if join.condition.exists(SubqueryExpression.hasSubquery) =>
+        ineligible("SUBQUERY_IN_JOIN_CONDITION", relation)
+      case None => Eligible
+    }
+  }
+
+  /** The CTE definitions in `plan` by id, which [[inlineCTEs]] inlines. */
+  def cteDefinitions(plan: LogicalPlan): Map[Long, CTERelationDef] =
+    if (plan.containsPattern(CTE)) {
+      plan.collect { case cteDef: CTERelationDef => cteDef.id -> cteDef }.toMap
+    } else {
+      Map.empty
+    }
+
+  /**
+   * `join` with the CTE references on the paths of unary operators of its 
inputs inlined, as
+   * InlineCTE inlines them for the analysis check. Only these paths decide 
how the join is
+   * classified, and the lookup side of an eligible join is its path alone, so 
it has no other CTE
+   * reference left.
+   */
+  def inlineCTEs(join: Join, cteDefs: Map[Long, CTERelationDef]): Join =
+    if (cteDefs.isEmpty) {
+      join
+    } else {
+      join.copy(
+        left = inlinePathCTEs(join.left, cteDefs),
+        right = inlinePathCTEs(join.right, cteDefs))
+    }
+
+  private def inlinePathCTEs(
+      plan: LogicalPlan,
+      cteDefs: Map[Long, CTERelationDef]): LogicalPlan = plan match {
+    case _ if !plan.containsPattern(CTE) => plan
+    case ref: CTERelationRef if cteDefs.contains(ref.cteId) =>
+      val cteDef = cteDefs(ref.cteId)
+      InlineCTE.inlineReference(ref, cteDef, inlinePathCTEs(cteDef.child, 
cteDefs))
+    case WithCTE(child, _) => inlinePathCTEs(child, cteDefs)
+    case unary: UnaryNode => 
unary.withNewChildren(Seq(inlinePathCTEs(unary.child, cteDefs)))
+    case other => other
+  }
+
+  /**
+   * The plans that external lookup joins in `plan` read by lookups: the 
lookup side of each join
+   * that must run as an external lookup join, and the CTE definitions that 
the side reads,
+   * directly or through other CTE definitions. Subqueries are not searched.
+   */
+  def lookupSidePlans(plan: LogicalPlan): Seq[LogicalPlan] =
+    // As in CheckExternalLookupJoin, other plans have no join that must run 
as a lookup join.
+    if (!plan.containsPattern(JOIN) ||
+        !plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      Nil
+    } else {
+      val cteDefs = cteDefinitions(plan)
+      val lookupSides = plan.collect {
+        case join: Join if apply(inlineCTEs(join, cteDefs)) != NotLookupJoin 
=> join.right
+      }
+      val readCTEs = mutable.LinkedHashMap.empty[Long, CTERelationDef]
+      def addReadCTEs(plan: LogicalPlan): Unit = plan.foreach {
+        case ref: CTERelationRef if !readCTEs.contains(ref.cteId) =>
+          cteDefs.get(ref.cteId).foreach { cteDef =>
+            readCTEs(ref.cteId) = cteDef
+            addReadCTEs(cteDef)
+          }
+        case _ =>
+      }
+      lookupSides.foreach(addReadCTEs)
+      lookupSides ++ readCTEs.values
+    }
+
+  /**
+   * The lookup side of an eligible join, without its `EXTERNAL_LOOKUP` hint. 
The lookup side of an
+   * eligible join is a chain of hints, aliases, views, projections and 
filters over the table, so
+   * every marker in it is the join's own.
+   */
+  def lookupSide(join: Join): LogicalPlan =
+    join.right.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_HINT)) 
{
+      case marker: ExternalLookupHint => marker.child
+    }
+
+  /**
+   * The cache options of an eligible join, with its CTEs inlined by 
[[inlineCTEs]]: its hint's, or
+   * the session defaults.
+   */
+  def cacheOptions(join: Join): ExternalLookupCacheOptions =
+    lookupHints(join.right).headOption.map(_.cacheOptions)
+      .getOrElse(ResolveExternalLookupHint.defaultCacheOptions)
+
+  private def ineligible(
+      subClass: String,
+      relation: String,
+      parameters: Map[String, String] = Map.empty): Ineligible =
+    Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+      subClass, parameters + ("relation" -> relation)))
+
+  /** The relation that a join input reads: the first operator that has no 
single child. */
+  @tailrec
+  private def input(plan: LogicalPlan): LogicalPlan = plan match {
+    case unary: UnaryNode => input(unary.child)
+    case other => other
+  }
+
+  /**
+   * The first operator below a join input that is not a hint, an alias, a 
view, or a projection or
+   * filter that the lookup join can evaluate on the lookup results. A Python 
or external UDF or a
+   * subquery in one cannot be evaluated there, and the optimizer would 
rewrite some of them into
+   * other operators.
+   */
+  @tailrec
+  private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+    case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | 
_: View) =>
+      lookupRelation(node.children.head)
+    case node @ (_: Project | _: Filter)
+        if 
node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) =>
+      lookupRelation(node.children.head)
+    case other => other
+  }
+
+  /**
+   * The `EXTERNAL_LOOKUP` hints on a join input. Like a join strategy hint, 
the hint applies to the
+   * join that the input feeds, through any unary operator.
+   */
+  @tailrec
+  private def lookupHints(
+      plan: LogicalPlan,
+      found: Seq[ExternalLookupHint] = Nil): Seq[ExternalLookupHint] = plan 
match {
+    case marker: ExternalLookupHint => lookupHints(marker.child, found :+ 
marker)
+    case unary: UnaryNode => lookupHints(unary.child, found)
+    case _ => found
+  }
+
+  /**
+   * The physical join strategy hint, such as `BROADCAST` or `MERGE`, that 
EliminateResolvedHint
+   * would attach to the join, or None if there is none. The `EXTERNAL_LOOKUP` 
hint is never
+   * returned: it is an [[ExternalLookupHint]] marker, not a 
[[JoinStrategyHint]]. A `HintInfo`
+   * without a strategy asks for nothing, so it is skipped.
+   */
+  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 cannot run as the external 
lookup join it must
+ * be. 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 reported only for the query of a streaming 
write, which is analyzed
+ * in full when the query starts, so that `start()` throws it. Other plans can 
still get their
+ * condition: 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 = {
+    // A join must run as a lookup join only over a lookup-only table, which 
is a DSv2 relation, or
+    // under the hint, so other plans need no walk.
+    if (plan.containsPattern(JOIN) &&
+        plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      val complete = plan.isInstanceOf[WriteToStream]
+      plan.foreachUp {
+        case join: Join if join.resolved =>
+          ExternalLookupJoinEligibility(join) match {
+            case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+            case ExternalLookupJoinEligibility.MissingCondition if complete =>
+              throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+                "MISSING_JOIN_CONDITION")
+            case _ =>
+          }
+        case _ =>
+      }
+    }
+  }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an 
[[ExternalLookupJoin]], and
+ * removes the `EXTERNAL_LOOKUP` hints that no join consumed.
+ *
+ * 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. It also runs before CTEs are 
inlined, so it classifies a
+ * join with the CTEs of its inputs inlined, as the analysis check does, and 
inlines the CTEs of
+ * the lookup side into the lookup join.
+ */
+object FormExternalLookupJoin extends Rule[LogicalPlan] {
+  import ExternalLookupJoinEligibility._
+
+  // As in CheckExternalLookupJoin, a join runs as a lookup join only over a 
lookup-only table,
+  // which is a DSv2 relation, or under the hint, so other plans have no join 
to convert.
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    if (!plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) plan
+    else formLookupJoins(plan)
+
+  private def formLookupJoins(plan: LogicalPlan): LogicalPlan = {
+    val cteDefs = cteDefinitions(plan)
+    val formed = plan.transformUpWithPruning(_.containsPattern(JOIN)) {
+      case join: Join =>
+        val inlined = inlineCTEs(join, cteDefs)

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 #60019, which owns this code 
([d64fd7718c3](https://github.com/apache/spark/commit/d64fd7718c3fa0e97ead053b76b7479300ef1605)):
 forming lookup joins, CheckExternalLookupJoin and `lookupSidePlans` now first 
check for the hint pattern or a lookup-only table, before any CTE inlining. A 
test checks that a CTE self-join over a batch-readable DSv2 table is left alone.
   



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