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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,666 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+import java.util.concurrent.locks.LockSupport
+
+import scala.collection.mutable
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, CollationKey, 
Expression,
+  GenericInternalRow, JoinedRow, Predicate, SpecializedGetters, 
UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.optimizer.NormalizeFloatingNumbers
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time. For each batch it sends one request with the distinct parameters 
that can match, and
+ * streams the connector's result rows into output rows. Parameters are 
deduplicated per request,
+ * that is within one batch: a key repeated in a later batch is requested 
again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    maxBatchBytes: Long,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(rows, parameters, resultRows, 
joinOutput, reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes 
&& input.hasNext) {
+        val row = input.next() match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+        bytes += row.getSizeInBytes
+        rows += row
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      joinOutput: JoinOutput,
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct key that can match, in the order of first 
occurrence. A row
+    // that can never match, because it fails the stream condition or has a 
null parameter, is
+    // finished right away, and its key is not requested. The stream condition 
is checked before
+    // the key is computed, so that it can guard the parameter expressions.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    rows.indices.foreach { index =>
+      lazy val key = parameters.key(rows(index))
+      if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(key)) 
{
+        finish(index)
+      } else {
+        keyEntries.get(key) match {
+          case Some(entry) => entry.rowIndexes += index
+          case None => keyEntries.put(
+            key.copy(),
+            KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+
+    // No connector request, and no reader, when no key can match. The 
connector gets copies of
+    // the request rows, so that the ones that Spark checks the results 
against stay its own.
+    private var cursor: ExternalLookupResultCursor =
+      if (keyEntries.isEmpty) EmptyLookupCursor
+      else 
connectorCall(reader.lookup(keyEntries.values.map(_.requestRow.copy()).toArray))
+
+    override def hasNext: Boolean = {
+      tryFillPending()
+      pending.nonEmpty
+    }
+
+    override def next(): InternalRow = {
+      tryFillPending()
+      if (pending.isEmpty) throw new NoSuchElementException("external lookup 
result")
+      val (index, lookupRow) = pending.dequeue()
+      joinOutput.project(rows(index), lookupRow)
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryFillPending(): Unit = {
+      try {
+        while (pending.isEmpty && advanceCursor()) {
+          reader.resultRowRead()
+          // A close() during either call fails the read before Spark copies 
or joins the row.
+          val start = System.nanoTime()
+          val ordinal = cursor.inputOrdinal()
+          reader.ensureOpen()
+          val connectorRow = cursor.get()
+          metrics.lookupTime += System.nanoTime() - start
+          if (connectorRow == null) {
+            throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+              tableName, "NULL_RESULT_ROW")
+          }
+          val key = requestedKey(ordinal)
+          val resultRow = 
reader.copyRow(resultRows.validatedCopy(connectorRow))
+          if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, 
resultRow)) {

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.
   
   Thanks. I'd leave this as it is. It is constant work next to the connector 
call, and the review of #59910 withdrew the same point for that reason.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,3385 @@
+/*
+ * 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.nio.charset.StandardCharsets
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, 
AtomicReference}
+
+import scala.collection.mutable
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import org.apache.spark.{SparkException, SparkIllegalArgumentException, 
SparkRuntimeException,
+  SparkUnsupportedOperationException, TaskContext}
+import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Encoders, 
Row, SaveMode,
+  SQLContext}
+import org.apache.spark.sql.IntegratedUDFTestUtils.{shouldTestPythonUDFs, 
TestPythonUDF}
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.NoSuchTableException
+import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, 
AttributeReference, Cast,
+  EqualTo, GenericInternalRow, LessThan, Literal, Rand}
+import org.apache.spark.sql.catalyst.plans.QueryPlan
+import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, LeafNode, 
LogicalPlan,
+  PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.classic.Dataset
+import org.apache.spark.sql.connector.catalog.{Identifier, 
InMemoryTableCatalog, SupportsRead,
+  Table, TableCapability, TableCatalog, TableChange, TableProvider}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.connector.expressions.{NamedReference, Transform}
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.metric.{CustomMetric, CustomSumMetric, 
CustomTaskMetric}
+import org.apache.spark.sql.connector.read.{Batch, ExternalLookup, 
ExternalLookupReader,
+  ExternalLookupReaderFactory, ExternalLookupResultCursor, InputPartition, 
LookupParameter,
+  PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, 
SupportsExternalLookup,
+  SupportsPushDownRequiredColumns, SupportsPushDownV2Filters}
+import org.apache.spark.sql.execution.{CoalesceExec, LocalTableScanExec}
+import org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
ExternalLookupRelation,
+  TableCapabilityCheck}
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+import org.apache.spark.sql.execution.joins.ExternalLookupJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.StreamingDeduplicateExec
+import org.apache.spark.sql.execution.streaming.runtime.{IncrementalExecution, 
MemoryStream,
+  StreamingQueryWrapper}
+import org.apache.spark.sql.execution.streaming.sources.LowLatencyMemoryStream
+import org.apache.spark.sql.functions.{broadcast, coalesce, col, concat, expr, 
length, lit,
+  raise_error, to_json, when}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, 
InsertableRelation,
+  RelationProvider, SchemaRelationProvider}
+import org.apache.spark.sql.streaming.{StreamingQueryException, 
StreamRealTimeModeE2ESuiteBase}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DoubleType, 
IntegerType,
+  MapType, StringType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
+
+class ExternalLookupJoinSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  private val EXTERNAL_LOOKUP_CATALOG_NAME = "external_lookup_cat"
+
+  private val streamRunCount = new AtomicInteger()
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    SimpleExternalLookupDataSource.resetCounters()
+    SemanticKeyExternalLookupDataSource.requestSizes.clear()
+  }
+
+  /** The rows of `df` as a streaming DataFrame: one micro-batch, in 
`numPartitions` partitions. */
+  private def streamOf(df: DataFrame, numPartitions: Int = 1): DataFrame = {
+    val input = MemoryStream[Row](numPartitions)(Encoders.row(df.schema), 
spark.sqlContext)
+    input.addData(df.collect().toSeq)
+    input.toDF()
+  }
+
+  private case class StreamRun(rows: Seq[Row], execution: 
IncrementalExecution) {
+    def plan: LogicalPlan = execution.optimizedPlan
+    def lookupJoin: ExternalLookupJoinExec = 
execution.executedPlan.collectFirst {
+      case exec: ExternalLookupJoinExec => exec
+    }.get
+  }
+
+  /** Runs the streaming `df` on a memory sink until it has processed all of 
its input. */
+  private def runStream(df: DataFrame, outputMode: String = "append"): 
StreamRun = {
+    val queryName = 
s"external_lookup_stream_${streamRunCount.incrementAndGet()}"
+    val query =
+      
df.writeStream.format("memory").outputMode(outputMode).queryName(queryName).start()
+    try {
+      query.processAllAvailable()
+      StreamRun(
+        spark.table(queryName).collect().toSeq,
+        query.asInstanceOf[StreamingQueryWrapper].streamingQuery.lastExecution)
+    } finally {
+      query.stop()
+      spark.catalog.dropTempView(queryName)
+    }
+  }
+
+  private def checkStream(df: DataFrame, expected: Seq[Row]): Unit =
+    QueryTest.sameRows(expected, runStream(df).rows).foreach(fail(_))
+
+  /** The error that the streaming `df` fails with. */
+  private def streamFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val cause = intercept[StreamingQueryException](runStream(df)).getCause
+    assert(classTag[T].runtimeClass.isInstance(cause), cause)
+    cause.asInstanceOf[T]
+  }
+
+  test("external lookup capability produces a unary external lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val joined = left.join(lookup, left("id") === lookup("id"), "inner")
+
+    val plan = runStream(joined).plan
+    assert(plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    assert(!plan.toString.contains("SimpleExternalLookupScan"))
+  }
+
+  test("a dual-capability source keeps an ordinary join unless the hint opts 
in") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))
+
+    assert(lookup.queryExecution.analyzed.isInstanceOf[DataSourceV2Relation])
+    assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation] 
=== false)
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(lookup, left("id") === lookup("id"), "inner")
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, expected)
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+    SimpleExternalLookupDataSource.resetCounters()
+    val hinted = lookup.hint("external_lookup")
+    val lookupJoin = left.join(hinted, left("id") === hinted("id"), "inner")
+    
assert(runStream(lookupJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(lookupJoin, expected)
+    assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+  }
+
+  test("a hinted or aliased lookup side follows the stream-static contract") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // Without the hint, a dual-capability table keeps an ordinary batch join.
+    checkAnswer(
+      batch.join(dual, batch("id") === dual("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    // With it, the batch join fails: a hint the user wrote is never silently 
dropped.
+    Seq(
+      dual -> "`DualCapabilityExternalLookupTable`",
+      lookupOnly -> "`SimpleExternalLookupTable`").foreach { case (table, 
relation) =>
+      val hinted = table.hint("external_lookup")
+      checkError(
+        exception = intercept[AnalysisException] {
+          batch.join(hinted, batch("id") === hinted("id"))
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+        parameters = Map("relation" -> relation))
+    }
+    // A lookup-only table on the left side is found beneath an alias too.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookupOnly.as("l").join(stream, $"l.id" === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("a physical join strategy hint conflicts with the external lookup 
hint") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      "broadcast" -> "BROADCAST",
+      "merge" -> "MERGE",
+      "shuffle_hash" -> "SHUFFLE_HASH",
+      "shuffle_replicate_nl" -> "SHUFFLE_REPLICATE_NL").foreach { case (hint, 
strategy) =>
+      val lookupSide = dual.hint("external_lookup").hint(hint)
+      val streamSide = left.hint(hint)
+      val hinted = dual.hint("external_lookup")
+      Seq(
+        () => left.join(lookupSide, left("id") === lookupSide("id")),
+        () => streamSide.join(hinted, streamSide("id") === 
hinted("id"))).foreach { query =>
+        checkError(
+          exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map(
+            "strategy" -> strategy,
+            "relation" -> "`DualCapabilityExternalLookupTable`"))
+      }
+    }
+    // Both hints may name the same relation, in either order. A strategy hint 
is never merged
+    // into the lookup hint, so the conflict is still reported.
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      dual.createOrReplaceTempView("external_lookup_right")
+      Seq("EXTERNAL_LOOKUP(r), MERGE(r)", "MERGE(r), 
EXTERNAL_LOOKUP(r)").foreach { hints =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"SELECT /*+ $hints */ * FROM external_lookup_left l " +
+              "JOIN external_lookup_right r ON l.id = r.id")
+          },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map(
+            "strategy" -> "MERGE",
+            "relation" -> "`DualCapabilityExternalLookupTable`"))
+      }
+    }
+
+    // Without the lookup hint, the strategy hint plans the ordinary join it 
asks for.
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(dual.hint("merge"), left("id") === dual("id"))
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+  }
+
+  test("a hinted dual-capability source fails when no lookup access path 
exists") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val invoices = streamOf(Seq((1, "sales")).toDF("invoice", "costCenter"))
+
+    checkStream(
+      invoices.join(lookup, invoices("costCenter") === lookup("department")),
+      Seq(Row(1, "sales", 2, "sales")))
+    val hinted = lookup.hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](
+        invoices.join(hinted, invoices("costCenter") === 
hinted("department"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`DualCapabilityExternalLookupTable`"))
+  }
+
+  test("a physical strategy hint on a lookup-only join is rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val withLookupHint = lookup.hint("external_lookup").hint("shuffle_hash")
+    Seq(
+      "BROADCAST" ->
+        (() => left.join(lookup.hint("broadcast"), left("id") === 
lookup("id"), "left_outer")),
+      "BROADCAST" ->
+        (() => left.join(broadcast(lookup), left("id") === lookup("id"), 
"left_outer")),
+      "MERGE" -> (() => left.hint("merge").join(lookup, left("id") === 
lookup("id"))),
+      "SHUFFLE_HASH" ->
+        (() => left.join(withLookupHint, left("id") === 
withLookupHint("id")))).foreach {
+      case (strategy, query) =>
+        checkError(
+          exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+          condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map("strategy" -> strategy, "relation" -> 
"`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("an ordinary join over an enriched lookup join result stays ordinary") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val events = streamOf(Seq(1, 2).toDF("id"))
+    val enriched = events.join(lookup, events("id") === lookup("id"))
+      .select(events("id").as("event_id"), lookup("department"))
+    val base = Seq((1, "a"), (2, "b")).toDF("id", "tag")
+    val expected = Seq(
+      Row(1, "a", 1, "engineering"), Row(1, "a", 1, "research"), Row(2, "b", 
2, "sales"))
+    def lookupJoinCount(df: DataFrame): Int =
+      runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j 
}.size
+
+    val joined = base.join(enriched, base("id") === enriched("event_id"))
+    assert(lookupJoinCount(joined) === 1)
+    checkStream(joined, expected)
+
+    withTempView("external_lookup_base", "external_lookup_events", 
"external_lookup_right") {
+      base.createOrReplaceTempView("external_lookup_base")
+      events.createOrReplaceTempView("external_lookup_events")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      val sqlJoined = sql(
+        """
+          |SELECT b.id, b.tag, e.event_id, e.department
+          |FROM external_lookup_base b JOIN (
+          |  SELECT v.id AS event_id, r.department
+          |  FROM external_lookup_events v JOIN external_lookup_right r ON 
v.id = r.id) e
+          |ON b.id = e.event_id
+          |""".stripMargin)
+      assert(lookupJoinCount(sqlJoined) === 1)
+      checkStream(sqlJoined, expected)
+    }
+  }
+
+  test("an external lookup hint outside any join is ignored") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales"))
+
+    checkAnswer(dual.hint("external_lookup"), expected)
+    assert(dual.hint("external_lookup").count() === 3)
+    withTempView("external_lookup_right") {
+      dual.createOrReplaceTempView("external_lookup_right")
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP */ * FROM 
external_lookup_right"), expected)
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ * FROM 
external_lookup_right r"), expected)
+      checkAnswer(
+        sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ id, count(*) FROM 
external_lookup_right r " +
+          "GROUP BY id"),
+        Seq(Row(1, 2), Row(2, 1)))
+    }
+  }
+
+  test("a lookup side with another operator above the table fails when the 
DataFrame is built") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    withTempView("operator_side_lookup", "operator_side_left") {
+      lookup.createOrReplaceTempView("operator_side_lookup")
+      left.createOrReplaceTempView("operator_side_left")
+      // A lookup-only table, which no other join can read, and a hinted table 
that supports batch
+      // reads too. The join fails even where the optimizer would remove the 
operator.
+      Seq(
+        lookup.where(lit(false)),
+        lookup.select($"id", $"department"),
+        dual.select($"id", $"department").hint("external_lookup"),
+        dual.hint("external_lookup").where($"id" > 0)).foreach { right =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            left.join(right, left("id") === right("id"), "left_outer")
+          },
+          condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+          parameters = Map.empty)
+      }
+      checkError(
+        exception = intercept[AnalysisException] {
+          sql("SELECT * FROM operator_side_left l JOIN " +
+            "(SELECT * FROM operator_side_lookup WHERE 1 = 0) r ON l.id = 
r.id")
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+        parameters = Map.empty)
+    }
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+  }
+
+  test("a USING join with the EXTERNAL_LOOKUP hint runs as an external lookup 
join") {
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    Seq[Class[_]](
+      classOf[DualCapabilityExternalLookupDataSource],
+      classOf[SimpleExternalLookupDataSource]).foreach { source =>
+      val lookup = 
spark.read.format(source.getName).load().hint("external_lookup")
+      val joined = left.join(lookup, Seq("id"), "left_outer")
+      
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+      checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), 
Row(3, null)))
+    }
+
+    // Without a condition the hinted join still fails, on the final plan.
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](left.join(dual)),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+  }
+
+  test("an external lookup hint is found beneath an alias on either join 
side") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    val aliased = dual.hint("external_lookup").as("r")
+    val joined = left.join(aliased, left("id") === $"r.id")
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").as("l").join(dual, $"l.id" === dual("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("a strategy hint on a nested join does not disable an outer lookup 
join") {
+    val left = streamOf(Seq((1, 10), (2, 20)).toDF("id", "k"))
+    val other = Seq((10, "a"), (20, "b")).toDF("k", "v")
+    val nested = left.join(other.hint("merge"), "k")
+    def usesLookup(df: DataFrame): Boolean =
+      runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val dualJoin = nested.join(dual, nested("id") === dual("id"))
+    assert(usesLookup(dualJoin))
+    checkStream(dualJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+
+    // A lookup-only table on the outer join becomes a lookup join too, 
despite the nested join's
+    // MERGE hint.
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookupOnlyJoin = nested.join(lookupOnly, nested("id") === 
lookupOnly("id"))
+    assert(usesLookup(lookupOnlyJoin))
+    checkStream(lookupOnlyJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+  }
+
+  test("an external lookup hint on an ineligible join is rejected") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val left = streamOf(Seq(1).toDF("id"))
+
+    // A cross join fails with its join type too, although it has no condition.
+    Seq[(() => DataFrame, String)](
+      (() => left.join(dual, left("id") === dual("id"), "right_outer"), "RIGHT 
OUTER"),
+      (() => left.crossJoin(dual), "CROSS")).foreach { case (joined, joinType) 
=>
+      val error = intercept[AnalysisException](joined())
+      assert(error.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+      assert(error.getMessageParameters.get("joinType") === joinType)
+      assert(error.getMessageParameters.get("relation") === 
"`DualCapabilityExternalLookupTable`")
+    }
+  }
+
+  test("an external lookup join is a stream-static join with the lookup-only 
table on the right") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // The left side must be a streaming query.
+    checkError(
+      exception = intercept[AnalysisException] {
+        batch.join(lookup, batch("id") === lookup("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+    // The sides are never swapped.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookup.join(stream, lookup("id") === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup validates connector planning and request contracts") {
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      ("nullKeySelection", "true", "NULL_PREDICATE_SELECTION", 
Map.empty[String, String]),
+      ("selectionMode", "nullElement", "NULL_PREDICATE_SELECTION", 
Map.empty[String, String]),
+      ("selectionMode", "duplicate", "DUPLICATE_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("selectionMode", "copy", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("maxBatchSize", "0", "NON_POSITIVE_MAX_PARAMETER_ROWS", Map("value" -> 
"0"))).foreach {
+      case (option, value, subClass, parameters) =>
+        val lookup = spark.read
+          .format(classOf[SimpleExternalLookupDataSource].getName)
+          .option(option, value)
+          .load()
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = Map("table" -> "`SimpleExternalLookupTable`") ++ 
parameters)
+    }
+
+    def misconfigured(kind: String): DataFrame = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", kind)
+      .load()
+    val table = Map("table" -> "`MisconfiguredExternalLookupTable`")
+    Seq(
+      ("unknownField", "UNKNOWN_SCAN_FIELD", Map("field" -> "`unknown`")),
+      ("duplicateField", "DUPLICATE_SCAN_FIELD", Map("field" -> 
"`id`"))).foreach {
+      case (kind, subClass, parameters) =>
+        val lookup = misconfigured(kind)
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = table ++ parameters)
+    }
+
+    val noExternalLookup = misconfigured("noExternalLookup")
+    checkError(
+      exception = streamFailure[SparkUnsupportedOperationException](
+        left.join(noExternalLookup, left("id") === noExternalLookup("id"))),
+      condition = "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED",
+      parameters = Map("description" -> "NoExternalLookupScan"))
+
+    // Violations found while the join runs are reported the same way, by the 
tasks.
+    val nullCursor = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("nullCursor", "true")
+      .load()
+    Seq(
+      (nullCursor, "NULL_RESULT_CURSOR", Map("table" -> 
"`SimpleExternalLookupTable`")),
+      (misconfigured("nullReader"), "NULL_LOOKUP_READER", table),
+      (misconfigured("invalidOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "5", "numParameterRows" -> "1")),
+      // The ordinals just outside the request's parameter rows.
+      (misconfigured("negativeOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "-1", "numParameterRows" -> "1")),
+      (misconfigured("ordinalAtCount"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "1", "numParameterRows" -> "1")),
+      (misconfigured("nullRow"), "NULL_RESULT_ROW", table),
+      // A value that breaks its column's type, which Spark relied on while it 
optimized.
+      (misconfigured("nullValue"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("nullUnderNotNullReadSchema"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("decimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")),
+      // The same checks reach nested values: a decimal array element with too 
many digits, and
+      // a decimal map value that would need rounding.
+      (misconfigured("nestedDecimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amounts`.`element`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      (misconfigured("nestedDecimalRounding"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`rates`.`value`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      // A map key is never null, whether it is a primitive or a struct.
+      (misconfigured("nullMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`labels`.`key`")),
+      (misconfigured("nullComplexMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`parts`.`key`"))).foreach {
+      case (lookup, subClass, parameters) =>
+        checkError(
+          exception = streamFailure[SparkRuntimeException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = parameters)
+    }
+
+    // Planning failures that need no hint. A catalog can serve a table 
without SupportsRead.
+    val noLookupBuilder = misconfigured("noLookupBuilder")
+    val nonReadable = Dataset.ofRows(spark, DataSourceV2Relation.create(
+      NonReadableExternalLookupTable, None, None, 
CaseInsensitiveStringMap.empty))
+    val simple = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    Seq(
+      (noLookupBuilder, left("id") === noLookupBuilder("id"), "SCAN_BUILDER",
+        "MisconfiguredExternalLookupTable"),
+      (nonReadable, left("id") === nonReadable("id"), "TABLE", 
"NonReadableExternalLookupTable"),
+      (simple, simple("department") === "sales", "NO_LOOKUP_PREDICATE",
+        "SimpleExternalLookupTable")).foreach { case (lookup, condition, 
subClass, name) =>
+      checkError(
+        exception = streamFailure[AnalysisException](left.join(lookup, 
condition)),
+        condition = s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass",
+        parameters = Map("table" -> s"`$name`"))
+    }
+    // A BIGINT stream key casts the INT lookup column, so Spark has no 
candidate to offer.
+    val bigintLeft = streamOf(Seq(1L).toDF("id"))
+    checkError(
+      exception = streamFailure[AnalysisException](
+        bigintLeft.join(simple, bigintLeft("id") === simple("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("an external lookup hinted DataFrame can be reused by multiple joins") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+
+    val first = streamOf(Seq(1).toDF("id"))
+    val second = streamOf(Seq(2).toDF("id"))
+    checkStream(first.join(lookup, first("id") === lookup("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    checkStream(second.join(lookup, second("id") === lookup("id")),
+      Seq(Row(2, 2, "sales")))
+  }
+
+  test("external lookup finalizes expressions on the stream side after 
analysis") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id"))
+
+    checkStream(
+      left.join(
+        lookup,
+        coalesce(left("id"), lit(0)) === lookup("id"),
+        "inner"),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+  }
+
+  test("external lookup hint rejects invalid placement and relation targets") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").join(lookup, left("id") === lookup("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+    checkError(
+      exception = intercept[AnalysisException] {
+        val hinted = lookup.hint("external_lookup").hint("external_lookup")
+        left.join(hinted, left("id") === hinted("id")).queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.MULTIPLE_HINTS",
+      parameters = Map.empty)
+
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      def query(hint: String): DataFrame = sql(
+        s"""
+          |SELECT /*+ $hint */ l.id, r.department
+          |FROM external_lookup_left l JOIN external_lookup_right r ON l.id = 
r.id
+          |""".stripMargin)
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(missing)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+        parameters = Map("relations" -> "`missing`"))
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(r, r)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.DUPLICATE_RELATION",
+        parameters = Map("relation" -> "`r`"))
+    }
+
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(stream.hint("external_lookup"), left("id") === stream("id"))
+          .queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STREAMING_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("external lookup reports lookup sides and conditions it cannot plan") {
+    val claims = streamOf(Seq((1, "sales")).toDF("id", "costCenter"))
+    def planningError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      streamFailure[AnalysisException](claims.join(lookup, condition))
+    def analysisError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      intercept[AnalysisException](claims.join(lookup, condition))
+
+    // A hinted lookup side fails when the DataFrame is built: with 
LOOKUP_PLAN when it reads no
+    // DSv2 table, as a local relation does, and with TABLE for a DSv2 table 
that does not support
+    // external lookup.
+    val local = Seq(1).toDF("id").hint("external_lookup")
+    checkError(
+      exception = analysisError(local, claims("id") === local("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+      parameters = Map.empty)
+
+    val batchOnly = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "batchOnly")
+      .load()
+      .hint("external_lookup")
+    checkError(
+      exception = analysisError(batchOnly, claims("id") === batchOnly("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.TABLE",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val noLookupBuilder = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "noLookupBuilder")
+      .load()
+    checkError(
+      exception = planningError(noLookupBuilder, claims("id") === 
noLookupBuilder("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SCAN_BUILDER",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    checkError(
+      exception = planningError(lookup, claims("costCenter") === 
lookup("department")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup maps a selected predicate to its own occurrence") {
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "last")
+      .load()
+    val left = streamOf(Seq((1, 2), (2, 2), (2, 1)).toDF("a", "b"))
+
+    // Both candidates have the shape `id = ?`; only the second one, bound to 
`b`, is selected.
+    val joined =
+      left.join(lookup, lookup("id") === left("a") && lookup("id") === 
left("b"), "left_outer")
+    assert(runStream(joined).rows.toSet ===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("=", "id", IntegerType), ("=", "id", IntegerType)))
+    assert(SimpleExternalLookupDataSource.lookupCandidateDescriptions.get() ===
+      Seq("id = ?", "id = ?"))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 1))
+
+    // Selected in reverse order, each parameter row is `(b, a)`.
+    SimpleExternalLookupDataSource.resetCounters()
+    val reversed = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "reversed")
+      .load()
+    val condition = reversed("id") === left("a") && reversed("id") === 
left("b")
+    assert(runStream(left.join(reversed, condition, "left_outer")).rows.toSet 
===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 2, 1))
+  }
+
+  test("a parent projection of some lookup columns still plans an external 
lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    // Generic column pruning must not project the lookup relation, which 
would hide it from
+    // lookup planning; the join's requiredLookupOutput keeps it from doing so.
+    val joined = left.join(lookup, left("id") === lookup("id"), "left_outer")
+      .select(left("id"), lookup("department"))
+
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null)))
+  }
+
+  test("external lookup join supports inner and left outer joins") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, "one"), (2, "two"), (3, "three")).toDF("id", 
"label"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"),
+        Row(2, "two", 2, "sales")))
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_outer"),
+      Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"),
+        Row(2, "two", 2, "sales"), Row(3, "three", null, null)))
+
+    // Only comparisons of a lookup field with a stream-side value are 
offered. The connector
+    // selects `id = ?`, and Spark evaluates the other conjuncts: the 
stream-side one on each stream
+    // row before the lookup, and the others on the joined rows.
+    SimpleExternalLookupDataSource.resetCounters()
+    val flagged = streamOf(Seq((1, true), (2, true), (1, false)).toDF("id", 
"flag"))
+    checkStream(
+      flagged.join(
+        lookup,
+        flagged("id") === lookup("id") && flagged("flag") &&
+          lookup("department") === "engineering" && 
length(lookup("department")) > lookup("id"),
+        "left_outer"),
+      Seq(Row(1, true, 1, "engineering"), Row(2, true, null, null), Row(1, 
false, null, null)))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("=", "id", IntegerType), ("=", "department", StringType)))
+  }
+
+  test("a stream row that fails a stream-side conjunct of the condition is not 
looked up") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(
+      Seq((1, Some(true)), (2, Some(false)), (3, Some(true)), (4, 
None)).toDF("id", "flag"))
+    val key = left("id") === lookup("id")
+    // The join checks `flag` on each stream row before the lookup. A row 
where it is false or null
+    // cannot match, so its key is not requested: an inner join drops the row, 
and a left outer
+    // join pads it with nulls.
+    val matched = Seq(Row(1, true, 1, "engineering"), Row(1, true, 1, 
"research"))
+    val unmatched =
+      Seq(Row(2, false, null, null), Row(3, true, null, null), Row(4, null, 
null, null))
+    Seq("inner" -> matched, "left_outer" -> (matched ++ unmatched)).foreach {
+      case (joinType, expected) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        checkStream(left.join(lookup, key && left("flag"), joinType), expected)
+        assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 3))
+    }
+
+    // A conjunct that can throw is not checked early: it is evaluated on the 
joined rows only, so
+    // never for id 3, which has no match, and every key is requested.
+    SimpleExternalLookupDataSource.resetCounters()
+    val throwing = when(left("id") === 3, raise_error(lit("evaluated for id 
3"))).otherwise(true)
+    checkStream(
+      left.join(lookup, key && throwing, "left_outer"),
+      matched ++ Seq(Row(2, false, 2, "sales"), Row(3, true, null, null), 
Row(4, null, null, null)))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 2, 3, 4))
+
+    // A conjunct that is not deterministic is not checked early either. 
Analysis rejects one in a
+    // join condition, so the physical join gets one directly: `id + rand(0) < 
0`. It is false for
+    // every row, but it is evaluated on the joined rows only, so every key is 
requested.
+    val lookupJoin = runStream(left.join(lookup, key, "left_outer")).lookupJoin
+    val streamId = lookupJoin.child.output.head
+    val nonDeterministic =
+      LessThan(Add(Cast(streamId, DoubleType), Rand(Literal(0L))), 
Literal(0.0))
+    SimpleExternalLookupDataSource.resetCounters()
+    val rows = lookupJoin.copy(
+      residualCondition = Some(nonDeterministic),
+      child = LocalTableScanExec(
+        lookupJoin.child.output, Seq(InternalRow(1, true), InternalRow(2, 
false)), None))
+      .executeCollect()
+    assert(rows.map(row => row.getInt(0) -> row.isNullAt(2)).toSeq === Seq(1 
-> true, 2 -> true))
+    // Each row is in its own partition, so the order of the requests can vary.
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq.sorted 
=== Seq(1, 2))
+  }
+
+  test("external lookup-only source joins without an explicit hint") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation])
+    val joined = left.join(lookup, "id")
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research")))
+  }
+
+  test("an external lookup-only source cannot be read outside an eligible 
lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    checkError(
+      exception = intercept[AnalysisException] { 
lookup.queryExecution.optimizedPlan },
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map(
+        "tableName" -> "`SimpleExternalLookupTable`",
+        "operation" -> "batch scan"))
+    // A join that reads it but cannot be a lookup join fails with the reason. 
The condition must
+    // be written in the join, not in a later filter.
+    checkError(
+      exception = streamFailure[AnalysisException](
+        left.join(lookup).where(left("id") === lookup("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+    // An unsupported join type fails when the DataFrame is built, with or 
without a condition.
+    Seq[(() => DataFrame, String)](
+      (() => left.join(lookup, left("id") === lookup("id"), "full_outer"), 
"FULL OUTER"),
+      (() => left.crossJoin(lookup), "CROSS"),
+      (() => left.crossJoin(lookup).where(left("id") === lookup("id")), 
"CROSS")).foreach {
+      case (joined, joinType) =>
+        val error = intercept[AnalysisException](joined())
+        assert(error.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+        assert(error.getMessageParameters.asScala.toMap - "supportedJoinTypes" 
===
+          Map("joinType" -> joinType, "relation" -> 
"`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("catalog-resolved tables follow the same lookup selection") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        def query(table: String, hint: String = ""): DataFrame = sql(
+          s"""
+            |SELECT $hint l.id, r.department
+            |FROM external_lookup_left l
+            |LEFT JOIN $EXTERNAL_LOOKUP_CATALOG_NAME.ns.$table r ON l.id = r.id
+            |""".stripMargin)
+        val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null))
+        def usesLookup(df: DataFrame): Boolean =
+          runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+        SimpleExternalLookupDataSource.resetCounters()
+        val lookupOnly = query("lookup")
+        assert(usesLookup(lookupOnly))
+        checkStream(lookupOnly, expected)
+        assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+
+        SimpleExternalLookupDataSource.resetCounters()
+        val dual = query("dual")
+        assert(!usesLookup(dual))
+        checkStream(dual, expected)
+        assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+        val hintedDual = query("dual", "/*+ EXTERNAL_LOOKUP(r) */")
+        assert(usesLookup(hintedDual))
+        checkStream(hintedDual, expected)
+      }
+    }
+  }
+
+  test("a named external lookup hint marks every relation that it names") {
+    // As with join strategy hints, the name matches each unaliased reference 
to the table, so
+    // both joins read it through external lookup.
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+        val twice = sql(
+          s"""
+            |SELECT /*+ EXTERNAL_LOOKUP(dual) */ *
+            |FROM external_lookup_left JOIN $catalogTable USING (id) JOIN 
$catalogTable USING (id)
+            |""".stripMargin)
+        val run = runStream(twice)
+        assert(run.plan.collect { case join: PreparedExternalLookupJoin => 
join }.size === 2)
+        QueryTest.sameRows(
+          Seq(Row(1, "engineering", "engineering"), Row(1, "engineering", 
"research"),
+            Row(1, "research", "engineering"), Row(1, "research", "research")),
+          run.rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("a named external lookup hint targets unaliased, multipart, and aliased 
relations") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left", "external_lookup_right") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+          .createOrReplaceTempView("external_lookup_right")
+        val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null))
+        def query(hintTarget: String, right: String, rightName: String): 
DataFrame = sql(
+          s"""
+            |SELECT /*+ EXTERNAL_LOOKUP($hintTarget) */ l.id, 
$rightName.department
+            |FROM external_lookup_left l LEFT JOIN $right ON l.id = 
$rightName.id
+            |""".stripMargin)
+
+        val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+        Seq(
+          ("external_lookup_right", "external_lookup_right", 
"external_lookup_right"),
+          ("dual", catalogTable, "dual"),
+          ("ns.dual", catalogTable, "dual"),
+          (catalogTable, catalogTable, "dual"),
+          ("r", s"$catalogTable r", "r")).foreach {
+          case (hintTarget, right, rightName) =>
+            val df = query(hintTarget, right, rightName)
+            
assert(runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]),
+              hintTarget)
+            checkStream(df, expected)
+        }
+
+        // An aliased subquery can be named, but its projection is an operator 
between the table
+        // and the join.
+        checkError(
+          exception = intercept[AnalysisException] {
+            query("s", "(SELECT * FROM external_lookup_right) s", "s")
+          },
+          condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+          parameters = Map.empty)
+        // Like join strategy hints, a target name does not reach into an 
aliased subquery.
+        checkError(
+          exception = intercept[AnalysisException] {
+            query("external_lookup_right", "(SELECT * FROM 
external_lookup_right) s", "s")
+              .queryExecution.analyzed
+          },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+          parameters = Map("relations" -> "`external_lookup_right`"))
+      }
+    }
+  }
+
+  test("a catalog-resolved lookup-only table in an ineligible join fails with 
the reason") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      val left = streamOf(Seq(1).toDF("id"))
+      val crossJoin = 
intercept[AnalysisException](left.crossJoin(spark.read.table(table)))
+      assert(crossJoin.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+      assert(crossJoin.getMessageParameters.asScala.toMap - 
"supportedJoinTypes" ===
+        Map("joinType" -> "CROSS", "relation" -> 
"`SimpleExternalLookupTable`"))
+      withTempView("external_lookup_left") {
+        left.createOrReplaceTempView("external_lookup_left")
+        val fullOuter = intercept[AnalysisException] {
+          sql(s"SELECT * FROM external_lookup_left l FULL OUTER JOIN $table r 
ON l.id = r.id")
+        }
+        assert(fullOuter.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+        assert(fullOuter.getMessageParameters.asScala.toMap - 
"supportedJoinTypes" ===
+          Map("joinType" -> "FULL OUTER", "relation" -> 
"`SimpleExternalLookupTable`"))
+      }
+    }
+  }
+
+  test("a catalog-resolved table can be composed into DataFrame joins") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val left = streamOf(Seq(1, 3).toDF("id"))
+      val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research"), 
Row(3, null, null))
+      def usesLookup(df: DataFrame): Boolean =
+        runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+      val lookupOnly = spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup")
+      val lookupJoin = left.join(lookupOnly, left("id") === lookupOnly("id"), 
"left_outer")
+      assert(usesLookup(lookupJoin))
+      checkStream(lookupJoin, expected)
+
+      val dual = spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual")
+      val ordinary = left.join(dual, left("id") === dual("id"), "left_outer")
+      assert(!usesLookup(ordinary))
+      checkStream(ordinary, expected)
+      val hinted = dual.hint("external_lookup")
+      val hintedJoin = left.join(hinted, left("id") === hinted("id"), 
"left_outer")
+      assert(usesLookup(hintedJoin))
+      checkStream(hintedJoin, expected)
+
+      checkError(
+        exception = intercept[AnalysisException] { lookupOnly.collect() },
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+    }
+  }
+
+  test("a common expression in the join condition is evaluated in the lookup 
join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, "b"), (2, "c")).toDF("id", "code"))
+    val sameId = left("id") === lookup("id")
+    // BETWEEN evaluates its input once, and upper() is not cheap enough to 
repeat, so it would
+    // otherwise be computed in a projection below the join: over the lookup 
side, or the stream.
+    Seq(
+      expr("upper(department) BETWEEN 'F' AND 'Z'") ->
+        Seq(Row(1, "b", 1, "research"), Row(2, "c", 2, "sales")),
+      expr("upper(code) BETWEEN 'A' AND 'B'") ->
+        Seq(Row(1, "b", 1, "engineering"), Row(1, "b", 1, 
"research"))).foreach {
+      case (between, expected) =>
+        val run = runStream(left.join(lookup, sameId && between))
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+    }
+  }
+
+  test("a subquery in the join condition of a lookup join is rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 1)).toDF("id", "x"))
+    val values = Seq(1).toDF("v")
+    val sameId = left("id") === lookup("id")
+    // The optimizer rewrites such subqueries only in a Join, so they fail 
when the DataFrame is
+    // built, whether they read the stream side, the lookup side or neither. 
The scalar subquery
+    // references neither side, so it could be offered as a parameter.
+    Seq(
+      sameId && left("x").isin(values),
+      sameId && values.where(col("v") === 1).exists(),
+      lookup("id") === values.scalar(),
+      sameId && lookup("id").isin(values)).foreach { condition =>
+      checkError(
+        exception = intercept[AnalysisException](left.join(lookup, condition)),
+        condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SUBQUERY_IN_JOIN_CONDITION",
+        parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("a SQL subquery over lookup columns in the join condition of a lookup 
join is rejected") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("events", "codes") {
+        streamOf(Seq(1).toDF("id")).createOrReplaceTempView("events")
+        Seq(1).toDF("code").createOrReplaceTempView("codes")
+        // A correlated subquery cannot be written in a Dataset join 
condition, but can in SQL.
+        Seq(
+          "EXISTS (SELECT 1 FROM codes WHERE codes.code = l.id)",
+          "l.id IN (SELECT code FROM codes)").foreach { subquery =>
+          checkError(
+            exception = intercept[AnalysisException] {
+              sql(s"SELECT * FROM events e JOIN 
$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup l " +
+                s"ON e.id = l.id AND $subquery")
+            },
+            condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SUBQUERY_IN_JOIN_CONDITION",
+            parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+        }
+      }
+    }
+  }
+
+  test("Dataset join APIs that analyze a join plan lookup joins or fail with a 
named error") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 2)).toDF("sender", "receiver"))
+
+    val typed = left.joinWith(lookup, left("sender") === lookup("id"))
+    val typedRun = runStream(typed.toDF())
+    assert(typedRun.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    QueryTest.sameRows(
+      Seq(Row(Row(1, 2), Row(1, "engineering")), Row(Row(1, 2), Row(1, 
"research"))),
+      typedRun.rows).foreach(fail(_))
+
+    // A lookup DataFrame reused in a second join is ambiguous, as any other 
DataFrame is.
+    def reusedJoinError(right: DataFrame): AnalysisException = 
intercept[AnalysisException] {
+      val enriched = left.join(right, left("sender") === right("id"))
+      enriched.join(right, enriched("receiver") === right("id"))
+    }
+    val ordinary = Seq((1, "engineering")).toDF("id", "department")
+    Seq("true", "false").foreach { autoResolve =>
+      withSQLConf(SQLConf.DATAFRAME_SELF_JOIN_AUTO_RESOLVE_AMBIGUITY.key -> 
autoResolve) {
+        val error = reusedJoinError(lookup)
+        assert(error.getCondition === reusedJoinError(ordinary).getCondition)
+        assert(error.getMessage.contains("ambiguous"), error)
+      }
+    }
+    // Loaded twice, the table enriches the stream with two lookup joins.
+    val receivers = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val enriched = left.join(lookup, left("sender") === lookup("id"))
+    val twice = enriched.join(receivers, enriched("receiver") === 
receivers("id"))
+    val twiceRun = runStream(twice)
+    assert(twiceRun.plan.collect { case join: PreparedExternalLookupJoin => 
join }.size === 2)
+    QueryTest.sameRows(
+      Seq(Row(1, 2, 1, "engineering", 2, "sales"), Row(1, 2, 1, "research", 2, 
"sales")),
+      twiceRun.rows).foreach(fail(_))
+
+    // An AS OF join reads the lookup-only table outside a lookup join.
+    checkError(
+      exception = 
streamFailure[AnalysisException](left.asInstanceOf[Dataset[Row]].joinAsOf(
+        lookup, left("sender"), lookup("id"), left("sender") === lookup("id"), 
"inner",
+        tolerance = null, allowExactMatches = true, direction = "backward")),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map(
+        "tableName" -> "`SimpleExternalLookupTable`",
+        "operation" -> "batch scan"))
+
+    // A condition that is not boolean fails as for any other join.
+    val notBoolean = intercept[AnalysisException] {
+      left.join(lookup, left("sender") + lookup("id"))
+    }
+    assert(notBoolean.getCondition === "JOIN_CONDITION_IS_NOT_BOOLEAN_TYPE")
+  }
+
+  test("a catalog-resolved external lookup-only table cannot be read outside a 
lookup join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      val left = Seq(1).toDF("id")
+      Seq[() => DataFrame](
+        () => spark.table(table),
+        () => sql(s"SELECT * FROM $table WHERE id = 1")).foreach {
+        df =>
+          checkError(
+            exception = intercept[AnalysisException] { 
df().queryExecution.optimizedPlan },
+            condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+            parameters = Map(
+              "tableName" -> "`SimpleExternalLookupTable`",
+              "operation" -> "batch scan"))
+      }
+    }
+  }
+
+  test("a command that reads a lookup-only table outside a lookup join fails 
before it writes") {
+    withSQLConf(
+        "spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName,
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      val catalogLookup = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      def checkBatchScanError(write: () => Any): Unit = checkError(
+        exception = intercept[AnalysisException](write()),
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+
+      // Each write would replace the archived assignment that its target 
holds.
+      withTable("testcat.ns.target", "v1_target") {
+        sql("CREATE TABLE testcat.ns.target (id INT, department STRING)")
+        sql("INSERT INTO testcat.ns.target VALUES (7, 'archive')")
+        sql("CREATE TABLE v1_target (id INT, department STRING) USING parquet")
+        sql("INSERT INTO v1_target VALUES (7, 'archive')")
+        Seq[(String, () => Any)](
+          "testcat.ns.target" ->
+            (() => 
lookup.write.mode("overwrite").saveAsTable("testcat.ns.target")),
+          "testcat.ns.target" -> (() => 
lookup.writeTo("testcat.ns.target").replace()),
+          "testcat.ns.target" -> (() =>
+            sql(s"REPLACE TABLE testcat.ns.target USING foo AS SELECT * FROM 
$catalogLookup")),
+          "testcat.ns.target" ->
+            (() => sql(s"INSERT OVERWRITE testcat.ns.target SELECT * FROM 
$catalogLookup")),
+          "v1_target" -> (() => 
lookup.write.mode("overwrite").saveAsTable("v1_target")),
+          "v1_target" -> (() => 
lookup.write.mode("overwrite").insertInto("v1_target")),
+          // A subquery of the query reads it.
+          "v1_target" -> (() => sql(
+            "INSERT OVERWRITE v1_target SELECT id, 'none' FROM VALUES (8) AS 
t(id) " +
+              s"WHERE id NOT IN (SELECT id FROM $catalogLookup)"))).foreach {
+          case (target, write) =>
+            checkBatchScanError(write)
+            checkAnswer(spark.table(target), Row(7, "archive"))
+        }
+      }
+
+      // V1 commands that hold their query outside their children.
+      RecordingV1WriteSource.writes.clear()
+      withTempView("recording_sink") {
+        sql("CREATE TEMPORARY VIEW recording_sink (id INT, department STRING) 
" +
+          s"USING ${classOf[RecordingV1WriteSource].getName}")
+        checkBatchScanError(() =>
+          
lookup.write.mode("overwrite").format(classOf[RecordingV1WriteSource].getName).save())
+        checkBatchScanError(() =>
+          sql(s"INSERT OVERWRITE TABLE recording_sink SELECT * FROM 
$catalogLookup"))
+      }
+      assert(RecordingV1WriteSource.writes.isEmpty)
+    }
+  }
+
+  test("a command reads a lookup-only table only through a lookup join, and a 
view not at all") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    def save(query: DataFrame): LogicalPlan = SaveIntoDataSourceCommand(
+      query.queryExecution.analyzed, new RecordingV1WriteSource, Map.empty, 
SaveMode.Overwrite)
+    TableCapabilityCheck(save(left.join(lookup, left("id") === lookup("id"))))
+    // A join of a command, which is analyzed in full, cannot gain a condition 
later.
+    checkError(
+      exception = 
intercept[AnalysisException](TableCapabilityCheck(save(left.join(lookup)))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+
+    withTempView("lookup_view", "enriched_view") {
+      lookup.createOrReplaceTempView("lookup_view")
+      left.join(lookup, left("id") === 
lookup("id")).createOrReplaceTempView("enriched_view")
+      checkStream(
+        spark.table("enriched_view"), Seq(Row(1, 1, "engineering"), Row(1, 1, 
"research")))
+      checkError(
+        exception = intercept[AnalysisException] {
+          spark.table("lookup_view").queryExecution.optimizedPlan
+        },
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+    }
+  }
+
+  test("foreachBatch writes the micro-batches of a lookup join with batch 
commands") {
+    withSQLConf("spark.sql.catalog.testcat" -> 
classOf[InMemoryTableCatalog].getName) {
+      withTempPath { path =>
+        withTable("enriched_events") {
+          val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+          val events = streamOf(Seq(1, 2, 3).toDF("id"))
+          val enriched = events.join(lookup, events("id") === lookup("id"))
+            .select(events("id"), lookup("department"))
+          val v2Rows = new AtomicReference(Seq.empty[Row])
+          // Each micro-batch reaches the function as a plan that is already 
planned, so the batch
+          // commands over it read no lookup-only table.
+          val query = enriched.writeStream.foreachBatch { (batch: DataFrame, 
_: Long) =>
+            
batch.write.format("parquet").mode("append").save(path.getCanonicalPath)
+            batch.write.mode("append").saveAsTable("enriched_events")
+            // The function runs in the query's session, which has its own 
instance of the test
+            // catalog, so the V2 table is created and read there.
+            val session = batch.sparkSession
+            session.sql(
+              "CREATE TABLE IF NOT EXISTS testcat.ns.enriched_events (id INT, 
department STRING)")
+            batch.writeTo("testcat.ns.enriched_events").append()
+            
v2Rows.set(session.table("testcat.ns.enriched_events").collect().toSeq)
+          }.start()
+          try query.processAllAvailable() finally query.stop()
+          val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales"))
+          checkAnswer(spark.read.parquet(path.getCanonicalPath), expected)
+          checkAnswer(spark.table("enriched_events"), expected)
+          QueryTest.sameRows(expected, v2Rows.get()).foreach(fail(_))
+          // Each write computes the micro-batch again, as batchDF is not 
persisted.
+          assert(SimpleExternalLookupDataSource.requestCount.get() === 3)
+        }
+      }
+    }
+  }
+
+  test("a table that also supports batch read is read as a batch scan outside 
a lookup join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      Seq[() => DataFrame](
+        () => 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load(),
+        () => spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual")).foreach { 
dual =>
+        val df = dual()
+        
assert(df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation])
 === false)
+        checkAnswer(df, Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales")))
+      }
+      assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    }
+  }
+
+  test("a provider with a V1 read path cannot serve a lookup-only table") {
+    Seq(
+      classOf[RelationProviderExternalLookupDataSource],
+      classOf[SchemaRelationProviderExternalLookupDataSource],
+      classOf[FileFormatExternalLookupDataSource]).foreach { provider =>
+      val parameters = Map("table" -> "`SimpleExternalLookupTable`", 
"provider" -> provider.getName)
+      checkError(
+        exception = 
intercept[AnalysisException](spark.read.format(provider.getName).load()),
+        condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ",
+        parameters = parameters)
+      withTempView("hybrid_view") {
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"CREATE TEMPORARY VIEW hybrid_view USING ${provider.getName}")
+          },
+          condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ",
+          parameters = parameters)
+      }
+    }
+
+    // A provider without a V1 read path loads the table through both.
+    val provider = classOf[SimpleExternalLookupDataSource].getName
+    def readsLookupOnlyTable(df: DataFrame): Boolean =
+      df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation])
+    assert(readsLookupOnlyTable(spark.read.format(provider).load()))
+    withTempView("lookup_view") {
+      sql(s"CREATE TEMPORARY VIEW lookup_view USING $provider")
+      assert(readsLookupOnlyTable(spark.table("lookup_view")))
+    }
+  }
+
+  test("an external lookup hint without relation names marks the whole query") 
{
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val expected = Seq(Row(1, "engineering"), Row(1, "research"))
+
+    // As with a join strategy hint, the hint applies to the plan it 
annotates, here the join
+    // itself rather than its lookup side, so it is ignored. A lookup-only 
table still needs no
+    // hint.
+    withTempView("external_lookup_left", "external_lookup_right", 
"external_lookup_dual") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      dual.createOrReplaceTempView("external_lookup_dual")
+      Seq("external_lookup_right" -> true, "external_lookup_dual" -> 
false).foreach {
+        case (right, usesLookup) =>
+          val df = sql(s"""
+            |SELECT /*+ EXTERNAL_LOOKUP */ l.id, r.department
+            |FROM external_lookup_left l JOIN $right r ON l.id = r.id
+            |""".stripMargin)
+          
assert(runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) ===
+            usesLookup, right)
+          checkStream(df, expected)
+      }
+    }
+    val dataFrameJoin = left.join(dual, left("id") === 
dual("id")).hint("external_lookup")
+    assert(
+      
runStream(dataFrameJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+  }
+
+  test("external lookup join handles null, missing, duplicate, and partial 
batches") {
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("maxBatchSize", "3")
+      .load()
+    val left = streamOf(Seq[java.lang.Integer](1, 1, null, 3, 2).toDF("id"))
+
+    val run = runStream(left.join(lookup, left("id") === lookup("id"), 
"left_outer"))
+    val rows = run.rows
+    assert(rows.toSet === Set(
+      Row(1, 1, "engineering"),
+      Row(1, 1, "research"),
+      Row(null, null, null),
+      Row(3, null, null),
+      Row(2, 2, "sales")))
+    assert(rows.count(_.get(0) == 1) === 4)
+    assert(SimpleExternalLookupDataSource.requestSizes.asScala.toSeq === 
Seq(1, 2))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 3, 2))
+    assert(SimpleExternalLookupDataSource.nullKeyRequests.get() === 0)
+    // Two batches, [1, 1, null] and [3, 2], send their 1 + 2 distinct 
requestable keys.
+    val metrics = run.lookupJoin.metrics
+    assert(Seq("numInputRows", "numInputBatches", "numLookupRequests", 
"numLookupParameterRows",
+      "numOutputRows").map(metrics(_).value) === Seq(5, 2, 2, 3, 7))
+    assert(metrics("lookupTime").value > 0)
+  }
+
+  test("external lookup join supports complete composite equi-keys") {
+    val lookup = spark.read
+      .format(classOf[CompositeExternalLookupDataSource].getName)
+      .load()
+    val left = streamOf(Seq((1, 1), (1, 2), (2, 1)).toDF("tenant", "id"))
+
+    checkStream(
+      left.join(
+        lookup,
+        left("tenant") === lookup("tenant") && left("id") === lookup("id"),
+        "left_outer"),
+      Seq(Row(1, 1, 1, 1, "one-one"), Row(1, 2, null, null, null),
+        Row(2, 1, 2, 1, "two-one")))
+  }
+
+  test("an upstream limit stops one-to-many cursor consumption") {
+    SimpleExternalLookupDataSource.departmentsById.set(Map(1 -> (1 to 
2000).map(_.toString)))
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    assert(runStream(left.join(
+      lookup, left("id") === lookup("id"), "inner")
+      .limit(1)).rows.size === 1)
+    assert(SimpleExternalLookupDataSource.resultRowsRead.get() === 1)
+    assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor", "reader"))
+  }
+
+  test("external lookup samples connector metrics while consuming a large 
response") {
+    SimpleExternalLookupDataSource.departmentsById.set(Map(1 -> (1 to 
250).map(_.toString)))
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    assert(runStream(left.join(
+      lookup, left("id") === lookup("id"), "inner")).rows.size === 250)
+    // Two periodic samples, followed by request-completion and reader-close 
samples.
+    assert(SimpleExternalLookupDataSource.metricSamples.get() >= 4)
+  }
+
+  test("external lookup offers no lookup key on a double or a string with a 
non-binary collation") {
+    // A store may compare such values differently from Spark, for NaN and 
-0.0 or for case, so the
+    // equality stays in Spark's residual condition. Without another lookup 
key the join fails.
+    Seq(
+      "double" -> streamOf(Seq(-0.0d, 0.0d).toDF("key")),
+      "string collate utf8_lcase" -> streamOf(Seq("lookup", 
"LOOKUP").toDF("key"))
+        .selectExpr("CAST(key AS STRING COLLATE UTF8_LCASE) AS key")).foreach {
+      case (keyType, left) =>
+        val lookup = semanticKeyLookup(keyType)
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("key") === lookup("key"))),
+          condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+          parameters = Map("table" -> "`SemanticKeyExternalLookupTable`"))
+        assert(SemanticKeyExternalLookupDataSource.requestSizes.isEmpty)
+    }
+  }
+
+  test("external lookup drops returned rows that do not satisfy the selected 
lookup predicates") {
+    // The store matches SKUs case-insensitively, so it returns both `AB-1` 
and `ab-1` for every
+    // order. Spark checks `sku = ?` itself, and keeps only the product with 
the exact SKU.
+    val products =
+      
spark.read.format(classOf[CaseInsensitiveExternalLookupDataSource].getName).load()
+    val orders = streamOf(Seq((1, "AB-1"), (2, "ab-1"), (3, 
"Ab-1")).toDF("order", "sku"))
+    val matched = Seq(Row(1, "AB-1", "AB-1", "adapter"), Row(2, "ab-1", 
"ab-1", "cable"))
+    Seq("inner" -> matched, "left_outer" -> (matched :+ Row(3, "Ab-1", null, 
null))).foreach {
+      case (joinType, expected) =>
+        CaseInsensitiveExternalLookupTable.returnedRows.set(0)
+        checkStream(orders.join(products, orders("sku") === products("sku"), 
joinType), expected)
+        assert(CaseInsensitiveExternalLookupTable.returnedRows.get() === 6)
+    }
+  }
+
+  test("external lookup checks returned rows against its own copy of each 
request row") {
+    // A connector that overwrites the parameter rows it was given cannot make 
Spark drop rows.
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 2).toDF("id"))
+    
SimpleExternalLookupDataSource.afterParameterRowsRead.set(_.foreach(_.setInt(0, 
-1)))
+    checkStream(
+      left.join(lookup, left("id") === lookup("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research"), Row(2, 2, "sales")))
+  }
+
+  test("a stream-side guard keeps a lookup key or a residual from failing on 
rows it rejects") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val employees = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      // The guard is checked before the key is computed, so the badge `bad` 
is never cast.
+      val scans = streamOf(Seq(("1", true), ("bad", false)).toDF("badge", 
"verified"))
+      checkStream(
+        scans.join(employees,
+          scans("verified") && employees("id") === scans("badge").cast("int"), 
"left_outer"),
+        Seq(Row("1", true, 1, "engineering"), Row("1", true, 1, "research"),
+          Row("bad", false, null, null)))
+      // A conjunct that can fail is evaluated on joined rows only, as a join 
does, so never for
+      // employee 99, who has no match.
+      val timesheets = streamOf(Seq((1, "8"), (99, "bad")).toDF("id", "hours"))
+      checkStream(
+        timesheets.join(employees,
+          timesheets("id") === employees("id") && 
timesheets("hours").cast("int") > 0,
+          "left_outer"),
+        Seq(Row(1, "8", 1, "engineering"), Row(1, "8", 1, "research"),
+          Row(99, "bad", null, null)))
+    }
+  }
+
+  test("external lookup finishes no stream row after a failed or closed read") 
{
+    // After a failure or a close the result may be partial, so a stream row 
without a match could
+    // be one whose match was never read: Spark emits no unmatched row then. 
Id 1 has two matches
+    // and id 3 has none, and both are in one request.
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val outerJoin =
+      runStream(left.join(lookup, left("id") === lookup("id"), 
"left_outer")).lookupJoin
+    val input = CoalesceExec(1,
+      LocalTableScanExec(outerJoin.child.output, Seq(InternalRow(1), 
InternalRow(3)), None))
+    Seq(
+      "cursorFailure" -> 0,
+      "closeDuringNext" -> 0,
+      "closeDuringGet" -> 0,
+      "closeBetweenResultRows" -> 1,
+      "closeAtCursorEnd" -> 2).foreach {
+      case (failure, outputRows) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        val readerFactory = outerJoin.readerFactory match {
+          case factory: SimpleExternalLookupReaderFactory if failure == 
"cursorFailure" =>
+            factory.copy(failAt = "cursor")
+          case factory => factory
+        }
+        val failingJoin = outerJoin.copy(readerFactory = readerFactory, child 
= input)
+        val rdd = failingJoin.execute()
+        val context = TaskContext.empty()
+        TaskContext.setTaskContext(context)
+        try {
+          val rows = rdd.iterator(rdd.partitions.head, context)
+          val completeTask = () => context.markTaskCompleted(None)
+          failure match {
+            case "closeBetweenResultRows" =>
+              rows.next()
+              completeTask()
+            case "closeAtCursorEnd" =>
+              SimpleExternalLookupDataSource.beforeCursorEnds.set(completeTask)
+            // The cursor had a row when the close came, but Spark reads no 
row from it.
+            case "closeDuringNext" =>
+              
SimpleExternalLookupDataSource.beforeNextReturns.set(completeTask)
+            // The close comes while the row is read, so Spark neither copies 
nor joins it.
+            case "closeDuringGet" =>
+              SimpleExternalLookupDataSource.beforeGetReturns.set(completeTask)
+            case _ =>
+          }
+          intercept[Exception] {
+            while (rows.hasNext) rows.next()
+          }
+          assert(failingJoin.metrics("numOutputRows").value === outputRows, 
failure)
+          assert(SimpleExternalLookupDataSource.rowReadsAfterClose.get() === 
0, failure)
+        } finally {
+          TaskContext.unset()
+        }
+    }
+  }
+
+  private def semanticKeyLookup(keyType: String): DataFrame = {
+    spark.read
+      .format(classOf[SemanticKeyExternalLookupDataSource].getName)
+      .option("keyType", keyType)
+      .load()
+  }
+
+  test("a join strategy hint on the stream side of a lookup-only join is 
rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("merge").join(lookup, left("id") === 
lookup("id")).queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+      parameters = Map("strategy" -> "MERGE", "relation" -> 
"`SimpleExternalLookupTable`"))
+
+    // A strategy hint on a different join of the same query does not conflict.
+    val other = Seq((1, "a")).toDF("id", "tag")
+    val nested = left.join(other.hint("merge"), "id")
+    val joined = nested.join(lookup, nested("id") === lookup("id"))
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, "a", 1, "engineering"), Row(1, "a", 1, 
"research")))
+  }
+
+  test("a lookup join whose condition folds to false does not call the 
connector") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3, 3).toDF("id")).dropDuplicates("id")
+    Seq(
+      "inner" -> Seq.empty[Row],
+      "left_outer" -> Seq(Row(1, null, null), Row(3, null, null))).foreach {
+      case (joinType, expected) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        val joined = left.join(lookup, left("id") === lookup("id") && 
lit(false), joinType)
+        val run = runStream(joined)
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === 
false)
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+        // The stateful stream side still runs.
+        assert(run.plan.exists(_.isInstanceOf[Deduplicate]))
+        val deduplicate = run.execution.executedPlan.collectFirst {
+          case exec: StreamingDeduplicateExec => exec
+        }.get
+        assert(deduplicate.metrics("numTotalStateRows").value === 2)
+        assert(SimpleExternalLookupDataSource.lookupCandidates.get() === 
Seq.empty)
+        assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+        assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+    }
+  }
+
+  private def readSchemaLookup(kind: String): DataFrame = spark.read
+    .format(classOf[ReadSchemaExternalLookupDataSource].getName)
+    .option("kind", kind)
+    .load()
+
+  test("external lookup reads value rows that follow the read schema") {
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    val varchar = readSchemaLookup("varchar")
+    checkStream(
+      left.join(varchar, left("id") === varchar("id")),
+      Seq(Row(1, 1, "ab"), Row(2, 2, "ab")))
+    // The read schema lists the table columns in another order.
+    val reordered = readSchemaLookup("reordered")
+    checkStream(
+      left.join(reordered, left("id") === reordered("id")),
+      Seq(Row(1, 1, "ab"), Row(2, 2, "ab")))
+    // The table declares `s.a` NOT NULL and the read schema does not, which 
the binding accepts.
+    // Returned values must satisfy both, so the null that the connector 
returns for id 2 fails
+    // the task.
+    val nested = readSchemaLookup("nested")
+    val firstId = streamOf(Seq(1).toDF("id"))
+    checkStream(
+      firstId.join(nested, firstId("id") === nested("id"))
+        .select(firstId("id"), to_json(nested("s"))),
+      Seq(Row(1, "{\"a\":10}")))
+    checkError(
+      exception = streamFailure[SparkRuntimeException](
+        left.join(nested, left("id") === nested("id"))),
+      condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_IN_NOT_NULL_FIELD",
+      parameters = Map("table" -> "`ReadSchemaExternalLookupTable`", "field" 
-> "`s`.`a`"))
+    // A field whose type really differs is still rejected.
+    val wrongType = readSchemaLookup("wrongType")
+    checkError(
+      exception = streamFailure[AnalysisException](
+        left.join(wrongType, left("id") === wrongType("id"))),
+      condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.UNKNOWN_SCAN_FIELD",
+      parameters = Map("table" -> "`ReadSchemaExternalLookupTable`", "field" 
-> "`name`"))
+  }
+
+  test("external lookup checks nested nulls against the stricter of the two 
schemas") {
+    // At each nested level, the table rules out a null that the read schema 
allows, and the
+    // connector returns that null.
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      "nullArrayElement" -> "`tags`.`element`",
+      "nullMapValue" -> "`scores`.`value`",
+      "nullStructInArray" -> "`items`.`element`.`a`").foreach { case (kind, 
field) =>
+      val lookup = readSchemaLookup(kind)
+      checkError(
+        exception = streamFailure[SparkRuntimeException](
+          left.join(lookup, left("id") === lookup("id"))),
+        condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_IN_NOT_NULL_FIELD",
+        parameters = Map("table" -> "`ReadSchemaExternalLookupTable`", "field" 
-> field))
+    }
+  }
+
+  test("a lookup-only table that needs read-side CHAR or VARCHAR handling is 
rejected") {
+    val parameters = Map("relation" -> "`ReadSchemaExternalLookupTable`", 
"column" -> "`name`")
+    checkError(
+      exception = intercept[AnalysisException](readSchemaLookup("char")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CHAR_VARCHAR_COLUMN",
+      parameters = parameters)
+    withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+      checkError(
+        exception = intercept[AnalysisException](readSchemaLookup("varchar")),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CHAR_VARCHAR_COLUMN",
+        parameters = parameters)
+    }
+  }
+
+  test("external lookup keeps a decimal that fits its type, at any nested 
level") {
+    val lookup = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "decimalInRange")
+      .load()
+    val left = streamOf(Seq(1).toDF("id"))
+    def decimal(value: String): java.math.BigDecimal = new 
java.math.BigDecimal(value)
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"))
+        .select(lookup("amount"), lookup("amounts"), lookup("rates")),
+      Seq(Row(
+        decimal("999.99"),
+        Seq(decimal("-999.99"), decimal("1.50")),
+        Map("EUR" -> decimal("0.01")))))
+  }
+
+  test("a lookup-only CHAR column is read as stored when read-side padding is 
off") {
+    val left = streamOf(Seq(1).toDF("id"))
+    withSQLConf(SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") {
+      // The connector returns "ab" for a CHAR(5) column, and Spark returns it 
unpadded.
+      val char = readSchemaLookup("char")
+      checkStream(left.join(char, left("id") === char("id")), Seq(Row(1, 1, 
"ab")))
+      // Standard semantics apply the read-side padding anyway, so the table 
is still rejected.
+      withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+        checkError(
+          exception = intercept[AnalysisException](readSchemaLookup("char")),
+          condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CHAR_VARCHAR_COLUMN",
+          parameters =
+            Map("relation" -> "`ReadSchemaExternalLookupTable`", "column" -> 
"`name`"))
+      }
+    }
+  }
+
+  test("a Python UDF over lookup columns in the join condition") {
+    assume(shouldTestPythonUDFs)
+    val pythonUDF = TestPythonUDF("lookup_department")
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 2).toDF("id"))
+    val condition =
+      left("id") === lookup("id") && pythonUDF(lookup("department")) === 
"engineering"
+
+    // An inner join evaluates it above the lookup join; a left outer join 
cannot.
+    checkStream(left.join(lookup, condition), Seq(Row(1, 1, "engineering")))
+    checkError(
+      exception = streamFailure[AnalysisException](left.join(lookup, 
condition, "left_outer")),
+      condition = "UNSUPPORTED_FEATURE.PYTHON_UDF_IN_ON_CLAUSE",
+      parameters = Map("joinType" -> "LEFT OUTER"))
+  }
+
+  test("external lookup merges the connector metrics of every reader in a 
task") {
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SQL_STRING_REDACTION_PATTERN.key -> "secret-token") {
+      val lookup = 
spark.read.format(classOf[MetricsExternalLookupDataSource].getName).load()
+      // Two one-row input partitions, computed by one task under the 
coalesce, open two readers
+      // that send one request each.
+      val left = streamOf(spark.range(0, 2).selectExpr("CAST(id + 1 AS INT) AS 
id"), 2)
+      val joined = left.join(lookup, left("id") === lookup("id")).coalesce(1)
+
+      val run = runStream(joined)
+      assert(run.rows.length === 2)
+      val lookupJoin = run.lookupJoin
+      assert(lookupJoin.metrics("source.connectorRequests").value === 2)
+      // A connector metric named like an operator metric is kept apart from 
it.
+      assert(lookupJoin.metrics("source.numOutputRows").value === 7)
+      assert(lookupJoin.metrics("numOutputRows").value === 2)
+      // The connector description is redacted.
+      
assert(lookupJoin.simpleString(10).contains("MetricsExternalLookupScan(token="))
+      assert(run.execution.executedPlan.toString.contains("secret-token") === 
false)
+    }
+  }
+
+  test("external lookup closes task-local readers after success and failure") {
+    def lookup(options: (String, String)*): DataFrame = {
+      var reader = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName)
+      options.foreach { case (key, value) => reader = reader.option(key, 
value) }
+      reader.load()
+    }
+    val left = streamOf(Seq(1).toDF("id"))
+
+    val successfulLookup = lookup()
+    runStream(left.join(successfulLookup, left("id") === 
successfulLookup("id")))
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 1)
+    // The cursor is closed before its reader.
+    assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor", "reader"))
+
+    // A request that fails returns no cursor; a failing cursor is still 
closed.
+    Seq("request" -> Seq("reader"), "cursor" -> Seq("cursor", 
"reader")).foreach {
+      case (failAt, closeEvents) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        val failingLookup = lookup("failAt" -> failAt)
+        val failure = streamFailure[SparkException](
+          left.join(failingLookup, left("id") === failingLookup("id")))
+        assert(failure.getMessage.contains(s"injected external lookup $failAt 
failure"))
+        assert(SimpleExternalLookupDataSource.readerCount.get() === 1)
+        assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
closeEvents)
+    }
+  }
+
+  test("external lookup makes no connector call once its task completed") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val lookupJoin = runStream(left.join(lookup, left("id") === 
lookup("id"))).lookupJoin
+    // Computes the join over a local input, in a task that completes before 
the join is
+    // consumed, before its first request, while its reader is created, while 
the request is in
+    // progress, or between the two result rows of the request. Another thread 
consumes the join,
+    // as when a thread other than the task's drives it.
+    val rdd = lookupJoin
+      .copy(child = LocalTableScanExec(lookupJoin.child.output, 
Seq(InternalRow(1)), None))
+      .execute()
+    val completions = Seq(
+      "beforeEval", "beforeRequest", "duringReaderCreation", "duringRequest", 
"betweenResultRows")
+    completions.foreach { completion =>
+      SimpleExternalLookupDataSource.resetCounters()
+      val context = TaskContext.empty()
+      TaskContext.setTaskContext(context)
+      try {
+        if (completion == "beforeEval") context.markTaskCompleted(None)
+        val rows = rdd.iterator(rdd.partitions.head, context)
+        if (completion == "betweenResultRows") rows.next()
+        val completeTask = () => context.markTaskCompleted(None)
+        completion match {
+          case "duringReaderCreation" =>
+            
SimpleExternalLookupDataSource.beforeReaderReturns.set(completeTask)
+          case "duringRequest" =>
+            
SimpleExternalLookupDataSource.beforeLookupReturns.set(completeTask)
+          case _ => completeTask()
+        }
+        val resultRowsRead = 
SimpleExternalLookupDataSource.resultRowsRead.get()
+
+        val failure = new AtomicReference[Throwable]()
+        val consumer = new Thread(() => {
+          try rows.hasNext catch { case error: Throwable => failure.set(error) 
}
+        })
+        consumer.start()
+        consumer.join()
+        // No new reader, request or cursor advance after the close, and every 
reader and cursor
+        // is closed.
+        val (readers, requests) = completion match {
+          case "beforeEval" | "beforeRequest" => (0, 0)
+          case "duringReaderCreation" => (1, 0)
+          case _ => (1, 1)
+        }
+        assert(SimpleExternalLookupDataSource.readerCount.get() === readers)
+        assert(SimpleExternalLookupDataSource.requestCount.get() === requests)
+        assert(SimpleExternalLookupDataSource.resultRowsRead.get() === 
resultRowsRead)
+        // The close closes the cursor before the reader. A cursor that a 
request in progress
+        // returns after the close is closed after the reader.
+        val closeEvents = completion match {
+          case "beforeEval" | "beforeRequest" => Seq.empty
+          case "duringReaderCreation" => Seq("reader")
+          case "duringRequest" => Seq("reader", "cursor")
+          case _ => Seq("cursor", "reader")
+        }
+        assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
closeEvents)
+        checkError(
+          exception = failure.get().asInstanceOf[SparkException],
+          condition = "INTERNAL_ERROR",
+          parameters = Map("message" -> "External lookup reader used after it 
was closed"))
+      } finally {
+        TaskContext.unset()
+      }
+    }
+  }
+
+  /**
+   * Runs the join of `lookupJoin` over stream row 1 in a task, on a consuming 
thread, and ends the
+   * task on another thread once the consumer has reached `hook`, which then 
blocks it until
+   * `whileBlocked` has run. Returns the consumer's failure.
+   */
+  private def endTaskWhileConsumerIsIn(
+      lookupJoin: ExternalLookupJoinExec,
+      hook: AtomicReference[() => Unit])(whileBlocked: Thread => Unit): 
Throwable = {
+    val rdd = lookupJoin
+      .copy(child = LocalTableScanExec(lookupJoin.child.output, 
Seq(InternalRow(1)), None))
+      .execute()
+    SimpleExternalLookupDataSource.resetCounters()
+    val reached = new CountDownLatch(1)
+    val release = new CountDownLatch(1)
+    val first = new AtomicBoolean(true)
+    hook.set { () =>
+      if (first.getAndSet(false)) {
+        reached.countDown()
+        assert(release.await(30, TimeUnit.SECONDS))
+      }
+    }
+    val context = TaskContext.empty()
+    TaskContext.setTaskContext(context)
+    try {
+      val rows = rdd.iterator(rdd.partitions.head, context)
+      val failure = new AtomicReference[Throwable]()
+      val consumer = new Thread(() => {
+        try {
+          while (rows.hasNext) rows.next()
+        } catch {
+          case error: Throwable => failure.set(error)
+        }
+      })
+      consumer.start()
+      try {
+        assert(reached.await(10, TimeUnit.SECONDS))
+        val completion = new Thread(() => context.markTaskCompleted(None))
+        completion.start()
+        whileBlocked(completion)
+      } finally {
+        release.countDown()
+        consumer.join(TimeUnit.SECONDS.toMillis(10))
+      }
+      assert(consumer.isAlive === false)
+      failure.get()
+    } finally {
+      TaskContext.unset()
+    }
+  }
+
+  test("once the join has seen the task end, it makes no connector call") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val lookupJoin = runStream(left.join(lookup, left("id") === 
lookup("id"))).lookupJoin
+    // The consumer is inside the cursor's next() or get() when the task ends 
on another thread.
+    Seq(
+      "next" -> SimpleExternalLookupDataSource.beforeNextReturns,
+      "get" -> SimpleExternalLookupDataSource.beforeGetReturns).foreach { case 
(call, hook) =>
+      var metricSamples = 0
+      var resultRowsRead = 0
+      val failure = endTaskWhileConsumerIsIn(lookupJoin, hook) { completion =>
+        // The close does not wait for the call: it closes the cursor, then 
the reader.
+        completion.join(TimeUnit.SECONDS.toMillis(10))
+        assert(completion.isAlive === false, call)
+        assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor", "reader"))
+        metricSamples = SimpleExternalLookupDataSource.metricSamples.get()
+        resultRowsRead = SimpleExternalLookupDataSource.resultRowsRead.get()
+      }
+      checkError(
+        exception = failure.asInstanceOf[SparkException],
+        condition = "INTERNAL_ERROR",
+        parameters = Map("message" -> "External lookup reader used after it 
was closed"))
+      // When the call returns, the consumer sees the close and leaves the 
cursor and the reader's
+      // metrics to it: each is closed once, and no call follows.
+      assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor", "reader"))
+      assert(SimpleExternalLookupDataSource.metricSamples.get() === 
metricSamples, call)
+      assert(SimpleExternalLookupDataSource.resultRowsRead.get() === 
resultRowsRead, call)
+      assert(SimpleExternalLookupDataSource.rowReadsAfterClose.get() === 0, 
call)
+    }
+  }
+
+  test("task completion closes the reader only after a copy of a value row in 
progress") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val lookupJoin = runStream(left.join(lookup, left("id") === 
lookup("id"))).lookupJoin
+    // The consumer is copying the first value row when the task ends on 
another thread.
+    val failure = endTaskWhileConsumerIsIn(
+        lookupJoin, SimpleExternalLookupDataSource.beforeValueRead) { 
completion =>
+      // The close closes the cursor, which must leave the row readable, and 
then waits for the
+      // copy before it closes the reader, which may own the memory behind the 
row.
+      eventually(timeout(10.seconds)) {
+        assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor"))
+      }
+      completion.join(500)
+      assert(completion.isAlive)
+      assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor"))
+    }
+    // After the copy, the reader is closed, and the consumer then fails on 
its next read.
+    assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === 
Seq("cursor", "reader"))

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 
[7412930c368](https://github.com/apache/spark/commit/7412930c3688d84fc17527b204fcbbc5a6d3a751).
 The helper now joins the completion thread, with a bound, before it returns, 
so every close-event assertion runs after the close.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java:
##########
@@ -167,6 +167,11 @@ public enum TableCapability {
    * implement {@link SupportsRead}, its scan builder must implement
    * {@link org.apache.spark.sql.connector.read.SupportsExternalLookup}, and 
the built scan must
    * implement {@link 
org.apache.spark.sql.connector.read.Scan#toExternalLookup()}.
+   * <p>
+   * A table that supports both batch reads and lookups reports both {@link 
#BATCH_READ} and this
+   * capability. A table that reports this capability without {@link 
#BATCH_READ} is lookup-only,
+   * and its provider must then have no V1 read path, such as {@code 
RelationProvider}: Spark

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 
[7412930c368](https://github.com/apache/spark/commit/7412930c3688d84fc17527b204fcbbc5a6d3a751).
 The Javadoc now says what Spark does on each path. `spark.read` and `CREATE 
TEMPORARY VIEW … USING` fail. A session-catalog table created `USING` such a 
provider loads the V2 table. A custom session catalog may return a V1 table. A 
source listed in `spark.sql.sources.useV1SourceList` is read through V1.



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