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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,334 @@
+/*
+ * 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.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, Coalesce,
+  EqualNullSafe, EqualTo, Expression, ExprUtils, ExternalUserDefinedFunction, 
Literal,
+  PredicateHelper, PythonUDF}
+import org.apache.spark.sql.catalyst.plans.LeftOuter
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, 
ExternalLookupKeyTypes,
+  Filter, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_JOIN}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, 
StructType}
+
+/** Finalizes an optimized external lookup side immediately before ordinary V2 
scan preparation. */
+object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper
+  with QueryErrorsBase {
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val prepared = 
plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) {
+      case join: ExternalLookupJoin if provablyEmpty(join) => 
emptyJoinResult(join)
+      case join: ExternalLookupJoin => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+      prepared.foreach { node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+      }
+    }
+    prepared
+  }
+
+  // The optimizer folds `WHERE false` on the lookup side into an empty 
relation, and a condition
+  // such as `s.id = r.id AND false` into `false`. Such a join needs no 
connector call.
+  private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+    join.right.maxRows.contains(0L) || (join.condition match {
+      case Some(Literal(value, BooleanType)) => value == null || value == false
+      case _ => false
+    })
+
+  private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+    val nullLookupColumns = join.right.output.map { attr =>
+      Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+    }
+    val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+    join.joinType match {
+      case LeftOuter => unmatched
+      // The stream side is kept under a false filter rather than replaced by 
an empty relation,
+      // so that its sources, watermarks and stateful operators still run in 
every micro-batch.
+      // PruneFilters decides whether a streaming subplan may be pruned.
+      case _ => Filter(Literal.FalseLiteral, unmatched)
+    }
+  }
+
+  private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+    val relation = extractLookupPlan(join.right).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    // A Python or external UDF over lookup columns cannot run in the 
residual. The rules that move
+    // one out of a join condition match only Join and run later, so this rule 
does it: an inner
+    // join evaluates the conjunct in a filter above the join, and an outer 
join is rejected.
+    if (join.joinType == LeftOuter) {
+      conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+        case _: ExternalUserDefinedFunction =>
+          throw 
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+        case _ =>
+          throw 
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+      }
+    }
+    val offeredCandidates = conjuncts.zipWithIndex.collect {
+      case (EqualTo(leftExpr, rightAttr: Attribute), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+      case (EqualTo(rightAttr: Attribute, leftExpr), index)
+          if isLookupEquality(join, leftExpr, rightAttr) =>
+        OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false)
+    }
+    if (offeredCandidates.isEmpty) {
+      throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName)))
+    }
+
+    val scanBuilder = supportsRead.newScanBuilder(relation.options)
+    val lookupBuilder = scanBuilder match {
+      case builder: SupportsExternalLookup => builder
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "SCAN_BUILDER", Map("table" -> toSQLId(tableName)))
+    }
+    // A column is offered under the table's name for it. Under 
case-insensitive analysis, the
+    // condition may spell it in another case, as `ID` for `id`, with the same 
exprId; filter
+    // pushdown renames it the same way, with 
DataSourceStrategy.normalizeExprs.
+    val columnNames = AttributeMap(relation.output.map(attr => attr -> 
attr.name))
+    val offeredPredicates = offeredCandidates.map { candidate =>
+      new V2Predicate(candidate.predicateName, Array[V2Expression](
+        FieldReference.column(columnNames(candidate.projectedField)),
+        new LookupParameter(candidate.parameter.dataType)))
+    }.toArray
+    val selectedPredicates = selectedCandidates(tableName, offeredPredicates, 
offeredCandidates,
+      lookupBuilder.selectLookupPredicates(offeredPredicates))
+    val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet
+    // As a hash join matches its keys before it evaluates its other 
conditions, the residual
+    // evaluates the equalities between the two sides first, together with the 
conjuncts that
+    // cannot fail. A conjunct that can fail then runs only for rows that pass 
them. Each group
+    // keeps the written order.
+    val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect {
+      case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct
+    }.partition(lookupSideUDF(join, _).isEmpty)
+    val (residualFirst, residualRest) = residualConjuncts.partition { conjunct 
=>
+      isJoinKeyEquality(join, conjunct) || 
ExprUtils.canEvaluateUnconditionally(conjunct)

Review Comment:
   Agreed, thanks. With the stack landing in one release, the predicate 
pushdown in #60198 moves a guard like the RLIKE onto the lookup side before the 
residual, as for an ordinary join, and its test runs this example, so the 
residual order can stay as it is here.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4525480156","thread_id":"inline:4525480156","verdict_sha256":"dcacee167f8cb665d8717e3bab33846f9c641cc4a01582f61dbffb7109029da6"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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 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, Expression, 
GenericInternalRow,
+  JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow}
+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, UserDefinedType}
+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 inner join emits nothing for a stream row that cannot match, because 
it fails the stream
+    // condition or has a null parameter that is not null-safe, as an ordinary 
inner join filters
+    // such a row out before it joins. So the row takes no place in a batch 
and is not copied: it
+    // counts only as an input row. A left outer join emits it, so a batch 
keeps it.
+    private val keepsRowsThatCannotMatch = joinType != Inner
+
+    private def canMatch(row: InternalRow): Boolean =
+      joinOutput.canMatch(row) && 
!parameters.matchesNothing(parameters.requestRow(row))
+
+    // 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 keeps one row, when one remains.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes 
&& input.hasNext) {
+        val next = input.next()
+        if (keepsRowsThatCannotMatch || canMatch(next)) {
+          val row = next match {
+            case unsafe: UnsafeRow => unsafe.copy()
+            case other => toUnsafe(other).copy()
+          }
+          bytes += row.getSizeInBytes
+          rows += row
+        } else {
+          metrics.inputRows += 1
+        }
+      }
+      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 request row 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 parameters are not requested. The 
stream condition is
+    // checked before the parameters are evaluated, so that it can guard their 
expressions.
+    private val keyEntries = {
+      val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+      rows.indices.foreach { index =>
+        lazy val requestRow = parameters.requestRow(rows(index))
+        if (!joinOutput.canMatch(rows(index)) || 
parameters.matchesNothing(requestRow)) {

Review Comment:
   **Nit (P3):** For an inner join, every row that reaches this check has 
already passed it: `readBatch` admits a stream row only after `canMatch` has 
evaluated the stream condition, projected the request row and checked it for 
nulls, and it then discards that request row. Both are deterministic, since the 
stream condition holds only conjuncts that `canEvaluateUnconditionally` accepts 
and analysis rejects a nondeterministic join condition, so this second 
evaluation never rejects a row; it only doubles the cost of these expressions 
for each row that can match. For a bare-column key that cost is small next to 
the request, but for a key computed by an expensive expression, such as 
`get_json_object(orders("payload"), "$.customer").cast("int") === 
customers("id")`, it doubles that expression's CPU. A left outer join evaluates 
them once.
   
   Suggested fix: decide once per row while `readBatch` reads it, grouping each 
row that can match under its request row and copying each distinct request row 
once, as this map does now, and hand the grouped entries, together with the 
left outer rows to finish without a request, to `BatchJoinIterator` instead of 
evaluating them again. A left outer join keeps its current batching.
   
   **Verification:**
   - **Behavior:** An inner lookup join whose lookup key is computed by an 
expression over stream columns evaluates that expression once for each stream 
row that passes the stream condition, and not at all for the rows that fail it, 
as a left outer join does.
   - **Regression:** Inner and left outer lookup joins over stream rows with 
null keys, rows that fail the stream condition and repeated keys return the 
same rows, request sizes, requested keys and row, batch and request metrics as 
before, and a stream-side guard still keeps a key expression that would fail 
under ANSI mode from being evaluated on the rows it rejects.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2530,6 +2530,30 @@ object SQLConf {
     .bytesConf(ByteUnit.BYTE)
     .createWithDefault(8L << 30)
 
+  val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES =
+    buildConf("spark.sql.join.externalLookup.maxBatchBytes")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("Size in bytes of input rows at which an external lookup join stops 
adding rows to " +
+        "a lookup request. The row that reaches this size stays in the 
request, so a request " +
+        "can exceed it by one row. A request always takes at least one row, 
and never more rows " +
+        "than the source allows, or 1000.")
+      .version("4.4.0")
+      .bytesConf(ByteUnit.BYTE)
+      .checkValue(_ > 0, "External lookup join max batch bytes must be 
positive")
+      .createWithDefaultString("64m")
+
+  val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED =
+    buildConf("spark.sql.join.externalLookup.startupCheck.enabled")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("When true, a streaming query plans its external lookup joins once 
when its " +
+        "execution starts, including the planning calls to their connectors, 
so that a join " +
+        "that cannot be planned stops the query before its first micro-batch, 
also without " +

Review Comment:
   **Nit (P3):** The check stops the query only for errors of the classes 
`EXTERNAL_LOOKUP_JOIN_UNSUPPORTED`, `DATA_SOURCE_INVALID_EXTERNAL_LOOKUP` and 
`DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED`; it logs every other planning 
failure and leaves it to the first micro-batch, as its class Scaladoc says. So 
a left outer lookup join with a Python UDF over lookup columns, whose planning 
fails with `UNSUPPORTED_FEATURE.PYTHON_UDF_IN_ON_CLAUSE`, or a lookup table 
whose `newScanBuilder()` throws, starts and fails only at its first 
micro-batch, while this doc says it stops before it.
   
   Suggested fix: say that a planning error of a lookup join or of its 
connector contract stops the query before its first micro-batch, also without 
data, while any other error, such as one that an ordinary join raises too, is 
left to the first micro-batch; and that when the conf is false, those lookup 
join errors also fail the first micro-batch that runs.
   
   **Verification:**
   - **Inspection:** The documentation of the startup check configuration names 
the planning errors that stop a streaming query when it starts, those of the 
lookup join and of its connector contract, says that other errors, such as an 
exception that the connector throws while Spark plans the lookup, still fail 
the first micro-batch, and agrees with the check's class documentation.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,3312 @@
+/*
+ * 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.{CheckExternalLookupJoin, 
FormExternalLookupJoin,
+  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.{Inner, QueryPlan}
+import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, 
ExternalLookupJoin, Join, JoinHint,
+  LeafNode, LogicalPlan, PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.trees.TreePattern.LOOKUP_ONLY_RELATION
+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, PrepareExternalLookupJoin, 
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, UserDefinedType}
+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
+  }
+
+  /** The last two metric reads or closes that the connector's readers saw, in 
order. */
+  private def lastReaderEvents: Seq[String] =
+    SimpleExternalLookupDataSource.readerEvents.asScala.toSeq.takeRight(2)
+
+  /** 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") {

Review Comment:
   **Nit (P3):** This test and 'an external lookup join matches each offered 
key type exactly' are the only ones whose source returns rows that fail a 
selected predicate, and both select a single predicate; the sources that select 
several, the composite-key source and the simple source in its `all` and 
`reversed` modes, filter on all of them themselves. Since the selected 
conjuncts leave the residual, `lookupKeyCheck` is the only place where Spark 
enforces them on returned rows. Reading the code, a check that kept only the 
first comparison, for example `headOption` in place of `reduceOption(And)`, 
would pass every test, while a composite `(tenant, id)` store that ignored `id` 
would join the stream row `(1, 2)` with the stored rows `(1, 1)` and `(1, 3)`.
   
   Suggested fix: add a join test over the composite `(tenant, id)` source in 
which the source selects both predicates but ignores one of them, each in turn, 
when it matches, and check for inner and left outer joins that only the stored 
rows whose tenant and id both match the stream row are joined, and that the 
source did return the rows that Spark dropped.
   
   **Verification:**
   - **Regression:** With a source that selects two lookup predicates but 
ignores the second one when it matches, inner and left outer joins return only 
the stored rows that satisfy both predicates, and the test fails when the 
re-check compares only the first selected predicate.
   - **Behavior:** With the source ignoring each selected predicate in turn, it 
is observed to return rows that fail the ignored predicate, and the join drops 
exactly those rows, so the expected rows come from Spark's check rather than 
from the source.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinStartupCheckSuite.scala:
##########
@@ -0,0 +1,626 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
+
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row, SQLContext}
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.expressions.{CurrentBatchTimestamp, 
CurrentDate,
+  CurrentTimestamp, LocalTimestamp, OuterReference, SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability, TableProvider}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.connector.read.ScanBuilder
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation}
+import 
org.apache.spark.sql.execution.streaming.runtime.{ExternalLookupJoinStartupCheck,
+  MemoryStream, MicroBatchExecution, StreamingQueryCheckpointMetadata, 
StreamingQueryWrapper,
+  StreamingV2ScanPushDown}
+import org.apache.spark.sql.functions.{col, current_timestamp, lit, max}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.{StreamingQuery, StreamingQueryException,
+  StreamingQueryListener}
+import 
org.apache.spark.sql.streaming.StreamingQueryListener.{QueryProgressEvent,
+  QueryStartedEvent, QueryTerminatedEvent}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{DateType, StructType, TimestampNTZType, 
TimestampType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/** Which errors of an external lookup join stop a streaming query when it 
starts. */
+class ExternalLookupJoinStartupCheckSuite extends QueryTest with 
SharedSparkSession {
+  import testImplicits._
+
+  private val queryCount = new AtomicInteger()
+
+  private val timeoutMs = 60000L
+
+  private implicit def sqlContextOfStreams: SQLContext = spark.sqlContext
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    SimpleExternalLookupDataSource.resetCounters()
+    ThrowingScanBuilderTable.scanBuilderCount.set(0)
+  }
+
+  private def lookupOnly: DataFrame =
+    spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+
+  private def throwingStatic: DataFrame =
+    spark.read.format(classOf[ThrowingScanBuilderDataSource].getName).load()
+
+  private def start(df: DataFrame): StreamingQuery =
+    
df.writeStream.format("memory").queryName(s"startup_check_${queryCount.incrementAndGet()}")
+      .start()
+
+  /** The error that `start()` throws for `df`, which analysis reports. */
+  private def startFailure(df: DataFrame): AnalysisException = {
+    val e = intercept[AnalysisException](start(df).stop())
+    // The connector served no lookup at the start.
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    e
+  }
+
+  /**
+   * The error that stops the query of `df` when its execution starts: 
`start()` returns, and the
+   * query stops before it has any data.
+   */
+  private def queryFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val query = start(df)
+    val e = try {
+      intercept[StreamingQueryException](query.awaitTermination(timeoutMs))
+    } finally {
+      query.stop()
+    }
+    assert(query.exception.contains(e))
+    // The connector served no lookup at the start.
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    assert(classTag[T].runtimeClass.isInstance(e.getCause), e.getCause)
+    e.getCause.asInstanceOf[T]
+  }
+
+  /** Waits until `query` has planned its lookup joins and created its 
sources. */
+  private def awaitInitialization(query: StreamingQuery): Unit =
+    
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.awaitInitialization(timeoutMs)
+
+  /** Runs `body`, and returns the warnings that the startup check logged 
meanwhile. */
+  private def startupWarnings(body: => Unit): Seq[String] = {
+    val appender = new LogAppender("the startup check")
+    withLogAppender(
+        appender,
+        loggerNames = 
Seq(ExternalLookupJoinStartupCheck.getClass.getName.stripSuffix("$")),
+        level = Some(Level.WARN)) {
+      body
+    }
+    appender.loggingEvents.map(_.getMessage.getFormattedMessage).toSeq
+  }
+
+  /** Adds `rows` to `input`, and fails unless the first micro-batch of 
`query` fails. */
+  private def firstBatchFailure(
+      query: StreamingQuery,
+      input: MemoryStream[Int],
+      rows: Int*): StreamingQueryException = {
+    try {
+      query.processAllAvailable()
+      assert(query.isActive && query.exception.isEmpty)
+      input.addData(rows)
+      intercept[StreamingQueryException](query.processAllAvailable())
+    } finally {
+      query.stop()
+    }
+  }
+
+  test("an ordinary stream-static join fails at its first micro-batch, not at 
start") {
+    val input = MemoryStream[Int]
+    val stream = input.toDF().toDF("id")
+    val static = throwingStatic
+    val query = start(stream.join(static, stream("id") === static("id")))
+    awaitInitialization(query)
+    // Without data, no micro-batch runs, so the query keeps running.
+    assert(ThrowingScanBuilderTable.scanBuilderCount.get() === 0)
+    val e = firstBatchFailure(query, input, 1)
+    assert(e.getCause.getMessage.contains("The scan builder fails"))
+  }
+
+  test("MISSING_JOIN_CONDITION fails start()") {
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    val lookup = lookupOnly
+    Seq(
+      stream.join(lookup).where(stream("id") === lookup("id")),
+      stream.join(lookup, Seq.empty[String], "left_outer")).foreach { joined =>
+      checkError(
+        exception = startFailure(joined),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+        parameters = Map.empty)
+    }
+    // A USING join gets its condition after its first analysis, so it starts.
+    start(stream.join(lookup, Seq("id"))).stop()
+  }
+
+  test("NO_LOOKUP_CANDIDATE stops the query when it starts, before any data 
arrives") {
+    val stream = MemoryStream[Long].toDF().toDF("id")
+    val lookup = lookupOnly
+    // A BIGINT stream key casts the INT lookup column, so Spark has no 
candidate to offer.
+    checkError(
+      exception = queryFailure[AnalysisException](
+        stream.join(lookup, stream("id") === lookup("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("NO_LOOKUP_PREDICATE stops the query when it starts") {
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    val lookup = lookupOnly
+    checkError(
+      exception = queryFailure[AnalysisException](
+        stream.join(lookup, lookup("department") === "sales")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("connector contract errors stop the query when Spark prepares the 
lookup, not later") {
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    def source(format: Class[_], option: String, value: String): DataFrame =
+      spark.read.format(format.getName).option(option, value).load()
+    val duplicate =
+      source(classOf[SimpleExternalLookupDataSource], "selectionMode", 
"duplicate")
+    checkError(
+      exception = queryFailure[AnalysisException](
+        stream.join(duplicate, stream("id") === duplicate("id"))),
+      condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.DUPLICATE_SELECTED_PREDICATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`", "predicate" 
-> "id = ?"))
+    val noLookup =
+      source(classOf[MisconfiguredExternalLookupDataSource], "kind", 
"noExternalLookup")
+    val e = queryFailure[SparkUnsupportedOperationException](
+      stream.join(noLookup, stream("id") === noLookup("id")))
+    assert(e.getCondition === "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED")
+
+    // A violation found while the join runs is reported by the tasks of a 
micro-batch.
+    val input = MemoryStream[Int]
+    val running = input.toDF().toDF("id")
+    val nullCursor = source(classOf[SimpleExternalLookupDataSource], 
"nullCursor", "true")
+    val query = start(running.join(nullCursor, running("id") === 
nullCursor("id")))
+    val failure = firstBatchFailure(query, input, 1).getMessage
+    
assert(failure.contains("DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.NULL_RESULT"), 
failure)
+    assert(failure.contains("ExternalLookupReader.lookupBatch()"), failure)
+  }
+
+  test("a connector exception while Spark plans the lookup is left to the 
micro-batch") {
+    // Also a SparkThrowable that is not an error of the lookup join or of its 
connector contract.
+    Seq(classOf[ThrowingLookupScanBuilderDataSource],
+        classOf[SparkThrowingLookupScanBuilderDataSource]).foreach { format =>
+      val input = MemoryStream[Int]
+      val stream = input.toDF().toDF("id")
+      val lookup = spark.read.format(format.getName).load()
+      var query: StreamingQuery = null
+      val warnings = startupWarnings {
+        query = start(stream.join(lookup, stream("id") === lookup("id")))
+        awaitInitialization(query)
+      }
+      assert(warnings.exists(_.contains("Could not plan the external lookup 
joins")), format)
+      val e = firstBatchFailure(query, input, 1)
+      assert(e.getCause.getMessage.contains("The scan builder fails"), format)
+    }
+  }
+
+  test("a lookup predicate that the optimizer finds does not stop the query") {
+    val lookup = lookupOnly
+    // The written condition offers no candidate until the optimizer 
simplifies it: also through
+    // date conversions, which the start folds as each micro-batch does.
+    Seq(lit(false), lit("1999-01-01").cast("date") > 
lit("2000-01-01").cast("date")).foreach {
+      never =>
+        val input = MemoryStream[Int]
+        val stream = input.toDF().toDF("id")
+        val joined = stream.join(lookup, stream("id") === lookup("id") || 
never)
+        var query: StreamingQuery = null
+        assert(startupWarnings {
+          query = start(joined.select("department"))
+          awaitInitialization(query)
+        }.isEmpty, never)
+        try {
+          input.addData(1, 3)
+          query.processAllAvailable()
+          checkAnswer(spark.table(query.name), Seq(Row("engineering"), 
Row("research")))
+        } finally {
+          query.stop()
+        }
+    }
+  }
+
+  test("the start reads the current time and date as the batch timestamp, as 
micro-batches do") {
+    val plan = sql("SELECT current_timestamp(), current_date(), 
localtimestamp()")
+      .queryExecution.analyzed
+    val rewritten = MicroBatchExecution.withBatchTimestamp(plan, 1234L)
+    val batchTimestamps = rewritten.expressions.flatMap(_.collect {
+      case timestamp: CurrentBatchTimestamp => timestamp
+    })
+    assert(batchTimestamps.map(t => (t.timestampMs, t.dataType)) ===
+      Seq((1234L, TimestampType), (1234L, DateType), (1234L, 
TimestampNTZType)))
+    assert(rewritten.expressions.forall(_.collect {
+      case _: CurrentTimestamp | _: CurrentDate | _: LocalTimestamp => true
+    }.isEmpty))
+  }
+
+  test("the start plans only the lookup sides") {
+    val input = MemoryStream[Int]
+    val stream = input.toDF().toDF("id")
+    val static = throwingStatic
+    val lookup = lookupOnly
+    val joined = stream.join(static, stream("id") === static("id"))
+      .join(lookup, stream("id") === lookup("id"))
+    val query = start(joined)
+    awaitInitialization(query)
+    assert(ThrowingScanBuilderTable.scanBuilderCount.get() === 0)
+    val e = firstBatchFailure(query, input, 1)
+    assert(e.getCause.getMessage.contains("The scan builder fails"))
+  }
+
+  test("the start keeps correlated subqueries correlated and plans none of 
their tables") {
+    // The stream key has a name that the subqueries cannot resolve, so 
`outer()` references it.
+    def withSubqueries(stream: DataFrame, static: DataFrame): DataFrame = {
+      val keys = static.select(col("id").as("key"))
+      stream
+        .where(keys.where(col("key") === col("sid").outer()).exists())
+        .where(col("sid") <= keys.select(max("key")).scalar())
+    }
+    val lookup = lookupOnly
+    def lookupJoin(stream: DataFrame): DataFrame =
+      stream.join(lookup, stream("sid") === lookup("id"))
+    val joined = 
lookupJoin(withSubqueries(MemoryStream[Int].toDF().toDF("sid"), throwingStatic))
+    val masked = StreamingV2ScanPushDown.forStartup(
+      joined.queryExecution.analyzed, withStartupValues = false)
+    // The placeholder of the column pruning of streaming scans is private to 
it.
+    def isPlaceholder(plan: LogicalPlan): Boolean = plan.nodeName == 
"BatchRelation"
+    val subqueryPlans = masked.flatMap(_.expressions.flatMap(_.collect {
+      case subquery: SubqueryExpression => subquery.plan
+    }))
+    def isCorrelated(plan: LogicalPlan): Boolean =
+      
plan.exists(_.expressions.exists(_.exists(_.isInstanceOf[OuterReference])))
+    // The correlated EXISTS keeps the filter with its outer reference, over a 
placeholder.
+    val Seq(correlated) = subqueryPlans.filter(isCorrelated)
+    assert(correlated.collectLeaves().forall(isPlaceholder))
+    // The plan of the uncorrelated scalar subquery is one placeholder.
+    assert(subqueryPlans.filterNot(isCorrelated).map(isPlaceholder) === 
Seq(true))
+    // Only the lookup side keeps its table.
+    assert(masked.collectWithSubqueries {
+      case relation @ (_: DataSourceV2Relation | _: ExternalLookupRelation) => 
relation
+    }.length === 1)
+
+    // The start plans the lookup join through the subqueries, without their 
scans.
+    val bigintStream = MemoryStream[Long].toDF().toDF("sid")
+    checkError(
+      exception = queryFailure[AnalysisException](
+        lookupJoin(withSubqueries(bigintStream, throwingStatic))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+    assert(ThrowingScanBuilderTable.scanBuilderCount.get() === 0)
+
+    val input = MemoryStream[Int]
+    val valid = lookupJoin(withSubqueries(input.toDF().toDF("sid"), Seq(1, 
2).toDF("id")))
+      .select("department")
+    var query: StreamingQuery = null
+    assert(startupWarnings {
+      query = start(valid)
+      awaitInitialization(query)
+    }.isEmpty)
+    try {
+      input.addData(1, 3)
+      query.processAllAvailable()
+      checkAnswer(spark.table(query.name), Seq(Row("engineering"), 
Row("research")))
+    } finally {
+      query.stop()
+    }
+  }
+
+  test("foreachBatch and toTable stop the query when it starts too") {
+    val stream = MemoryStream[Long].toDF().toDF("id")
+    val lookup = lookupOnly
+    val joined = stream.join(lookup, stream("id") === lookup("id"))
+      .select(stream("id"), lookup("department"))
+    def failure(query: StreamingQuery): String = try {
+      intercept[StreamingQueryException](query.awaitTermination(timeoutMs))
+        .getCause.asInstanceOf[AnalysisException].getCondition
+    } finally {
+      query.stop()
+    }
+    assert(failure(joined.writeStream.foreachBatch((_: DataFrame, _: Long) => 
()).start()) ===
+      "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE")
+    withTempDir { dir =>
+      withTable("startup_check_sink") {
+        val query = joined.writeStream.option("checkpointLocation", 
dir.getCanonicalPath)
+          .toTable("startup_check_sink")
+        assert(failure(query) === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE")
+      }
+    }
+  }
+
+  test("the start plans with the confs that the offset log pins for a 
restarted query") {
+    val policy = SQLConf.STREAMING_MULTIPLE_WATERMARK_POLICY
+    withTempDir { dir =>
+      val checkpoint = dir.getCanonicalPath
+      val input = MemoryStream[Int]
+      val stream = input.toDF().toDF("id")
+      val lookup = lookupOnly
+      val joined = stream.join(lookup, stream("id") === lookup("id"))
+      // The query thread passes the last entry of the offset log, which it 
reads anyway.
+      def startupConf(): SQLConf = 
ExternalLookupJoinStartupCheck.startupConf(spark,
+        new StreamingQueryCheckpointMetadata(spark, checkpoint, readOnly = 
true)
+          .offsetLog.getLatest().flatMap(_._2.metadataOpt))
+      withSQLConf(policy.key -> "max", SQLConf.CBO_ENABLED.key -> "true") {
+        // A new query plans with the session's values, without CBO.
+        assert(startupConf().getConf(policy) === "max")
+        assert(startupConf().getConf(SQLConf.CBO_ENABLED) === false)
+        val query = 
joined.writeStream.format("memory").queryName("startup_check_restarted")
+          .option("checkpointLocation", checkpoint).start()
+        try {
+          input.addData(1)
+          query.processAllAvailable()
+        } finally {
+          query.stop()
+        }
+      }
+      withSQLConf(policy.key -> "min") {
+        assert(startupConf().getConf(policy) === "max")
+        assert(spark.conf.get(policy) === "min")
+      }
+    }
+  }
+
+  test("start() returns while a planning call to the lookup connector blocks") 
{
+    BlockingLookupTable.reset()
+    val input = MemoryStream[Int]
+    val stream = input.toDF().toDF("id")
+    val lookup = 
spark.read.format(classOf[BlockingLookupDataSource].getName).load()
+    val query = start(stream.join(lookup, stream("id") === 
lookup("id")).select("department"))
+    try {
+      // start() has returned, and the query thread is in the call, which 
waits to be released.
+      assert(BlockingLookupTable.entered.get().await(timeoutMs, 
TimeUnit.MILLISECONDS))
+      assert(query.isActive && query.exception.isEmpty)

Review Comment:
   **Nit (P3):** Neither assertion depends on which thread runs the planning: 
`BlockingLookupTable.newScanBuilder` returns after its 60-second wait whether 
or not the test released it, and nothing builds a scan before the planning 
does. Reading the code, if the startup check ran in the thread that calls 
`start()`, as an earlier revision of this PR did, `start()` would block until 
the wait ran out and then return, `entered` would already be counted down and 
the query active, and the test would pass about a minute late, well within the 
per-test timeout.
   
   Suggested fix: have `BlockingLookupTable` record when `newScanBuilder` 
returns, and assert, once `entered` is counted down, that it has not returned 
yet, before the test releases it.
   
   **Verification:**
   - **Regression:** If the startup planning ran in the thread that calls 
start(), the test would fail, because the blocked planning call would already 
have returned, after its wait ran out, when start() returns.
   - **Behavior:** With the planning in the query thread, start() returns while 
the connector's planning call is still blocked, the query stays active without 
an error, and after the call is released the query returns the joined rows.



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