spark-test commented on code in PR #60019:
URL: https://github.com/apache/spark/pull/60019#discussion_r4535294733


##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinStartupCheckSuite.scala:
##########
@@ -0,0 +1,668 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
+
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row, SQLContext}
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.expressions.{CurrentBatchTimestamp, 
CurrentDate,
+  CurrentTimestamp, LocalTimestamp, OuterReference, SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability, TableProvider}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.connector.read.ScanBuilder
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation}
+import 
org.apache.spark.sql.execution.streaming.runtime.{ExternalLookupJoinStartupCheck,
+  MemoryStream, MicroBatchExecution, StreamingQueryCheckpointMetadata, 
StreamingQueryWrapper,
+  StreamingV2ScanPushDown}
+import org.apache.spark.sql.functions.{col, current_timestamp, lit, max}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.{StreamingQuery, StreamingQueryException,
+  StreamingQueryListener}
+import 
org.apache.spark.sql.streaming.StreamingQueryListener.{QueryProgressEvent,
+  QueryStartedEvent, QueryTerminatedEvent}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DateType, StructType, TimestampNTZType, 
TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/** Which errors of an external lookup join stop a streaming query when it 
starts. */
+class ExternalLookupJoinStartupCheckSuite extends QueryTest with 
SharedSparkSession {
+  import testImplicits._
+
+  private val queryCount = new AtomicInteger()
+
+  private val timeoutMs = 60000L
+
+  private implicit def sqlContextOfStreams: SQLContext = spark.sqlContext
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    SimpleExternalLookupDataSource.resetCounters()
+    ThrowingScanBuilderTable.scanBuilderCount.set(0)
+  }
+
+  private def lookupOnly: DataFrame =
+    spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+
+  private def throwingStatic: DataFrame =
+    spark.read.format(classOf[ThrowingScanBuilderDataSource].getName).load()
+
+  private def start(df: DataFrame): StreamingQuery =
+    
df.writeStream.format("memory").queryName(s"startup_check_${queryCount.incrementAndGet()}")
+      .start()
+
+  /** The error that `start()` throws for `df`, which analysis reports. */
+  private def startFailure(df: DataFrame): AnalysisException = {
+    val e = intercept[AnalysisException](start(df).stop())
+    // The connector served no lookup at the start.
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    e
+  }
+
+  /**
+   * The error that stops the query of `df` when its execution starts: 
`start()` returns, and the
+   * query stops before it has any data.
+   */
+  private def queryFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val query = start(df)
+    val e = try {
+      intercept[StreamingQueryException](query.awaitTermination(timeoutMs))
+    } finally {
+      query.stop()
+    }
+    assert(query.exception.contains(e))
+    // The connector served no lookup at the start.
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    assert(classTag[T].runtimeClass.isInstance(e.getCause), e.getCause)
+    e.getCause.asInstanceOf[T]
+  }
+
+  /** Waits until `query` has planned its lookup joins and created its 
sources. */
+  private def awaitInitialization(query: StreamingQuery): Unit =
+    
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.awaitInitialization(timeoutMs)
+
+  /** Runs `body`, and returns the warnings that the startup check logged 
meanwhile. */
+  private def startupWarnings(body: => Unit): Seq[String] = {
+    val appender = new LogAppender("the startup check")
+    withLogAppender(
+        appender,
+        loggerNames = 
Seq(ExternalLookupJoinStartupCheck.getClass.getName.stripSuffix("$")),
+        level = Some(Level.WARN)) {
+      body
+    }
+    appender.loggingEvents.map(_.getMessage.getFormattedMessage).toSeq
+  }
+
+  /** Adds `rows` to `input`, and fails unless the first micro-batch of 
`query` fails. */
+  private def firstBatchFailure(
+      query: StreamingQuery,
+      input: MemoryStream[Int],
+      rows: Int*): StreamingQueryException = {
+    try {
+      query.processAllAvailable()
+      assert(query.isActive && query.exception.isEmpty)
+      input.addData(rows)
+      intercept[StreamingQueryException](query.processAllAvailable())
+    } finally {
+      query.stop()
+    }
+  }
+
+  test("an ordinary stream-static join fails at its first micro-batch, not at 
start") {
+    val input = MemoryStream[Int]
+    val stream = input.toDF().toDF("id")
+    val static = throwingStatic
+    val query = start(stream.join(static, stream("id") === static("id")))
+    awaitInitialization(query)
+    // Without data, no micro-batch runs, so the query keeps running.
+    assert(ThrowingScanBuilderTable.scanBuilderCount.get() === 0)
+    val e = firstBatchFailure(query, input, 1)
+    assert(e.getCause.getMessage.contains("The scan builder fails"))
+  }
+
+  test("MISSING_JOIN_CONDITION fails start()") {
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    val lookup = lookupOnly
+    Seq(
+      stream.join(lookup).where(stream("id") === lookup("id")),
+      stream.join(lookup, Seq.empty[String], "left_outer")).foreach { joined =>
+      checkError(
+        exception = startFailure(joined),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+        parameters = Map.empty)
+    }
+    // A USING join gets its condition after its first analysis, so it starts.
+    start(stream.join(lookup, Seq("id"))).stop()
+  }
+
+  test("MISSING_JOIN_CONDITION fails start() for a hinted join") {
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    checkError(
+      exception = 
startFailure(stream.join(lookupOnly.hint("external_lookup"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+  }
+
+  test("the start plans a lookup side read through a WITH clause") {
+    withTempView("startup_stream", "startup_bigint_stream", "startup_lookup", 
"startup_dual") {
+      
MemoryStream[Long].toDF().toDF("id").createOrReplaceTempView("startup_bigint_stream")
+      lookupOnly.createOrReplaceTempView("startup_lookup")
+      
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+        .createOrReplaceTempView("startup_dual")
+      def withClause(stream: String, table: String, hint: String = ""): 
DataFrame = spark.sql(
+        s"WITH lk AS (TABLE $table) SELECT $hint lk.department " +
+          s"FROM $stream s JOIN lk ON s.id = lk.id")
+      checkError(
+        exception = queryFailure[AnalysisException](
+          withClause("startup_bigint_stream", "startup_lookup")),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+        parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+      Seq(("startup_lookup", ""), ("startup_dual", "/*+ EXTERNAL_LOOKUP(lk) 
*/")).foreach {

Review Comment:
   **Nit (P3):** This case and `MISSING_JOIN_CONDITION fails start() for a 
hinted join` are the startup suite's only hinted joins. That one fails while 
`start()` analyzes the query, and this one checks only that a valid query 
starts without warnings, which also holds when the start plans nothing. Every 
failing startup test here reads the lookup-only table. In 
`ExternalLookupJoinSuite`, `a hinted dual-capability source fails when no 
lookup access path exists` runs `streamFailure` on a stream that already holds 
data, so it also passes when the error first comes from a micro-batch. Suppose 
the start stopped treating a hinted lookup side as one, for example by 
returning early when the plan has no `LOOKUP_ONLY_RELATION`. Then `forStartup` 
would hide the side in a `BatchRelation`, and a hinted join that cannot be 
planned, such as a `BIGINT` stream key against the dual-capability table's 
`INT` column (`NO_LOOKUP_CANDIDATE`), would fail only after data arrives, 
possibly much later. Every tes
 t would still pass. A test like `NO_LOOKUP_CANDIDATE stops the query when it 
starts, before any data arrives`, run through `queryFailure` over 
`startup_dual` with the hint, both directly and through the WITH clause here, 
would catch that.
   
   **Verification:**
   - **Behavior:** A hinted lookup join over a dual-capability table, whose 
stream key type gives no lookup candidate, stops the query with 
NO_LOOKUP_CANDIDATE after start() returns, before any input is added and with 
no lookup served by the connector.
   - **Regression:** Coverage includes both the directly hinted table and the 
hinted WITH-clause reference. It fails if the start no longer treats a hinted 
lookup side, or the WITH definition that it reads, as a lookup side, so that 
the error first appears in a micro-batch after data arrives.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,181 @@
+/*
+ * 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, AttributeSeq, 
AttributeSet, Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter, 
QueryPlan}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_HINT, 
EXTERNAL_LOOKUP_JOIN,
+  TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint 
asks an external
+ * lookup join to read. The external lookup join rules consume it when they 
form the join.
+ *
+ * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. 
This hint is not,
+ * because that representation cannot keep two of its guarantees:
+ *  - A strategy hint that conflicts with it must fail the query. [[HintInfo]] 
holds one strategy,
+ *    and `ResolveJoinStrategyHints` merges a strategy hint on an already 
hinted relation into the
+ *    existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one 
strategy and only warns.
+ *  - It selects how the lookup side is read, not a physical join. 
`EliminateResolvedHint` moves
+ *    every [[ResolvedHint]] it can attach into `Join.hint`, for physical join 
selection.
+ */
+case class ExternalLookupHint(child: LogicalPlan) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
ExternalLookupHint =
+    copy(child = newChild)
+}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput 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.
+ *
+ * @param lookupKeys The table column that each selected lookup predicate 
compares with the
+ *   parameter at the same position. Spark checks each row that the connector 
returns against
+ *   them, so the read schema must hold these columns.
+ */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    tableName: String,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    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)
+
+  // The lookup-side attributes are not in the child's output, so the default 
canonicalization
+  // gives each top-level one the next id, whichever column it is: two joins 
that keep different
+  // lookup columns of one type would canonicalize alike. Each is normalized 
by its place in the
+  // child's output and the read schema instead.
+  override protected def doCanonicalize(): LogicalPlan = {
+    val attributes: AttributeSeq = child.output ++ lookupInput
+    def normalize[T <: Expression](expression: T): T =
+      QueryPlan.normalizeExpressions(expression, attributes)
+    copy(
+      child = child.canonicalized,
+      lookupInput = lookupInput.map(normalize),
+      lookupOutput = lookupOutput.map(normalize),
+      lookupParameters = lookupParameters.map(normalize),
+      lookupKeys = lookupKeys.map(normalize),
+      residualCondition = residualCondition.map(normalize))
+  }
+
+  // Connector descriptions may contain secrets, so the scan and the reader 
factory are not shown.
+  // The physical node renders the scan's redacted description, and nothing of 
the reader factory.
+  override protected def stringArgs: Iterator[Any] =
+    Iterator(joinType, lookupParameters, residualCondition, child)
+
+  // The join keeps the size estimate it had before preparation, as an 
ordinary join's: the product

Review Comment:
   **Nit (P3):** This comment says that the join keeps the size estimate it had 
before preparation: the stream side's size times Spark's default size for a 
table it cannot scan. That held while every lookup side was the 
`ExternalLookupRelation` placeholder, whose `computeStats` returns 
`spark.sql.defaultSizeInBytes`. This PR's look-through also lets the lookup 
side be the `DataSourceV2Relation` of a catalog or SQL reference, or of a table 
that supports batch reads under the hint. Outside tests, that relation's 
`computeStats` builds a scan and uses its `SupportsReportStatistics` estimate, 
while `stats` here always multiplies by the default size. So for those sides 
the estimate changes during preparation. Nothing reads the unprepared join's 
statistics today, so only the comment is wrong. It would stay accurate if it 
said what the code computes: the stream size times 
`spark.sql.defaultSizeInBytes`, because the side is read by lookups rather than 
scanned, which can differ from the earlie
 r estimate when the side's scan reports statistics.
   
   **Verification:**
   - **Inspection:** The comment on the prepared join's size estimate matches 
the computation, the stream side's size times Spark's default size. It claims 
no equality with the estimate before preparation, which fails for a DSv2 lookup 
side whose scan reports statistics.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,361 @@
+/*
+ * 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, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LogicalPlan, 
ResolvedHint,
+  SetOperation, SubqueryAlias, UnaryNode, Union, 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 and views only, 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)
+
+  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 (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases and 
views only. There is
+    // none when another operator 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.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      // 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
+    }
+  }
+
+  /**
+   * Whether `plan` can have a join that must run as an external lookup join: 
one over a lookup-only
+   * table, which is a DSv2 relation, or under the hint. Classifying the joins 
of a plan inlines its
+   * CTE references, so a plan without either is left alone, and an ordinary 
query does not pay
+   * for lookup joins.
+   */
+  def mayHaveLookupJoin(plan: LogicalPlan): Boolean =
+    plan.containsPattern(JOIN) && (plan.containsPattern(EXTERNAL_LOOKUP_HINT) 
||
+      plan.containsPattern(DATA_SOURCE_V2_RELATION) &&
+        plan.exists(ExternalLookupRelations.lookupOnlyTable(_).isDefined))
+
+  /** 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] =
+    if (!mayHaveLookupJoin(plan)) {
+      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 and views 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
+    }
+
+  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 or a 
view. */
+  @tailrec
+  private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+    case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | 
_: View) =>

Review Comment:
   Thanks for checking this against #60055. Deferring it there is fine: until 
then the micro-batch fails loudly with `LOOKUP_PLAN`, and a query restarted 
from a DataFrame built after the schema change reads the new schema.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4525541175","thread_id":"inline:4525541175","verdict_sha256":"fb50436dea4160d248066bd86918daf3aca35cc8ec462a93c458b37c1ef12e79"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala:
##########
@@ -0,0 +1,94 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Expression, StringLiteral}
+import org.apache.spark.sql.catalyst.plans.logical.{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}
+
+/**
+ * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. As 
with join strategy
+ * hints, a hint without parameters marks the plan it is attached to, and a 
hint with relation
+ * names, given as identifiers or strings, marks each named relation.
+ */
+object ResolveExternalLookupHint extends Rule[LogicalPlan] with 
QueryErrorsBase {
+  private val HINT_NAME = "EXTERNAL_LOOKUP"
+
+  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]]
+    parameters.foreach {
+      // As in ResolveJoinStrategyHints: the Dataset API, PySpark and Spark 
Connect pass a relation
+      // name as a string, and SQL as an identifier.
+      case StringLiteral(name) =>
+        relationNames += UnresolvedAttribute.parseAttributeName(name)
+      case attr: UnresolvedAttribute =>
+        relationNames += attr.nameParts
+      case other =>
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other)))
+    }
+    if (relationNames.isEmpty) {
+      ExternalLookupHint(child)
+    } 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)
+        case alias: SubqueryAlias
+            if matches(alias.identifier.qualifier :+ alias.identifier.name) =>
+          ExternalLookupHint(alias)
+        case _: View | _: UnresolvedWith | _: SubqueryAlias => plan
+        case _ => plan.mapChildren(applyHint)
+      }
+      val rewritten = applyHint(child)
+      // As with join strategy hints, a name may be repeated.
+      val missing = relationNames.distinct.filterNot(matched.contains)

Review Comment:
   **Nit (P3):** `missing` is computed per name, so `/*+ EXTERNAL_LOOKUP(r, 
missing) */` fails for `missing` even though `r` matches. That keeps a typo in 
one of several names from being ignored. But every `RELATION_NOT_FOUND` 
assertion in `ExternalLookupJoinSuite` uses a hint in which no name matches: 
`EXTERNAL_LOOKUP(missing)`, `EXTERNAL_LOOKUP(missing, missing)`, and a name 
that does not reach into an aliased subquery. The multi-name hints it runs, 
`(d, d)` and `(d, D)`, match every name. So if this check failed only when no 
name matched, or reported only one of several missing names, every test would 
still pass. Two tests would catch both: a hint with one matching and one 
missing name, in SQL and through `hint("external_lookup", ...)`, and a hint 
with one matching and two missing names.
   
   **Verification:**
   - **Behavior:** A hint naming one existing relation and one missing name 
fails with RELATION_NOT_FOUND, whose relations parameter is exactly the missing 
name, both in SQL and through the Dataset API.
   - **Regression:** A hint naming one existing relation and two missing names 
fails with both missing names in the relations parameter and without the 
existing one. The coverage therefore fails if a missing name is ignored next to 
a matching one, or if only one of several missing names is reported.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,363 @@
+/*
+ * 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, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LogicalPlan, 
ResolvedHint,
+  SetOperation, SubqueryAlias, UnaryNode, Union, 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, 
EXTERNAL_LOOKUP_HINT, JOIN,
+  LOOKUP_ONLY_RELATION}
+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 and views only, 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)
+
+  def apply(join: Join): Eligibility = {
+    // Every other outcome needs the hint or a lookup-only relation on an 
input of the join.
+    if (!join.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION)) 
return NotLookupJoin
+    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 (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases and 
views only. There is
+    // none when another operator 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.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      // 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
+    }
+  }
+
+  /**
+   * Whether `plan` can have a join that must run as an external lookup join: 
one over a lookup-only
+   * table, whose relation carries LOOKUP_ONLY_RELATION, or under the hint. 
Classifying the joins of
+   * a plan inlines its CTE references, so a plan without either is left 
alone. The pattern bits of
+   * a plan include those of its CTE definitions and subquery plans, so they 
tell this without a
+   * walk, and an ordinary query does not pay for lookup joins.
+   */
+  def mayHaveLookupJoin(plan: LogicalPlan): Boolean =
+    plan.containsPattern(JOIN) &&
+      plan.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION)
+
+  /** 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] =
+    if (!mayHaveLookupJoin(plan)) {
+      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 and views 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
+    }
+
+  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 or a 
view. */
+  @tailrec
+  private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+    case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | 
_: View) =>
+      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 = {
+    if (ExternalLookupJoinEligibility.mayHaveLookupJoin(plan)) {
+      val complete = plan.isInstanceOf[WriteToStream]
+      plan.foreachUp {
+        case join: Join if join.resolved =>

Review Comment:
   **Non-blocking (P2):** This check classifies only `Join` nodes, and it runs 
only when `mayHaveLookupJoin` finds the `JOIN` pattern. ASOF and NEAREST BY 
joins are `AsOfJoin` and `NearestByJoin` nodes, carrying only `AS_OF_JOIN` and 
`NEAREST_BY_JOIN`, until Finish Analysis rewrites them. A lateral join is a 
unary `LateralJoin` with only `LATERAL_JOIN` until operator optimization turns 
it into a `Join`. Both rewrites run after the Form External Lookup Join batch. 
`readsJoin` also returns false at an `AsOfJoin` or `NearestByJoin`, and it 
passes through a `LateralJoin` like any unary node. So an `EXTERNAL_LOOKUP` 
marker on an input of an ASOF or NEAREST BY join, on the left input of a 
lateral join, or above any of them reaches `stripHints`, which drops it with 
only a warning. Yet the PR says the hint fails on a join that cannot be a 
lookup join.
   
   From the code, a streaming `SELECT /*+ EXTERNAL_LOOKUP(p) */ s.id, p.price 
FROM s ASOF JOIN p MATCH_CONDITION(s.ts >= p.ts) ON s.id = p.id`, over a table 
that reports `BATCH_READ` and `EXTERNAL_LOOKUP`, runs as an ordinary 
stream-static ASOF join that scans `p` in every micro-batch. `SELECT /*+ 
EXTERNAL_LOOKUP */ s.id, d.dept FROM s, LATERAL (SELECT dept FROM p WHERE p.id 
= s.id) d` loses its hint the same way, although the same hint above a regular 
join fails with `NOT_ON_LOOKUP_SIDE`. In batch queries the hinted ASOF join's 
outcome even depends on how it is written. `Dataset.joinAsOf` first analyzes an 
intermediate `Join` of its two inputs and fails with `STATIC_LEFT_SIDE`, while 
SQL `ASOF JOIN` runs with the hint dropped. The rows are those of the ordinary 
join in every case. A hint inside a lateral subquery stays ignored, as one 
inside other correlated subqueries does, so that case is not part of this 
finding.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60019#discussion_r4515313955).
   
   **Recommended change:** Make the EXTERNAL_LOOKUP analysis check treat ASOF, 
NEAREST BY and lateral joins as joins. Define once, in 
ExternalLookupJoinEligibility, the operators that the hint can annotate as a 
join: Join, AsOfJoin, NearestByJoin, and a LateralJoin that the query writes. 
Use that one definition in the check's gate, in its classification of hinted 
inputs and in readsJoin. Then a hint on an input of an ASOF or NEAREST BY join, 
on the left input of a lateral join, or above any of these joins fails while 
the query is analyzed, instead of reaching FormExternalLookupJoin, which drops 
it with a warning, and a join operator added later is covered in one place. Add 
ASOF, NEAREST BY and lateral join cases, in SQL and the Dataset API, to the 
external lookup join tests.
   
   **Why this works:** The check runs when the plan's tree-pattern bits show 
the hint together with the pattern of any of these joins, or a lookup-only 
relation together with a Join, as now. For each resolved AsOfJoin or 
NearestByJoin, it looks for markers on each input through unary operators, as 
it does for a Join. A marker on the left input fails with 
INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE. A marker on the right input 
fails with EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE, which names the ASOF or 
NEAREST BY join, the table that the input reads through hints, aliases and 
views, and the supported inner and left outer joins. When the input reads no 
DSv2 table, it fails with LOOKUP_PLAN, found with the same helper and rejection 
as a regular join's lookup side. For a lateral join that the query writes, a 
marker on its left input fails with NOT_ON_LOOKUP_SIDE, and its subquery stays 
a subquery plan that the check already runs on. readsJoin counts the same 
operators as joins, so 
 a parameterless hint above any of them, or above a set operation with one 
below an input, fails with NOT_ON_LOOKUP_SIDE. The analyzer also checks 
subquery plans, so no marker on or above these joins reaches 
FormExternalLookupJoin, and its removal of the remaining markers again drops 
only hints that attach to no join, including those inside a subquery without a 
join.
   
   **Scope:** Make the analysis check of the EXTERNAL_LOOKUP hint recognize 
ASOF, NEAREST BY and lateral joins, so the hint on or above them fails while 
the query is analyzed instead of being dropped with a warning.
   
   **Compatibility:** Every query without the hint keeps its plan and result, 
including ASOF, NEAREST BY and lateral joins over tables that support external 
lookup, and a hint that attaches to no join, or that sits inside a subquery 
without a join, is still dropped with a warning.
   
   **Risks:** Queries that write the hint on or above an ASOF, NEAREST BY or 
lateral join, which now run with the hint ignored, fail while they are 
analyzed. The hint is new in this pull request and has not been released, and 
reverting the change restores the warning. The analysis check now walks the 
plans of queries that have both the hint and one of these joins. Only queries 
that write the hint pay for that walk, and its cost is bounded by the size of 
the plan.
   
   **Constraints:** Keep the check's gate a test of tree-pattern bits, so 
queries without the hint or a lookup-only relation do not walk their plans. 
Leave the formation of lookup joins, cache substitution and the streaming 
start's search for lookup sides unchanged. An ASOF, NEAREST BY or lateral join 
never becomes a lookup join, so they have no new lookup side to find. Keep a 
hint that attaches to no join, such as one over a single table, ignored with a 
warning. Treat as a join only a lateral join that the query writes. A lateral 
join that analysis adds for a table argument of a table function, tagged 
LateralJoin.BY_TABLE_ARGUMENT, stays a plain unary node for the check, as it is 
today. Reuse the lookup-side helper and the LOOKUP_PLAN rejection of a regular 
join for the right input of ASOF and NEAREST BY joins, so that the TODO marking 
the deferred lookup-side projections and filters stays at the one place that 
rejects them. Dataset.joinAsOf keeps analyzing the join of its two input
 s first. In a batch query it can therefore report the static left side where 
SQL reports the join type, and both fail while the query is analyzed.
   
   **Exclusions:**
   - A lookup-only table read by an ASOF or NEAREST BY join without the hint 
keeps failing later as a batch scan, as a lookup-only table below other 
operators does. It already fails, and the change is only about the hint that 
must not be dropped.
   - Running ASOF, NEAREST BY or lateral joins as external lookup joins.
   - A hint inside the subquery of a lateral join, including on the right 
Dataset of Dataset.lateralJoin, stays ignored like a hint inside other 
correlated subqueries, as this pull request states for subqueries.
   
   **Success:** The EXTERNAL_LOOKUP hint, named or parameterless, on the right 
input of an ASOF join, written in SQL or, in a streaming query, with 
Dataset.joinAsOf, or of a NEAREST BY join, which only batch queries allow, 
fails while the query is analyzed. It fails with 
EXTERNAL_LOOKUP_JOIN_UNSUPPORTED naming the join as an unsupported join type, 
or with LOOKUP_PLAN when that input reads no DSv2 table, instead of being 
ignored with a warning. The hint on the left input of an ASOF, NEAREST BY or 
lateral join, and a parameterless hint above any of them or above a set 
operation with one below an input, fails with 
INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE, as it does for a regular join. 
In a batch query, a hinted ASOF join fails while it is analyzed whether it is 
written in SQL or with Dataset.joinAsOf. ASOF, NEAREST BY and lateral joins 
without the hint plan and run as before, also over a table that supports both 
batch reads and external lookup, and a hint with no join below it, 
 or inside a lateral subquery without a join, is still ignored with a warning.
   
   **Verification:**
   - **Behavior:** A streaming ASOF join written in SQL and one written with 
Dataset.joinAsOf, each with the hint on its right input in named and in 
parameterless form, fail while the query is analyzed with the unsupported join 
type error naming the ASOF join, and the query never starts.
   - **Regression:** For an ASOF, a NEAREST BY and a lateral join, each 
placement of the hint on or above the join fails while the query is analyzed 
with the error for that placement: on the right input of the ASOF and NEAREST 
BY joins, on the left input of all three, and above each of them, in named and 
parameterless form where the placement allows. So no hint that the user writes 
on or above any of these joins, outside a lateral subquery, is dropped with a 
warning.
   - **Behavior:** In a batch query, a hinted ASOF join fails while it is 
analyzed both when it is written in SQL and when it is written with 
Dataset.joinAsOf.
   - **Compatibility:** ASOF, NEAREST BY and lateral joins without the hint, 
over a table that supports both batch reads and external lookup, return the 
same rows as before, and a parameterless hint over a single table with no join 
below it, or inside a lateral subquery without a join, is still ignored.
   - **Inspection:** The operators that the check treats as joins are defined 
in one place and are used both to classify hinted join inputs and to find a 
join below a hint.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,361 @@
+/*
+ * 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, LeftOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LogicalPlan, 
ResolvedHint,
+  SetOperation, SubqueryAlias, UnaryNode, Union, 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 and views only, 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)
+
+  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 (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases and 
views only. There is
+    // none when another operator 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"))

Review Comment:
   Understood that the code shouldn't point at an open PR, but a TODO doesn't 
have to: it only needs to name what is still missing, with a JIRA id if you 
like. This check had `TODO: look through projections, filters and aliases above 
the lookup relation.` until this PR added the alias and view part. Keeping the 
rest, for example `TODO: look through projections and filters on the lookup 
side, such as those that a SQL-defined view, read-side CHAR padding, a second 
reference to a WITH clause or the refresh of a versioned table puts above the 
table`, tells someone who reads this check later that the limit is temporary, 
which the PR description can't do from here.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4525541212","thread_id":"inline:4525541212","verdict_sha256":"fb50436dea4160d248066bd86918daf3aca35cc8ec462a93c458b37c1ef12e79"}
 -->



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