viirya commented on code in PR #60055: URL: https://github.com/apache/spark/pull/60055#discussion_r4532217311
########## 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: With one key per batch, every row shares one parameter row, so the source's `maxParameterRowsPerRequest` no longer limits the request, yet it still caps the batch here (`requests(5, "2") === Seq(1, 1, 1)`). A source that declares 1 goes back to one request per stream row for equal range keys, and range lookups skip the cache. The 1000 cap and `maxBatchBytes` already bound what the task buffers. Is there a reason to keep the source's limit for these batches? ########## 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: nit: with one key per batch, an inner or semi join computes `requestRowOf` for a row three times: here, again in `readBatch`, and again for `keyEntries`. Outer and anti joins compute it twice. Could `nextKeptRow` hand its request row back to `readBatch`? -- 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]
