HeartSaVioR commented on code in PR #60019: URL: https://github.com/apache/spark/pull/60019#discussion_r4545288564
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,443 @@ +/* + * 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.{AsOfJoin, CTERelationDef, CTERelationRef, + ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LateralJoin, LogicalPlan, + NearestByJoin, 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.{AS_OF_JOIN, CTE, EXTERNAL_LOOKUP_HINT, JOIN, + LATERAL_JOIN, LOOKUP_ONLY_RELATION, NEAREST_BY_JOIN, TreePattern} +import org.apache.spark.sql.catalyst.util.MetadataColumnHelper +import org.apache.spark.sql.connector.catalog.{Table, 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) + + /** + * An operator that the `EXTERNAL_LOOKUP` hint can annotate as a join, as a join strategy hint + * can: a [[Join]], an ASOF or NEAREST BY join, which Finish Analysis turns into joins, and a + * lateral join that the query writes, which operator optimization turns into a join. A lateral + * join that analysis adds for a table argument of a table function is not written by the query, + * so it is a unary operator for the hint, as for any other analysis check. + */ + object HintableJoin { + def unapply(plan: LogicalPlan): Boolean = plan match { + case _: Join | _: AsOfJoin | _: NearestByJoin => true + case lateral: LateralJoin => !lateral.containsTag(LateralJoin.BY_TABLE_ARGUMENT) + case _ => false + } + + /** The tree patterns of these operators. */ + val patterns: Seq[TreePattern] = Seq(JOIN, AS_OF_JOIN, NEAREST_BY_JOIN, LATERAL_JOIN) + } + + def apply(join: Join): Eligibility = { + // Every other outcome needs the hint or a lookup-only relation on an input of the join. + if (!join.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION)) return NotLookupJoin + 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")) + } + val (tableRelation, table) = lookupTable(join.right) match { + case Right(found) => found + case Left(rejection) => return rejection + } + val relation = toSQLId(table.name()) 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 [d0d36d5ee78](https://github.com/apache/spark/commit/d0d36d5ee78aee31f0baf04c10f62459de3541bd). The table's name is rendered only when an error is built again, as on the base branch. A new test runs a lookup join over a lookup-only table and over a hinted table that also supports batch reads, both named `./users`, with and without an unrelated DataFrame cached, and checks the rows. Rendering the name eagerly fails the test with `INVALID_ATTRIBUTE_NAME_SYNTAX`. The errors of ineligible joins over ordinary names keep their conditions and parameters. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,443 @@ +/* + * 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.{AsOfJoin, CTERelationDef, CTERelationRef, + ExternalLookupHint, ExternalLookupJoin, Join, JoinStrategyHint, LateralJoin, LogicalPlan, + NearestByJoin, 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.{AS_OF_JOIN, CTE, EXTERNAL_LOOKUP_HINT, JOIN, + LATERAL_JOIN, LOOKUP_ONLY_RELATION, NEAREST_BY_JOIN, TreePattern} +import org.apache.spark.sql.catalyst.util.MetadataColumnHelper +import org.apache.spark.sql.connector.catalog.{Table, 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) + + /** + * An operator that the `EXTERNAL_LOOKUP` hint can annotate as a join, as a join strategy hint + * can: a [[Join]], an ASOF or NEAREST BY join, which Finish Analysis turns into joins, and a + * lateral join that the query writes, which operator optimization turns into a join. A lateral + * join that analysis adds for a table argument of a table function is not written by the query, + * so it is a unary operator for the hint, as for any other analysis check. + */ + object HintableJoin { + def unapply(plan: LogicalPlan): Boolean = plan match { + case _: Join | _: AsOfJoin | _: NearestByJoin => true + case lateral: LateralJoin => !lateral.containsTag(LateralJoin.BY_TABLE_ARGUMENT) + case _ => false + } + + /** The tree patterns of these operators. */ + val patterns: Seq[TreePattern] = Seq(JOIN, AS_OF_JOIN, NEAREST_BY_JOIN, LATERAL_JOIN) + } + + def apply(join: Join): Eligibility = { + // Every other outcome needs the hint or a lookup-only relation on an input of the join. + if (!join.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION)) return NotLookupJoin + 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")) + } + val (tableRelation, table) = lookupTable(join.right) match { + case Right(found) => found + case Left(rejection) => return rejection + } + 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 + } + } + + /** + * The error of an `EXTERNAL_LOOKUP` hint on an input of an ASOF, NEAREST BY or lateral join, none + * of which runs as an external lookup join, or None. A hint on the left input is on the lookup + * side of no join, as for a [[Join]]. A hint on the right input of an ASOF or NEAREST BY join + * asks for a join type that a lookup join does not support, or for a lookup side that reads no + * DSv2 table. The subquery of a lateral join is checked as a subquery plan. + */ + def otherJoinHintError(join: LogicalPlan): Option[Throwable] = { + val (left, right, joinType) = join match { + case asOf: AsOfJoin => (asOf.left, Some(asOf.right), "ASOF") + case nearestBy: NearestByJoin => (nearestBy.left, Some(nearestBy.right), "NEAREST BY") + case lateral: LateralJoin => (lateral.left, None, "LATERAL") + case _ => return None + } + if (!join.containsPattern(EXTERNAL_LOOKUP_HINT)) None else { + if (lookupHints(left).nonEmpty) { + Some(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE")) + } else { + right.filter(lookupHints(_).nonEmpty).map { lookupSide => + lookupTable(lookupSide) match { + case Left(rejection) => rejection.error + case Right((_, table)) => + ineligible("JOIN_TYPE", toSQLId(table.name()), Map( + "joinType" -> toSQLStmt(joinType), + "supportedJoinTypes" -> + SUPPORTED_JOIN_TYPES.map(t => toSQLStmt(t.sql)).mkString(", "))).error + } + } + } + } + } + + /** + * Whether the analysis check of `plan` has anything to check: a join that can be one over a + * lookup-only table, or the hint with an operator that it can annotate as a join. The pattern + * bits tell this without a walk, as for [[mayHaveLookupJoin]]. + */ + def mayHaveHintOrLookupJoin(plan: LogicalPlan): Boolean = + mayHaveLookupJoin(plan) || plan.containsPattern(EXTERNAL_LOOKUP_HINT) && + plan.containsAnyPattern(HintableJoin.patterns: _*) + + /** + * Whether `plan` can have a join that must run as an external lookup join: one over a lookup-only + * table, whose relation carries LOOKUP_ONLY_RELATION, or under the hint. Classifying the joins of + * a plan inlines its CTE references, so a plan without either is left alone. The pattern bits of + * a plan include those of its CTE definitions and subquery plans, so they tell this without a + * walk, and an ordinary query does not pay for lookup joins. + */ + def mayHaveLookupJoin(plan: LogicalPlan): Boolean = + plan.containsPattern(JOIN) && + plan.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION) + + /** 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) => 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 [d0d36d5ee78](https://github.com/apache/spark/commit/d0d36d5ee78aee31f0baf04c10f62459de3541bd), as you recommend. - **One decision:** the new `InlineCTE.keepsDefinition` decides which definitions are never inlined, MATERIALIZED and force-skip ones, and `shouldInline` now uses it too. - **One classification:** `ExternalLookupJoinEligibility.classify` stops the lookup-side search at a reference to such a definition, and classifies the join as ineligible with the new reason `EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MATERIALIZED_CTE`, which names the CTE. The analysis check, the formation, cache substitution and the start check all classify through it. - **Fails when built:** analysis runs this check on the plan before its CTEs are inlined, right after `MaterializedCTECheck`. If the join is ineligible for another reason as well, that reason is reported first. Tests: a hinted lookup side over a table that also supports batch reads, and a lookup-only one, each read through a MATERIALIZED CTE, fail when the DataFrame is built. With NOT MATERIALIZED, or with no option, they run as lookup joins. A MATERIALIZED CTE that no lookup side reads is still evaluated once. Plan tests cover MATERIALIZED and force-skip definitions. Removing the analysis check, or the stop at a kept definition, fails them. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala: ########## @@ -550,12 +552,25 @@ class CacheManager extends Logging with AdaptiveSparkPlanHelper { */ private[sql] def useCachedData( plan: LogicalPlan, - canUse: CachedData => Boolean = _ => true): LogicalPlan = { - val newPlan = plan transformDown { + canUse: CachedData => Boolean = _ => true): LogicalPlan = + useCachedEntries(plan, canUse, cachedData) + + // `entries` is one read of the cache list, which another thread may replace meanwhile, so that + // an entry that is used is also one that the lookup sides were protected from. + private def useCachedEntries( + plan: LogicalPlan, + canUse: CachedData => Boolean, + entries: IndexedSeq[CachedData]): LogicalPlan = { + // An external lookup join reads its lookup side by lookups. If cached data replaced that 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. Added in [d0d36d5ee78](https://github.com/apache/spark/commit/d0d36d5ee78aee31f0baf04c10f62459de3541bd). A TODO at the lookup-side skip names the follow-up: protect only the lookup side's path, so that a WITH definition's other readers keep the cached data. -- 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]
