HeartSaVioR commented on code in PR #59910: URL: https://github.com/apache/spark/pull/59910#discussion_r4420108270
########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,410 @@ +/* + * 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 + +import scala.collection.mutable + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkIllegalStateException, + TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, CollationKey, Expression, + GenericInternalRow, JoinedRow, Predicate, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.optimizer.NormalizeFloatingNumbers +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter} +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReader, ExternalLookupReaderFactory, + ExternalLookupResultCursor} +import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric} +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. + */ +class ExternalLookupJoinEvaluatorFactory( + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + streamOutput: Seq[Attribute], + lookupOutput: Seq[Attribute], + output: Seq[Attribute], + joinType: JoinType, + residualCondition: Option[Expression], + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + 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 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, joinOutput, reader) + inputExhausted = !input.hasNext + } + if (inputExhausted && !batch.hasNext) reader.close() + } + + private def readBatch(): Seq[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + while (rows.length < maxParameterRowsPerRequest && input.hasNext) { + rows += input.next().copy() + } + rows.toSeq + } + } + + /** 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 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: Seq[InternalRow], + parameters: LookupParameters, + joinOutput: JoinOutput, + reader: LookupReader) extends Iterator[InternalRow] { + metrics.inputRows += rows.size + metrics.inputBatches += 1 + + private val matched = Array.fill(rows.length)(false) + private val finished = mutable.BitSet.empty + // Output rows not yet returned: a stream row index and the lookup row it is joined with. + private val pending = mutable.Queue.empty[(Int, InternalRow)] + + // One entry for each distinct key that can match, in the order of first occurrence. A row + // that can never match is finished right away, and its key is not requested. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + val key = parameters.key(rows(index)) + if (parameters.matchesNothing(key)) { + finish(index) + } else { + keyEntries.get(key) match { + case Some(entry) => entry.rowIndexes += index + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + private val requestedKeys = keyEntries.keys.toArray + + private val lookupStartNanos = System.nanoTime() + // No connector request, and no reader, when no key can match. + private var cursor: ExternalLookupResultCursor = + if (keyEntries.isEmpty) EmptyLookupCursor + else reader.lookup(keyEntries.values.map(_.requestRow).toArray) + + override def hasNext: Boolean = { + tryFillPending() + pending.nonEmpty + } + + override def next(): InternalRow = { + tryFillPending() + if (pending.isEmpty) throw new NoSuchElementException("external lookup result") + val (index, lookupRow) = pending.dequeue() + joinOutput.project(rows(index), lookupRow) + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryFillPending(): Unit = { + try { + while (pending.isEmpty && cursor.next()) { + reader.resultRowRead() + val key = requestedKey(cursor.inputOrdinal()) + // The connector may reuse its row, and several stream rows can join it. + joinResultRow(key, cursor.get().copy()) + } + if (pending.isEmpty) finishCursor() + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor() + } + } + } + + private def requestedKey(ordinal: Int): UnsafeRow = { + if (ordinal < 0 || ordinal >= requestedKeys.length) { + throw new SparkIllegalStateException( + errorClass = "INTERNAL_ERROR", + messageParameters = Map("message" -> + (s"External lookup returned invalid input ordinal $ordinal for " + + s"${requestedKeys.length} requested parameter rows"))) + } + requestedKeys(ordinal) + } + + private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit = + keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow)) + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + if (joinOutput.matches(rows(index), lookupRow)) { + matched(index) = true + joinOutput.matched(lookupRow).foreach(emit(index, _)) + } + } + + /** Closes the cursor once, and finishes every stream row that was waiting for its results. */ + private def finishCursor(): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + try { + reader.closeCursor() + } finally { + metrics.lookupTime += System.nanoTime() - lookupStartNanos + reader.updateMetrics() + } + keyEntries.values.foreach(_.rowIndexes.foreach(finish)) + } + + private def finish(index: Int): Unit = if (!finished.contains(index)) { + finished += index + if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _)) + } + + private def emit(index: Int, lookupRow: InternalRow): Unit = { + pending.enqueue(index -> lookupRow) + metrics.outputRows += 1 + } + } + + /** The cursor of a batch that sends no request, or whose cursor is finished. */ + private object EmptyLookupCursor extends ExternalLookupResultCursor { + override def next(): Boolean = false + override def inputOrdinal(): Int = throw new NoSuchElementException("external lookup result") + override def get(): InternalRow = throw new NoSuchElementException("external lookup result") + override def close(): Unit = {} + } + + /** + * Evaluates the lookup parameters of stream rows: the request row that is sent to the + * connector, and the key that identifies equal parameters under Spark equality, which + * normalizes floating-point values and collations. + */ + private class LookupParameters(partitionIndex: Int) { + private val requestProjection = UnsafeProjection.create(lookupParameters, streamOutput) + private val keyProjection = UnsafeProjection.create(lookupParameters.map { parameter => + NormalizeFloatingNumbers.normalize(CollationKey.injectCollationKey(parameter)) + }, streamOutput) + requestProjection.initialize(partitionIndex) + keyProjection.initialize(partitionIndex) + + def requestRow(streamRow: InternalRow): UnsafeRow = requestProjection(streamRow).copy() + + /** The key of a stream row, in a reused row: copy it to retain it. */ + def key(streamRow: InternalRow): UnsafeRow = keyProjection(streamRow) + + /** + * A null parameter that is not null-safe matches no lookup row, so it is not requested. + * The key has the request row's nulls. + */ + def matchesNothing(key: InternalRow): Boolean = + nullSafeParameters.indices.exists { index => + !nullSafeParameters(index) && key.isNullAt(index) + } + } + + /** Evaluates the residual condition on joined rows and builds output rows per join type. */ + private class JoinOutput(partitionIndex: Int) { + private val joinedLookupOutput = + if (joinType == LeftOuter) lookupOutput.map(_.withNullability(true)) else lookupOutput + private val joinedInput = streamOutput ++ joinedLookupOutput + private val joinedRow = new JoinedRow() + private val residual = residualCondition.map(Predicate.create(_, joinedInput)) + private val projection = UnsafeProjection.create(output, joinedInput) + private val nullLookupRow = new GenericInternalRow(lookupOutput.length) + residual.foreach(_.initialize(partitionIndex)) + projection.initialize(partitionIndex) + + def matches(streamRow: InternalRow, lookupRow: InternalRow): Boolean = + residual.forall(_.eval(joinedRow(streamRow, lookupRow))) + + /** The lookup row that the output for a match joins, if the join type emits one. */ + def matched(lookupRow: InternalRow): Option[InternalRow] = joinType match { + case Inner | LeftOuter => Some(lookupRow) + case _ => None + } + + /** The lookup row that the output for a stream row without a match joins, if any. */ + def unmatched: Option[InternalRow] = joinType match { + case LeftOuter => Some(nullLookupRow) + case _ => None + } + + /** The output row, projected into a reused row. */ + def project(streamRow: InternalRow, lookupRow: InternalRow): InternalRow = + projection(joinedRow(streamRow, lookupRow)) + } + + /** + * The connector reader of one partition and its active cursor. The reader is opened by the + * first request, and closed once, after the last batch or when the task completes. + */ + private class LookupReader { + private val taskReaders = readerMetrics.forCurrentTask() + private val closed = new AtomicBoolean(false) + private var reader: ExternalLookupReader = null + private var activeCursor: ExternalLookupResultCursor = null + private var resultRowsSinceMetricsUpdate = 0 + Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => close())) + + /** Sends one request and returns the cursor over its result rows. */ + def lookup(requestRows: Array[UnsafeRow]): ExternalLookupResultCursor = { 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. A correction to my earlier reply, which claimed more than the code guaranteed. After the task-completion close, `lookup()` failed, but a helper thread still consuming the join could keep advancing the open cursor. A close that landed while that thread was creating the reader also missed the new reader: the thread then sent a request on it, and the reader was never closed. And `close()` can overlap a call that thread already has in progress. In [3363f1b75c7](https://github.com/apache/spark/commit/3363f1b75c7bdfd5597ac41ab4147a2ff11a4ff0), the join checks the reader's closed flag before every request and every cursor advance, and fails the same way. The reader and the active cursor are each taken by exactly one closer, so neither is closed twice. A reader created while the close ran is closed before any request is sent on it, and a cursor returned by a request the close interrupted is closed when the join fails right after. What is now guaranteed, as `ExternalLookupReader` documents since [11ca7a2f59e](https://github.com/apache/spark/commit/11ca7a2f59e8f68003dd5415db4e68f50fc2d21d) in #59908: when the task ends, `close()` on the reader and on its open cursor may overlap the one call already in progress on another thread. Spark starts no new call after the close, and every reader and cursor it obtained is closed, even when the close lands while a reader is being created or a request is in flight. There is still no lock. A synchronized close would make task completion wait for a slow or hung connector call, which is worse than the one overlapping call the contract allows. `DataSourceRDD` does not lock its readers against the completion listener either. The post-close test now also completes the task while the reader is being created, while the request is in flight, and between the two result rows of one request. In each case it checks that a consumer on another thread fails without a new request, cursor advance or reader, and that every reader and cursor is closed. -- 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]
