viirya commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4515369757
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,193 @@ +/* + * 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.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries" + private val CACHE_TTL_OPTION = "cache_ttl" + private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key" + private val SUPPORTED_OPTIONS = Set( + CACHE_ENABLED_OPTION, + CACHE_MAX_ENTRIES_OPTION, + CACHE_TTL_OPTION, + CACHE_MAX_ROWS_PER_KEY_OPTION) + private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 5s, or 10m" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = defaultCacheOptions + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case Literal(value: String, _) => addString(value) + case attr: UnresolvedAttribute => + relationNames += attr.nameParts + case other => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other))) + } + relationNames.diff(relationNames.distinct).headOption.foreach { duplicate => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "DUPLICATE_RELATION", Map("relation" -> toSQLId(duplicate))) + } + + if (relationNames.isEmpty) { + ExternalLookupHint(child, cacheOptions) Review Comment: Without a relation name the marker lands above the join, where `lookupHints` never sees it. So `SELECT /*+ EXTERNAL_LOOKUP('cache_enabled=false') */ ... FROM l JOIN lookup r` keeps the cache on with no error, as does `l.join(r, ...).hint("external_lookup", "cache_enabled=false")`. Ignoring a bare hint is harmless, but this drops an explicit freshness request. Could `CheckExternalLookupJoin` reject a marker with explicit options over a join? The marker would need to keep only the options the user set, which would also stop `.hint()` from freezing the unset ones from the session conf at hint time. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,819 @@ +/* + * 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, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} +import java.util.concurrent.locks.LockSupport + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder} + +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, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + 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} +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 + * are not cached, and streams the connector's result rows into output rows. Parameters are + * deduplicated within a batch. With the cache enabled, a key whose complete result an earlier + * request of the same input partition returned is served from the cache, within the cache's + * bounds; otherwise 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, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + 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 val cache = if (cacheOptions.enabled) Some(new LookupCache) else None + 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, cache, 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]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[InternalRow], 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, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + 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. A key is classified + // once, on its first occurrence, as a cache hit or a key to request: every path fans out to + // all the rows sharing the key, so a key must not be both, e.g. across a TTL boundary. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + 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).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => cache.flatMap(_.get(key)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(key.copy(), CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + } + private val requestedKeys = keyEntries.keys.toArray Review Comment: No test has a batch mixing hits and misses, the usual case once `maxBatchSize > 1`. Changing this to `(cachedKeys.keys ++ keyEntries.keys).toArray` leaves the whole suite green. Could you add one across the join types, asserting `requestSizes` and `requestedKeys`? ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,193 @@ +/* + * 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.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries" + private val CACHE_TTL_OPTION = "cache_ttl" + private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key" + private val SUPPORTED_OPTIONS = Set( + CACHE_ENABLED_OPTION, + CACHE_MAX_ENTRIES_OPTION, + CACHE_TTL_OPTION, + CACHE_MAX_ROWS_PER_KEY_OPTION) + private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 5s, or 10m" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = defaultCacheOptions + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case Literal(value: String, _) => addString(value) Review Comment: This looks unreachable: string literals hold `UTF8String`, matched on the line above, and `Literal("x", StringType)` fails validation. Can it be dropped? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,819 @@ +/* + * 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, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} +import java.util.concurrent.locks.LockSupport + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder} + +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, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + 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} +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 + * are not cached, and streams the connector's result rows into output rows. Parameters are + * deduplicated within a batch. With the cache enabled, a key whose complete result an earlier + * request of the same input partition returned is served from the cache, within the cache's + * bounds; otherwise 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, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + 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 val cache = if (cacheOptions.enabled) Some(new LookupCache) else None + 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, cache, 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]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[InternalRow], 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, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + 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. A key is classified + // once, on its first occurrence, as a cache hit or a key to request: every path fans out to + // all the rows sharing the key, so a key must not be both, e.g. across a TTL boundary. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + 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).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => cache.flatMap(_.get(key)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(key.copy(), CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + } + private val requestedKeys = keyEntries.keys.toArray + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) + finish(index) + } + } + + private val cacheWriter = cache.map(new CacheWriter(_, requestedKeys)) + + // 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", Map("method" -> "ExternalLookupResultCursor.get()")) + } + val key = requestedKey(ordinal) + val resultRow = reader.copyRow(resultRows.validatedCopy(connectorRow)) + if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, resultRow)) { + // The lookup-side stages reuse their output row, and several stream rows can join it. + transforms(resultRow).foreach { transformed => + val lookupRow = transformed.copy() + cacheWriter.foreach(_.add(key, lookupRow)) + joinResultRow(key, lookupRow) + } + } + } + if (pending.isEmpty) finishCursor(completed = true) + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor(completed = false) + } + } + } + + /** + * Advances the connector's cursor, unless the reader was closed meanwhile. A close() while + * next() ran fails the read once next() returns: Spark then reads no row from the closed + * cursor, and does not take a missing row for a complete result. + */ + private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && { + reader.ensureOpen() + val advanced = connectorCall(cursor.next()) + reader.ensureOpen() + advanced + } + + /** + * Runs a connector call and adds its time to the lookup time metric, which counts only the + * time in the connector, not that of the work above the join while a cursor is open. + */ + private def connectorCall[T](call: => T): T = { + val start = System.nanoTime() + try call finally metrics.lookupTime += System.nanoTime() - start + } + + private def requestedKey(ordinal: Int): UnsafeRow = { + if (ordinal < 0 || ordinal >= requestedKeys.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> requestedKeys.length.toString)) + } + requestedKeys(ordinal) + } + + private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit = + keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow)) + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + // A semi or anti join knows a stream row's answer at its first match, so it evaluates the + // residual condition no further for that row, as the other join operators do. It still + // reads the whole result, for the other stream rows of the key. + if (!(joinOutput.answeredByFirstMatch && matched(index)) && + joinOutput.matches(rows(index), lookupRow)) { + val firstMatch = !matched(index) + matched(index) = true + joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _)) + } + } + + /** + * Closes the cursor once. After a complete read, caches the results and finishes every stream + * row that was waiting for them. After a failure or a close, the results may be partial, so it + * caches nothing and finishes no row: a row without a match could be a row whose match was + * never read. A failure fails the task, which discards the cache, and the join never retries a + * request. Once the reader is closed, its close owns the cursor and the reader's metrics, so + * the join makes no further connector call. + */ + private def finishCursor(completed: Boolean): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + if (!reader.isClosed) { + try { + connectorCall(reader.closeCursor()) + } finally { + reader.updateMetrics() + } + } + if (completed) { + cacheWriter.foreach(_.write()) + 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 lookup results by key, within a task, per input partition (a task that reads several input + * partitions, e.g. after coalesce, has one cache per partition). Beyond `maxEntries` keys, the + * least recently used entry is evicted; an entry expires once it is older than the TTL. + */ + private class LookupCache { + // One segment, so that eviction is exactly least recently used. + private val entries: Cache[UnsafeRow, Array[InternalRow]] = { + val builder = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumSize(cacheOptions.maxEntries) + .ticker(new Ticker { + override def read(): Long = ExternalLookupJoinExec.cacheClock.nanoTime() + }) + val expiring = if (cacheOptions.ttlMillis > 0) { + builder.expireAfterWrite(cacheOptions.ttlMillis, TimeUnit.MILLISECONDS) + } else { + builder + } + expiring.build[UnsafeRow, Array[InternalRow]]() + } + + def get(key: UnsafeRow): Option[Array[InternalRow]] = Option(entries.getIfPresent(key)) + + def put(key: UnsafeRow, values: Array[InternalRow]): Unit = entries.put(key.copy(), values) Review Comment: nit: the keys are already the batch's own copies, so this `copy()` can go. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,819 @@ +/* + * 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, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} +import java.util.concurrent.locks.LockSupport + +import scala.collection.mutable + +import com.google.common.base.Ticker +import com.google.common.cache.{Cache, CacheBuilder} + +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, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + 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} +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 + * are not cached, and streams the connector's result rows into output rows. Parameters are + * deduplicated within a batch. With the cache enabled, a key whose complete result an earlier + * request of the same input partition returned is served from the cache, within the cache's + * bounds; otherwise 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, + maxBatchBytes: Long, + cacheOptions: ExternalLookupCacheOptions, + 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 val cache = if (cacheOptions.enabled) Some(new LookupCache) else None + 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, cache, 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]) + + /** The stream rows that share a key, and the cached lookup rows that they join. */ + private case class CachedKey(lookupRows: Array[InternalRow], 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, + transforms: LookupTransforms, + joinOutput: JoinOutput, + cache: Option[LookupCache], + 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. A key is classified + // once, on its first occurrence, as a cache hit or a key to request: every path fans out to + // all the rows sharing the key, so a key must not be both, e.g. across a TTL boundary. + private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey] + 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).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes)) match { + case Some(rowIndexes) => rowIndexes += index + case None => cache.flatMap(_.get(key)) match { + case Some(lookupRows) => + metrics.cacheHits += 1 + cachedKeys.put(key.copy(), CachedKey(lookupRows, mutable.ArrayBuffer(index))) + case None => keyEntries.put( + key.copy(), + KeyEntry(parameters.requestRow(rows(index)), mutable.ArrayBuffer(index))) + } + } + } + } + private val requestedKeys = keyEntries.keys.toArray + cachedKeys.values.foreach { cached => + cached.rowIndexes.foreach { index => + cached.lookupRows.foreach(joinMatch(index, _)) + finish(index) + } + } + + private val cacheWriter = cache.map(new CacheWriter(_, requestedKeys)) + + // 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", Map("method" -> "ExternalLookupResultCursor.get()")) + } + val key = requestedKey(ordinal) + val resultRow = reader.copyRow(resultRows.validatedCopy(connectorRow)) + if (parameters.selectedPredicatesHold(keyEntries(key).requestRow, resultRow)) { + // The lookup-side stages reuse their output row, and several stream rows can join it. + transforms(resultRow).foreach { transformed => + val lookupRow = transformed.copy() + cacheWriter.foreach(_.add(key, lookupRow)) + joinResultRow(key, lookupRow) + } + } + } + if (pending.isEmpty) finishCursor(completed = true) + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor(completed = false) + } + } + } + + /** + * Advances the connector's cursor, unless the reader was closed meanwhile. A close() while + * next() ran fails the read once next() returns: Spark then reads no row from the closed + * cursor, and does not take a missing row for a complete result. + */ + private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && { + reader.ensureOpen() + val advanced = connectorCall(cursor.next()) + reader.ensureOpen() + advanced + } + + /** + * Runs a connector call and adds its time to the lookup time metric, which counts only the + * time in the connector, not that of the work above the join while a cursor is open. + */ + private def connectorCall[T](call: => T): T = { + val start = System.nanoTime() + try call finally metrics.lookupTime += System.nanoTime() - start + } + + private def requestedKey(ordinal: Int): UnsafeRow = { + if (ordinal < 0 || ordinal >= requestedKeys.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> requestedKeys.length.toString)) + } + requestedKeys(ordinal) + } + + private def joinResultRow(key: UnsafeRow, lookupRow: InternalRow): Unit = + keyEntries(key).rowIndexes.foreach(joinMatch(_, lookupRow)) + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + // A semi or anti join knows a stream row's answer at its first match, so it evaluates the + // residual condition no further for that row, as the other join operators do. It still + // reads the whole result, for the other stream rows of the key. + if (!(joinOutput.answeredByFirstMatch && matched(index)) && + joinOutput.matches(rows(index), lookupRow)) { + val firstMatch = !matched(index) + matched(index) = true + joinOutput.matched(lookupRow, firstMatch).foreach(emit(index, _)) + } + } + + /** + * Closes the cursor once. After a complete read, caches the results and finishes every stream + * row that was waiting for them. After a failure or a close, the results may be partial, so it + * caches nothing and finishes no row: a row without a match could be a row whose match was + * never read. A failure fails the task, which discards the cache, and the join never retries a + * request. Once the reader is closed, its close owns the cursor and the reader's metrics, so + * the join makes no further connector call. + */ + private def finishCursor(completed: Boolean): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + if (!reader.isClosed) { + try { + connectorCall(reader.closeCursor()) + } finally { + reader.updateMetrics() + } + } + if (completed) { + cacheWriter.foreach(_.write()) + 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 lookup results by key, within a task, per input partition (a task that reads several input + * partitions, e.g. after coalesce, has one cache per partition). Beyond `maxEntries` keys, the + * least recently used entry is evicted; an entry expires once it is older than the TTL. + */ + private class LookupCache { + // One segment, so that eviction is exactly least recently used. + private val entries: Cache[UnsafeRow, Array[InternalRow]] = { + val builder = CacheBuilder.newBuilder() + .concurrencyLevel(1) + .maximumSize(cacheOptions.maxEntries) Review Comment: The default-on worst case is 1000 x 100 = 100k rows per input partition of any width, outside `TaskMemoryManager`, and `CacheWriter` buffers the same amount before the cursor finishes. The stream side has `maxBatchBytes`, but lookup results have no equivalent. I'd want a byte bound if this stays on by default, otherwise default off for now. Could a `maximumWeight` with a weigher replace `maxEntries` and `maxRowsPerKey` with one setting? It can't be combined with `maximumSize`, and `CacheWriter` would still need its own cutoff. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinExec.scala: ########## @@ -0,0 +1,241 @@ +/* + * 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 org.apache.spark.SparkException +import org.apache.spark.rdd.RDD +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{And, Attribute, AttributeMap, AttributeSet, + BoundReference, EqualNullSafe, EqualTo, Expression, ExprUtils, GreaterThan, GreaterThanOrEqual, + LessThan, LessThanOrEqual, PredicateHelper} +import org.apache.spark.sql.catalyst.plans.{JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions, + ExternalLookupTransform} +import org.apache.spark.sql.catalyst.plans.physical.Partitioning +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan} +import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode} +import org.apache.spark.sql.execution.datasources.v2.SupportsCustomDriverMetrics +import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.{Clock, SystemClock, Utils} + +/** + * Executes synchronous, parameterized external lookup joins without a shuffle. Each task joins + * its input rows in batches, through an [[ExternalLookupJoinEvaluatorFactory]]. + */ +case class ExternalLookupJoinExec( + tableName: String, + lookupParameters: Seq[Expression], + lookupInput: Seq[Attribute], + lookupOutput: Seq[Attribute], + lookupTransforms: Seq[ExternalLookupTransform], + nullSafeParameters: Seq[Boolean], + lookupKeys: Seq[Attribute], + lookupKeyPredicates: Seq[String], + joinType: JoinType, + residualCondition: Option[Expression], + @transient scan: Scan, + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + cacheOptions: ExternalLookupCacheOptions, + child: SparkPlan) extends UnaryExecNode with SupportsCustomDriverMetrics with PredicateHelper { + + // The connector's value rows follow the read schema, which `lookupInput` describes, and the + // lookup-side stages turn them into rows of `transformedLookup`. The lookup columns keep their + // analyzed order, and take the types and nullability of those rows. In `lookupInput`, the + // nullability at every nested level combines the table's and the read schema's: a field is NOT + // NULL when either says so. + private lazy val transformedLookup = lookupTransforms.lastOption.map(_.output) + .getOrElse(lookupInput) + private lazy val inputByLookupOutput = + AttributeMap(transformedLookup.map(attr => attr -> attr)) + private lazy val lookupColumns = lookupOutput.map(inputByLookupOutput) + + override def output: Seq[Attribute] = joinType match { + case LeftOuter => child.output ++ lookupColumns.map(_.withNullability(true)) + case LeftSemi | LeftAnti => child.output + case _ => child.output ++ lookupColumns + } + + // Each task joins its input rows where they are, so the stream side's partitioning holds. + override def outputPartitioning: Partitioning = child.outputPartitioning + + // The conjuncts of the residual condition that read only stream columns, and the rest. A stream + // row that fails the first cannot match, so the join checks them on each stream row before the + // lookup, and does not request the row's key. The join then evaluates them for rows without a + // match too, and before the conjuncts written ahead of them, so only conjuncts that can never + // fail are checked early: those that ExprUtils.canEvaluateUnconditionally accepts, as for the + // streamed side of other joins. `Expression.throwable` is not enough, because most expressions + // that can fail, such as an ANSI cast, do not report it. A conjunct that reads no column stays + // with the rest: the optimizer has already folded it if it could. + private def splitResidualCondition: (Option[Expression], Option[Expression]) = { + val (streamConjuncts, joinedConjuncts) = + residualCondition.toSeq.flatMap(splitConjunctivePredicates).partition { conjunct => + conjunct.references.nonEmpty && conjunct.references.subsetOf(child.outputSet) && + ExprUtils.canEvaluateUnconditionally(conjunct) + } + (streamConjuncts.reduceOption(And), joinedConjuncts.reduceOption(And)) + } + + // Spark does not trust the connector to evaluate the selected lookup predicates as Spark does, + // so it checks them itself on each row that the connector returns. The check reads that row + // after the parameter row of its request, and compares lookup key i with parameter i as its + // selected predicate does. + private def lookupKeyCheck: Option[Expression] = lookupParameters.indices.map { index => + val parameter = lookupParameters(index) + val parameterValue = BoundReference(index, parameter.dataType, parameter.nullable) + val keyOrdinal = lookupInput.indexWhere(_.exprId == lookupKeys(index).exprId) + val key = lookupInput(keyOrdinal) + val keyValue = BoundReference(lookupParameters.length + keyOrdinal, key.dataType, key.nullable) + lookupKeyPredicates(index) match { + case "=" => EqualTo(keyValue, parameterValue) + case "<=>" => EqualNullSafe(keyValue, parameterValue) + case "<" => LessThan(keyValue, parameterValue) + case "<=" => LessThanOrEqual(keyValue, parameterValue) + case ">" => GreaterThan(keyValue, parameterValue) + case ">=" => GreaterThanOrEqual(keyValue, parameterValue) + case other => throw SparkException.internalError(s"Unexpected lookup predicate $other") + } + }.reduceOption(And) + + override def references: AttributeSet = + AttributeSet(lookupParameters.flatMap(_.references)) ++ + residualCondition.map(_.references.intersect(child.outputSet)).getOrElse(AttributeSet.empty) + + // A connector's custom metrics are registered under prefixed keys, so that they never collide + // with the operator's own metrics; the UI shows the connector's descriptions. + override lazy val customMetrics: Map[String, SQLMetric] = + scan.supportedCustomMetrics().map { metric => + ExternalLookupJoinExec.sourceMetricKey(metric.name()) -> + SQLMetrics.createV2CustomMetric(sparkContext, metric) + }.toMap + + override protected lazy val sparkMetrics: Map[String, SQLMetric] = + ExternalLookupJoinExec.OPERATOR_METRICS.map { metric => + val sqlMetric = if (metric.isTiming) { + SQLMetrics.createNanoTimingMetric(sparkContext, metric.description) + } else { + SQLMetrics.createMetric(sparkContext, metric.description) + } + metric.name -> sqlMetric + }.toMap + + override protected def doExecute(): RDD[InternalRow] = { + postDriverMetrics(scan.reportDriverMetrics().map { metric => + new CustomTaskMetric { + override def name(): String = ExternalLookupJoinExec.sourceMetricKey(metric.name()) + override def value(): Long = metric.value() + } + }) + val (streamCondition, joinedCondition) = splitResidualCondition + val evaluatorFactory = new ExternalLookupJoinEvaluatorFactory( + tableName, + lookupParameters, + nullSafeParameters, + lookupKeyCheck, + child.output, + lookupInput, + lookupTransforms, + transformedLookup, + output, + joinType, + streamCondition, + joinedCondition.map(_.transform { + case attr: Attribute => inputByLookupOutput.getOrElse(attr, attr) + }), + readerFactory, + math.min(ExternalLookupJoinExec.MAX_PARAMETER_ROWS_PER_REQUEST, maxParameterRowsPerRequest), + conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES), + cacheOptions, + ExternalLookupJoinMetrics( + outputRows = longMetric("numOutputRows"), + inputRows = longMetric("numInputRows"), + inputBatches = longMetric("numInputBatches"), + requests = longMetric("numLookupRequests"), + parameterRows = longMetric("numLookupParameterRows"), + cacheHits = longMetric("numCacheHits"), + lookupTime = longMetric("lookupTime")), + new ExternalLookupReaderMetrics(customMetrics)) + if (conf.usePartitionEvaluator) { + child.execute().mapPartitionsWithEvaluator(evaluatorFactory) + } else { + child.execute().mapPartitionsWithIndexInternal { (index, input) => + evaluatorFactory.createEvaluator().eval(index, input) + } + } + } + + override protected def withNewChildInternal(newChild: SparkPlan): ExternalLookupJoinExec = + copy(child = newChild) + + override def simpleString(maxFields: Int): String = { + Utils.redact(conf.stringRedactionPattern, s"$nodeName ${scan.description()}") + } + + override protected def stringArgs: Iterator[Any] = + Iterator(child, simpleString(conf.maxToStringFields)) +} + +object ExternalLookupJoinExec { + /** The clock of the cache TTL; tests replace it. */ + @volatile private[sql] var cacheClock: Clock = new SystemClock() Review Comment: This operator runs only in micro-batch tasks today, so what does TTL buy in this PR? It costs a conf, a hint option, and this global mutable test hook. If it's for real-time mode, could it land with that? If it stays, could the clock be passed in instead? ########## sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/ExternalLookupReader.java: ########## @@ -28,13 +28,31 @@ * A task-local client that executes lookup requests. * <ul> * <li>Calls to a reader and its cursors are sequential, but may come from different threads. - * The one exception is the end of the task: if another thread is still consuming the join, - * Spark may call {@link #close()} on the reader, and {@code close()} on its open cursor, while - * one call from that thread is in progress. Spark starts no new call after the close, so - * implementations must tolerate {@code close()} during an in-progress call, for example by - * cancelling or failing that call.</li> + * The one exception is the end of the task, when another thread may still be consuming the + * join. Spark then calls {@code close()} on the open cursor and then {@link #close()} on this + * reader, from the thread that ends the task. Exactly these may overlap or follow that close: + * <ul> + * <li>One call from the consuming thread that was in progress, or that Spark checked just + * before the close. Implementations must tolerate the close during or before such a call, + * for example by cancelling or failing it. Spark does not wait for it.</li> + * <li>Spark's read of the value row that the cursor returned, and of its buffers, which may + * overlap the cursor's {@code close()}. Spark waits for this read to end before it closes + * this reader, so this reader may release the memory behind its rows in + * {@code close()}.</li> + * <li>{@link #currentMetricsValues()}, on this reader and on the task's other readers, while + * a call is in progress on the consuming thread. That method must be safe to call + * concurrently and must not wait for the call in progress.</li> + * <li>The close of the cursor that a request in progress returns, which comes after this + * reader's close, as {@link #lookupBatch} describes.</li> + * <li>For a reader that a {@link ExternalLookupReaderFactory#createReader()} call in progress + * returns, a read of its metrics and its close, with no other call on it.</li> + * </ul> + * Apart from the closes listed above, once the consuming thread has seen the close, Spark makes + * no further call on this reader or its cursors. Spark closes each of them exactly once.</li> * <li>Requests are not snapshot boundaries: results may mix source versions.</li> - * <li>Retried or speculative tasks may repeat a request; duplicates must be tolerated.</li> + * <li>Retried or speculative tasks may send the same request again, so a source must Review Comment: Worth stating the other direction too: within a task, Spark may serve a repeated key from its cache and not send it again. Should a source with volatile data be able to opt out? Today only the query author can. ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -4299,6 +4435,72 @@ ], "sqlState" : "42K09" }, + "INVALID_EXTERNAL_LOOKUP_HINT" : { + "message" : [ + "The `EXTERNAL_LOOKUP` hint is invalid:" + ], + "subClass" : { + "CONFLICTING_JOIN_STRATEGY" : { + "message" : [ + "The join over <relation> also has the join strategy hint <strategy>, which asks for a different join. Remove one of the two hints." + ] + }, + "DUPLICATE_RELATION" : { + "message" : [ + "The relation <relation> is specified more than once." + ] + }, + "MULTIPLE_HINTS" : { + "message" : [ + "The lookup side of a join can have at most one `EXTERNAL_LOOKUP` hint." + ] + }, + "NOT_ON_LOOKUP_SIDE" : { + "message" : [ + "The hint must be placed on the right lookup side of the join." + ] + }, + "RELATION_NOT_FOUND" : { + "message" : [ + "Cannot find the relation(s) <relations> named by the hint. A string parameter that does not contain `=` is a relation name. Write a cache option as key=value, such as 'cache_enabled=false'." + ] + }, + "UNSUPPORTED_PARAMETER" : { + "message" : [ + "The hint accepts only relation names and string options, but got <parameter>." + ] + } + }, + "sqlState" : "42601" + }, + "INVALID_EXTERNAL_LOOKUP_OPTION" : { Review Comment: Could these be subclasses of `INVALID_EXTERNAL_LOOKUP_HINT`? Both report a bad hint, but that one is 42601 and this one is 22023. -- 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]
