HeartSaVioR commented on code in PR #60198: URL: https://github.com/apache/spark/pull/60198#discussion_r4534057552
########## sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,6480 @@ +/* + * 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, AtomicLong, AtomicReference} + +import scala.collection.mutable +import scala.concurrent.duration._ +import scala.jdk.CollectionConverters._ +import scala.reflect.{classTag, ClassTag} + +import com.google.common.base.Ticker + +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.{registerTestUDF, shouldTestPythonUDFs, + TestPythonUDF} +import org.apache.spark.sql.QueryTest +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.{CheckExternalLookupJoin, + ExternalLookupJoinEligibility, FormExternalLookupJoin, NoSuchTableException} +import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, AttributeMap, AttributeReference, + Cast, EqualTo, Expression, GenericInternalRow, LessThan, Literal, Rand, SubqueryExpression, + UnsafeProjection} +import org.apache.spark.sql.catalyst.optimizer.{EliminateOuterJoin, PushDownPredicates} +import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter, QueryPlan} +import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, ExternalLookupCacheOptions, + ExternalLookupHint, ExternalLookupHintCacheOptions, ExternalLookupJoin, ExternalLookupProject, + Filter, 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, MetadataColumn, SupportsMetadataColumns, 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.{broadcast, coalesce, col, concat, count, current_date, + current_timestamp, date_from_unix_date, expr, length, lit, max, raise_error, rand, struct, + to_json, udf, upper, 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, LEFT SEMI, LEFT ANTI" + + 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) + } + } + + /** + * Runs the lookup join of the streaming `joined` again, over stream rows with the given ids, in + * one task, with [[ExternalLookupTestTicker]] as the clock of its cache. + */ + private def runWithTestTicker(joined: DataFrame, ids: Seq[Int]): Seq[InternalRow] = { + val lookupJoin = runStream(joined).lookupJoin + SimpleExternalLookupDataSource.resetCounters() + val streamRows = + CoalesceExec(1, LocalTableScanExec(lookupJoin.child.output, ids.map(InternalRow(_)), None)) + lookupJoin.copy(child = streamRows, cacheTicker = ExternalLookupTestTicker) + .executeCollect().toSeq + } + + // Excludes the optimizer rules that push predicates through joins. + private val withoutPredicatePushdown = + Seq(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> PushDownPredicates.ruleName) + + 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 over a left outer lookup join that also counts lookup values, so the join + // runs, and the pruned scan still reads the stream column that the aggregate reads. + val latestByDoor = swipes.join(lookup, swipes("employee") === lookup("id"), "left_outer") + .groupBy(swipes("door")).agg(max(swipes("minute")), count(lookup("department"))) + val run = runStream(latestByDoor, "complete") + assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + QueryTest.sameRows( + Seq(Row("lobby", 10, 2L), Row("garage", 20, 0L)), run.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 over a left outer join that counts a lookup value, so that the join + // stays, with its filters pushed to the stream. + runStream(swipes.join(lookup, onEmployee, "left_outer").where(swipes("minute") > 15) + .groupBy(swipes("door")).agg(max(swipes("minute")), count(lookup("department"))), + "complete")) + assert(runs.forall(_.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))) + 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("a dual-capability source keeps an ordinary join unless the hint opts in") { + val lookup = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research")) + + assert(lookup.queryExecution.analyzed.isInstanceOf[DataSourceV2Relation]) + assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation] === false) + SimpleExternalLookupDataSource.resetCounters() + val ordinary = left.join(lookup, left("id") === lookup("id"), "inner") + assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === false) + checkStream(ordinary, expected) + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + + SimpleExternalLookupDataSource.resetCounters() + val hinted = lookup.hint("external_lookup") + val lookupJoin = left.join(hinted, left("id") === hinted("id"), "inner") + assert(runStream(lookupJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + checkStream(lookupJoin, expected) + assert(SimpleExternalLookupDataSource.requestCount.get() > 0) + } + + test("a hinted or aliased lookup side follows the stream-static contract") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val lookupOnly = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val batch = Seq(1).toDF("id") + // Without the hint, a dual-capability table keeps an ordinary batch join. + checkAnswer( + batch.join(dual, batch("id") === dual("id")), + Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + // With it, the batch join fails: a hint the user wrote is never silently dropped. + Seq( + dual -> "`DualCapabilityExternalLookupTable`", + lookupOnly -> "`SimpleExternalLookupTable`").foreach { case (table, relation) => + val hinted = table.hint("external_lookup") + checkError( + exception = intercept[AnalysisException] { + batch.join(hinted, batch("id") === hinted("id")) + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE", + parameters = Map("relation" -> relation)) + } + // A lookup-only table on the left side is found beneath an alias too. + val stream = streamOf(batch) + checkError( + exception = intercept[AnalysisException] { + lookupOnly.as("l").join(stream, $"l.id" === stream("id")) + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT", + parameters = Map("relation" -> "`SimpleExternalLookupTable`")) + } + + test("a physical join strategy hint conflicts with the external lookup hint") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + val lookupSide = dual.hint("external_lookup").hint("broadcast") + val streamSide = left.hint("broadcast") + val hinted = dual.hint("external_lookup") + Seq( + () => left.join(lookupSide, left("id") === lookupSide("id")), + () => streamSide.join(hinted, streamSide("id") === hinted("id"))).foreach { query => + checkError( + exception = intercept[AnalysisException] { query().queryExecution.analyzed }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY", + parameters = Map( + "strategy" -> "BROADCAST", + "relation" -> "`DualCapabilityExternalLookupTable`")) + } + // Both hints may name the same relation, in either order. A strategy hint is never merged + // into the lookup hint, so the conflict is still reported. + withTempView("external_lookup_left", "external_lookup_right") { + left.createOrReplaceTempView("external_lookup_left") + dual.createOrReplaceTempView("external_lookup_right") + Seq("EXTERNAL_LOOKUP(r), MERGE(r)", "MERGE(r), EXTERNAL_LOOKUP(r)").foreach { hints => + checkError( + exception = intercept[AnalysisException] { + sql(s"SELECT /*+ $hints */ * FROM external_lookup_left l " + + "JOIN external_lookup_right r ON l.id = r.id") + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY", + parameters = Map( + "strategy" -> "MERGE", + "relation" -> "`DualCapabilityExternalLookupTable`")) + } + } + + // Without the lookup hint, the strategy hint plans the ordinary join it asks for. + SimpleExternalLookupDataSource.resetCounters() + val ordinary = left.join(dual.hint("merge"), left("id") === dual("id")) + assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === false) + checkStream(ordinary, Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + assert(SimpleExternalLookupDataSource.requestCount.get() === 0) + } + + test("a hinted dual-capability source fails when no lookup access path exists") { + val lookup = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val invoices = streamOf(Seq((1, "sales")).toDF("invoice", "costCenter")) + + checkStream( + invoices.join(lookup, invoices("costCenter") === lookup("department")), + Seq(Row(1, "sales", 2, "sales"))) + val hinted = lookup.hint("external_lookup") + checkError( + exception = streamFailure[AnalysisException]( + invoices.join(hinted, invoices("costCenter") === hinted("department"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE", + parameters = Map("table" -> "`DualCapabilityExternalLookupTable`")) + } + + test("a physical strategy hint on a lookup-only join is rejected") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1, 3).toDF("id")) + val withLookupHint = lookup.hint("external_lookup").hint("shuffle_hash") + Seq( + "BROADCAST" -> + (() => left.join(lookup.hint("broadcast"), left("id") === lookup("id"), "left_outer")), + "BROADCAST" -> + (() => left.join(broadcast(lookup), left("id") === lookup("id"), "left_outer")), + "MERGE" -> (() => left.hint("merge").join(lookup, left("id") === lookup("id"))), + "SHUFFLE_HASH" -> + (() => left.join(withLookupHint, left("id") === withLookupHint("id")))).foreach { + case (strategy, query) => + checkError( + exception = intercept[AnalysisException] { query().queryExecution.analyzed }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY", + parameters = Map("strategy" -> strategy, "relation" -> "`SimpleExternalLookupTable`")) + } + } + + test("an ordinary join over an enriched lookup join result stays ordinary") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val events = streamOf(Seq(1, 2).toDF("id")) + val enriched = events.join(lookup, events("id") === lookup("id")) + .select(events("id").as("event_id"), lookup("department")) + val base = Seq((1, "a"), (2, "b")).toDF("id", "tag") + val expected = Seq( + Row(1, "a", 1, "engineering"), Row(1, "a", 1, "research"), Row(2, "b", 2, "sales")) + def lookupJoinCount(df: DataFrame): Int = + runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j }.size + + val joined = base.join(enriched, base("id") === enriched("event_id")) + assert(lookupJoinCount(joined) === 1) + checkStream(joined, expected) + + withTempView("external_lookup_base", "external_lookup_events", "external_lookup_right") { + base.createOrReplaceTempView("external_lookup_base") + events.createOrReplaceTempView("external_lookup_events") + lookup.createOrReplaceTempView("external_lookup_right") + val sqlJoined = sql( + """ + |SELECT b.id, b.tag, e.event_id, e.department + |FROM external_lookup_base b JOIN ( + | SELECT v.id AS event_id, r.department + | FROM external_lookup_events v JOIN external_lookup_right r ON v.id = r.id) e + |ON b.id = e.event_id + |""".stripMargin) + assert(lookupJoinCount(sqlJoined) === 1) + checkStream(sqlJoined, expected) + } + } + + test("an external lookup hint outside any join is ignored") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, "sales")) + + checkAnswer(dual.hint("external_lookup"), expected) + assert(dual.hint("external_lookup", "cache_enabled=false").count() === 3) + withTempView("external_lookup_right") { + dual.createOrReplaceTempView("external_lookup_right") + checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP */ * FROM external_lookup_right"), expected) + checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ * FROM external_lookup_right r"), expected) + checkAnswer( + sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ id, count(*) FROM external_lookup_right r " + + "GROUP BY id"), + Seq(Row(1, 2), Row(2, 1))) + } + } + + test("a query without a lookup-only table or the hint is not searched for lookup joins") { + // Classifying the joins of a plan inlines its CTE references, so a plan that can have no lookup + // join is left alone, such as this self-join of a CTE over a table that supports batch reads. + // The pattern bits tell it, so the plan is not walked and its tables are not asked for their + // capabilities, also for a subquery, a micro-batch, cache substitution and each join. + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val lookupOnly = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + withTempView("employee_directory", "lookup_directory", "badge_swipes") { + dual.createOrReplaceTempView("employee_directory") + lookupOnly.createOrReplaceTempView("lookup_directory") + streamOf(Seq((1, "lobby")).toDF("employee", "door")).createOrReplaceTempView("badge_swipes") + val ordinary = sql( + """ + |WITH d AS (TABLE employee_directory) + |SELECT a.id, a.department, b.department FROM d a JOIN d b ON a.id = b.id + |""".stripMargin) + val withSubquery = sql( + """ + |SELECT id, department FROM employee_directory WHERE id IN ( + | SELECT a.id FROM employee_directory a JOIN employee_directory b ON a.id = b.id) + |""".stripMargin) + val microBatch = runStream(sql( + """ + |SELECT s.door, d.department + |FROM badge_swipes s JOIN employee_directory d ON s.employee = d.id + |""".stripMargin)).execution.analyzed + // An entry in the cache makes cache substitution look for lookup sides. + val cached = spark.range(1).toDF("cached").cache() + try { + assert(cached.count() === 1) + Seq(ordinary.queryExecution.analyzed, withSubquery.queryExecution.analyzed, microBatch) + .foreach { plan => + // Computes the pattern bits, with which each relation asks its table once. + assert(ExternalLookupJoinEligibility.mayHaveLookupJoin(plan) === false) + DualCapabilityExternalLookupTable.capabilityCalls.set(0) + assert(ExternalLookupJoinEligibility.lookupSidePlans(plan).isEmpty) + CheckExternalLookupJoin(plan) + assert(FormExternalLookupJoin(plan) eq plan) + spark.sharedState.cacheManager.useCachedData(plan) + plan.collectWithSubqueries { case join: Join => join }.foreach { join => + assert( + ExternalLookupJoinEligibility(join) === ExternalLookupJoinEligibility.NotLookupJoin) + } + assert(DualCapabilityExternalLookupTable.capabilityCalls.get() === 0) + } + } finally { + cached.unpersist(blocking = true) + } + checkAnswer(ordinary, Seq( + Row(1, "engineering", "engineering"), Row(1, "engineering", "research"), + Row(1, "research", "engineering"), Row(1, "research", "research"), + Row(2, "sales", "sales"))) + // The hint or a lookup-only table makes a lookup join possible, so the joins are classified. + Seq("/*+ EXTERNAL_LOOKUP(d) */" -> "employee_directory", "" -> "lookup_directory").foreach { + case (hint, table) => + val query = sql( + s""" + |WITH d AS (TABLE $table) + |SELECT $hint s.door, d.department FROM badge_swipes s JOIN d ON s.employee = d.id + |""".stripMargin) + assert(ExternalLookupJoinEligibility.mayHaveLookupJoin(query.queryExecution.analyzed)) + checkStream(query, Seq(Row("lobby", "engineering"), Row("lobby", "research"))) + } + } + } + + test("a lookup side may be hinted more than once") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val swipes = streamOf(Seq((1, "door-a")).toDF("employee", "door")) + val expected = Seq(Row(1, "door-a", "engineering"), Row(1, "door-a", "research")) + def lookupJoinCount(df: DataFrame): Int = + runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j }.size + + val twice = dual.hint("external_lookup").hint("external_lookup") + val joined = swipes.join(twice, swipes("employee") === twice("id")) + .select(swipes("employee"), swipes("door"), twice("department")) + assert(lookupJoinCount(joined) === 1) + checkStream(joined, expected) + withTempView("badge_swipes", "hinted_directory", "employee_directory") { + swipes.createOrReplaceTempView("badge_swipes") + dual.hint("external_lookup").createOrReplaceTempView("hinted_directory") + dual.createOrReplaceTempView("employee_directory") + // A view over a hinted table that the hint names too, and a name given twice in any case. + Seq( + "EXTERNAL_LOOKUP(d)" -> "hinted_directory", + "EXTERNAL_LOOKUP(d, d)" -> "employee_directory", + "EXTERNAL_LOOKUP(d, D)" -> "employee_directory").foreach { case (hint, directory) => + val df = sql( + s""" + |SELECT /*+ $hint */ s.employee, s.door, d.department + |FROM badge_swipes s JOIN $directory d ON s.employee = d.id + |""".stripMargin) + assert(lookupJoinCount(df) === 1, hint) + checkStream(df, expected) + } + } + } + + test("an external lookup hint in a subquery without a join is ignored like a strategy hint") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + withTempView("badge_swipes", "employee_directory") { + Seq((1, "door-a"), (3, "door-b")).toDF("employee", "door") + .createOrReplaceTempView("badge_swipes") + dual.createOrReplaceTempView("employee_directory") + Seq("BROADCAST", "EXTERNAL_LOOKUP").foreach { hint => + checkAnswer( + sql( + s""" + |SELECT door FROM badge_swipes s WHERE EXISTS ( + | SELECT /*+ $hint */ * FROM employee_directory d WHERE d.id = s.employee) + |""".stripMargin), + Seq(Row("door-a"))) + checkAnswer( + sql( + s""" + |SELECT door, ( + | SELECT /*+ $hint */ max(d.department) FROM employee_directory d + | WHERE d.id = s.employee) + |FROM badge_swipes s + |""".stripMargin), + Seq(Row("door-a", "research"), Row("door-b", null))) + } + } + } + + test("an empty lookup side does not call the connector") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1, 3).toDF("id")) + withTempView("empty_side_lookup", "empty_side_left") { + lookup.createOrReplaceTempView("empty_side_lookup") + left.createOrReplaceTempView("empty_side_left") + Seq("inner" -> "INNER", "left_outer" -> "LEFT OUTER").foreach { case (joinType, sqlJoin) => + val expected = + if (joinType == "inner") Seq.empty[Row] else Seq(Row(1, null, null), Row(3, null, null)) + val empty = lookup.where(lit(false)) + Seq( + () => left.join(empty, left("id") === empty("id"), joinType), + () => sql(s"SELECT * FROM empty_side_left l $sqlJoin JOIN " + + "(SELECT * FROM empty_side_lookup WHERE 1 = 0) r ON l.id = r.id")).foreach { query => + SimpleExternalLookupDataSource.resetCounters() + val joined = query() + assert( + runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === false) + checkStream(joined, expected) + assert(SimpleExternalLookupDataSource.lookupCandidates.get() === Seq.empty) + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + assert(SimpleExternalLookupDataSource.requestCount.get() === 0) + } + } + } + } + + test("a lookup side with another operator above the table fails when the DataFrame is built") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1, 3).toDF("id")) + val values = Seq(1).toDF("v") + // A lookup-only table, which no other join can read, and a hinted table that supports batch + // reads too. The join fails even where the optimizer would remove the operator. A subquery is + // planned apart from the lookup results, so a projection or filter with one cannot run either. + Seq( + lookup.limit(1), + lookup.distinct(), + dual.limit(1).hint("external_lookup"), + lookup.filter($"id".isin(values)), + lookup.filter(values.where(col("v") === 1).exists()), + lookup.filter($"id" < spark.range(2).select(max($"id")).scalar())).foreach { right => + checkError( + exception = intercept[AnalysisException] { + left.join(right, left("id") === right("id"), "left_outer") + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN", + parameters = Map.empty) + } + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + } + + test("a USING join with the EXTERNAL_LOOKUP hint runs as an external lookup join") { + val left = streamOf(Seq(1, 3).toDF("id")) + Seq[Class[_]]( + classOf[DualCapabilityExternalLookupDataSource], + classOf[SimpleExternalLookupDataSource]).foreach { source => + val lookup = spark.read.format(source.getName).load().hint("external_lookup") + val joined = left.join(lookup, Seq("id"), "left_outer") + assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), Row(3, null))) + } + + // Without a condition the hinted join still fails, on the final plan. + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + .hint("external_lookup") + checkError( + exception = streamFailure[AnalysisException](left.join(dual)), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + } + + test("an external lookup hint is found beneath an alias on either join side") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + val aliased = dual.hint("external_lookup").as("r") + val joined = left.join(aliased, left("id") === $"r.id") + assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + checkStream(joined, Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + + checkError( + exception = intercept[AnalysisException] { + left.hint("external_lookup").as("l").join(dual, $"l.id" === dual("id")) + .queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + } + + test("a strategy hint on a nested join does not disable an outer lookup join") { + val left = streamOf(Seq((1, 10), (2, 20)).toDF("id", "k")) + val other = Seq((10, "a"), (20, "b")).toDF("k", "v") + val nested = left.join(other.hint("merge"), "k") + def usesLookup(df: DataFrame): Boolean = + runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) + + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + .hint("external_lookup") + val dualJoin = nested.join(dual, nested("id") === dual("id")) + assert(usesLookup(dualJoin)) + checkStream(dualJoin, Seq( + Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"), + Row(20, 2, "b", 2, "sales"))) + + // A lookup-only table on the outer join becomes a lookup join too, despite the nested join's + // MERGE hint. + val lookupOnly = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val lookupOnlyJoin = nested.join(lookupOnly, nested("id") === lookupOnly("id")) + assert(usesLookup(lookupOnlyJoin)) + checkStream(lookupOnlyJoin, Seq( + Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"), + Row(20, 2, "b", 2, "sales"))) + } + + test("an explicit external lookup option marker rejects unsupported join shapes") { + val lookup = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + checkError( + exception = intercept[AnalysisException] { + left.join( + lookup.hint("external_lookup", "cache_enabled=false"), + left("id") === lookup("id"), + "right_outer").queryExecution.analyzed + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE", + parameters = Map( + "joinType" -> "RIGHT OUTER", + "relation" -> "`DualCapabilityExternalLookupTable`", + "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES)) + + // A cross join is an inner join, which fails without a key when the query starts. + checkError( + exception = streamFailure[AnalysisException](left.crossJoin(lookup.hint("external_lookup"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + + // A strategy hint on the same join conflicts before the join type is checked. + checkError( + exception = intercept[AnalysisException] { + left.join( + lookup.hint("external_lookup", "cache_enabled=false").hint("merge"), + left("id") === lookup("id"), + "right_outer").queryExecution.analyzed + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY", + parameters = Map("strategy" -> "MERGE", "relation" -> "`DualCapabilityExternalLookupTable`")) + } + + test("external lookup predicate negotiation includes type and null semantics") { + SimpleExternalLookupDataSource.resetCounters() + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id")) + + runStream(left.join(lookup, left("id") <=> lookup("id"), "inner")) + assert(SimpleExternalLookupDataSource.lookupCandidates.get() === + Seq(("<=>", "id", IntegerType))) + } + + test("an external lookup hint on an ineligible join is rejected") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + .hint("external_lookup") + val left = streamOf(Seq(1).toDF("id")) + + Seq[(() => DataFrame, String)]( + (() => left.join(dual, left("id") === dual("id"), "right_outer"), "RIGHT OUTER"), + (() => left.join(dual, left("id") === dual("id"), "full_outer"), "FULL OUTER")).foreach { + case (joined, joinType) => + val error = intercept[AnalysisException](joined()) + assert(error.getCondition === "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE") + assert(error.getMessageParameters.get("joinType") === joinType) + assert(error.getMessageParameters.get("relation") === "`DualCapabilityExternalLookupTable`") + } + } + + 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("an external lookup hinted DataFrame can be reused by multiple joins") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + .hint("external_lookup") + + val first = streamOf(Seq(1).toDF("id")) + val second = streamOf(Seq(2).toDF("id")) + checkStream(first.join(lookup, first("id") === lookup("id")), + Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))) + checkStream(second.join(lookup, second("id") === lookup("id")), + Seq(Row(2, 2, "sales"))) + } + + 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 prunes unused throwable lookup expressions") { + val rawLookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val lookup = rawLookup.select($"id", expr("raise_error('unused')").as("unused")) + val left = streamOf(Seq(1).toDF("id")) + + checkStream( + left.join(lookup, left("id") === lookup("id"), "left_semi"), + Seq(Row(1))) + + val projected = left.as("left").join( + lookup.as("lookup"), + $"left.id" === $"lookup.id", + "inner").select($"left.id") + checkStream(projected, Seq(Row(1), Row(1))) + } + + test("external lookup rejects a non-deterministic lookup-side projection or filter") { + val rawLookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1, 1, 2).toDF("id")) + // The join evaluates the lookup-side stages on each returned row, so a random value could + // differ between two stream rows that join the same stored row. + Seq( + rawLookup.select($"id", $"department", rand(3).as("sample")), + rawLookup.filter(rand(3) >= 0.5)).foreach { lookup => + checkError( + exception = intercept[AnalysisException] { + left.join(lookup, left("id") === lookup("id"), "inner") + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN", + parameters = Map.empty) + } + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + } + + test("external lookup hint rejects duplicate and malformed options") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val positiveSize = Map("expected" -> "a positive size, such as 64k, 16m, or 1g") + val duration = Map("expected" -> ("a non-negative duration, such as 500ms, 5s, or 10m; " + + "a number without a unit is in milliseconds")) + val supportedOptions = Map("supportedOptions" -> + "\"cache_enabled\", \"cache_max_bytes\", \"cache_ttl\"") + Seq( + (Seq("cache_enabled=true", "cache_enabled=false"), "cache_enabled", "DUPLICATE_OPTION", + Map()), + (Seq("cache_enabled=unknown"), "cache_enabled", "INVALID_OPTION_VALUE", + Map("expected" -> "true or false")), + (Seq("cache_enabled="), "cache_enabled=", "INVALID_OPTION_FORMAT", Map()), + (Seq("=true"), "=true", "INVALID_OPTION_FORMAT", Map()), + (Seq("cache_mode=enabled"), "cache_mode", "UNSUPPORTED_OPTION", supportedOptions), + (Seq("cache_max_bytes=0"), "cache_max_bytes", "INVALID_OPTION_VALUE", positiveSize), + (Seq("cache_max_bytes=abc"), "cache_max_bytes", "INVALID_OPTION_VALUE", positiveSize), + (Seq("cache_ttl=-1ms"), "cache_ttl", "INVALID_OPTION_VALUE", duration), + (Seq("cache_ttl=abc"), "cache_ttl", "INVALID_OPTION_VALUE", duration), + (Seq("cache_max_entries=100"), "cache_max_entries", "UNSUPPORTED_OPTION", + supportedOptions), + (Seq("unknown_option=1"), "unknown_option", "UNSUPPORTED_OPTION", supportedOptions)).foreach { + case (options, option, subClass, parameters) => + checkError( + exception = intercept[AnalysisException] { + lookup.hint("external_lookup", options: _*).queryExecution.analyzed + }, + condition = s"INVALID_EXTERNAL_LOOKUP_HINT.$subClass", + parameters = Map("option" -> ("\"" + option + "\"")) ++ parameters) + } + checkError( + exception = intercept[AnalysisException] { + lookup.hint("external_lookup", 1).queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.UNSUPPORTED_PARAMETER", + parameters = Map("parameter" -> "\"1\"")) + // A string without `=` is a relation name. When it names no relation, as an option without a + // value does, the error says how to write an option. + val noValue = intercept[AnalysisException] { + lookup.hint("external_lookup", "cache_enabled").queryExecution.analyzed + } + checkError( + exception = noValue, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND", + parameters = Map("relations" -> "`cache_enabled`")) + assert(noValue.getMessage.contains("Cannot find the relation(s) `cache_enabled` 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'.")) + } + + test("external lookup hint options ignore the case of a name and blanks around it and a value") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + def hintOptions(options: String*): ExternalLookupHintCacheOptions = + lookup.hint("external_lookup", options: _*).queryExecution.analyzed.collectFirst { + case marker: ExternalLookupHint => marker.cacheOptions + }.get + assert(hintOptions("CACHE_TTL = 5s").ttlMillis === Some(5000L)) + assert(hintOptions("Cache_Max_Bytes=8k").maxBytes === Some(8192L)) + // The size and duration parsers trim their input themselves, so only a boolean shows that the + // value is trimmed. + assert(hintOptions("cache_enabled = TRUE").enabled === Some(true)) + assert(hintOptions("cache_enabled=False").enabled === Some(false)) + // An option that differs from another only in case is the same option. + checkError( + exception = intercept[AnalysisException] { + lookup.hint("external_lookup", "cache_ttl=1s", "CACHE_TTL=2s").queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.DUPLICATE_OPTION", + parameters = Map("option" -> "\"cache_ttl\"")) + } + + test("a hint can mix relation names and cache options given as strings") { + withSQLConf( + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName) { + val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual" + val swipes = streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", "door")) + val expected = Seq(Row(1, "lobby", "engineering"), Row(1, "lobby", "research")) + def checkCacheOptions(df: DataFrame, check: ExternalLookupCacheOptions => Boolean): Unit = { + val run = runStream(df) + QueryTest.sameRows(expected, run.rows).foreach(fail(_)) + val prepared = run.plan.collectFirst { case join: PreparedExternalLookupJoin => join } + assert(prepared.exists(join => check(join.cacheOptions)), prepared) + } + + val directory = spark.table(catalogTable).as("r") + checkCacheOptions( + swipes.join(directory, swipes("employee") === $"r.id") + .hint("external_lookup", "r", "cache_enabled=false") + .select("employee", "door", "department"), + _.enabled === false) + withTempView("badge_swipes") { + swipes.createOrReplaceTempView("badge_swipes") + checkCacheOptions( + sql( + s""" + |SELECT /*+ EXTERNAL_LOOKUP('cache_ttl=2s', 'r') */ s.employee, s.door, r.department + |FROM badge_swipes s JOIN $catalogTable r ON s.employee = r.id + |""".stripMargin), + _.ttlMillis === 2000L) + } + } + } + + test("the cache options of a hint in a WITH clause apply to its lookup join") { + withSQLConf( + s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" -> + classOf[ExternalLookupTestCatalog].getName) { + withTempView("badge_swipes") { + streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", "door")) + .createOrReplaceTempView("badge_swipes") + val run = runStream(sql( + s""" + |WITH lk AS ( + | SELECT /*+ EXTERNAL_LOOKUP('cache_enabled=false') */ * + | FROM $EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual) + |SELECT s.door, lk.department FROM badge_swipes s JOIN lk ON s.employee = lk.id + |""".stripMargin)) + QueryTest.sameRows( + Seq(Row("lobby", "engineering"), Row("lobby", "research")), run.rows).foreach(fail(_)) + val prepared = run.plan.collectFirst { case join: PreparedExternalLookupJoin => join } + assert(prepared.map(_.cacheOptions.enabled) === Some(false)) + } + } + } + + test("a hint with cache options over a join fails") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + val swipes = streamOf(Seq((1, "lobby")).toDF("employee", "door")) + // The options would apply to no join, so the hint fails rather than leave the cache on. + withTempView("badge_swipes", "employee_directory") { + swipes.createOrReplaceTempView("badge_swipes") + dual.createOrReplaceTempView("employee_directory") + checkError( + exception = intercept[AnalysisException] { + sql( + """ + |SELECT /*+ EXTERNAL_LOOKUP('cache_enabled=false') */ s.door, d.department + |FROM badge_swipes s JOIN employee_directory d ON s.employee = d.id + |""".stripMargin) + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + } + checkError( + exception = intercept[AnalysisException] { + swipes.join(dual, swipes("employee") === dual("id")) + .hint("external_lookup", "cache_enabled=false").queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + // Nor do the joins below a set operation read the options of a hint over it. + val visits = streamOf(Seq((2, "garage")).toDF("employee", "door")) + checkError( + exception = intercept[AnalysisException] { + swipes.join(dual, swipes("employee") === dual("id")) + .union(visits.join(dual, visits("employee") === dual("id"))) + .hint("external_lookup", "cache_enabled=false").queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + withTempView("badge_swipes", "garage_visits", "employee_directory") { + swipes.createOrReplaceTempView("badge_swipes") + visits.createOrReplaceTempView("garage_visits") + dual.createOrReplaceTempView("employee_directory") + checkError( + exception = intercept[AnalysisException] { + sql( + """ + |SELECT /*+ EXTERNAL_LOOKUP('cache_ttl=5s') */ door FROM ( + | SELECT s.door FROM badge_swipes s JOIN employee_directory d ON s.employee = d.id + | UNION ALL + | SELECT v.door FROM garage_visits v JOIN employee_directory d ON v.employee = d.id) + |""".stripMargin) + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + } + } + + test("a cache option that a hint does not set follows its configuration when the query runs") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName) + .option("maxBatchSize", "1").load() + // The hint is written before the configuration is set, and sets only the byte bound, + // cache_max_bytes. + val hinted = lookup.hint("external_lookup", "cache_max_bytes=5k") + val swipes = streamOf(Seq((1, "lobby"), (2, "garage"), (1, "lobby")).toDF("employee", "door")) + val joined = swipes.join(hinted, swipes("employee") === hinted("id")) + withSQLConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED.key -> "false") { + SimpleExternalLookupDataSource.resetCounters() + val run = runStream(joined) + val prepared = run.plan.collectFirst { case join: PreparedExternalLookupJoin => join }.get + assert(prepared.cacheOptions.enabled === false) + assert(prepared.cacheOptions.maxBytes === 5 * 1024) + assert(SimpleExternalLookupDataSource.requestCount.get() === 3) + } + } + + test("of several hints on one lookup side, an outer hint's cache option wins") { + val dual = spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + withTempView("badge_swipes", "uncached_directory") { + streamOf(Seq((1, "lobby")).toDF("employee", "door")).createOrReplaceTempView("badge_swipes") + dual.hint("external_lookup", "cache_enabled=false", "cache_max_bytes=7k") + .createOrReplaceTempView("uncached_directory") + def cacheOptions(hint: String): ExternalLookupCacheOptions = runStream(sql( + s""" + |SELECT /*+ $hint */ s.door, d.department + |FROM badge_swipes s JOIN uncached_directory d ON s.employee = d.id + |""".stripMargin)).plan.collectFirst { + case join: PreparedExternalLookupJoin => join.cacheOptions + }.get + // The query's hint names the view, whose own hint sets two options. + val inner = cacheOptions("EXTERNAL_LOOKUP(d)") + assert(inner.enabled === false) + assert(inner.maxBytes === 7 * 1024) + val overridden = cacheOptions("EXTERNAL_LOOKUP(d, 'cache_enabled=true')") + assert(overridden.enabled === true) + assert(overridden.maxBytes === 7 * 1024) + } + // Two hints that name one relation: the outer one wins, which is the first in a comment and + // the later of two Dataset calls. + val swipes = streamOf(Seq((1, "lobby")).toDF("employee", "door")) + def ttlMillis(df: DataFrame): Long = runStream(df).plan.collectFirst { + case join: PreparedExternalLookupJoin => join.cacheOptions.ttlMillis + }.get + withTempView("badge_swipes", "employee_directory") { + swipes.createOrReplaceTempView("badge_swipes") + dual.createOrReplaceTempView("employee_directory") + assert(ttlMillis(sql( + """ + |SELECT /*+ EXTERNAL_LOOKUP(r, 'cache_ttl=5s'), EXTERNAL_LOOKUP(r, 'cache_ttl=10s') */ + | s.door, r.department + |FROM badge_swipes s JOIN employee_directory r ON s.employee = r.id + |""".stripMargin)) === 5000) + } + val directory = dual.as("r") + val joined = swipes.join(directory, swipes("employee") === $"r.id") + assert(ttlMillis(joined.hint("external_lookup", "r", "cache_ttl=5s") + .hint("external_lookup", "r", "cache_ttl=10s")) === 10000) + // The same when the inner hint marks a projection of the relation that the outer one names. + val projected = directory.select($"r.id", $"r.department") + .hint("external_lookup", "cache_ttl=5s") + assert(ttlMillis(swipes.join(projected, swipes("employee") === projected("id")) + .hint("external_lookup", "r", "cache_ttl=10s")) === 10000) + } + + test("external lookup hint rejects invalid placement and relation targets") { + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + val left = streamOf(Seq(1).toDF("id")) + + checkError( + exception = intercept[AnalysisException] { + left.hint("external_lookup").join(lookup, left("id") === lookup("id")) + .queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE", + parameters = Map.empty) + + withTempView("external_lookup_left", "external_lookup_right") { + left.createOrReplaceTempView("external_lookup_left") + lookup.createOrReplaceTempView("external_lookup_right") + def query(hint: String): DataFrame = sql( + s""" + |SELECT /*+ $hint */ l.id, r.department + |FROM external_lookup_left l JOIN external_lookup_right r ON l.id = r.id + |""".stripMargin) + checkError( + exception = intercept[AnalysisException] { + query("EXTERNAL_LOOKUP(missing)").queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND", + parameters = Map("relations" -> "`missing`")) + // A name that is repeated is reported once. + checkError( + exception = intercept[AnalysisException] { + query("EXTERNAL_LOOKUP(missing, missing)").queryExecution.analyzed + }, + condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND", + parameters = Map("relations" -> "`missing`")) + } + + val stream = MemoryStream[Int].toDF().toDF("id") + checkError( + exception = intercept[AnalysisException] { + left.join(stream.hint("external_lookup"), left("id") === stream("id")) + .queryExecution.analyzed + }, + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STREAMING_LOOKUP_SIDE", + parameters = Map.empty) + } + + test("external lookup reports lookup sides and conditions it cannot plan") { + val claims = streamOf(Seq((1, "sales")).toDF("id", "costCenter")) + def planningError(lookup: DataFrame, condition: Column): AnalysisException = + streamFailure[AnalysisException](claims.join(lookup, condition)) + def analysisError(lookup: DataFrame, condition: Column): AnalysisException = + intercept[AnalysisException](claims.join(lookup, condition)) + + // A hinted lookup side fails when the DataFrame is built: with LOOKUP_PLAN when it reads no + // DSv2 table, as a local relation does, and with TABLE for a DSv2 table that does not support + // external lookup. + val local = Seq(1).toDF("id").hint("external_lookup") + checkError( + exception = analysisError(local, claims("id") === local("id")), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN", + parameters = Map.empty) + + val batchOnly = spark.read + .format(classOf[MisconfiguredExternalLookupDataSource].getName) + .option("kind", "batchOnly") + .load() + .hint("external_lookup") + checkError( + exception = analysisError(batchOnly, claims("id") === batchOnly("id")), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.TABLE", + parameters = Map("table" -> "`MisconfiguredExternalLookupTable`")) + + val noLookupBuilder = spark.read + .format(classOf[MisconfiguredExternalLookupDataSource].getName) + .option("kind", "noLookupBuilder") + .load() + checkError( + exception = planningError(noLookupBuilder, claims("id") === noLookupBuilder("id")), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SCAN_BUILDER", + parameters = Map("table" -> "`MisconfiguredExternalLookupTable`")) + + val lookup = spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + checkError( + exception = planningError(lookup, claims("costCenter") === lookup("department")), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE", + parameters = Map("table" -> "`SimpleExternalLookupTable`")) + } + + test("external lookup maps a selected predicate to its own occurrence") { + val lookup = spark.read + .format(classOf[SimpleExternalLookupDataSource].getName) + .option("selectionMode", "last") + .load() + .hint("external_lookup", "cache_enabled=false") + 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")) + // Column pruning narrows the join's requiredLookupOutput to the lookup columns that the + // projection reads, and projects the lookup side once the join no longer needs some of its + // columns, which lookup planning accepts. Here the join still reads both columns of the table, + // the key and `department`, so the lookup side stays the table. + val joined = left.join(lookup, left("id") === lookup("id"), "left_outer") + .select(left("id"), lookup("department")) + + assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])) + // The source is asked for the lookup column that the projection reads, and for the key, which + // Spark checks on every returned row. + assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id", "department")) + 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))) + + // The connector is offered `id = ?` from the condition, and the comparisons with constants of + // the lookup side, where predicate pushdown moves the lookup-side conjuncts: `department = ?`, + // and `id < ?`, which constant propagation derives from the last conjunct. Spark evaluates the + // stream-side conjunct on each stream row before the lookup, and the lookup-side ones on the + // returned 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), ("<", "id", IntegerType))) + } + + 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 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 [da986b58363](https://github.com/apache/spark/commit/da986b58363a408c88f3fe2b8d296468acbcb7a1). Both tests now also run with `PushDownPredicates` excluded, for inner and left semi joins, where the join's own check runs. The `flag` runs request the same keys, 1 and 3, and the ANSI guard runs complete without casting `bad`. Computing the request row before the stream-side check fails the new runs. The comments now say that pushdown moves the conjunct below inner and left semi joins, as for an ordinary join, and that the join checks it when it stays in the condition. -- 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]
