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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TableCapabilityCheck.scala:
##########
@@ -38,7 +42,15 @@ object TableCapabilityCheck extends (LogicalPlan => Unit) {
 
   override def apply(plan: LogicalPlan): Unit = {
     plan foreach {
-      case r: DataSourceV2Relation if !r.table.supports(BATCH_READ) =>
+      // A table that supports external lookup may be read by a lookup join 
formed later, e.g.
+      // when a DataFrame over it is joined. In a plan that is not a command,
+      // PrepareExternalLookupJoin rejects it when it remains a plain scan 
after lookup joins are
+      // prepared. A command is checked here, below.
+      case r: DataSourceV2Relation
+          if !r.table.supports(BATCH_READ) && 
!r.table.supports(EXTERNAL_LOOKUP) =>
+        throw QueryCompilationErrors.unsupportedBatchReadError(r.table)
+
+      case r: ExternalLookupRelation if !r.table.supports(EXTERNAL_LOOKUP) =>

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.
   
   Removed in 
[4bc87c4843a](https://github.com/apache/spark/commit/4bc87c4843aa239cec21df938b2a9733b6e64c32).
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,682 @@
+/*
+ * 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()

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 
[4bc87c4843a](https://github.com/apache/spark/commit/4bc87c4843aa239cec21df938b2a9733b6e64c32):
 the consuming thread now checks for the close before each connector call, 
including the metrics sample and `inputOrdinal()`. With the narrower contract 
(see viirya's thread), `close()` may overlap only the one call in progress.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,2913 @@
+/*
+ * 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.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, 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, 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.{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, 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"
+  // 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("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 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"))),

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 
[4bc87c4843a](https://github.com/apache/spark/commit/4bc87c4843aa239cec21df938b2a9733b6e64c32):
 the runtime contract cases, and the nested read-schema and nested-null tests, 
also run a left outer join.
   



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