HeartSaVioR commented on code in PR #60019: URL: https://github.com/apache/spark/pull/60019#discussion_r4537722419
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,363 @@ +/* + * 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, EXTERNAL_LOOKUP_HINT, JOIN, + LOOKUP_ONLY_RELATION} +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 = { + // 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")) + } + // 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, 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) => + 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) => + lookupRelation(node.children.head) + case other => other + } + + /** + * The `EXTERNAL_LOOKUP` hints on a join input. Like a join strategy hint, the hint applies to the + * join that the input feeds, through any unary operator. + */ + @tailrec + private def lookupHints( + plan: LogicalPlan, + found: Seq[ExternalLookupHint] = Nil): Seq[ExternalLookupHint] = plan match { + case marker: ExternalLookupHint => lookupHints(marker.child, found :+ marker) + case unary: UnaryNode => lookupHints(unary.child, found) + case _ => found + } + + /** + * The physical join strategy hint, such as `BROADCAST` or `MERGE`, that EliminateResolvedHint + * would attach to the join, or None if there is none. The `EXTERNAL_LOOKUP` hint is never + * returned: it is an [[ExternalLookupHint]] marker, not a [[JoinStrategyHint]]. A `HintInfo` + * without a strategy asks for nothing, so it is skipped. + */ + private def joinStrategyHint(join: Join): Option[JoinStrategyHint] = { + // Only the hints that EliminateResolvedHint will attach to this join count; a strategy hint + // on a nested join belongs to that join. + val attached = join.hint.leftHint.toSeq ++ join.hint.rightHint.toSeq ++ + Seq(join.left, join.right).flatMap(EliminateResolvedHint.extractHintsFromPlan(_)._2) + attached.flatMap(_.strategy).headOption + } +} + +/** + * Reports, while a query is analyzed, why a join cannot run as the external lookup join it must + * be. It does not change the plan: the join stays a [[Join]] until [[FormExternalLookupJoin]] + * converts it, so the APIs and rules that expect an analyzed join keep working. A join that is not + * resolved, for example one whose condition is not boolean, is left to the analyzer's own join + * checks. + * + * A missing join condition is reported only for the query of a streaming write, which is analyzed + * in full when the query starts, so that `start()` throws it. Other plans can still get their + * condition: the classic Dataset API analyzes a USING join first as a join without a condition. + */ +object CheckExternalLookupJoin extends (LogicalPlan => Unit) { + override def apply(plan: LogicalPlan): Unit = { + if (ExternalLookupJoinEligibility.mayHaveLookupJoin(plan)) { + val complete = plan.isInstanceOf[WriteToStream] + plan.foreachUp { + case join: Join if join.resolved => 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 [549eae9bdc1](https://github.com/apache/spark/commit/549eae9bdc1432e89f4e66904bda19d2592ddab4), as you recommend. - `ExternalLookupJoinEligibility` defines once the operators that the hint can annotate as a join: a join, an ASOF or NEAREST BY join, and a lateral join that the query writes, not one that analysis adds for a table argument. - The analysis check uses that definition in its gate, which still tests only tree-pattern bits, in classifying the hinted inputs and in finding a join below a hint. - A hint on the right input of an ASOF or NEAREST BY join fails with `JOIN_TYPE`, which names the join, or with `LOOKUP_PLAN` when the input reads no DSv2 table. A hint on the left input of any of these joins, or a parameterless hint above one, fails with `NOT_ON_LOOKUP_SIDE`. A hint with no join below it, or inside a lateral subquery, is still ignored with a warning. Tests cover each placement, in SQL and with `Dataset.joinAsOf`, in streaming and batch queries. These joins without the hint, over a table that supports both reads, return the rows they return over a copy of it. If the check skips these operators, or if `readsJoin` counts only joins, the tests fail. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinStartupCheckSuite.scala: ########## @@ -0,0 +1,668 @@ +/* + * 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.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit} +import java.util.concurrent.atomic.{AtomicInteger, AtomicReference} + +import scala.jdk.CollectionConverters._ +import scala.reflect.{classTag, ClassTag} + +import org.apache.logging.log4j.Level + +import org.apache.spark.{SparkRuntimeException, SparkUnsupportedOperationException} +import org.apache.spark.sql.{AnalysisException, DataFrame, Row, SQLContext} +import org.apache.spark.sql.QueryTest +import org.apache.spark.sql.catalyst.expressions.{CurrentBatchTimestamp, CurrentDate, + CurrentTimestamp, LocalTimestamp, OuterReference, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan +import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, TableCapability, TableProvider} +import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, EXTERNAL_LOOKUP} +import org.apache.spark.sql.connector.expressions.Transform +import org.apache.spark.sql.connector.read.ScanBuilder +import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, + ExternalLookupRelation} +import org.apache.spark.sql.execution.streaming.runtime.{ExternalLookupJoinStartupCheck, + MemoryStream, MicroBatchExecution, StreamingQueryCheckpointMetadata, StreamingQueryWrapper, + StreamingV2ScanPushDown} +import org.apache.spark.sql.functions.{col, current_timestamp, lit, max} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.streaming.{StreamingQuery, StreamingQueryException, + StreamingQueryListener} +import org.apache.spark.sql.streaming.StreamingQueryListener.{QueryProgressEvent, + QueryStartedEvent, QueryTerminatedEvent} +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{DateType, StructType, TimestampNTZType, TimestampType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +/** Which errors of an external lookup join stop a streaming query when it starts. */ +class ExternalLookupJoinStartupCheckSuite extends QueryTest with SharedSparkSession { + import testImplicits._ + + private val queryCount = new AtomicInteger() + + private val timeoutMs = 60000L + + private implicit def sqlContextOfStreams: SQLContext = spark.sqlContext + + override def beforeEach(): Unit = { + super.beforeEach() + SimpleExternalLookupDataSource.resetCounters() + ThrowingScanBuilderTable.scanBuilderCount.set(0) + } + + private def lookupOnly: DataFrame = + spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load() + + private def throwingStatic: DataFrame = + spark.read.format(classOf[ThrowingScanBuilderDataSource].getName).load() + + private def start(df: DataFrame): StreamingQuery = + df.writeStream.format("memory").queryName(s"startup_check_${queryCount.incrementAndGet()}") + .start() + + /** The error that `start()` throws for `df`, which analysis reports. */ + private def startFailure(df: DataFrame): AnalysisException = { + val e = intercept[AnalysisException](start(df).stop()) + // The connector served no lookup at the start. + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + e + } + + /** + * The error that stops the query of `df` when its execution starts: `start()` returns, and the + * query stops before it has any data. + */ + private def queryFailure[T <: Throwable : ClassTag](df: DataFrame): T = { + val query = start(df) + val e = try { + intercept[StreamingQueryException](query.awaitTermination(timeoutMs)) + } finally { + query.stop() + } + assert(query.exception.contains(e)) + // The connector served no lookup at the start. + assert(SimpleExternalLookupDataSource.readerCount.get() === 0) + assert(classTag[T].runtimeClass.isInstance(e.getCause), e.getCause) + e.getCause.asInstanceOf[T] + } + + /** Waits until `query` has planned its lookup joins and created its sources. */ + private def awaitInitialization(query: StreamingQuery): Unit = + query.asInstanceOf[StreamingQueryWrapper].streamingQuery.awaitInitialization(timeoutMs) + + /** Runs `body`, and returns the warnings that the startup check logged meanwhile. */ + private def startupWarnings(body: => Unit): Seq[String] = { + val appender = new LogAppender("the startup check") + withLogAppender( + appender, + loggerNames = Seq(ExternalLookupJoinStartupCheck.getClass.getName.stripSuffix("$")), + level = Some(Level.WARN)) { + body + } + appender.loggingEvents.map(_.getMessage.getFormattedMessage).toSeq + } + + /** Adds `rows` to `input`, and fails unless the first micro-batch of `query` fails. */ + private def firstBatchFailure( + query: StreamingQuery, + input: MemoryStream[Int], + rows: Int*): StreamingQueryException = { + try { + query.processAllAvailable() + assert(query.isActive && query.exception.isEmpty) + input.addData(rows) + intercept[StreamingQueryException](query.processAllAvailable()) + } finally { + query.stop() + } + } + + test("an ordinary stream-static join fails at its first micro-batch, not at start") { + val input = MemoryStream[Int] + val stream = input.toDF().toDF("id") + val static = throwingStatic + val query = start(stream.join(static, stream("id") === static("id"))) + awaitInitialization(query) + // Without data, no micro-batch runs, so the query keeps running. + assert(ThrowingScanBuilderTable.scanBuilderCount.get() === 0) + val e = firstBatchFailure(query, input, 1) + assert(e.getCause.getMessage.contains("The scan builder fails")) + } + + test("MISSING_JOIN_CONDITION fails start()") { + val stream = MemoryStream[Int].toDF().toDF("id") + val lookup = lookupOnly + Seq( + stream.join(lookup).where(stream("id") === lookup("id")), + stream.join(lookup, Seq.empty[String], "left_outer")).foreach { joined => + checkError( + exception = startFailure(joined), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + } + // A USING join gets its condition after its first analysis, so it starts. + start(stream.join(lookup, Seq("id"))).stop() + } + + test("MISSING_JOIN_CONDITION fails start() for a hinted join") { + val stream = MemoryStream[Int].toDF().toDF("id") + checkError( + exception = startFailure(stream.join(lookupOnly.hint("external_lookup"))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION", + parameters = Map.empty) + } + + test("the start plans a lookup side read through a WITH clause") { + withTempView("startup_stream", "startup_bigint_stream", "startup_lookup", "startup_dual") { + MemoryStream[Long].toDF().toDF("id").createOrReplaceTempView("startup_bigint_stream") + lookupOnly.createOrReplaceTempView("startup_lookup") + spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load() + .createOrReplaceTempView("startup_dual") + def withClause(stream: String, table: String, hint: String = ""): DataFrame = spark.sql( + s"WITH lk AS (TABLE $table) SELECT $hint lk.department " + + s"FROM $stream s JOIN lk ON s.id = lk.id") + checkError( + exception = queryFailure[AnalysisException]( + withClause("startup_bigint_stream", "startup_lookup")), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE", + parameters = Map("table" -> "`SimpleExternalLookupTable`")) + Seq(("startup_lookup", ""), ("startup_dual", "/*+ EXTERNAL_LOOKUP(lk) */")).foreach { 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 [549eae9bdc1](https://github.com/apache/spark/commit/549eae9bdc1432e89f4e66904bda19d2592ddab4). A hinted join over a table that supports both reads, with a stream key that gives no lookup candidate, stops the query when it starts, before any data arrives. The test runs it directly and through a WITH clause. If the startup check skips hinted lookup sides, the test fails. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala: ########## @@ -0,0 +1,181 @@ +/* + * 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, AttributeSeq, AttributeSet, Expression} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter, QueryPlan} +import org.apache.spark.sql.catalyst.trees.TreePattern.{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, LongType, ShortType, StringType, TimestampNTZType, + TimestampType, VarcharType} + +/** + * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint asks an external + * lookup join to read. 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) 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 Every output attribute of the lookup side. They are all part of this + * node's references, so column pruning never puts a projection over the lookup relation, which + * preparation needs directly under the join. A narrower list would let it do so. + */ +case class ExternalLookupJoin( + left: LogicalPlan, + right: LogicalPlan, + joinType: JoinType, + condition: Option[Expression], + 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 other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + override protected def withNewChildrenInternal( + newLeft: LogicalPlan, + newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right = newRight) +} + +/** + * A lookup join after its optimized lookup side has been converted to an external operation. + * + * @param lookupKeys The table column that each selected lookup predicate compares with the + * parameter at the same position. Spark checks each row that the connector returns against + * them, so the read schema must hold these columns. + */ +case class PreparedExternalLookupJoin( + child: LogicalPlan, + tableName: String, + @transient scan: Scan, + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + lookupInput: Seq[Attribute], + lookupOutput: Seq[Attribute], + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + lookupKeys: Seq[Attribute], + joinType: JoinType, + residualCondition: Option[Expression]) extends UnaryNode { + + override def output: Seq[Attribute] = joinType match { + case Inner => child.output ++ lookupOutput + case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true)) + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + override def references: AttributeSet = + AttributeSet(lookupParameters.flatMap(_.references)) ++ + residualCondition.map(_.references.intersect(child.outputSet)) + .getOrElse(AttributeSet.empty) + + override protected def withNewChildInternal(newChild: LogicalPlan): PreparedExternalLookupJoin = + copy(child = newChild) + + // The lookup-side attributes are not in the child's output, so the default canonicalization + // gives each top-level one the next id, whichever column it is: two joins that keep different + // lookup columns of one type would canonicalize alike. Each is normalized by its place in the + // child's output and the read schema instead. + override protected def doCanonicalize(): LogicalPlan = { + val attributes: AttributeSeq = child.output ++ lookupInput + def normalize[T <: Expression](expression: T): T = + QueryPlan.normalizeExpressions(expression, attributes) + copy( + child = child.canonicalized, + lookupInput = lookupInput.map(normalize), + lookupOutput = lookupOutput.map(normalize), + lookupParameters = lookupParameters.map(normalize), + lookupKeys = lookupKeys.map(normalize), + residualCondition = residualCondition.map(normalize)) + } + + // Connector descriptions may contain secrets, so the scan and the reader factory are not shown. + // The physical node renders the scan's redacted description, and nothing of the reader factory. + override protected def stringArgs: Iterator[Any] = + Iterator(joinType, lookupParameters, residualCondition, child) + + // The join keeps the size estimate it had before preparation, as an ordinary join's: the product 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 [549eae9bdc1](https://github.com/apache/spark/commit/549eae9bdc1432e89f4e66904bda19d2592ddab4). The comment now says what the code computes: the stream side's size times `spark.sql.defaultSizeInBytes`, as the lookup side is read by lookups. It also says that this can differ from the estimate before preparation. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,94 @@ +/* + * 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 java.util.Locale + +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{Expression, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupHint, LogicalPlan, + SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. As with join strategy + * hints, a hint without parameters marks the plan it is attached to, and a hint with relation + * names, given as identifiers or strings, marks each named relation. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + parameters.foreach { + // As in ResolveJoinStrategyHints: the Dataset API, PySpark and Spark Connect pass a relation + // name as a string, and SQL as an identifier. + case StringLiteral(name) => + relationNames += UnresolvedAttribute.parseAttributeName(name) + case attr: UnresolvedAttribute => + relationNames += attr.nameParts + case other => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other))) + } + if (relationNames.isEmpty) { + ExternalLookupHint(child) + } else { + // As with join strategy hints, a name marks every relation that it matches. `matched` only + // tells which names matched nothing. + val matched = mutable.HashSet.empty[Seq[String]] + def matches(identifier: Seq[String]): Boolean = { + val names = relationNames.filter { name => + ResolveHints.matchedIdentifier(name, identifier, conf.resolver) + } + matched ++= names + names.nonEmpty + } + // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: a name matches an + // unaliased (possibly multipart) table or an alias, and does not reach into a view, + // a WITH clause, or an aliased subquery. + def applyHint(plan: LogicalPlan): LogicalPlan = plan match { + case relation: UnresolvedRelation if matches(relation.multipartIdentifier) => + ExternalLookupHint(relation) + case alias: SubqueryAlias + if matches(alias.identifier.qualifier :+ alias.identifier.name) => + ExternalLookupHint(alias) + case _: View | _: UnresolvedWith | _: SubqueryAlias => plan + case _ => plan.mapChildren(applyHint) + } + val rewritten = applyHint(child) + // As with join strategy hints, a name may be repeated. + val missing = relationNames.distinct.filterNot(matched.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. Added in [549eae9bdc1](https://github.com/apache/spark/commit/549eae9bdc1432e89f4e66904bda19d2592ddab4). A hint with one matching and one missing name, and one with one matching and two missing names, report exactly the missing names, in SQL and through the Dataset API. Reporting only the first missing name fails the test. ########## 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")) 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. Fair point: the check had that TODO before this PR. Restored in [549eae9bdc1](https://github.com/apache/spark/commit/549eae9bdc1432e89f4e66904bda19d2592ddab4) for what this PR still doesn't look through: the projections and filters on the lookup side, such as those that a SQL-defined view, read-side CHAR padding, a second reference to a WITH clause or the refresh of a versioned table puts above the table. #60055, which looks through them, removes it. -- 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]
