spark-test commented on code in PR #60019:
URL: https://github.com/apache/spark/pull/60019#discussion_r4509901831
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/TableCapabilityCheck.scala:
##########
@@ -73,6 +84,16 @@ object TableCapabilityCheck extends (LogicalPlan => Unit) {
case _ => // OK
}
+ // A command may drop, truncate or replace its target before it optimizes
its query, where
+ // PrepareExternalLookupJoin would reject a lookup-only table that no
lookup join reads. So a
+ // command whose query reads one outside a lookup join fails here, during
analysis. A view
+ // definition stores its query without reading it, for a lookup join that
reads the view.
+ plan.foreach {
Review Comment:
**Blocking (P1):** This second `plan.foreach` runs on every analyzed plan,
because TableCapabilityCheck is an extended check rule and `checkAnalysis0`
also applies it to every subquery plan. So every query without a command, such
as any SELECT, DataFrame or streaming plan, now pays one more full plan
traversal during analysis, which master does not. `Command.nodePatterns` is
final and always includes `COMMAND`, and `foreach` visits only children, whose
pattern bits roll up to the root. Wrapping the walk in `if
(plan.containsPattern(COMMAND))` therefore gives the same result and skips it
for those plans. The cost per query is small, but every query pays it,
including queries that never touch an external lookup table.
**Verification:**
- **Regression:** A command whose query reads a lookup-only table outside a
lookup join, including inside a subquery, still fails during analysis with the
same error.
- **Behavior:** Temporary and persistent view definitions over a lookup-only
table are still accepted.
- **Inspection:** The command walk is skipped for plans that do not contain
the COMMAND tree pattern.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,666 @@
+/*
+ * 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 java.util.concurrent.locks.LockSupport
+
+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, CollationKey,
Expression,
+ GenericInternalRow, JoinedRow, Predicate, SpecializedGetters,
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.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}
+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 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 takes one row.
+ private def readBatch(): Array[InternalRow] = {
+ val rows = mutable.ArrayBuffer.empty[InternalRow]
+ var bytes = 0L
+ while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes
&& input.hasNext) {
+ val row = input.next() match {
+ case unsafe: UnsafeRow => unsafe.copy()
+ case other => toUnsafe(other).copy()
+ }
+ bytes += row.getSizeInBytes
+ rows += row
+ }
+ 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 key 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 key is not requested. The stream condition
is checked before
+ // the key is computed, so that it can guard the parameter expressions.
+ private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+ rows.indices.foreach { index =>
+ lazy val key = parameters.key(rows(index))
+ if (!joinOutput.canMatch(rows(index)) || 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
+
+ // No connector request, and no reader, when no key can match. The
connector gets copies of
+ // the request rows, so that the ones that Spark checks the results
against stay its own.
+ private var cursor: ExternalLookupResultCursor =
+ if (keyEntries.isEmpty) EmptyLookupCursor
+ else
connectorCall(reader.lookup(keyEntries.values.map(_.requestRow.copy()).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 && advanceCursor()) {
+ reader.resultRowRead()
+ // A close() during either call fails the read before Spark copies
or joins the row.
+ val start = System.nanoTime()
+ val ordinal = cursor.inputOrdinal()
+ reader.ensureOpen()
+ val connectorRow = cursor.get()
+ metrics.lookupTime += System.nanoTime() - start
+ if (connectorRow == null) {
+ throw QueryExecutionErrors.invalidDataSourceExternalLookupError(
+ tableName, "NULL_RESULT_ROW")
+ }
+ val key = requestedKey(ordinal)
+ val resultRow =
reader.copyRow(resultRows.validatedCopy(connectorRow))
+ if (parameters.selectedPredicatesHold(keyEntries(key).requestRow,
resultRow)) {
Review Comment:
**Nit (P3):** `requestedKey(ordinal)` already identifies the entry, because
`requestedKeys` and the request rows come from the same insertion-ordered
`keyEntries` map. Yet each returned row is looked up twice by `UnsafeRow` key,
here and again in `joinResultRow` (line 279), and each lookup re-hashes and
compares the key bytes. Keeping the entries in an array in request order, with
the same `INVALID_INPUT_ORDINAL` bounds check, and passing the entry to
`joinResultRow` gives the same output without any hashing. The cost per row is
small next to the request, but it grows with the number of result rows.
**Verification:**
- **Regression:** Lookup joins with repeated stream keys, residual
conditions and out-of-range ordinals produce the same rows and errors as before.
- **Inspection:** The per-result-row path resolves the key entry by array
index only.
--
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]