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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,762 @@
+/*
+ * 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, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupProject,
+  ExternalLookupTransform}
+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, and with `oneKeyPerBatch`, of stream rows that share one key. 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],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    oneKeyPerBatch: Boolean,
+    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 transforms = new LookupTransforms(partitionIndex)
+    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, transforms, joinOutput, reader)
+        }
+        inputExhausted = !hasInput
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // An inner or left semi 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 or left 
anti join emits it, so a
+    // batch keeps it.
+    private val keepsRowsThatCannotMatch = joinType != Inner && joinType != 
LeftSemi
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes stream
+    // rows of one key. It ends before the first row with another key, which 
starts the next batch.
+    // A row that cannot match has no key, and any batch that keeps it takes 
it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    /** The next row that a batch keeps, copied, or null after a row that it 
leaves out. */
+    private def nextKeptRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      val next = input.next()
+      if (keepsRowsThatCannotMatch || requestRowOf(next) != null) {
+        next match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+      } else {
+        metrics.inputRows += 1
+        null
+      }
+    }
+
+    /** The request row of a stream row that can match, in a reused row, or 
null. */
+    private def requestRowOf(row: InternalRow): UnsafeRow =
+      if (!joinOutput.canMatch(row)) null else {
+        val requestRow = parameters.requestRow(row)
+        if (parameters.matchesNothing(requestRow)) null else requestRow
+      }
+
+    // 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, and at 
maxParameterRowsPerRequest rows, also
+    // with one key per batch, where it stops at another key too. It always 
keeps one row, when one
+    // remains.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      var batchKey: UnsafeRow = null
+      var keyChanged = false
+      while (!keyChanged && rows.length < maxParameterRowsPerRequest &&

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.
   
   No, there wasn't. Fixed in 
[2d8550bbec1](https://github.com/apache/spark/commit/2d8550bbec115caab7bae3c3f9ac22142210bac8):
 a batch of one key is now capped only at 1000 rows and `maxBatchBytes`, since 
its request holds one parameter row whatever the source's limit. Ordinary 
batches keep the source's limit. The test that pinned the old cap now expects 
one request for five equal range keys with a source limit of 1 or 2, and two 
requests for 1,500.
   
   On the cache: range lookups skip it by design, whatever the source's limit. 
When a selected range reads a stream column, the join caches nothing, because 
range values such as event times rarely repeat, as #60087's description says. 
The range-cache test in #60087 had a comment that this change made wrong. 
[bdc7d0a8efb](https://github.com/apache/spark/commit/bdc7d0a8efbbad0a42da8b88de63dddd4f55eb56)
 fixes it, and checks that two equal range keys in a row share one request 
while nothing is cached.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,762 @@
+/*
+ * 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, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupProject,
+  ExternalLookupTransform}
+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, and with `oneKeyPerBatch`, of stream rows that share one key. 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],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    oneKeyPerBatch: Boolean,
+    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 transforms = new LookupTransforms(partitionIndex)
+    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, transforms, joinOutput, reader)
+        }
+        inputExhausted = !hasInput
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // An inner or left semi 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 or left 
anti join emits it, so a
+    // batch keeps it.
+    private val keepsRowsThatCannotMatch = joinType != Inner && joinType != 
LeftSemi
+
+    // When a request holds one parameter row because of a selected range, a 
batch takes stream
+    // rows of one key. It ends before the first row with another key, which 
starts the next batch.
+    // A row that cannot match has no key, and any batch that keeps it takes 
it.
+    private var heldRow: UnsafeRow = null
+
+    private def hasInput: Boolean = heldRow != null || input.hasNext
+
+    /** The next row that a batch keeps, copied, or null after a row that it 
leaves out. */
+    private def nextKeptRow(): UnsafeRow = if (heldRow != null) {
+      val row = heldRow
+      heldRow = null
+      row
+    } else {
+      val next = input.next()
+      if (keepsRowsThatCannotMatch || requestRowOf(next) != null) {

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.
   
   Done in 
[2d8550bbec1](https://github.com/apache/spark/commit/2d8550bbec115caab7bae3c3f9ac22142210bac8):
 `nextKeptRow` computes a row's request row once and hands it to `readBatch`. A 
batch of one key also passes it on to `keyEntries`, so it is computed once per 
row for every join type. Ordinary batches of inner and semi joins still compute 
it again in `keyEntries`, because passing it on would mean copying each row's 
request row.
   



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