HeartSaVioR commented on code in PR #59910: URL: https://github.com/apache/spark/pull/59910#discussion_r4537716792
########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,659 @@ +/* + * 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, 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, 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. 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 inner 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 join emits it, so a batch keeps it. + private val keepsRowsThatCannotMatch = joinType != Inner + + private def canMatch(row: InternalRow): Boolean = + joinOutput.canMatch(row) && !parameters.matchesNothing(parameters.requestRow(row)) + + // 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 keeps one row, when one remains. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes && input.hasNext) { + val next = input.next() + if (keepsRowsThatCannotMatch || canMatch(next)) { + val row = next match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).copy() + } + bytes += row.getSizeInBytes + rows += row + } else { + metrics.inputRows += 1 + } + } + 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 request row 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 parameters are not requested. The stream condition is + // checked before the parameters are evaluated, so that it can guard their expressions. + private val keyEntries = { + val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + lazy val requestRow = parameters.requestRow(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(requestRow)) { Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [cd9a68fd105](https://github.com/apache/spark/commit/cd9a68fd105e0f772b2b06873d5f2ca6a245ff7d). A batch now decides once for each stream row whether it can match, as it reads the row. It groups the rows that can match by their request row, copying each distinct request row once, and hands the groups, with the left outer rows that cannot match, to the join of the batch. A new test computes the key with a counting UDF: of 4 stream rows, 3 pass the stream condition, and the UDF runs 3 times in an inner and in a left outer join. The old code ran it 6 times in the inner join. Inner and left outer joins over null keys, rows that fail the stream condition and repeated keys keep their rows, request sizes, requested keys and metrics. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,3312 @@ +/* + * 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.connector + +import java.nio.charset.StandardCharsets +import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit} +import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, AtomicReference} + +import scala.collection.mutable +import scala.concurrent.duration._ +import scala.jdk.CollectionConverters._ +import scala.reflect.{classTag, ClassTag} + +import org.apache.spark.{SparkException, SparkIllegalArgumentException, SparkRuntimeException, + SparkThrowable, SparkUnsupportedOperationException, TaskContext} +import org.apache.spark.rdd.DeterministicLevel +import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Encoders, Row, SaveMode, + SQLContext} +import org.apache.spark.sql.IntegratedUDFTestUtils.{shouldTestPythonUDFs, TestPythonUDF} +import org.apache.spark.sql.QueryTest +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.{CheckExternalLookupJoin, FormExternalLookupJoin, + NoSuchTableException} +import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, AttributeMap, AttributeReference, + Cast, EqualTo, Expression, GenericInternalRow, LessThan, Literal, Rand, UnsafeProjection} +import org.apache.spark.sql.catalyst.plans.{Inner, QueryPlan} +import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, ExternalLookupJoin, Join, JoinHint, + LeafNode, LogicalPlan, PreparedExternalLookupJoin} +import org.apache.spark.sql.catalyst.trees.TreePattern.LOOKUP_ONLY_RELATION +import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} +import org.apache.spark.sql.classic.Dataset +import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable, + InMemoryTableCatalog, SupportsRead, Table, TableCapability, TableCatalog, TableChange, + TableProvider} +import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, EXTERNAL_LOOKUP} +import org.apache.spark.sql.connector.expressions.{NamedReference, Transform} +import org.apache.spark.sql.connector.expressions.filter.Predicate +import org.apache.spark.sql.connector.metric.{CustomMetric, CustomSumMetric, CustomTaskMetric} +import org.apache.spark.sql.connector.read.{Batch, ExternalLookup, ExternalLookupReader, + ExternalLookupReaderFactory, ExternalLookupResultCursor, InputPartition, LookupParameter, + PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsExternalLookup, + SupportsPushDownRequiredColumns, SupportsPushDownV2Filters} +import org.apache.spark.sql.execution.{CoalesceExec, LocalTableScanExec} +import org.apache.spark.sql.execution.datasources.{FileFormat, SaveIntoDataSourceCommand} +import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat +import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, ExternalLookupRelation, + FileDataSourceV2, PrepareExternalLookupJoin, StreamingDataSourceV2ScanRelation, + TableCapabilityCheck} +import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec +import org.apache.spark.sql.execution.joins.ExternalLookupJoinExec +import org.apache.spark.sql.execution.streaming.operators.stateful.StreamingDeduplicateExec +import org.apache.spark.sql.execution.streaming.runtime.{IncrementalExecution, MemoryStream, + StreamingQueryWrapper} +import org.apache.spark.sql.execution.streaming.sources.LowLatencyMemoryStream +import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector +import org.apache.spark.sql.functions.{coalesce, col, concat, expr, length, lit, max, raise_error, + to_json, when} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, InsertableRelation, + RelationProvider, SchemaRelationProvider} +import org.apache.spark.sql.streaming.{StreamingQueryException, StreamRealTimeModeE2ESuiteBase} +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, DoubleType, + IntegerType, MapType, StringType, StructType, UserDefinedType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap +import org.apache.spark.sql.vectorized.ColumnarBatch +import org.apache.spark.unsafe.types.UTF8String + +class ExternalLookupJoinSuite extends QueryTest with SharedSparkSession { + + import testImplicits._ + + private val EXTERNAL_LOOKUP_CATALOG_NAME = "external_lookup_cat" + // The supportedJoinTypes parameter of a JOIN_TYPE error. + private val SUPPORTED_JOIN_TYPES = "INNER, LEFT OUTER" + + private val streamRunCount = new AtomicInteger() + + override def beforeEach(): Unit = { + super.beforeEach() + SimpleExternalLookupDataSource.resetCounters() + SemanticKeyExternalLookupDataSource.requestSizes.clear() + } + + /** The rows of `df` as a streaming DataFrame: one micro-batch, in `numPartitions` partitions. */ + private def streamOf(df: DataFrame, numPartitions: Int = 1): DataFrame = { + val input = MemoryStream[Row](numPartitions)(Encoders.row(df.schema), spark.sqlContext) + input.addData(df.collect().toSeq) + input.toDF() + } + + private case class StreamRun(rows: Seq[Row], execution: IncrementalExecution) { + def plan: LogicalPlan = execution.optimizedPlan + def lookupJoin: ExternalLookupJoinExec = execution.executedPlan.collectFirst { + case exec: ExternalLookupJoinExec => exec + }.get + } + + /** The last two metric reads or closes that the connector's readers saw, in order. */ + private def lastReaderEvents: Seq[String] = + SimpleExternalLookupDataSource.readerEvents.asScala.toSeq.takeRight(2) + + /** Runs the streaming `df` on a memory sink until it has processed all of its input. */ + private def runStream(df: DataFrame, outputMode: String = "append"): StreamRun = { + val queryName = s"external_lookup_stream_${streamRunCount.incrementAndGet()}" + val query = + df.writeStream.format("memory").outputMode(outputMode).queryName(queryName).start() + try { + query.processAllAvailable() + StreamRun( + spark.table(queryName).collect().toSeq, + query.asInstanceOf[StreamingQueryWrapper].streamingQuery.lastExecution) + } finally { + query.stop() + spark.catalog.dropTempView(queryName) + } + } + + private def checkStream(df: DataFrame, expected: Seq[Row]): Unit = + QueryTest.sameRows(expected, runStream(df).rows).foreach(fail(_)) + + /** The error that the streaming `df` fails with, when it starts or in a micro-batch. */ + private def streamFailure[T <: Throwable : ClassTag](df: DataFrame): T = { + val cause = try { + runStream(df) + fail("The streaming query did not fail") + } catch { + case e: StreamingQueryException => e.getCause + case e: Throwable with SparkThrowable => e + } + assert(classTag[T].runtimeClass.isInstance(cause), cause) + cause.asInstanceOf[T] + } + + test("a stream whose scan is pruned at the start reads the columns of its lookup joins") { + withSQLConf( + "spark.sql.catalog.stream_cat" -> classOf[InMemoryTableCatalog].getName, + SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "true") { + withTable("stream_cat.ns.badge_swipes") { + sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door STRING, minute INT) " + + s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_COLUMN_PRUNING}' = 'true')") + sql("INSERT INTO stream_cat.ns.badge_swipes VALUES (1, 'lobby', 10), (3, 'garage', 20)") + val swipes = spark.readStream.table("stream_cat.ns.badge_swipes") + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + checkStream( + swipes.join(lookup, swipes("employee") === lookup("id")) + .select(swipes("door"), lookup("department")), + Seq(Row("lobby", "engineering"), Row("lobby", "research"))) + // An aggregate that reads only stream columns and ignores duplicates does not need a left + // outer join, so the optimizer removes an ordinary one. A lookup join stays. + val latestByDoor = swipes.join(lookup, swipes("employee") === lookup("id"), "left_outer") + .groupBy(swipes("door")).agg(max(swipes("minute"))) + QueryTest.sameRows( + Seq(Row("lobby", 10), Row("garage", 20)), + runStream(latestByDoor, "complete").rows).foreach(fail(_)) + } + } + } + + test("a stream whose scan gets the query's filters joins its lookup joins as without them") { + // The stream drops the rows that fail the filters that its scan builder took when the query + // started, so a micro-batch that does not apply one of them fails. + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + def results(pushdown: Boolean): (Seq[Seq[Row]], Seq[Seq[Expression]]) = { + var result: (Seq[Seq[Row]], Seq[Seq[Expression]]) = null + withSQLConf( + "spark.sql.catalog.stream_cat" -> classOf[InMemoryTableCatalog].getName, + SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key -> pushdown.toString) { + withTable("stream_cat.ns.badge_swipes") { + sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door STRING, minute INT) " + + s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN}' = 'true', " + + s"'${InMemoryBaseTable.SIMULATE_STREAMING_FILTERS}' = 'true')") + sql("INSERT INTO stream_cat.ns.badge_swipes VALUES " + + "(1, 'lobby', 10), (2, 'garage', 20), (3, 'dock', 30), (1, 'garage', 40)") + val swipes = spark.readStream.table("stream_cat.ns.badge_swipes") + val onEmployee = swipes("employee") === lookup("id") + val runs = Seq( + // A filter on stream columns below the join, and above an inner and a left outer join. + runStream(swipes.where(swipes("minute") > 15).join(lookup, onEmployee)), + runStream(swipes.join(lookup, onEmployee).where(swipes("minute") > 15)), + runStream(swipes.join(lookup, onEmployee, "left_outer") + .where(swipes("door") === "garage")), + // A filter on both sides, which predicate pushdown can move into the join condition. + runStream(swipes.join(lookup, onEmployee) + .where(swipes("door") =!= lookup("department") && swipes("minute") < 35)), + // An aggregate that ignores duplicates needs no ordinary left outer join, which the + // optimizer removes, with its filters pushed to the stream. A lookup join stays. + runStream(swipes.join(lookup, onEmployee, "left_outer").where(swipes("minute") > 15) + .groupBy(swipes("door")).agg(max(swipes("minute"))), "complete")) + val pushed = runs.map(_.execution.optimizedPlan.collect { + case relation: StreamingDataSourceV2ScanRelation => relation.pushedFilters + }.flatten) + result = (runs.map(_.rows), pushed) + } + } + result + } + val (rows, pushed) = results(pushdown = true) + val (expected, notPushed) = results(pushdown = false) + rows.zip(expected).foreach { case (actual, expected) => + QueryTest.sameRows(expected, actual).foreach(fail(_)) + } + assert(notPushed.forall(_.isEmpty)) + // At least the filter below the join reaches the stream's scan. + assert(pushed.head.nonEmpty) + } + + test("external lookup capability produces a unary external lookup join") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + val joined = left.join(lookup, left("id") === lookup("id"), "inner") + + val plan = runStream(joined).plan + assert(plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + assert(!plan.toString.contains("SimpleExternalLookupScan")) + } + + test("an external lookup join is a stream-static join with the lookup-only table on the right") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val batch = Seq(1).toDF("id") + // The left side must be a streaming query. + checkError( + exception = intercept[AnalysisException] { + batch.join(lookup, batch("id") === lookup("id")) + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE", + parameters = Map("relation" -> "`SimpleExternalLookupTable`")) + // The sides are never swapped. + val stream = streamOf(batch) + checkError( + exception = intercept[AnalysisException] { + lookup.join(stream, lookup("id") === stream("id")) + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT", + parameters = Map("relation" -> "`SimpleExternalLookupTable`")) + } + + test("external lookup validates connector planning and request contracts") { + val left = streamOf(Seq(1).toDF("id")) + Seq( + ("nullKeySelection", "true", "NULL_RESULT", + Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")), + ("selectionMode", "nullElement", "UNOFFERED_SELECTED_PREDICATE", Map("predicate" -> "null")), + ("selectionMode", "duplicate", "DUPLICATE_SELECTED_PREDICATE", Map("predicate" -> "id = ?")), + ("selectionMode", "copy", "UNOFFERED_SELECTED_PREDICATE", Map("predicate" -> "id = ?")), + ("maxBatchSize", "0", "NON_POSITIVE_MAX_PARAMETER_ROWS", Map("value" -> "0"))).foreach { + case (option, value, subClass, parameters) => + val lookup = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option(option, value) + .load() + checkError( + exception = streamFailure[AnalysisException]( + left.join(lookup, left("id") === lookup("id"))), + condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass", + parameters = Map("table" -> "`SimpleExternalLookupTable`") ++ parameters) + } + + def misconfigured(kind: String): DataFrame = spark.read + .format(classOf[MisconfiguredExternalLookupDataSource].getName) + .option("kind", kind) + .load() + val table = Map("table" -> "`MisconfiguredExternalLookupTable`") + Seq( + ("unknownField", "UNKNOWN_SCAN_FIELD", Map("field" -> "`unknown`")), + ("duplicateField", "DUPLICATE_SCAN_FIELD", Map("field" -> "`id`"))).foreach { + case (kind, subClass, parameters) => + val lookup = misconfigured(kind) + checkError( + exception = streamFailure[AnalysisException]( + left.join(lookup, left("id") === lookup("id"))), + condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass", + parameters = table ++ parameters) + } + + val noExternalLookup = misconfigured("noExternalLookup") + checkError( + exception = streamFailure[SparkUnsupportedOperationException]( + left.join(noExternalLookup, left("id") === noExternalLookup("id"))), + condition = "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED", + parameters = Map("description" -> "NoExternalLookupScan")) + + // Violations found while the join runs are reported the same way, by the tasks. + val nullCursor = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option("nullCursor", "true") + .load() + Seq( + (nullCursor, "NULL_RESULT", Map("table" -> "`SimpleExternalLookupTable`", + "method" -> "ExternalLookupReader.lookupBatch()")), + (misconfigured("nullReader"), "NULL_RESULT", + table ++ Map("method" -> "ExternalLookupReaderFactory.createReader()")), + (misconfigured("invalidOrdinal"), "INVALID_INPUT_ORDINAL", + table ++ Map("ordinal" -> "5", "numParameterRows" -> "1")), + // The ordinals just outside the request's parameter rows. + (misconfigured("negativeOrdinal"), "INVALID_INPUT_ORDINAL", + table ++ Map("ordinal" -> "-1", "numParameterRows" -> "1")), + (misconfigured("ordinalAtCount"), "INVALID_INPUT_ORDINAL", + table ++ Map("ordinal" -> "1", "numParameterRows" -> "1")), + (misconfigured("nullRow"), "NULL_RESULT", + table ++ Map("method" -> "ExternalLookupResultCursor.get()")), + // A value that breaks its column's type, which Spark relied on while it optimized. + (misconfigured("nullValue"), "NULL_IN_NOT_NULL_FIELD", + table ++ Map("field" -> "`department`")), + (misconfigured("nullUnderNotNullReadSchema"), "NULL_IN_NOT_NULL_FIELD", + table ++ Map("field" -> "`department`")), + (misconfigured("decimalOutOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")), + // The same checks reach nested values: a decimal array element with too many digits, and + // a decimal map value that would need rounding. + (misconfigured("nestedDecimalOutOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`amounts`.`element`", "type" -> "\"DECIMAL(5,2)\"")), + (misconfigured("nestedDecimalRounding"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`rates`.`value`", "type" -> "\"DECIMAL(5,2)\"")), + // A compact decimal with too many digits, written into an UnsafeRow, a struct in one, or a + // columnar row or array, each of which records its type's precision without checking it. + (misconfigured("compactDecimal:unsafe:outOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")), + (misconfigured("compactDecimal:unsafeNested:outOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`price`.`amount`", "type" -> "\"DECIMAL(5,2)\"")), + (misconfigured("compactDecimal:columnar:outOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")), + (misconfigured("compactDecimal:columnarArray:outOfRange"), "DECIMAL_OUT_OF_RANGE", + table ++ Map("field" -> "`amounts`.`element`", "type" -> "\"DECIMAL(5,2)\"")), + // A map key is never null, whether it is a primitive or a struct. + (misconfigured("nullMapKey"), "NULL_IN_NOT_NULL_FIELD", + table ++ Map("field" -> "`labels`.`key`")), + (misconfigured("nullComplexMapKey"), "NULL_IN_NOT_NULL_FIELD", + table ++ Map("field" -> "`parts`.`key`"))).foreach { + case (lookup, subClass, parameters) => + // A left outer join binds the lookup columns as nullable for its output, but checks the + // returned values against the table and the read schema, as an inner join does. + Seq("inner", "left_outer").foreach { joinType => + checkError( + exception = streamFailure[SparkRuntimeException]( + left.join(lookup, left("id") === lookup("id"), joinType)), + condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass", + parameters = parameters) + } + } + + // Planning failures that need no hint. A catalog can serve a table without SupportsRead. + val noLookupBuilder = misconfigured("noLookupBuilder") + val nonReadable = Dataset.ofRows(spark, DataSourceV2Relation.create( + NonReadableExternalLookupTable, None, None, CaseInsensitiveStringMap.empty)) + val simple = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + Seq( + (noLookupBuilder, left("id") === noLookupBuilder("id"), "SCAN_BUILDER", + "MisconfiguredExternalLookupTable"), + (nonReadable, left("id") === nonReadable("id"), "TABLE", "NonReadableExternalLookupTable"), + (simple, simple("department") === "sales", "NO_LOOKUP_PREDICATE", + "SimpleExternalLookupTable")).foreach { case (lookup, condition, subClass, name) => + checkError( + exception = streamFailure[AnalysisException](left.join(lookup, condition)), + condition = s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass", + parameters = Map("table" -> s"`$name`")) + } + // A BIGINT stream key casts the INT lookup column, so Spark has no candidate to offer. + val bigintLeft = streamOf(Seq(1L).toDF("id")) + checkError( + exception = streamFailure[AnalysisException]( + bigintLeft.join(simple, bigintLeft("id") === simple("id"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE", + parameters = Map("table" -> "`SimpleExternalLookupTable`")) + } + + test("external lookup finalizes expressions on the stream side after analysis") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id")) + + checkStream( + left.join( + lookup, + coalesce(left("id"), lit(0)) === lookup("id"), + "inner"), + Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + } + + test("external lookup maps a selected predicate to its own occurrence") { + val lookup = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option("selectionMode", "last") + .load() + val left = streamOf(Seq((1, 2), (2, 2), (2, 1)).toDF("a", "b")) + + // Both candidates have the shape `id = ?`; only the second one, bound to `b`, is selected. + val joined = + left.join(lookup, lookup("id") === left("a") && lookup("id") === left("b"), "left_outer") + assert(runStream(joined).rows.toSet === + Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null))) + assert(SimpleExternalLookupDataSource.lookupCandidates.get() === + Seq(("=", "id", IntegerType), ("=", "id", IntegerType))) + assert(SimpleExternalLookupDataSource.lookupCandidateDescriptions.get() === + Seq("id = ?", "id = ?")) + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === Seq(2, 1)) + + // Selected in reverse order, each parameter row is `(b, a)`. + SimpleExternalLookupDataSource.resetCounters() + val reversed = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option("selectionMode", "reversed") + .load() + val condition = reversed("id") === left("a") && reversed("id") === left("b") + assert(runStream(left.join(reversed, condition, "left_outer")).rows.toSet === + Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null))) + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === Seq(2, 2, 1)) + } + + test("a parent projection of some lookup columns still plans an external lookup join") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1, 3).toDF("id")) + // Generic column pruning must not project the lookup relation, which would hide it from + // lookup planning; the join's requiredLookupOutput keeps it from doing so. + val joined = left.join(lookup, left("id") === lookup("id"), "left_outer") + .select(left("id"), lookup("department")) + + assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), Row(3, null))) + } + + test("external lookup join supports inner and left outer joins") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq((1, "one"), (2, "two"), (3, "three")).toDF("id", "label")) + + checkStream( + left.join(lookup, left("id") === lookup("id"), "inner"), + Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"), + Row(2, "two", 2, "sales"))) + checkStream( + left.join(lookup, left("id") === lookup("id"), "left_outer"), + Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"), + Row(2, "two", 2, "sales"), Row(3, "three", null, null))) + + // Only comparisons of a lookup field with a stream-side value are offered. The connector + // selects `id = ?`, and Spark evaluates the other conjuncts: the stream-side one on each stream + // row before the lookup, and the others on the joined rows. + SimpleExternalLookupDataSource.resetCounters() + val flagged = streamOf(Seq((1, true), (2, true), (1, false)).toDF("id", "flag")) + checkStream( + flagged.join( + lookup, + flagged("id") === lookup("id") && flagged("flag") && + lookup("department") === "engineering" && length(lookup("department")) > lookup("id"), + "left_outer"), + Seq(Row(1, true, 1, "engineering"), Row(2, true, null, null), Row(1, false, null, null))) + assert(SimpleExternalLookupDataSource.lookupCandidates.get() === + Seq(("=", "id", IntegerType), ("=", "department", StringType))) + } + + test("a stream row that fails a stream-side conjunct of the condition is not looked up") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf( + Seq((1, Some(true)), (2, Some(false)), (3, Some(true)), (4, None)).toDF("id", "flag")) + val key = left("id") === lookup("id") + // The join checks `flag` on each stream row before the lookup. A row where it is false or null + // cannot match, so its key is not requested: an inner join drops the row, and a left outer + // join pads it with nulls. + val matched = Seq(Row(1, true, 1, "engineering"), Row(1, true, 1, "research")) + val unmatched = + Seq(Row(2, false, null, null), Row(3, true, null, null), Row(4, null, null, null)) + Seq("inner" -> matched, "left_outer" -> (matched ++ unmatched)).foreach { + case (joinType, expected) => + SimpleExternalLookupDataSource.resetCounters() + checkStream(left.join(lookup, key && left("flag"), joinType), expected) + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === Seq(1, 3)) + } + + // A conjunct that can throw is not checked early: it is evaluated on the joined rows only, so + // never for id 3, which has no match, and every key is requested. + SimpleExternalLookupDataSource.resetCounters() + val throwing = when(left("id") === 3, raise_error(lit("evaluated for id 3"))).otherwise(true) + checkStream( + left.join(lookup, key && throwing, "left_outer"), + matched ++ Seq(Row(2, false, 2, "sales"), Row(3, true, null, null), Row(4, null, null, null))) + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === Seq(1, 2, 3, 4)) + + // A conjunct that is not deterministic is not checked early either. Analysis rejects one in a + // join condition, so the physical join gets one directly: `id + rand(0) < 0`. It is false for + // every row, but it is evaluated on the joined rows only, so every key is requested. + val lookupJoin = runStream(left.join(lookup, key, "left_outer")).lookupJoin + val streamId = lookupJoin.child.output.head + val nonDeterministic = + LessThan(Add(Cast(streamId, DoubleType), Rand(Literal(0L))), Literal(0.0)) + SimpleExternalLookupDataSource.resetCounters() + val rows = lookupJoin.copy( + residualCondition = Some(nonDeterministic), + child = LocalTableScanExec( + lookupJoin.child.output, Seq(InternalRow(1, true), InternalRow(2, false)), None)) + .executeCollect() + assert(rows.map(row => row.getInt(0) -> row.isNullAt(2)).toSeq === Seq(1 -> true, 2 -> true)) + // Each row is in its own partition, so the order of the requests can vary. + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq.sorted === Seq(1, 2)) + } + + test("external lookup-only source joins without an explicit hint") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation]) + val joined = left.join(lookup, "id") + assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"))) + } + + test("an external lookup-only source cannot be read outside an eligible lookup join") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + checkError( + exception = intercept[AnalysisException] { lookup.queryExecution.optimizedPlan }, + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map( + "tableName" -> "`SimpleExternalLookupTable`", + "operation" -> "batch scan")) + // A join that reads it but cannot be a lookup join fails with the reason. The condition must + // be written in the join, not in a later filter. + checkError( + exception = streamFailure[AnalysisException]( + left.join(lookup).where(left("id") === lookup("id"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + // An unsupported join type fails when the DataFrame is built, with or without a condition. + Seq[(() => DataFrame, String)]( + (() => left.join(lookup, left("id") === lookup("id"), "full_outer"), "FULL OUTER"), + (() => left.crossJoin(lookup), "CROSS"), + (() => left.crossJoin(lookup).where(left("id") === lookup("id")), "CROSS")).foreach { + case (joined, joinType) => + val error = intercept[AnalysisException](joined()) + assert(error.getCondition === "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE") + assert(error.getMessageParameters.asScala.toMap === Map( + "joinType" -> joinType, + "relation" -> "`SimpleExternalLookupTable`", + "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES)) + } + } + + test("a common expression in the join condition is evaluated in the lookup join") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq((1, "b"), (2, "c")).toDF("id", "code")) + val sameId = left("id") === lookup("id") + // BETWEEN evaluates its input once, and upper() is not cheap enough to repeat, so it would + // otherwise be computed in a projection below the join: over the lookup side, or the stream. + Seq( + expr("upper(department) BETWEEN 'F' AND 'Z'") -> + Seq(Row(1, "b", 1, "research"), Row(2, "c", 2, "sales")), + expr("upper(code) BETWEEN 'A' AND 'B'") -> + Seq(Row(1, "b", 1, "engineering"), Row(1, "b", 1, "research"))).foreach { + case (between, expected) => + val run = runStream(left.join(lookup, sameId && between)) + assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + QueryTest.sameRows(expected, run.rows).foreach(fail(_)) + } + } + + test("a subquery in the join condition of a lookup join is rejected") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq((1, 1)).toDF("id", "x")) + val values = Seq(1).toDF("v") + val sameId = left("id") === lookup("id") + // The optimizer rewrites such subqueries only in a Join, so they fail when the DataFrame is + // built, whether they read the stream side, the lookup side or neither. The scalar subquery + // references neither side, so it could be offered as a parameter. + Seq( + sameId && left("x").isin(values), + sameId && values.where(col("v") === 1).exists(), + lookup("id") === values.scalar(), + sameId && lookup("id").isin(values)).foreach { condition => + checkError( + exception = intercept[AnalysisException](left.join(lookup, condition)), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SUBQUERY_IN_JOIN_CONDITION", + parameters = Map("relation" -> "`SimpleExternalLookupTable`")) + } + } + + test("Dataset join APIs that analyze a join plan lookup joins or fail with a named error") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq((1, 2)).toDF("sender", "receiver")) + + val typed = left.joinWith(lookup, left("sender") === lookup("id")) + val typedRun = runStream(typed.toDF()) + assert(typedRun.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + QueryTest.sameRows( + Seq(Row(Row(1, 2), Row(1, "engineering")), Row(Row(1, 2), Row(1, "research"))), + typedRun.rows).foreach(fail(_)) + + // A lookup DataFrame reused in a second join is ambiguous, as any other DataFrame is. + def reusedJoinError(right: DataFrame): AnalysisException = intercept[AnalysisException] { + val enriched = left.join(right, left("sender") === right("id")) + enriched.join(right, enriched("receiver") === right("id")) + } + val ordinary = Seq((1, "engineering")).toDF("id", "department") + Seq("true", "false").foreach { autoResolve => + withSQLConf(SQLConf.DATAFRAME_SELF_JOIN_AUTO_RESOLVE_AMBIGUITY.key -> autoResolve) { + val error = reusedJoinError(lookup) + assert(error.getCondition === reusedJoinError(ordinary).getCondition) + assert(error.getMessage.contains("ambiguous"), error) + } + } + // Loaded twice, the table enriches the stream with two lookup joins. + val receivers = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val enriched = left.join(lookup, left("sender") === lookup("id")) + val twice = enriched.join(receivers, enriched("receiver") === receivers("id")) + val twiceRun = runStream(twice) + assert(twiceRun.plan.collect { case join: PreparedExternalLookupJoin => join }.size === 2) + QueryTest.sameRows( + Seq(Row(1, 2, 1, "engineering", 2, "sales"), Row(1, 2, 1, "research", 2, "sales")), + twiceRun.rows).foreach(fail(_)) + + // An AS OF join reads the lookup-only table outside a lookup join. + checkError( + exception = streamFailure[AnalysisException](left.asInstanceOf[Dataset[Row]].joinAsOf( + lookup, left("sender"), lookup("id"), left("sender") === lookup("id"), "inner", + tolerance = null, allowExactMatches = true, direction = "backward")), + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map( + "tableName" -> "`SimpleExternalLookupTable`", + "operation" -> "batch scan")) + + // A condition that is not boolean fails as for any other join. + val notBoolean = intercept[AnalysisException] { + left.join(lookup, left("sender") + lookup("id")) + } + assert(notBoolean.getCondition === "JOIN_CONDITION_IS_NOT_BOOLEAN_TYPE") + } + + test("a catalog-resolved external lookup-only table cannot be read outside a lookup join") { + withSQLConf( + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName) { + val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup" + val left = Seq(1).toDF("id") + Seq[() => DataFrame]( + () => spark.table(table), + () => sql(s"SELECT * FROM $table WHERE id = 1")).foreach { + df => + checkError( + exception = intercept[AnalysisException] { df().queryExecution.optimizedPlan }, + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map( + "tableName" -> "`SimpleExternalLookupTable`", + "operation" -> "batch scan")) + } + } + } + + test("a command that reads a lookup-only table outside a lookup join fails before it writes") { + withSQLConf( + "spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName, + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName) { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val catalogLookup = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup" + def checkBatchScanError(write: () => Any): Unit = checkError( + exception = intercept[AnalysisException](write()), + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map( + "tableName" -> "`SimpleExternalLookupTable`", + "operation" -> "batch scan")) + + // Each write would replace the archived assignment that its target holds. + withTable("testcat.ns.target", "v1_target") { + sql("CREATE TABLE testcat.ns.target (id INT, department STRING)") + sql("INSERT INTO testcat.ns.target VALUES (7, 'archive')") + sql("CREATE TABLE v1_target (id INT, department STRING) USING parquet") + sql("INSERT INTO v1_target VALUES (7, 'archive')") + Seq[(String, () => Any)]( + "testcat.ns.target" -> + (() => lookup.write.mode("overwrite").saveAsTable("testcat.ns.target")), + "testcat.ns.target" -> (() => lookup.writeTo("testcat.ns.target").replace()), + "testcat.ns.target" -> (() => + sql(s"REPLACE TABLE testcat.ns.target USING foo AS SELECT * FROM $catalogLookup")), + "testcat.ns.target" -> + (() => sql(s"INSERT OVERWRITE testcat.ns.target SELECT * FROM $catalogLookup")), + "v1_target" -> (() => lookup.write.mode("overwrite").saveAsTable("v1_target")), + "v1_target" -> (() => lookup.write.mode("overwrite").insertInto("v1_target")), + // A subquery of the query reads it. + "v1_target" -> (() => sql( + "INSERT OVERWRITE v1_target SELECT id, 'none' FROM VALUES (8) AS t(id) " + + s"WHERE id NOT IN (SELECT id FROM $catalogLookup)"))).foreach { + case (target, write) => + checkBatchScanError(write) + checkAnswer(spark.table(target), Row(7, "archive")) + } + } + + // V1 commands that hold their query outside their children. + RecordingV1WriteSource.writes.clear() + withTempView("recording_sink") { + sql("CREATE TEMPORARY VIEW recording_sink (id INT, department STRING) " + + s"USING ${classOf[RecordingV1WriteSource].getName}") + checkBatchScanError(() => + lookup.write.mode("overwrite").format(classOf[RecordingV1WriteSource].getName).save()) + checkBatchScanError(() => + sql(s"INSERT OVERWRITE TABLE recording_sink SELECT * FROM $catalogLookup")) + // The query reads it below a union under an ordinary join, which is no lookup join at any + // layer, so the check reaches the read only by entering the sides of the join. + val departments = Seq((1, "x")).toDF("id", "label") + checkBatchScanError(() => departments.join(lookup.union(lookup), "id") + .write.mode("overwrite").format(classOf[RecordingV1WriteSource].getName).save()) + } + assert(RecordingV1WriteSource.writes.isEmpty) + } + } + + test("a command reads a lookup-only table only through a lookup join, and a view not at all") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + def save(query: DataFrame): LogicalPlan = SaveIntoDataSourceCommand( + query.queryExecution.analyzed, new RecordingV1WriteSource, Map.empty, SaveMode.Overwrite) + TableCapabilityCheck(save(left.join(lookup, left("id") === lookup("id")))) + // A join of a command, which is analyzed in full, cannot gain a condition later. + checkError( + exception = intercept[AnalysisException](TableCapabilityCheck(save(left.join(lookup)))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + + withTempView("lookup_view", "enriched_view") { + lookup.createOrReplaceTempView("lookup_view") + left.join(lookup, left("id") === lookup("id")).createOrReplaceTempView("enriched_view") + checkStream( + spark.table("enriched_view"), Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + checkError( + exception = intercept[AnalysisException] { + spark.table("lookup_view").queryExecution.optimizedPlan + }, + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map( + "tableName" -> "`SimpleExternalLookupTable`", + "operation" -> "batch scan")) + } + } + + test("foreachBatch writes the micro-batches of a lookup join with batch commands") { + withSQLConf("spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName) { + withTempPath { path => + withTable("enriched_events") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val events = streamOf(Seq(1, 2, 3).toDF("id")) + val enriched = events.join(lookup, events("id") === lookup("id")) + .select(events("id"), lookup("department")) + val v2Rows = new AtomicReference(Seq.empty[Row]) + // Each micro-batch reaches the function as a plan that is already planned, so the batch + // commands over it read no lookup-only table. + val query = enriched.writeStream.foreachBatch { (batch: DataFrame, _: Long) => + batch.write.format("parquet").mode("append").save(path.getCanonicalPath) + batch.write.mode("append").saveAsTable("enriched_events") + // The function runs in the query's session, which has its own instance of the test + // catalog, so the V2 table is created and read there. + val session = batch.sparkSession + session.sql( + "CREATE TABLE IF NOT EXISTS testcat.ns.enriched_events (id INT, department STRING)") + batch.writeTo("testcat.ns.enriched_events").append() + v2Rows.set(session.table("testcat.ns.enriched_events").collect().toSeq) + }.start() + try query.processAllAvailable() finally query.stop() + val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, "sales")) + checkAnswer(spark.read.parquet(path.getCanonicalPath), expected) + checkAnswer(spark.table("enriched_events"), expected) + QueryTest.sameRows(expected, v2Rows.get()).foreach(fail(_)) + // Each write computes the micro-batch again, as batchDF is not persisted. + assert(SimpleExternalLookupDataSource.requestCount.get() === 3) + } + } + } + } + + test("view definitions over a lookup-only table, in either view catalog, are not reads") { + withSQLConf( + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName, + "spark.sql.catalog.view_only" -> classOf[TestingViewOnlyCatalog].getName) { + val lookupTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup" + // ALTER VIEW of a session view, and CREATE VIEW and ALTER VIEW in a V2 view catalog. + withTempView("departments") { + sql("CREATE TEMPORARY VIEW departments AS SELECT 1 AS id, 'none' AS department") + sql(s"ALTER VIEW departments AS SELECT * FROM $lookupTable") + assert(spark.table("departments").queryExecution.analyzed.exists { + case relation: DataSourceV2Relation => relation.table eq SimpleExternalLookupTable + case _ => false + }) + } + val catalog = spark.sessionState.catalogManager.catalog("view_only") + .asInstanceOf[TestingViewOnlyCatalog] + sql(s"CREATE VIEW view_only.default.departments AS SELECT * FROM $lookupTable") + sql(s"ALTER VIEW view_only.default.pure_v AS SELECT * FROM $lookupTable") + Seq("departments", "pure_v").foreach { name => + assert(catalog.loadView(Identifier.of(Array("default"), name)).queryText() === + s"SELECT * FROM $lookupTable") + } + } + } + + test("a stream-only Python UDF in a lookup join's residual or lookup parameter") { + assume(shouldTestPythonUDFs) + // The UDF returns its input, so each join has the same rows as the one with the column itself. + val pythonUDF = TestPythonUDF("stream_key") + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq((1, 1), (2, -1), (3, 1)).toDF("id", "shift")) + Seq[(Column => Column, String)]( + (key => left("id") === lookup("id") && key > 0, "residual"), + (key => lookup("id") === key + left("id") - left("shift"), "parameter")).foreach { + case (condition, place) => + Seq("inner", "left_outer").foreach { joinType => + val withUDF = runStream(left.join(lookup, condition(pythonUDF(left("shift"))), joinType)) + assert(withUDF.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]), place) + val builtIn = runStream(left.join(lookup, condition(left("shift")), joinType)) + QueryTest.sameRows(builtIn.rows, withUDF.rows).foreach(error => fail(s"$place: $error")) + } + } + } + + test("a table that also supports batch read is read as a batch scan outside a lookup join") { + withSQLConf( + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName) { + Seq[() => DataFrame]( + () => spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load(), + () => spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual")).foreach { dual => + val df = dual() + assert(df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation]) === false) + checkAnswer(df, Seq(Row(1, "engineering"), Row(1, "research"), Row(2, "sales"))) + } + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + } + } + + test("a provider with a V1 read path cannot serve a lookup-only table") { + Seq( + classOf[RelationProviderExternalLookupDataSource], + classOf[SchemaRelationProviderExternalLookupDataSource], + classOf[FileFormatExternalLookupDataSource], + classOf[FileDataSourceV2ExternalLookupDataSource]).foreach { provider => + val parameters = Map("table" -> "`SimpleExternalLookupTable`", "provider" -> provider.getName) + checkError( + exception = intercept[AnalysisException](spark.read.format(provider.getName).load()), + condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ", + parameters = parameters) + withTempView("hybrid_view") { + checkError( + exception = intercept[AnalysisException] { + sql(s"CREATE TEMPORARY VIEW hybrid_view USING ${provider.getName}") + }, + condition = "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ", + parameters = parameters) + } + } + + // A provider without a V1 read path loads the table through both. + val provider = classOf[SimpleExternalLookupDataSource].getName + def readsLookupOnlyTable(df: DataFrame): Boolean = + df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation]) + assert(readsLookupOnlyTable(spark.read.format(provider).load())) + withTempView("lookup_view") { + sql(s"CREATE TEMPORARY VIEW lookup_view USING $provider") + assert(readsLookupOnlyTable(spark.table("lookup_view"))) + } + } + + test("external lookup join handles null, missing, duplicate, and partial batches") { + val lookup = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option("maxBatchSize", "3") + .load() + val left = streamOf(Seq[java.lang.Integer](1, 1, null, 3, 2).toDF("id")) + + val run = runStream(left.join(lookup, left("id") === lookup("id"), "left_outer")) + val rows = run.rows + assert(rows.toSet === Set( + Row(1, 1, "engineering"), + Row(1, 1, "research"), + Row(null, null, null), + Row(3, null, null), + Row(2, 2, "sales"))) + assert(rows.count(_.get(0) == 1) === 4) + assert(SimpleExternalLookupDataSource.requestSizes.asScala.toSeq === Seq(1, 2)) + assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === Seq(1, 3, 2)) + assert(SimpleExternalLookupDataSource.nullKeyRequests.get() === 0) + // Two batches, [1, 1, null] and [3, 2], send their 1 + 2 distinct requestable keys. + val metrics = run.lookupJoin.metrics + assert(Seq("numInputRows", "numInputBatches", "numLookupRequests", "numLookupParameterRows", + "numOutputRows").map(metrics(_).value) === Seq(5, 2, 2, 3, 7)) + assert(metrics("lookupTime").value > 0) + } + + test("external lookup join supports complete composite equi-keys") { + val lookup = spark.read + .format(classOf[CompositeExternalLookupDataSource].getName) + .load() + val left = streamOf(Seq((1, 1), (1, 2), (2, 1)).toDF("tenant", "id")) + + checkStream( + left.join( + lookup, + left("tenant") === lookup("tenant") && left("id") === lookup("id"), + "left_outer"), + Seq(Row(1, 1, 1, 1, "one-one"), Row(1, 2, null, null, null), + Row(2, 1, 2, 1, "two-one"))) + } + + test("an upstream limit stops one-to-many cursor consumption") { + SimpleExternalLookupDataSource.departmentsById.set(Map(1 -> (1 to 2000).map(_.toString))) + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + assert(runStream(left.join( + lookup, left("id") === lookup("id"), "inner") + .limit(1)).rows.size === 1) + assert(SimpleExternalLookupDataSource.resultRowsRead.get() === 1) + assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq === Seq("cursor", "reader")) + } + + test("external lookup samples connector metrics while consuming a large response") { + SimpleExternalLookupDataSource.departmentsById.set(Map(1 -> (1 to 250).map(_.toString))) + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + assert(runStream(left.join( + lookup, left("id") === lookup("id"), "inner")).rows.size === 250) + // Two periodic samples, followed by request-completion and reader-close samples. + assert(SimpleExternalLookupDataSource.metricSamples.get() >= 4) + } + + test("external lookup offers no lookup key on a double or a string with a non-binary collation") { + // A store may compare such values differently from Spark, for NaN and -0.0 or for case, so the + // equality stays in Spark's residual condition. Without another lookup key the join fails. + Seq( + "double" -> streamOf(Seq(-0.0d, 0.0d).toDF("key")), + "string collate utf8_lcase" -> streamOf(Seq("lookup", "LOOKUP").toDF("key")) + .selectExpr("CAST(key AS STRING COLLATE UTF8_LCASE) AS key")).foreach { + case (keyType, left) => + val lookup = semanticKeyLookup(keyType) + checkError( + exception = streamFailure[AnalysisException]( + left.join(lookup, left("key") === lookup("key"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE", + parameters = Map("table" -> "`SemanticKeyExternalLookupTable`")) + assert(SemanticKeyExternalLookupDataSource.requestSizes.isEmpty) + } + } + + test("external lookup drops returned rows that do not satisfy the selected lookup predicates") { Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Added in [cd9a68fd105](https://github.com/apache/spark/commit/cd9a68fd105e0f772b2b06873d5f2ca6a245ff7d). A composite `(tenant, id)` source selects both predicates but ignores one of them, each in turn, when it matches. In inner and left outer joins, only the stored rows whose tenant and id both match are joined, although the source returns the others. Keeping only the first comparison in the check fails the test. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala: ########## @@ -2530,6 +2530,30 @@ object SQLConf { .bytesConf(ByteUnit.BYTE) .createWithDefault(8L << 30) + val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES = + buildConf("spark.sql.join.externalLookup.maxBatchBytes") + .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE) + .doc("Size in bytes of input rows at which an external lookup join stops adding rows to " + + "a lookup request. The row that reaches this size stays in the request, so a request " + + "can exceed it by one row. A request always takes at least one row, and never more rows " + + "than the source allows, or 1000.") + .version("4.4.0") + .bytesConf(ByteUnit.BYTE) + .checkValue(_ > 0, "External lookup join max batch bytes must be positive") + .createWithDefaultString("64m") + + val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED = + buildConf("spark.sql.join.externalLookup.startupCheck.enabled") + .internal() + .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE) + .doc("When true, a streaming query plans its external lookup joins once when its " + + "execution starts, including the planning calls to their connectors, so that a join " + + "that cannot be planned stops the query before its first micro-batch, also without " + Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [cd9a68fd105](https://github.com/apache/spark/commit/cd9a68fd105e0f772b2b06873d5f2ca6a245ff7d). The doc now names the planning errors that stop a streaming query when it starts: those of the lookup join and of its connector contract. Any other error, such as one that an ordinary join raises too, or an exception that the connector throws while Spark plans the lookup, is left to the first micro-batch. With the config off, the lookup join errors fail the first micro-batch too. The check's Scaladoc says the same. -- 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]
