HeartSaVioR commented on code in PR #60198: URL: https://github.com/apache/spark/pull/60198#discussion_r4524190716
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,374 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.analysis + +import scala.annotation.tailrec +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.SubqueryExpression +import org.apache.spark.sql.catalyst.optimizer.{EliminateResolvedHint, InlineCTE} +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, CTERelationRef, + ExternalLookupCacheOptions, ExternalLookupHint, ExternalLookupHintCacheOptions, + ExternalLookupJoin, ExternalLookupJoinShapes, Filter, Join, JoinStrategyHint, LogicalPlan, + Project, ResolvedHint, SubqueryAlias, UnaryNode, View, WithCTE} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{CTE, DATA_SOURCE_V2_RELATION, + EXTERNAL_LOOKUP_HINT, JOIN} +import org.apache.spark.sql.catalyst.util.MetadataColumnHelper +import org.apache.spark.sql.connector.catalog.TableCapability +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations +import org.apache.spark.sql.internal.SQLConf + +/** + * Classifies a join for external lookup. [[CheckExternalLookupJoin]] and [[FormExternalLookupJoin]] + * share it, so analysis rejects every join that the optimizer cannot convert, except one without + * a condition: see [[CheckExternalLookupJoin]]. + * + * A join is an external lookup join when its right side reads a table that supports external + * lookup but not batch read, or when the right side carries an `EXTERNAL_LOOKUP` hint. A table + * that supports both keeps the ordinary join strategies unless the hint opts in. It must be a + * stream-static join: the left side is a streaming query, whose micro-batches tolerate lookup + * results that change between requests, and the lookup table is on the right side. The join reads + * the table directly, or through hints, aliases, views, and projections and filters that it can + * evaluate on the lookup results, so a join that must be a lookup join either runs as one or fails + * here, whatever the optimizer later does to its lookup side. + */ +object ExternalLookupJoinEligibility extends QueryErrorsBase { + sealed trait Eligibility + /** + * The join stays an ordinary join: it has no `EXTERNAL_LOOKUP` hint, and neither of its inputs is + * a lookup-only relation, directly or below unary operators. A lookup-only relation below another + * operator, such as a union, is not recognized, and fails later as a batch scan. + */ + case object NotLookupJoin extends Eligibility + /** The join runs as an external lookup join. */ + case object Eligible extends Eligibility + /** + * The join must run as an external lookup join, with a supported join type, but has no + * condition. + */ + case object MissingCondition extends Eligibility + /** The join must run as an external lookup join but cannot. */ + case class Ineligible(error: Throwable) extends Eligibility + + private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter, LeftSemi, LeftAnti) + + def apply(join: Join): Eligibility = { + if (lookupHints(join.left).nonEmpty) { + return Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE")) + } + // The lookup-only table must be on the right side; the sides are never swapped. + val leftLookupOnlyTable = ExternalLookupRelations.lookupOnlyTable(input(join.left)) + if (leftLookupOnlyTable.isDefined) { + return ineligible("LOOKUP_TABLE_ON_LEFT", toSQLId(leftLookupOnlyTable.get.name())) + } + val markers = lookupHints(join.right) + val lookupOnly = ExternalLookupRelations.lookupOnlyTable(input(join.right)).isDefined + // A lookup-only table can be read only by a lookup join, and the hint opts a join in. Either + // way the join must run as an external lookup join, and the checks below apply. + if (!lookupOnly && markers.isEmpty) return NotLookupJoin + if (join.right.isStreaming) { + return Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError( + "STREAMING_LOOKUP_SIDE")) + } + // The DSv2 table that the lookup side reads through hints, aliases, views, and projections and + // filters that the lookup join can evaluate. There is none when another operator, or a stage + // that it cannot evaluate, stands in between, or the side reads no DSv2 table. + val tableRelation = lookupRelation(join.right) + val table = ExternalLookupRelations.table(tableRelation) match { + case Some(table) => table + case None => + return Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")) + } + val relation = toSQLId(table.name()) + if (!table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP)) { + return Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> relation))) + } + // A lookup returns the data columns of the table only. The relation outputs a metadata column + // only when the query reads one. + if (tableRelation.output.exists(_.isMetadataCol)) return ineligible("METADATA_COLUMN", relation) + if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", relation) + // A join hint the user wrote is never silently dropped: an external lookup join cannot run a + // physical join strategy, and a lookup-only table has no batch scan for one. + joinStrategyHint(join) match { + // The user asked for a physical join, which an external lookup join cannot run. + case Some(strategy) => + ineligible("CONFLICTING_JOIN_STRATEGY", relation, + Map("strategy" -> toSQLStmt(strategy.displayName))) + // No physical join was asked for: the join runs as an external lookup join unless a check + // below fails. + // Checked before the condition, so that a cross join fails while it is analyzed. + case None if !SUPPORTED_JOIN_TYPES.contains(join.joinType) => 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 [d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9). The shared classifier treats a cross join as an inner join, as for an ordinary join, so `CROSS JOIN` and `crossJoin()` with the key in WHERE now plan like a comma join. A cross join with no key anywhere fails with `MISSING_JOIN_CONDITION`, and right and full outer joins still fail with `JOIN_TYPE`. The change is in this PR rather than in #59909, which owns the classifier, because a key in WHERE only reaches the join from this PR's pushdown on. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala: ########## @@ -0,0 +1,472 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.plans.logical + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, BinaryComparison, + Cast, CurrentBatchTimestamp, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Literal, + NamedExpression, PythonUDF, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, EXTERNAL_LOOKUP_HINT, + EXTERNAL_LOOKUP_JOIN, TreePattern} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, CharType, DataType, + DateType, DecimalType, IntegerType, IntegralType, LongType, ShortType, StringType, + TimestampNTZType, TimestampType, VarcharType} + +/** + * The cache settings of one external lookup join, from the + * `spark.sql.join.externalLookup.cache.*` configurations unless the join's `EXTERNAL_LOOKUP` hint + * overrides them. A cache lives within a task, per input partition, so these bound each such cache: + * its keys and their result rows take at most `maxBytes`, and each is kept for `ttlMillis` (0 keeps + * it until evicted). A key whose rows take more than a sixteenth of `maxBytes` is still joined but + * not cached, so that one large result cannot evict most of the cache. At present, a join that + * selects a range comparison (`<`, `<=`, `>`, `>=`) whose parameter reads a stream column caches + * nothing, whatever these settings say. + */ +case class ExternalLookupCacheOptions( + enabled: Boolean, + maxBytes: Long, + ttlMillis: Long) + +/** + * The cache options that one `EXTERNAL_LOOKUP` hint sets. An option that no hint of a join sets + * follows its `spark.sql.join.externalLookup.cache.*` configuration when the join is planned, not + * the one in effect when the hint was written. + */ +case class ExternalLookupHintCacheOptions( + enabled: Option[Boolean] = None, + maxBytes: Option[Long] = None, + ttlMillis: Option[Long] = None) { + /** These options, with the ones that they do not set taken from `other`. */ + def orElse(other: ExternalLookupHintCacheOptions): ExternalLookupHintCacheOptions = + ExternalLookupHintCacheOptions( + enabled.orElse(other.enabled), + maxBytes.orElse(other.maxBytes), + ttlMillis.orElse(other.ttlMillis)) + + /** These options, with the configurations of `conf` for the ones that they do not set. */ + def withDefaults(conf: SQLConf): ExternalLookupCacheOptions = ExternalLookupCacheOptions( + enabled = enabled.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED)), + maxBytes = maxBytes.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_MAX_BYTES)), + ttlMillis = ttlMillis.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_TTL))) +} + +/** + * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint asks an external + * lookup join to read, with the cache options that the hint sets. The external lookup join rules + * consume it when they form the join. + * + * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. This hint is not, + * because that representation cannot keep two of its guarantees: + * - A strategy hint that conflicts with it must fail the query. [[HintInfo]] holds one strategy, + * and `ResolveJoinStrategyHints` merges a strategy hint on an already hinted relation into the + * existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one strategy and only warns. + * - It selects how the lookup side is read, not a physical join. `EliminateResolvedHint` moves + * every [[ResolvedHint]] it can attach into `Join.hint`, for physical join selection. + */ +case class ExternalLookupHint( + child: LogicalPlan, + cacheOptions: ExternalLookupHintCacheOptions) extends UnaryNode { + override def output: Seq[Attribute] = child.output + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT) + + override protected def withNewChildInternal(newChild: LogicalPlan): ExternalLookupHint = + copy(child = newChild) +} + +/** + * A lookup join retained through ordinary expression and operator optimization. + * + * @param requiredLookupOutput Lookup-side attributes still required above this join. They are + * part of this node's references, so column pruning keeps them on the lookup side. + * `ColumnPruning` narrows them to what the parent reads, and `PrepareExternalLookupJoin` prunes + * the lookup scan to them. + */ +case class ExternalLookupJoin( + left: LogicalPlan, + right: LogicalPlan, + joinType: JoinType, + condition: Option[Expression], + cacheOptions: ExternalLookupCacheOptions, + requiredLookupOutput: Seq[Attribute]) extends BinaryNode { + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN) + + override def output: Seq[Attribute] = joinType match { + case Inner => left.output ++ right.output + case LeftOuter => left.output ++ right.output.map(_.withNullability(true)) + case LeftSemi | LeftAnti => left.output + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + // As an ordinary join's: a semi or anti join returns at most its stream rows, and the other join + // types get the product of both sides' sizes. + override def stats: Statistics = joinType match { + case LeftSemi | LeftAnti => left.stats + case _ => super.stats + } + + override def maxRows: Option[Long] = joinType match { + case LeftSemi | LeftAnti => left.maxRows + case _ => None + } + + override protected def withNewChildrenInternal( + newLeft: LogicalPlan, + newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right = newRight) +} + +/** + * The join-condition and lookup-side shapes that an external lookup join can run. Analysis, + * lookup planning and the optimizer rules for lookup joins share them. + */ +object ExternalLookupJoinShapes { + /** + * A lookup candidate: a comparison of a lookup column with a value, written with the lookup + * column on the left. + */ + case class LookupComparison( + lookupField: Attribute, + parameter: Expression, + comparison: LookupKeyComparison) + + /** + * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, `<=>`, `<`, `<=`, `>` + * or `>=` between a bare lookup column and a value, in either operand order. When the lookup + * column is written on the right, the comparison is rebuilt with it on the left, so + * `s.ts < t.event_time` is offered as `event_time > ?`. + * + * The value is the other operand, which Spark evaluates for each stream row to fill the + * comparison's parameter. It may read only stream columns, and it may read none, as a literal + * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a parameter. + * + * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets Spark offer the + * comparison. A comparison on another column is an ordinary conjunct. + * + * @param streamOutput The output of the join's left side, the stream side. 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 [d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9): the doc now describes both callers, including the lookup-side filters, which pass an empty stream output. ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -2855,6 +2918,79 @@ ], "sqlState" : "42822" }, + "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED" : { + "message" : [ + "The join cannot be executed as an external lookup join:" + ], + "subClass" : { + "CONFLICTING_JOIN_STRATEGY" : { + "message" : [ + "The join strategy hint <strategy> cannot be honored by an external lookup join over <relation>. Remove the <strategy> hint." + ] + }, + "JOIN_TYPE" : { + "message" : [ + "The join type <joinType> is not supported by an external lookup join over <relation>. Supported join types are <supportedJoinTypes>." + ] + }, + "LOOKUP_PLAN" : { + "message" : [ + "The lookup side must be a DSv2 table, optionally under projections and filters, which Spark evaluates on the lookup results. They cannot contain Python UDFs, external UDFs, subqueries or non-deterministic expressions: Spark evaluates them on each returned row, so a non-deterministic one could give one stored row different values for different stream rows. No other operator can be between the table and the join." + ] + }, + "LOOKUP_TABLE_ON_LEFT" : { + "message" : [ + "The lookup-only table <relation> must be on the right side of the join." + ] + }, + "METADATA_COLUMN" : { + "message" : [ + "An external lookup join over <relation> cannot read a metadata column of the table." + ] + }, + "MISSING_JOIN_CONDITION" : { + "message" : [ + "The join has no join condition, and predicate pushdown moved none into it from a later `WHERE` clause or filter. Compare a lookup column with a stream-side value in the join, such as in its `ON` clause or the condition argument of `join()`, or in a `WHERE` clause above an inner join." 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 [d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9): both messages, and the two comments that share the assumption, now hold in every case you list. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PushPredicateThroughExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,267 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import org.apache.spark.api.python.PythonEvalType +import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.dsl.plans._ +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, PythonUDF, Rand, + ScalarSubquery} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi, + PlanTest} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinHint, + LocalRelation, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.RuleExecutor +import org.apache.spark.sql.connector.catalog.{Table, TableCapability} +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.types.{BooleanType, DoubleType, StructType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +class PushPredicateThroughExternalLookupJoinSuite extends PlanTest { + private object Optimize extends RuleExecutor[LogicalPlan] { + val batches = Batch("Push down predicates", FixedPoint(10), PushDownPredicates) :: Nil + } + + // Operator optimization runs both rules. + private object OptimizeWithOuterJoinElimination extends RuleExecutor[LogicalPlan] { + val batches = Batch("Eliminate outer joins and push down predicates", FixedPoint(10), + EliminateOuterJoin, PushDownPredicates) :: Nil + } + + private val stream = LocalRelation(Seq($"streamKey".int), isStreaming = true) + private val lookup = DataSourceV2Relation.create( + LookupOnlyTable, None, None, CaseInsensitiveStringMap.empty) + private val streamKey = stream.output.head + private val Seq(lookupKey, lookupValue, lookupScore, lookupName) = lookup.output + private val keysEqual = streamKey === lookupKey + // A comparison with a stream-side value that is never offered: Spark offers no `=` on a DOUBLE. + private val neverOfferedKey = lookupScore === streamKey.cast(DoubleType) + // A conjunct over both sides, which only the join condition can evaluate. + private val bothSidesConjunct = streamKey + lookupValue > 0 + // A filter conjunct that is not deterministic never moves. + private val nonDeterministic = Rand(1L) > 0.5 + // A lookup-side conjunct that is not a lookup candidate, so it can move onto the lookup side. 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 [d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9). ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/ExternalLookupJoinStartupCheck.scala: ########## @@ -0,0 +1,96 @@ +/* + * 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.streaming.runtime + +import scala.util.control.NonFatal + +import org.apache.spark.SparkThrowable +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility +import org.apache.spark.sql.catalyst.streaming.WriteToStream +import org.apache.spark.sql.classic.SparkSession +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.execution.streaming.checkpointing.OffsetSeqMetadata +import org.apache.spark.sql.internal.SQLConf + +/** + * Plans the external lookup joins of a streaming query when it starts, in the thread that starts + * it, so that a join that cannot be planned fails `start()` instead of the first micro-batch that + * runs, which may come much later. Whether a join has a lookup predicate, and which ones the + * connector selects, depend on the condition as the optimizer leaves it, for example after it + * simplifies the condition. So the query is optimized once here, with the optimizer of its + * micro-batches and with their configuration, and the result is discarded. + * + * Only the lookup sides are planned. The other subtrees without a streaming relation, and the + * subtrees of subquery plans without an outer reference, become placeholders of their outputs, as + * in the optimization for the column pruning of streaming scans (see + * `StreamingV2ScanPushDown.forStartup`), so that their scans are neither built nor planned at the + * start, as for a query without a lookup join. + * + * Only the planning errors of the lookup join and of its connector contract fail the start. Any + * other error, such as one that an ordinary join raises too, is left to the micro-batch, which + * plans the query as before. + */ +private[sql] object ExternalLookupJoinStartupCheck extends Logging { + private val lookupErrorClasses = Set( + "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED", + "INVALID_EXTERNAL_LOOKUP_HINT", + "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP", + // The default Scan.toExternalLookup() of a scan that does not override it. + "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED") + + def apply(session: SparkSession, write: WriteToStream): Unit = { + val plan = write.inputQuery + if (!session.sessionState.conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED) || + ExternalLookupJoinEligibility.lookupSidePlans(plan).isEmpty) { + return + } + session.withActive { + try { + SQLConf.withExistingConf(startupConf(session, write)) { + val normalized = QueryExecution.normalize(session, plan) + // The values that depend on when they are evaluated fold as in the first micro-batch. + session.sessionState.optimizer.execute( + StreamingV2ScanPushDown.forStartup(normalized, withStartupValues = false)) 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 #59910, where the startup check lives ([232975c8fc5](https://github.com/apache/spark/commit/232975c8fc562f2f5e2568c72319ee3f775b171b)), with the cases tested here ([d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9)). The start now rewrites the current time as a micro-batch does. - **The WHERE forms:** a key that compares only with the current time now stops the query at start with `MISSING_JOIN_CONDITION`. A source that needs `validFrom` gives `NO_LOOKUP_PREDICATE`. Each matches the first micro-batch with the check off. - **The ON form behaves differently from what the review expected.** Its first micro-batch fails in analysis with `INVALID_NON_DETERMINISTIC_EXPRESSIONS`, because analysis rejects the batch timestamp in a join condition, and an ordinary stream-static join with the same condition fails the same way. Only lookup-specific errors move to the start, so the check skips such a plan, and the micro-batch reports that error, as for an ordinary join. The test asserts both joins. - **A comparison on the lookup side itself** still plans at start. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PushPredicateThroughExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,267 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.optimizer + +import org.apache.spark.api.python.PythonEvalType +import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.dsl.plans._ +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, PythonUDF, Rand, + ScalarSubquery} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi, + PlanTest} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinHint, + LocalRelation, LogicalPlan} +import org.apache.spark.sql.catalyst.rules.RuleExecutor +import org.apache.spark.sql.connector.catalog.{Table, TableCapability} +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.types.{BooleanType, DoubleType, StructType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +class PushPredicateThroughExternalLookupJoinSuite extends PlanTest { + private object Optimize extends RuleExecutor[LogicalPlan] { + val batches = Batch("Push down predicates", FixedPoint(10), PushDownPredicates) :: Nil + } + + // Operator optimization runs both rules. + private object OptimizeWithOuterJoinElimination extends RuleExecutor[LogicalPlan] { + val batches = Batch("Eliminate outer joins and push down predicates", FixedPoint(10), + EliminateOuterJoin, PushDownPredicates) :: Nil + } + + private val stream = LocalRelation(Seq($"streamKey".int), isStreaming = true) + private val lookup = DataSourceV2Relation.create( + LookupOnlyTable, None, None, CaseInsensitiveStringMap.empty) + private val streamKey = stream.output.head + private val Seq(lookupKey, lookupValue, lookupScore, lookupName) = lookup.output + private val keysEqual = streamKey === lookupKey + // A comparison with a stream-side value that is never offered: Spark offers no `=` on a DOUBLE. + private val neverOfferedKey = lookupScore === streamKey.cast(DoubleType) + // A conjunct over both sides, which only the join condition can evaluate. + private val bothSidesConjunct = streamKey + lookupValue > 0 + // A filter conjunct that is not deterministic never moves. + private val nonDeterministic = Rand(1L) > 0.5 + // A lookup-side conjunct that is not a lookup candidate, so it can move onto the lookup side. + private val lookupNonCandidate = lookupValue + 1 > 2 + private val lookupJoinTypes = Seq(Inner, LeftOuter, LeftSemi, LeftAnti) + private val booleanPythonUDF = (args: Seq[Expression]) => + PythonUDF("udf", null, BooleanType, args, PythonEvalType.SQL_BATCHED_UDF, true) + private val scalarSubquery = ScalarSubquery(LocalRelation($"subqueryValue".int)) + + /** An external lookup join, as the optimizer forms it. */ + private def lookupJoin(joinType: JoinType, conjuncts: Expression*): ExternalLookupJoin = + FormExternalLookupJoin( + Join(stream, lookup, joinType, Some(conjuncts.reduce(_ && _)), JoinHint.NONE)) + .asInstanceOf[ExternalLookupJoin] + + /** `join` with the given sides and condition conjuncts. */ + private def expectedJoin( + join: ExternalLookupJoin, + streamSide: LogicalPlan = stream, + lookupSide: LogicalPlan = lookup, + conjuncts: Seq[Expression]): ExternalLookupJoin = + join.copy(left = streamSide, right = lookupSide, condition = Some(conjuncts.reduce(_ && _))) + + test("push a filter above the join into the stream side and the join condition") { + Seq[(JoinType, Expression, ExternalLookupJoin => LogicalPlan)]( + // The lookup-side conjunct goes through the join condition onto the lookup side, and the + // conjunct on both sides into the join condition. + (Inner, streamKey > 1 && lookupNonCandidate && bothSidesConjunct && nonDeterministic, + join => expectedJoin(join, stream.where(streamKey > 1), lookup.where(lookupNonCandidate), + Seq(keysEqual, bothSidesConjunct)).where(nonDeterministic)), + // Under a left outer join, a filter on lookup columns also removes the null-padded rows of + // stream rows without a match. On the lookup side or in the join condition it would keep + // those rows, so it stays above. EliminateOuterJoin, which this batch does not run, makes + // the join inner when the filter rejects nulls, and the filter can then move. + (LeftOuter, streamKey > 1 && lookupNonCandidate, join => + expectedJoin(join, stream.where(streamKey > 1), conjuncts = Seq(keysEqual)) + .where(lookupNonCandidate)), + (LeftSemi, streamKey > 1 && nonDeterministic, join => + expectedJoin(join, stream.where(streamKey > 1), conjuncts = Seq(keysEqual)) + .where(nonDeterministic)), + (LeftAnti, streamKey > 1 && nonDeterministic, join => + expectedJoin(join, stream.where(streamKey > 1), conjuncts = Seq(keysEqual)) + .where(nonDeterministic))).foreach { + case (joinType, filter, expected) => + val join = lookupJoin(joinType, keysEqual) + comparePlans(Optimize.execute(join.where(filter)), expected(join)) + } + } + + test("push join condition conjuncts on one side into that side") { + val intoBothSides: ExternalLookupJoin => LogicalPlan = join => + expectedJoin(join, stream.where(streamKey > 1), lookup.where(lookupNonCandidate), + Seq(keysEqual, bothSidesConjunct)) + // A stream-side conjunct of a left outer or left anti join decides which stream rows find a + // match, so it stays in the condition. The join checks one that cannot fail, such as + // `streamKey > 1`, on each stream row before the lookup, and any other one on the joined rows. + val intoLookupSide: ExternalLookupJoin => LogicalPlan = join => + expectedJoin(join, lookupSide = lookup.where(lookupNonCandidate), + conjuncts = Seq(keysEqual, streamKey > 1, bothSidesConjunct)) + Seq( + Inner -> intoBothSides, + LeftSemi -> intoBothSides, + LeftOuter -> intoLookupSide, + LeftAnti -> intoLookupSide).foreach { case (joinType, expected) => + val join = + lookupJoin(joinType, keysEqual, streamKey > 1, lookupNonCandidate, bothSidesConjunct) + comparePlans(Optimize.execute(join), expected(join)) + } + } + + test("leave a join without movable conjuncts unchanged") { + Seq( + lookupJoin(Inner, keysEqual), + lookupJoin(LeftOuter, keysEqual, bothSidesConjunct), + lookupJoin(LeftAnti, keysEqual, streamKey > 1), + lookupJoin(Inner, keysEqual, nonDeterministic), + // A literal belongs to neither side, so a condition that folds to false keeps its result. + lookupJoin(Inner, keysEqual, Literal(false))).foreach { join => + assert(Optimize.execute(join) eq join) + } + val filtered = lookupJoin(LeftOuter, keysEqual).where(lookupNonCandidate && nonDeterministic) + assert(Optimize.execute(filtered) eq filtered) + } + + test("move a comparison with a constant onto the lookup side as for a join") { + // As for a join, a lookup-side conjunct goes onto the lookup side, where the connector receives + // it as a pushed filter. Lookup planning still offers it as a lookup candidate. + val constantComparisons = Seq[Expression]( + lookupValue === 5, lookupValue <=> 5, lookupValue < 5, lookupValue <= 5, lookupValue > 5, + lookupValue >= 5, Literal(5) === lookupValue, Literal(5) <=> lookupValue, + Literal(5) < lookupValue, Literal(5) >= lookupValue) + for (joinType <- lookupJoinTypes; comparison <- constantComparisons) { + val join = lookupJoin(joinType, keysEqual, comparison) + comparePlans(Optimize.execute(join), + expectedJoin(join, lookupSide = lookup.where(comparison), conjuncts = Seq(keysEqual))) + } + // So does one that is the join's only possible key, which lookup planning then offers from + // the lookup side. + for (joinType <- lookupJoinTypes; comparison <- Seq(lookupValue === 5, lookupValue >= 5)) { + val join = lookupJoin(joinType, comparison) + comparePlans(Optimize.execute(join), + join.copy(right = lookup.where(comparison), condition = None)) + } + // A filter above an inner join moves there too, whatever key the condition keeps. Under a + // left outer join it stays above. + val inner = lookupJoin(Inner, keysEqual) + for (comparison <- Seq(lookupValue === 5, lookupValue >= 5)) { + comparePlans(Optimize.execute(inner.where(comparison)), + expectedJoin(inner, lookupSide = lookup.where(comparison), conjuncts = Seq(keysEqual))) + } + val constantKey = lookupJoin(Inner, neverOfferedKey, lookupValue === 5) + comparePlans(Optimize.execute(constantKey.where(lookupName === "x")), + expectedJoin(constantKey, lookupSide = lookup.where(lookupValue === 5 && lookupName === "x"), + conjuncts = Seq(neverOfferedKey))) + val outer = lookupJoin(LeftOuter, keysEqual).where(lookupValue === 5) + assert(Optimize.execute(outer) eq outer) + // A comparison with a stream-side value in a filter above an inner join moves into the join + // condition, as for a join. + comparePlans(Optimize.execute(inner.where(streamKey < lookupValue)), + expectedJoin(inner, conjuncts = Seq(keysEqual, streamKey < lookupValue))) + // Any other lookup-side conjunct moves as well, including a comparison on a type that Spark + // never offers as a key: `=` or `<=>` on a DOUBLE, or a range on a STRING. + val notCandidates = Seq[Expression]( + lookupValue =!= 5, lookupValue + 1 > 5, lookupValue.in(1, 2), lookupValue.isNull, + lookupScore === 5.0, lookupScore <=> 5.0, lookupName < "m", lookupName >= "a") + for (conjunct <- notCandidates) { + val join = lookupJoin(Inner, keysEqual, conjunct) + comparePlans(Optimize.execute(join), expectedJoin(join, lookupSide = lookup.where(conjunct), + conjuncts = Seq(keysEqual))) + comparePlans(Optimize.execute(inner.where(conjunct)), + expectedJoin(inner, lookupSide = lookup.where(conjunct), conjuncts = Seq(keysEqual))) + } + } + + test("a comparison with a constant moves next to one on a computed lookup column") { + // `streamKey = computed` is never offered, as `computed` is no table column, and the + // comparison with a constant moves onto the lookup side as for a join, from where lookup + // planning offers it as the key. + val computed = (lookupValue + 1).as("computed") + val projected = lookup.select(lookupKey, lookupValue, computed) + val join = FormExternalLookupJoin(Join(stream, projected, Inner, + Some(streamKey === computed.toAttribute && lookupKey === 5), JoinHint.NONE)) + .asInstanceOf[ExternalLookupJoin] + comparePlans(Optimize.execute(join), join.copy( + right = lookup.where(lookupKey === 5).select(lookupKey, lookupValue, computed), + condition = Some(streamKey === computed.toAttribute))) + } + + test("keep a conjunct that a lookup-side stage cannot evaluate where it is") { + // The conjuncts read lookup columns, so a lookup-side stage would have to evaluate them, and + // a stage with a Python UDF or a subquery cannot be planned. + val pythonUDFs = Seq[Expression]( + booleanPythonUDF(Seq(lookupValue)), booleanPythonUDF(Seq(streamKey, lookupValue))) + // A subquery over lookup columns cannot be in the condition of a lookup join, only in a filter + // above it, where it stays. One that reads no column moves into the condition of an inner join, 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 [d3477aa9bb5](https://github.com/apache/spark/commit/d3477aa9bb5b7e6baee4b76f467a3fc940fe17c9): a plan test, and an end-to-end test with a scalar subquery and `EXISTS`, each true and false, with and without `PushDownPredicates`. -- 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]
