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


##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCapability.java:
##########
@@ -167,6 +167,21 @@ 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 should have no V1 read path, such as {@code 
RelationProvider}, because which
+   * of the two Spark uses depends on how the table is reached:
+   * <ul>
+   *   <li>{@code spark.read} and {@code CREATE TEMPORARY VIEW ... USING} fail 
for such a
+   *   provider.</li>
+   *   <li>A session catalog table created {@code USING} such a provider loads 
the lookup-only

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 
[d61e9e647d9](https://github.com/apache/spark/commit/d61e9e647d97088f545d3774f128f828c9d1a302):
 the capability Javadoc says that a session catalog table of a 
`FileDataSourceV2` provider is read through its fallback `FileFormat`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSeq, 
AttributeSet,
+  Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter, 
QueryPlan}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_JOIN, 
TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Every output attribute of the lookup side. They 
are all part of this
+ *   node's references, so column pruning never puts a projection over the 
lookup relation, which
+ *   preparation needs directly under the join. A narrower list would let it 
do so.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/**
+ * A lookup join after its optimized lookup side has been converted to an 
external operation.
+ *
+ * @param lookupKeys The table column that each selected lookup predicate 
compares with the
+ *   parameter at the same position. Spark checks each row that the connector 
returns against
+ *   them, so the read schema must hold these columns.
+ */
+case class PreparedExternalLookupJoin(
+    child: LogicalPlan,
+    tableName: String,
+    @transient scan: Scan,
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    lookupInput: Seq[Attribute],
+    lookupOutput: Seq[Attribute],
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeys: Seq[Attribute],
+    joinType: JoinType,
+    residualCondition: Option[Expression]) extends UnaryNode {
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => child.output ++ lookupOutput
+    case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true))
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  override def references: AttributeSet =
+    AttributeSet(lookupParameters.flatMap(_.references)) ++
+      residualCondition.map(_.references.intersect(child.outputSet))
+        .getOrElse(AttributeSet.empty)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
PreparedExternalLookupJoin =
+    copy(child = newChild)
+
+  // The lookup-side attributes are not in the child's output, so the default 
canonicalization
+  // gives each top-level one the next id, whichever column it is: two joins 
that keep different
+  // lookup columns of one type would canonicalize alike. Each is normalized 
by its place in the
+  // child's output and the read schema instead.
+  override protected def doCanonicalize(): LogicalPlan = {
+    val attributes: AttributeSeq = child.output ++ lookupInput
+    def normalize[T <: Expression](expression: T): T =
+      QueryPlan.normalizeExpressions(expression, attributes)
+    copy(
+      child = child.canonicalized,
+      lookupInput = lookupInput.map(normalize),
+      lookupOutput = lookupOutput.map(normalize),
+      lookupParameters = lookupParameters.map(normalize),
+      lookupKeys = lookupKeys.map(normalize),
+      residualCondition = residualCondition.map(normalize))
+  }
+
+  // Connector descriptions may contain secrets, so the scan and the reader 
factory are not shown.
+  // The physical node renders a redacted description of them.

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 #59909, which owns this line 
([7a4ef1369cb](https://github.com/apache/spark/commit/7a4ef1369cba83d95b681372348854a32aa6b327)):
 the comment now says that the physical node renders the scan's redacted 
description, and nothing of the reader factory.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,3093 @@
+/*
+ * 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,
+  SparkThrowable, SparkUnsupportedOperationException, TaskContext}
+import org.apache.spark.rdd.DeterministicLevel
+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, 
AttributeMap, AttributeReference,
+  Cast, EqualTo, Expression, GenericInternalRow, LessThan, Literal, Rand, 
UnsafeProjection}
+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, InMemoryBaseTable,
+  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.{FileFormat, 
SaveIntoDataSourceCommand}
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
ExternalLookupRelation,
+  FileDataSourceV2, StreamingDataSourceV2ScanRelation, 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.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{coalesce, col, concat, expr, length, 
lit, max, 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, DecimalType, 
DoubleType,
+  IntegerType, MapType, StringType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.unsafe.types.UTF8String
+
+class ExternalLookupJoinSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  private val EXTERNAL_LOOKUP_CATALOG_NAME = "external_lookup_cat"
+  // The supportedJoinTypes parameter of a JOIN_TYPE error.
+  private val SUPPORTED_JOIN_TYPES = "INNER, LEFT OUTER"
+
+  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, when it starts or in a 
micro-batch. */
+  private def streamFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val cause = try {
+      runStream(df)
+      fail("The streaming query did not fail")
+    } catch {
+      case e: StreamingQueryException => e.getCause
+      case e: Throwable with SparkThrowable => e
+    }
+    assert(classTag[T].runtimeClass.isInstance(cause), cause)
+    cause.asInstanceOf[T]
+  }
+
+  test("a stream whose scan is pruned at the start reads the columns of its 
lookup joins") {
+    withSQLConf(
+        "spark.sql.catalog.stream_cat" -> 
classOf[InMemoryTableCatalog].getName,
+        SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "true") {
+      withTable("stream_cat.ns.badge_swipes") {
+        sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door 
STRING, minute INT) " +
+          s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_COLUMN_PRUNING}' = 
'true')")
+        sql("INSERT INTO stream_cat.ns.badge_swipes VALUES (1, 'lobby', 10), 
(3, 'garage', 20)")
+        val swipes = spark.readStream.table("stream_cat.ns.badge_swipes")
+        val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+        checkStream(
+          swipes.join(lookup, swipes("employee") === lookup("id"))
+            .select(swipes("door"), lookup("department")),
+          Seq(Row("lobby", "engineering"), Row("lobby", "research")))
+        // An aggregate that reads only stream columns and ignores duplicates 
does not need a left
+        // outer join, so the optimizer removes an ordinary one. A lookup join 
stays.
+        val latestByDoor = swipes.join(lookup, swipes("employee") === 
lookup("id"), "left_outer")
+          .groupBy(swipes("door")).agg(max(swipes("minute")))
+        QueryTest.sameRows(
+          Seq(Row("lobby", 10), Row("garage", 20)),
+          runStream(latestByDoor, "complete").rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("a stream whose scan gets the query's filters joins its lookup joins as 
without them") {
+    // The stream drops the rows that fail the filters that its scan builder 
took when the query
+    // started, so a micro-batch that does not apply one of them fails.
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    def results(pushdown: Boolean): (Seq[Seq[Row]], Seq[Seq[Expression]]) = {
+      var result: (Seq[Seq[Row]], Seq[Seq[Expression]]) = null
+      withSQLConf(
+          "spark.sql.catalog.stream_cat" -> 
classOf[InMemoryTableCatalog].getName,
+          SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key -> 
pushdown.toString) {
+        withTable("stream_cat.ns.badge_swipes") {
+          sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door 
STRING, minute INT) " +
+            s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN}' 
= 'true', " +
+            s"'${InMemoryBaseTable.SIMULATE_STREAMING_FILTERS}' = 'true')")
+          sql("INSERT INTO stream_cat.ns.badge_swipes VALUES " +
+            "(1, 'lobby', 10), (2, 'garage', 20), (3, 'dock', 30), (1, 
'garage', 40)")
+          val swipes = spark.readStream.table("stream_cat.ns.badge_swipes")
+          val onEmployee = swipes("employee") === lookup("id")
+          val runs = Seq(
+            // A filter on stream columns below the join, and above an inner 
and a left outer join.
+            runStream(swipes.where(swipes("minute") > 15).join(lookup, 
onEmployee)),
+            runStream(swipes.join(lookup, onEmployee).where(swipes("minute") > 
15)),
+            runStream(swipes.join(lookup, onEmployee, "left_outer")
+              .where(swipes("door") === "garage")),
+            // A filter on both sides, which predicate pushdown can move into 
the join condition.
+            runStream(swipes.join(lookup, onEmployee)
+              .where(swipes("door") =!= lookup("department") && 
swipes("minute") < 35)),
+            // An aggregate that ignores duplicates needs no ordinary left 
outer join, which the
+            // optimizer removes, with its filters pushed to the stream. A 
lookup join stays.
+            runStream(swipes.join(lookup, onEmployee, 
"left_outer").where(swipes("minute") > 15)
+              .groupBy(swipes("door")).agg(max(swipes("minute"))), "complete"))
+          val pushed = runs.map(_.execution.optimizedPlan.collect {
+            case relation: StreamingDataSourceV2ScanRelation => 
relation.pushedFilters
+          }.flatten)
+          result = (runs.map(_.rows), pushed)
+        }
+      }
+      result
+    }
+    val (rows, pushed) = results(pushdown = true)
+    val (expected, notPushed) = results(pushdown = false)
+    rows.zip(expected).foreach { case (actual, expected) =>
+      QueryTest.sameRows(expected, actual).foreach(fail(_))
+    }
+    assert(notPushed.forall(_.isEmpty))
+    // At least the filter below the join reaches the stream's scan.
+    assert(pushed.head.nonEmpty)
+  }
+
+  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("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_RESULT",
+        Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")),
+      ("selectionMode", "nullElement", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "null")),
+      ("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", Map("table" -> "`SimpleExternalLookupTable`",
+        "method" -> "ExternalLookupReader.lookupBatch()")),
+      (misconfigured("nullReader"), "NULL_RESULT",
+        table ++ Map("method" -> 
"ExternalLookupReaderFactory.createReader()")),
+      (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",
+        table ++ Map("method" -> "ExternalLookupResultCursor.get()")),
+      // 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 compact decimal with too many digits, written into an UnsafeRow, a 
struct in one, or a
+      // columnar row or array, each of which records its type's precision 
without checking it.
+      (misconfigured("compactDecimal:unsafe:outOfRange"), 
"DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")),
+      (misconfigured("compactDecimal:unsafeNested:outOfRange"), 
"DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`price`.`amount`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      (misconfigured("compactDecimal:columnar:outOfRange"), 
"DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")),
+      (misconfigured("compactDecimal:columnarArray:outOfRange"), 
"DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amounts`.`element`", "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) =>
+        // A left outer join binds the lookup columns as nullable for its 
output, but checks the
+        // returned values against the table and the read schema, as an inner 
join does.
+        Seq("inner", "left_outer").foreach { joinType =>
+          checkError(
+            exception = streamFailure[SparkRuntimeException](
+              left.join(lookup, left("id") === lookup("id"), joinType)),
+            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("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 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 === Map(
+          "joinType" -> joinType,
+          "relation" -> "`SimpleExternalLookupTable`",
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+    }
+  }
+
+  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("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"))
+        // The query reads it below a union under an ordinary join, which is 
no lookup join at any
+        // layer, so the check reaches the read only by entering the sides of 
the join.
+        val departments = Seq((1, "x")).toDF("id", "label")
+        checkBatchScanError(() => departments.join(lookup.union(lookup), "id")
+          
.write.mode("overwrite").format(classOf[RecordingV1WriteSource].getName).save())
+      }
+      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("view definitions over a lookup-only table, in either view catalog, are 
not reads") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName,
+        "spark.sql.catalog.view_only" -> 
classOf[TestingViewOnlyCatalog].getName) {
+      val lookupTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      // ALTER VIEW of a session view, and CREATE VIEW and ALTER VIEW in a V2 
view catalog.
+      withTempView("departments") {
+        sql("CREATE TEMPORARY VIEW departments AS SELECT 1 AS id, 'none' AS 
department")
+        sql(s"ALTER VIEW departments AS SELECT * FROM $lookupTable")
+        assert(spark.table("departments").queryExecution.analyzed.exists {
+          case relation: DataSourceV2Relation => relation.table eq 
SimpleExternalLookupTable
+          case _ => false
+        })
+      }
+      val catalog = spark.sessionState.catalogManager.catalog("view_only")
+        .asInstanceOf[TestingViewOnlyCatalog]
+      sql(s"CREATE VIEW view_only.default.departments AS SELECT * FROM 
$lookupTable")
+      sql(s"ALTER VIEW view_only.default.pure_v AS SELECT * FROM $lookupTable")
+      Seq("departments", "pure_v").foreach { name =>
+        assert(catalog.loadView(Identifier.of(Array("default"), 
name)).queryText() ===
+          s"SELECT * FROM $lookupTable")
+      }
+    }
+  }
+
+  test("a stream-only Python UDF in a lookup join's residual or lookup 
parameter") {
+    assume(shouldTestPythonUDFs)
+    // The UDF returns its input, so each join has the same rows as the one 
with the column itself.
+    val pythonUDF = TestPythonUDF("stream_key")
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 1), (2, -1), (3, 1)).toDF("id", "shift"))
+    Seq[(Column => Column, String)](
+      (key => left("id") === lookup("id") && key > 0, "residual"),
+      (key => lookup("id") === key + left("id") - left("shift"), 
"parameter")).foreach {
+      case (condition, place) =>
+        Seq("inner", "left_outer").foreach { joinType =>
+          val withUDF = runStream(left.join(lookup, 
condition(pythonUDF(left("shift"))), joinType))
+          
assert(withUDF.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]), place)
+          val builtIn = runStream(left.join(lookup, condition(left("shift")), 
joinType))
+          QueryTest.sameRows(builtIn.rows, withUDF.rows).foreach(error => 
fail(s"$place: $error"))
+        }
+    }
+  }
+
+  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],
+      classOf[FileDataSourceV2ExternalLookupDataSource]).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("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("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"),

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Added in 
[d61e9e647d9](https://github.com/apache/spark/commit/d61e9e647d97088f545d3774f128f828c9d1a302):
 the stream-side guard test now runs an inner join too.
   



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