HeartSaVioR commented on code in PR #60198: URL: https://github.com/apache/spark/pull/60198#discussion_r4532155893
########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,526 @@ +/* + * 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.datasources.v2 + +import java.util.{Collections, IdentityHashMap} + +import scala.annotation.tailrec +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeMap, + AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, PythonUDF} +import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression +import org.apache.spark.sql.catalyst.planning.ScanOperation +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, ExternalLookupJoin, + ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, Filter, LogicalPlan, + LookupKeyComparison, PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, EXTERNAL_LOOKUP_JOIN} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability} +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference} +import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate} +import org.apache.spark.sql.connector.read.{LookupParameter, SupportsExternalLookup, + SupportsPushDownRequiredColumns} +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.execution.datasources.DataSourceStrategy +import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, StructType} + +/** Finalizes an optimized external lookup side immediately before ordinary V2 scan preparation. */ +object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper + with QueryErrorsBase { + override def apply(plan: LogicalPlan): LogicalPlan = { + val prepared = plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) { + case join: ExternalLookupJoin if provablyEmpty(join) => emptyJoinResult(join) + case join: ExternalLookupJoin => prepare(join) + } + // Prepared lookup joins no longer contain their lookup relation, so a lookup-only table that + // is still read here cannot run. + if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) { + prepared.foreach { node => + ExternalLookupRelations.lookupOnlyTable(node).foreach { table => + throw QueryCompilationErrors.unsupportedBatchReadError(table) + } + } + } + prepared + } + + // The optimizer folds `WHERE false` on the lookup side into an empty relation, and a condition + // such as `s.id = r.id AND false` into `false`. Such a join needs no connector call. + private def provablyEmpty(join: ExternalLookupJoin): Boolean = + join.right.maxRows.contains(0L) || (join.condition match { + case Some(Literal(value, BooleanType)) => value == null || value == false + case _ => false + }) + + private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = { + val nullLookupColumns = join.right.output.map { attr => + Alias(Literal(null, attr.dataType), attr.name)(attr.exprId) + } + val unmatched = Project(join.left.output ++ nullLookupColumns, join.left) + join.joinType match { + case LeftOuter => unmatched + case LeftAnti => join.left + // The stream side is kept under a false filter rather than replaced by an empty relation, + // so that its sources, watermarks and stateful operators still run in every micro-batch. + // PruneFilters decides whether a streaming subplan may be pruned. + case LeftSemi => Filter(Literal.FalseLiteral, join.left) + case _ => Filter(Literal.FalseLiteral, unmatched) + } + } + + private def prepare(join: ExternalLookupJoin): LogicalPlan = { + // Analysis already rejects a lookup side with a stage that cannot be evaluated, or with another + // operator; this is a fallback. + val hasUnevaluableStage = join.right.exists { + case node @ (_: Project | _: Filter) => + !node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) + case _ => false + } + // The lookup-side stages are built here, and no later rule reaches them. withField and + // dropFields values cannot be evaluated until ReplaceUpdateFieldsExpression, in the + // optimizer's last batch, lowers them, so the same rule lowers them now, and the current time + // of a micro-batch takes its value now too. + val lookupPlan = (if (hasUnevaluableStage) None else { + extractLookupPlan(ReplaceUpdateFieldsExpression( + ExternalLookupJoinShapes.withBatchTimestampValues(join.right))) + }).getOrElse { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN") + } + val relation = lookupPlan.relation + val tableName = relation.table.name() + val supportsRead = relation.table match { + case table: SupportsRead + if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => table + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> toSQLId(tableName))) + } + val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates) + // A Python or external UDF over lookup columns cannot run in the residual. The rules that move + // one out of a join condition match only Join and run later, so this rule does it: an inner + // join evaluates the conjunct in a filter above the join, and other join types are rejected. + if (join.joinType != Inner) { + conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach { + case _: ExternalUserDefinedFunction => + throw QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType) + case _ => + throw QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType) + } + } + val conditionCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, index) => + ExternalLookupJoinShapes.lookupComparison( + conjunct, join.left.outputSet, join.right.outputSet).flatMap { comparison => + tableColumn(comparison.lookupField, lookupPlan).map { column => + OfferedLookupPredicate(comparison.parameter, column, Some(index), comparison.comparison) + } + } + } + // Predicate pushdown moves a comparison of a lookup column with a constant onto the lookup + // side, as for an ordinary join, so the source receives it as a pushed filter. A source may + // need it in its access path, as the constant tenant of a composite key, so it is offered as + // well. The filter stays, and Spark evaluates it on the returned rows either way. + val lookupSideOutput = AttributeSet(lookupPlan.relation.output ++ + lookupPlan.fields.map(_.toAttribute) ++ lookupPlan.upperStages.flatMap(_.output)) + val filterCandidates = lookupFilterConjuncts(lookupPlan).flatMap { conjunct => + ExternalLookupJoinShapes.lookupComparison(conjunct, AttributeSet.empty, lookupSideOutput) + .filter(_.parameter.isInstanceOf[Literal]) 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 [6d508fd7d9b](https://github.com/apache/spark/commit/6d508fd7d9b7100414eb18ff5c6388d6a24f8b69): the Literal-only filter is gone, so `lookupComparison`'s own rule decides, as it does for the join condition. The tests use a constant tenant from a deterministic Scala UDF over a literal: in the join condition with and without `PushDownPredicates`, in a filter above an inner join, and as the only key of a join. Putting the filter back fails them. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala: ########## @@ -3195,6 +3211,27 @@ object PushPredicateThroughJoin extends Rule[LogicalPlan] with PredicateHelper { (leftEvaluateCondition, rightEvaluateCondition, commonCondition ++ stayUp) } + /** + * [[split]] for an external lookup join. A conjunct over lookup columns that a lookup-side stage + * cannot evaluate, such as one with a Python UDF or a subquery, is neither pushed nor moved into + * the condition, so it is left out of the result. A conjunct without references, such as a + * literal, belongs to neither side. It stays with the common conditions, so that a condition + * that folds to false keeps its result without a lookup, instead of leaving a join whose stream + * side is empty. A comparison of a lookup column with a constant moves as for a join; lookup + * planning still offers it to the connector as a lookup candidate. + * + * @return (canEvaluateInLeft, canEvaluateInRight, haveToEvaluateInBoth) + */ + private def splitLookupJoin(condition: Seq[Expression], join: ExternalLookupJoin) = { + val movable = condition.filterNot { cond => + cond.references.exists(join.right.outputSet.contains) && 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 [6d508fd7d9b](https://github.com/apache/spark/commit/6d508fd7d9b7100414eb18ff5c6388d6a24f8b69): each conjunct is now judged by where it can go. - In `splitLookupJoin`, `canEvaluateInLookupStage` applies only to a conjunct over lookup columns alone. A conjunct over both sides stays out only when it holds a subquery. - The Inner branch uses `canEvaluateWithinLookupJoin`, which is `canEvaluateWithinJoin` that also accepts a deterministic external UDF. - **End-to-end tests** run a Python UDF key in ON, in a comma join, `CROSS JOIN`, `JOIN ... ON TRUE` and `crossJoin().where()`, and offered next to another key in ON. - **Plan tests** cover the external UDF route. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,5828 @@ +/* + * 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.{shouldTestPythonUDFs, TestPythonUDF} +import org.apache.spark.sql.QueryTest +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.{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, + ExternalLookupProject, Filter, LeafNode, LogicalPlan, PreparedExternalLookupJoin} +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, 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, 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} +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 + } + + /** 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 that ignores duplicates needs no ordinary left outer join, which the + // optimizer removes, with its filters pushed to the stream. A lookup join stays. 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 [6d508fd7d9b](https://github.com/apache/spark/commit/6d508fd7d9b7100414eb18ff5c6388d6a24f8b69): both tests now count a lookup value, so the left outer lookup join stays, and each asserts that its plan holds one. -- 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]
