HeartSaVioR commented on code in PR #60019: URL: https://github.com/apache/spark/pull/60019#discussion_r4532147550
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,361 @@ +/* + * 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, LeftOuter} +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, CTERelationRef, + ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LogicalPlan, ResolvedHint, + SetOperation, SubqueryAlias, UnaryNode, Union, View, WithCTE} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.streaming.WriteToStream +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 + +/** + * 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 and views only, 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) + + 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 and views only. There is + // none when another operator 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) => + ineligible("JOIN_TYPE", relation, Map( + "joinType" -> toSQLStmt(join.joinType.sql), + "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => toSQLStmt(t.sql)).mkString(", "))) + case None if join.condition.isEmpty => MissingCondition + // The optimizer rewrites a subquery in a join condition only for a Join, which a lookup join + // no longer is by then. + case None if join.condition.exists(SubqueryExpression.hasSubquery) => + ineligible("SUBQUERY_IN_JOIN_CONDITION", relation) + case None => Eligible + } + } + + /** + * Whether `plan` can have a join that must run as an external lookup join: one over a lookup-only + * table, which is a DSv2 relation, or under the hint. Classifying the joins of a plan inlines its + * CTE references, so a plan without either is left alone, and an ordinary query does not pay + * for lookup joins. + */ + def mayHaveLookupJoin(plan: LogicalPlan): Boolean = + plan.containsPattern(JOIN) && (plan.containsPattern(EXTERNAL_LOOKUP_HINT) || + plan.containsPattern(DATA_SOURCE_V2_RELATION) && + plan.exists(ExternalLookupRelations.lookupOnlyTable(_).isDefined)) 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. Agreed, fixed with tree-pattern bits, so no ordinary plan is walked. - **#59909** ([7a4ef1369cb](https://github.com/apache/spark/commit/7a4ef1369cba83d95b681372348854a32aa6b327)) adds `LOOKUP_ONLY_RELATION`, which a DataSourceV2Relation or ExternalLookupRelation sets exactly when its table is lookup-only. It asks its table once. - **#59910** ([d61e9e647d9](https://github.com/apache/spark/commit/d61e9e647d97088f545d3774f128f828c9d1a302)) makes its two rules check (JOIN and LOOKUP_ONLY_RELATION). - **Here** ([afe85d777aa](https://github.com/apache/spark/commit/afe85d777aa47e289b05ceca6f06e06118fc763c)), `mayHaveLookupJoin` is (JOIN) and (the hint bit or the lookup-only bit), and ExternalLookupJoinEligibility returns `NotLookupJoin` first for a join whose subtree has neither bit. - **The test** covers an ordinary query, one with a subquery, and a micro-batch. It asserts that no `capabilities()` call happens in detection, the analysis check, the formation, cache substitution with a non-empty cache, or the classification of each join. Putting a walk back in fails it. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,361 @@ +/* + * 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, LeftOuter} +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, CTERelationRef, + ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LogicalPlan, ResolvedHint, + SetOperation, SubqueryAlias, UnaryNode, Union, View, WithCTE} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.streaming.WriteToStream +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 + +/** + * 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 and views only, 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) + + 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 and views only. There is + // none when another operator 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) => + ineligible("JOIN_TYPE", relation, Map( + "joinType" -> toSQLStmt(join.joinType.sql), + "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => toSQLStmt(t.sql)).mkString(", "))) + case None if join.condition.isEmpty => MissingCondition + // The optimizer rewrites a subquery in a join condition only for a Join, which a lookup join + // no longer is by then. + case None if join.condition.exists(SubqueryExpression.hasSubquery) => + ineligible("SUBQUERY_IN_JOIN_CONDITION", relation) + case None => Eligible + } + } + + /** + * Whether `plan` can have a join that must run as an external lookup join: one over a lookup-only + * table, which is a DSv2 relation, or under the hint. Classifying the joins of a plan inlines its + * CTE references, so a plan without either is left alone, and an ordinary query does not pay + * for lookup joins. + */ + def mayHaveLookupJoin(plan: LogicalPlan): Boolean = + plan.containsPattern(JOIN) && (plan.containsPattern(EXTERNAL_LOOKUP_HINT) || + plan.containsPattern(DATA_SOURCE_V2_RELATION) && + plan.exists(ExternalLookupRelations.lookupOnlyTable(_).isDefined)) + + /** The CTE definitions in `plan` by id, which [[inlineCTEs]] inlines. */ + def cteDefinitions(plan: LogicalPlan): Map[Long, CTERelationDef] = + if (plan.containsPattern(CTE)) { + plan.collect { case cteDef: CTERelationDef => cteDef.id -> cteDef }.toMap + } else { + Map.empty + } + + /** + * `join` with the CTE references on the paths of unary operators of its inputs inlined, as + * InlineCTE inlines them for the analysis check. Only these paths decide how the join is + * classified, and the lookup side of an eligible join is its path alone, so it has no other CTE + * reference left. + */ + def inlineCTEs(join: Join, cteDefs: Map[Long, CTERelationDef]): Join = + if (cteDefs.isEmpty) { + join + } else { + join.copy( + left = inlinePathCTEs(join.left, cteDefs), + right = inlinePathCTEs(join.right, cteDefs)) + } + + private def inlinePathCTEs( + plan: LogicalPlan, + cteDefs: Map[Long, CTERelationDef]): LogicalPlan = plan match { + case _ if !plan.containsPattern(CTE) => plan + case ref: CTERelationRef if cteDefs.contains(ref.cteId) => + val cteDef = cteDefs(ref.cteId) + InlineCTE.inlineReference(ref, cteDef, inlinePathCTEs(cteDef.child, cteDefs)) + case WithCTE(child, _) => inlinePathCTEs(child, cteDefs) + case unary: UnaryNode => unary.withNewChildren(Seq(inlinePathCTEs(unary.child, cteDefs))) + case other => other + } + + /** + * The plans that external lookup joins in `plan` read by lookups: the lookup side of each join + * that must run as an external lookup join, and the CTE definitions that the side reads, + * directly or through other CTE definitions. Subqueries are not searched. + */ + def lookupSidePlans(plan: LogicalPlan): Seq[LogicalPlan] = + if (!mayHaveLookupJoin(plan)) { + Nil + } else { + val cteDefs = cteDefinitions(plan) + val lookupSides = plan.collect { + case join: Join if apply(inlineCTEs(join, cteDefs)) != NotLookupJoin => join.right + } + val readCTEs = mutable.LinkedHashMap.empty[Long, CTERelationDef] + def addReadCTEs(plan: LogicalPlan): Unit = plan.foreach { + case ref: CTERelationRef if !readCTEs.contains(ref.cteId) => + cteDefs.get(ref.cteId).foreach { cteDef => + readCTEs(ref.cteId) = cteDef + addReadCTEs(cteDef) + } + case _ => + } + lookupSides.foreach(addReadCTEs) + lookupSides ++ readCTEs.values + } + + /** + * The lookup side of an eligible join, without its `EXTERNAL_LOOKUP` hint. The lookup side of an + * eligible join is a chain of hints, aliases and views over the table, so every marker in it is + * the join's own. + */ + def lookupSide(join: Join): LogicalPlan = + join.right.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_HINT)) { + case marker: ExternalLookupHint => marker.child + } + + private def ineligible( + subClass: String, + relation: String, + parameters: Map[String, String] = Map.empty): Ineligible = + Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError( + subClass, parameters + ("relation" -> relation))) + + /** The relation that a join input reads: the first operator that has no single child. */ + @tailrec + private def input(plan: LogicalPlan): LogicalPlan = plan match { + case unary: UnaryNode => input(unary.child) + case other => other + } + + /** The first operator below a join input that is not a hint, an alias or a view. */ + @tailrec + private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match { + case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | _: View) => 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. Thanks, this was worth checking. This PR stays as it is, because a lookup-side projection is a lookup-side stage from #60055 on, and this PR's scope has no lookup-side projections. A new test in #60055 ([429ae4da4fb](https://github.com/apache/spark/commit/429ae4da4fb8a6350f74a43be2d788ffb85be4fb)) covers your scenario: - **The setup:** a stream over a versioned catalog table that gains a top-level column, or a field in a struct column, between micro-batches. - **What it covers:** a lookup-only and a hinted table, with inner and left outer joins. - **Result:** the rows are right, and the micro-batch after the change still runs ExternalLookupJoinExec. At this PR, the same test fails with `LOOKUP_PLAN`, so it does exercise the refresh's projection. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala: ########## @@ -567,7 +567,12 @@ class CacheManager extends Logging with AdaptiveSparkPlanHelper { private[sql] def useCachedData( plan: LogicalPlan, canUse: CachedData => Boolean = _ => true): LogicalPlan = { - val newPlan = plan transformDown { + // An external lookup join reads its lookup side by lookups. If cached data replaced that side + // or a CTE definition that it reads, the join would silently read the cached data instead, or + // fail. + val lookupSidePlans = + if (cachedData.isEmpty) Nil else ExternalLookupJoinEligibility.lookupSidePlans(plan) 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 [afe85d777aa](https://github.com/apache/spark/commit/afe85d777aa47e289b05ceca6f06e06118fc763c): useCachedData reads `cachedData` once, and passes that list to every fragment match, including the call for each subquery plan. The existing cache tests cover the behavior; the race itself can't be tested deterministically. -- 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]
