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


##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[cd9a68fd105](https://github.com/apache/spark/commit/cd9a68fd105e0f772b2b06873d5f2ca6a245ff7d).
 The blocking table now records when its planning call returns, and the test 
asserts that `start()` returns while that call still blocks. Running the 
startup check in the thread that calls `start()` fails the test.
   



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

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Agreed, thanks. I'll do that as a follow-up: a left outer join emits a row 
that cannot match, padded with nulls, as soon as it reads it, so the row takes 
no place in a batch and today's memory bound holds. I've added it to ยง7 of the 
[design 
document](https://gist.github.com/HeartSaVioR/0143cdaad3079d1455be8004ee401ec4).
 It also helps real-time mode, where such a row now waits for its batch to fill.
   



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