HeartSaVioR commented on code in PR #59909: URL: https://github.com/apache/spark/pull/59909#discussion_r4518664752
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala: ########## @@ -0,0 +1,171 @@ +/* + * 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 org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint +import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinStrategyHint, + LogicalPlan, ResolvedHint} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN +import org.apache.spark.sql.connector.catalog.Table +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. 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-only + * table is on the right side. + */ +object ExternalLookupJoinEligibility extends QueryErrorsBase { + sealed trait Eligibility + /** + * The join stays an ordinary join: the classifier recognizes no lookup-only relation as either + * of its sides. A lookup-only relation under another operator, such as a projection or an + * alias, is not recognized yet, 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 reads a lookup-only table, with a supported join type, but has no condition. */ + case object MissingCondition extends Eligibility + /** The join reads a lookup-only table, which no other join can read, but cannot run. */ + case class Ineligible(error: Throwable) extends Eligibility + + private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter) + + def apply(join: Join): Eligibility = { + // The lookup-only table must be on the right side; the sides are never swapped. + // TODO: look through projections, filters and aliases above the lookup relation. + // TODO: allow the EXTERNAL_LOOKUP hint once it is introduced, and classify the joins it opts + // in. + (ExternalLookupRelations.lookupOnlyTable(join.left), lookupOnlyTableOnRight(join)) match { + case (Some(table), _) => ineligible("LOOKUP_TABLE_ON_LEFT", table) + case (None, Some(table)) => lookupJoinEligibility(join, table) + case (None, None) => NotLookupJoin + } + } + + /** + * The lookup-only table on the join's right side, also under a strategy hint, which is where a + * broadcast hint usually goes in a stream-static join. The hint is then reported as conflicting. + */ + private def lookupOnlyTableOnRight(join: Join): Option[Table] = { + def underStrategyHints(plan: LogicalPlan): LogicalPlan = plan match { + case ResolvedHint(child, hint) if hint.strategy.isDefined => underStrategyHints(child) + case other => other + } + ExternalLookupRelations.lookupOnlyTable(underStrategyHints(join.right)) + } + + private def lookupJoinEligibility(join: Join, table: Table): Eligibility = { + if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", table) + // 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 { + case Some(strategy) => + ineligible("CONFLICTING_JOIN_STRATEGY", table, + Map("strategy" -> toSQLStmt(strategy.displayName))) + // 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", table, Map( + "joinType" -> toSQLStmt(join.joinType.sql), + "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => toSQLStmt(t.sql)).mkString(", "))) + case None if join.condition.isEmpty => MissingCondition + case None => Eligible + } + } + + private def ineligible( + subClass: String, + table: Table, + parameters: Map[String, String] = Map.empty): Ineligible = + Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError( + subClass, parameters + ("relation" -> toSQLId(table.name())))) + + 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 over a lookup-only table cannot run as an + * external lookup join. 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 not reported here, because 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 (plan.containsPattern(JOIN)) { + plan.foreachUp { + case join: Join if join.resolved => + ExternalLookupJoinEligibility(join) match { + case ExternalLookupJoinEligibility.Ineligible(error) => throw error + case _ => + } + case _ => + } + } + } +} + +/** + * Replaces each join that runs as an external lookup join with an [[ExternalLookupJoin]]. + * + * It must run at the start of optimization, before Finish Analysis and operator optimization, so + * that it sees the join and its lookup side as analysis left them: no hint or alias eliminated, + * no predicate pushed into the join and no column pruned. These are the shapes that + * [[CheckExternalLookupJoin]] validated. + */ +object FormExternalLookupJoin extends Rule[LogicalPlan] { + import ExternalLookupJoinEligibility._ + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.transformUpWithPruning(_.containsPattern(JOIN), ruleId) { 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. Dropped in [e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa), together with its `RuleIdCollection` entry. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,185 @@ +/* + * 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.jdk.CollectionConverters._ + +import org.apache.spark.SparkException +import org.apache.spark.sql.AnalysisException +import org.apache.spark.sql.catalyst.QueryPlanningTracker +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.dsl.plans._ +import org.apache.spark.sql.catalyst.plans.{Cross, FullOuter, Inner, LeftOuter, RightOuter} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinHint, + LocalRelation, LogicalPlan, Project} +import org.apache.spark.sql.connector.catalog.{Table, TableCapability} +import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, EXTERNAL_LOOKUP} +import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, + ExternalLookupRelation} +import org.apache.spark.sql.types.StructType +import org.apache.spark.sql.util.CaseInsensitiveStringMap + +class FormExternalLookupJoinSuite extends AnalysisTest { + // The stream side of a stream-static join. + private val stream = LocalRelation(Seq($"streamTenant".int, $"streamId".int), isStreaming = true) + // A lookup-only table has no batch scan, so it reaches the join as this placeholder. + private val lookupOnly = ExternalLookupRelation(tableWith(EXTERNAL_LOOKUP)) + private val idsEqual = stream.output(1) === lookupOnly.output(1) + + private def tableWith(capabilities: TableCapability*): DataSourceV2Relation = + DataSourceV2Relation.create( + LookupCapabilityTable(capabilities.toSet), None, None, CaseInsensitiveStringMap.empty) + + // An inner join of the stream with `right`, on the id column of each. + private def innerJoinOnId(right: LogicalPlan): Join = + Join(stream, right, Inner, Some(stream.output(1) === right.output(1)), JoinHint.NONE) + + // Hints become ResolvedHint nodes, which only Finish Analysis moves into the join. + private def analyze(plan: LogicalPlan): LogicalPlan = + getAnalyzer.executeAndCheck(plan, new QueryPlanningTracker) + + test("an eligible join stays a Join in analysis and is converted when optimization starts") { + val Seq(tenant, id) = stream.output + val compositeKey = tenant === lookupOnly.output(0) && idsEqual + for (condition <- Seq(idsEqual, compositeKey); joinType <- Seq(Inner, LeftOuter)) { + val analyzed = analyze(stream.join(lookupOnly, joinType, Some(condition))) + assert(analyzed.isInstanceOf[Join]) + CheckExternalLookupJoin(analyzed) + FormExternalLookupJoin(analyzed) match { + case lookupJoin: ExternalLookupJoin => + assert(lookupJoin.joinType == joinType && lookupJoin.condition == Some(condition)) + assert(lookupJoin.requiredLookupOutput == lookupOnly.output) + assert(lookupJoin.output == analyzed.output) + assert(lookupJoin.output.drop(2).forall(_.nullable) == (joinType == LeftOuter)) + assert(lookupJoin.missingInput.isEmpty) + assert(FormExternalLookupJoin(lookupJoin) == lookupJoin) + case other => fail(s"Expected an external lookup join: $other") + } + } + } + + test("keep ordinary joins that cannot become external lookup joins") { + val other = LocalRelation($"k".int, $"k2".int) + Seq( + innerJoinOnId(tableWith(BATCH_READ, EXTERNAL_LOOKUP)), + innerJoinOnId(tableWith(BATCH_READ)), + innerJoinOnId(other), + innerJoinOnId(Project(lookupOnly.output, lookupOnly))).foreach { join => + CheckExternalLookupJoin(join) + assert(FormExternalLookupJoin(join) == join) + } + } + + test("validation and conversion reject a lookup-only join with the same reason") { + Seq( + // Only a stream-static join, with the lookup-only table on the right side. + (stream.copy(isStreaming = false).join(lookupOnly, Inner, Some(idsEqual)), + "STATIC_LEFT_SIDE", Map.empty[String, String]), + (lookupOnly.join(stream, Inner, Some(idsEqual)), "LOOKUP_TABLE_ON_LEFT", + Map.empty[String, String]), + (stream.join(lookupOnly, RightOuter, Some(idsEqual)), "JOIN_TYPE", + Map("joinType" -> "RIGHT OUTER")), + // A cross join fails with its join type, with or without a later filter. + (stream.join(lookupOnly, Cross), "JOIN_TYPE", Map("joinType" -> "CROSS")), + (stream.join(lookupOnly, Cross).where(idsEqual), "JOIN_TYPE", Map("joinType" -> "CROSS")), + // No join strategy hint applies to an external lookup join; sort merge is named MERGE. + (stream.hint("broadcast").join(lookupOnly, Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")), + (stream.hint("merge").join(lookupOnly, Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")), + (stream.hint("shuffle_hash").join(lookupOnly, Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")), + (stream.hint("shuffle_replicate_nl").join(lookupOnly, Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_REPLICATE_NL")), + // The same on the lookup side, where a broadcast hint usually goes in a stream-static join. + (stream.join(lookupOnly.hint("broadcast"), Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "BROADCAST")), + (stream.join(lookupOnly.hint("merge"), Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "MERGE")), + (stream.join(lookupOnly.hint("shuffle_hash"), Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_HASH")), + (stream.join(lookupOnly.hint("shuffle_replicate_nl"), Inner, Some(idsEqual)), + "CONFLICTING_JOIN_STRATEGY", Map("strategy" -> "SHUFFLE_REPLICATE_NL"))).foreach { + case (plan, subClass, parameters) => + val analyzed = analyze(plan) + Seq[LogicalPlan => Any](CheckExternalLookupJoin, FormExternalLookupJoin(_)).foreach { + rule => + val error = intercept[AnalysisException] { rule(analyzed) } + assert(error.getCondition == s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass") + // The list of supported join types grows in a later change. + assert(error.getMessageParameters.asScala.toMap - "supportedJoinTypes" == 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. Done in [e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa): the test asserts `supportedJoinTypes` now, and #60055 updates the expected value when it adds the semi and anti joins ([bd66301acae](https://github.com/apache/spark/commit/bd66301acae7ff882d172c3ea4d9218d7c4ec153)). ########## sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,398 @@ +/* + * 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 org.apache.spark.SparkException +import org.apache.spark.sql.AnalysisException +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, AttributeSet, + Expression, Literal} +import org.apache.spark.sql.catalyst.optimizer.ColumnPruning +import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, LeftOuter, PlanTest} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinHint, + LocalRelation, LogicalPlan, PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, TableCapability} +import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP +import org.apache.spark.sql.connector.expressions.FieldReference +import org.apache.spark.sql.connector.expressions.filter.Predicate +import org.apache.spark.sql.connector.read.{ExternalLookup, ExternalLookupReader, + ExternalLookupReaderFactory, Scan, ScanBuilder, SupportsExternalLookup} +import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, + ExternalLookupRelation, PrepareExternalLookupJoin} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{IntegerType, LongType, StructType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap +import org.apache.spark.unsafe.types.UTF8String + +class PrepareExternalLookupJoinSuite extends PlanTest { + private val stream = + LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = true) + private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`" + + private def lookupRelation(table: PlanningExternalLookupTable): ExternalLookupRelation = + ExternalLookupRelation( + DataSourceV2Relation.create(table, None, None, CaseInsensitiveStringMap.empty)) + + private def lookupJoin( + lookup: LogicalPlan, + condition: Expression, + joinType: JoinType = Inner, + left: LogicalPlan = stream): LogicalPlan = + FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), JoinHint.NONE)) + + private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan = + lookupJoin(lookup, stream.output.head === lookup.output.head) + + private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin = + PrepareExternalLookupJoin(plan) match { + case lookup: PreparedExternalLookupJoin => lookup + case other => fail(s"Expected a prepared external lookup join: $other") + } + + private def prepareError(plan: LogicalPlan): AnalysisException = + intercept[AnalysisException] { PrepareExternalLookupJoin(plan) } + + test("a lookup-only relation that no lookup join reads is rejected") { + val lookup = lookupRelation(PlanningExternalLookupTable()) + prepare(lookupJoinOnId(lookup)) + checkError( + exception = prepareError(Project(lookup.output, lookup)), + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch scan")) + } + + test("an equality is a lookup candidate only on a type that stores compare as Spark does") { + val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", "DECIMAL(10, 2)", + "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING COLLATE UTF8_BINARY") + val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)", + "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE UTF8_BINARY_RTRIM", + "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND") + for ((codeType, offered) <- offeredTypes.map(_ -> true) ++ notOfferedTypes.map(_ -> false)) { + var offeredCandidates = Seq.empty[String] + val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code $codeType", select = { + candidates => + offeredCandidates = candidates.map(_.toString).toSeq + candidates.take(1) + })) + val Seq(lookupId, lookupCode) = lookup.output + val streamId = stream.output.head + val streamCode = AttributeReference("streamCode", lookupCode.dataType)() + val codesEqual = streamCode === lookupCode + val prepared = prepare(lookupJoin(lookup, streamId === lookupId && codesEqual, + left = LocalRelation(Seq(streamId, streamCode), isStreaming = true))) + val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?") + assert(offeredCandidates === expected, codeType) + // The connector selects only `id = ?`, so Spark evaluates the code equality either way. + assert(prepared.residualCondition === Some(codesEqual), codeType) + } + + // Without another candidate, the join cannot run. + Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType => + val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code $codeType")) + val lookupCode = lookup.output(1) + val streamCode = AttributeReference("streamCode", lookupCode.dataType)() + checkError( + exception = prepareError(lookupJoin(lookup, streamCode === lookupCode, + left = LocalRelation(Seq(streamCode), isStreaming = true))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE", + parameters = Map("table" -> QUOTED_TABLE_NAME)) + } + } + + test("the residual evaluates key equalities and conjuncts that cannot fail first") { + val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label STRING, value STRING")) + val Seq(lookupId, lookupLabel, lookupValue) = lookup.output + val Seq(streamId, streamLabel) = stream.output + // A cast can fail, so it runs after the equality and the comparison written after it, which + // keep their written order. The connector selects only `id = ?`. + val mayFail = streamLabel.cast(IntegerType) > 0 + val conjuncts = + Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel, lookupValue > "a") + val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _))) + assert(prepared.residualCondition === + Some(streamLabel === lookupLabel && lookupValue > "a" && mayFail)) + + // Equalities between the sides go first even when they can fail, as a hash join's keys: `=` + // and `<=>`, each comparing a lookup column with a cast of a stream column, written after a + // conjunct that can fail. + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { 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. You're right that it had no effect on this base. It does now: SPARK-60882, merged to master on Nov 8, makes `ExprUtils.canEvaluateUnconditionally` accept a cast of a string to INT when ANSI mode is off. Without the setting, the test would fail in Apache's non-ANSI job. So in [e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa) the whole test runs with ANSI mode on, where the cast can fail with or without SPARK-60882, and a comment says why. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,398 @@ +/* + * 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 org.apache.spark.SparkException +import org.apache.spark.sql.AnalysisException +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin +import org.apache.spark.sql.catalyst.dsl.expressions._ +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, AttributeSet, + Expression, Literal} +import org.apache.spark.sql.catalyst.optimizer.ColumnPruning +import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, LeftOuter, PlanTest} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, JoinHint, + LocalRelation, LogicalPlan, PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, TableCapability} +import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP +import org.apache.spark.sql.connector.expressions.FieldReference +import org.apache.spark.sql.connector.expressions.filter.Predicate +import org.apache.spark.sql.connector.read.{ExternalLookup, ExternalLookupReader, + ExternalLookupReaderFactory, Scan, ScanBuilder, SupportsExternalLookup} +import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, + ExternalLookupRelation, PrepareExternalLookupJoin} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{IntegerType, LongType, StructType} +import org.apache.spark.sql.util.CaseInsensitiveStringMap +import org.apache.spark.unsafe.types.UTF8String + +class PrepareExternalLookupJoinSuite extends PlanTest { + private val stream = + LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = true) + private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`" + + private def lookupRelation(table: PlanningExternalLookupTable): ExternalLookupRelation = + ExternalLookupRelation( + DataSourceV2Relation.create(table, None, None, CaseInsensitiveStringMap.empty)) + + private def lookupJoin( + lookup: LogicalPlan, + condition: Expression, + joinType: JoinType = Inner, + left: LogicalPlan = stream): LogicalPlan = + FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), JoinHint.NONE)) + + private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan = + lookupJoin(lookup, stream.output.head === lookup.output.head) + + private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin = + PrepareExternalLookupJoin(plan) match { + case lookup: PreparedExternalLookupJoin => lookup + case other => fail(s"Expected a prepared external lookup join: $other") + } + + private def prepareError(plan: LogicalPlan): AnalysisException = + intercept[AnalysisException] { PrepareExternalLookupJoin(plan) } + + test("a lookup-only relation that no lookup join reads is rejected") { + val lookup = lookupRelation(PlanningExternalLookupTable()) + prepare(lookupJoinOnId(lookup)) + checkError( + exception = prepareError(Project(lookup.output, lookup)), + condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION", + parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch scan")) + } + + test("an equality is a lookup candidate only on a type that stores compare as Spark does") { + val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", "DECIMAL(10, 2)", + "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING COLLATE UTF8_BINARY") + val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)", + "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE UTF8_BINARY_RTRIM", + "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND") + for ((codeType, offered) <- offeredTypes.map(_ -> true) ++ notOfferedTypes.map(_ -> false)) { + var offeredCandidates = Seq.empty[String] + val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code $codeType", select = { + candidates => + offeredCandidates = candidates.map(_.toString).toSeq + candidates.take(1) + })) + val Seq(lookupId, lookupCode) = lookup.output + val streamId = stream.output.head + val streamCode = AttributeReference("streamCode", lookupCode.dataType)() + val codesEqual = streamCode === lookupCode + val prepared = prepare(lookupJoin(lookup, streamId === lookupId && codesEqual, + left = LocalRelation(Seq(streamId, streamCode), isStreaming = true))) + val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?") + assert(offeredCandidates === expected, codeType) + // The connector selects only `id = ?`, so Spark evaluates the code equality either way. + assert(prepared.residualCondition === Some(codesEqual), codeType) + } + + // Without another candidate, the join cannot run. + Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType => + val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code $codeType")) + val lookupCode = lookup.output(1) + val streamCode = AttributeReference("streamCode", lookupCode.dataType)() + checkError( + exception = prepareError(lookupJoin(lookup, streamCode === lookupCode, + left = LocalRelation(Seq(streamCode), isStreaming = true))), + condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE", + parameters = Map("table" -> QUOTED_TABLE_NAME)) + } + } + + test("the residual evaluates key equalities and conjuncts that cannot fail first") { + val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label STRING, value STRING")) + val Seq(lookupId, lookupLabel, lookupValue) = lookup.output + val Seq(streamId, streamLabel) = stream.output + // A cast can fail, so it runs after the equality and the comparison written after it, which + // keep their written order. The connector selects only `id = ?`. + val mayFail = streamLabel.cast(IntegerType) > 0 + val conjuncts = + Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel, lookupValue > "a") + val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _))) + assert(prepared.residualCondition === + Some(streamLabel === lookupLabel && lookupValue > "a" && mayFail)) + + // Equalities between the sides go first even when they can fail, as a hash join's keys: `=` + // and `<=>`, each comparing a lookup column with a cast of a stream column, written after a + // conjunct that can fail. + withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") { + val codes = lookupRelation(PlanningExternalLookupTable("id INT, code INT, alt INT")) + val Seq(codeId, code, alt) = codes.output + val codeEqual = code === streamLabel.cast(IntegerType) + val altEqual = alt <=> streamLabel.cast(IntegerType) + val keyed = prepare( + lookupJoin(codes, Seq(codeId === streamId, mayFail, codeEqual, altEqual).reduce(_ && _))) + assert(keyed.residualCondition === Some(codeEqual && altEqual && mayFail)) + } + } + + test("selected predicates bind in the connector's order, and the residual in written order") { + val Seq(streamId, streamLabel) = stream.output + def prepared(select: Array[Predicate] => Array[Predicate]) + : (PreparedExternalLookupJoin, Seq[Attribute], Seq[Expression]) = { + val lookup = lookupRelation( + PlanningExternalLookupTable("id INT, label STRING, value STRING", select = select)) + val Seq(id, label, value) = lookup.output + // `value = 'a'` is offered as well; `streamId > 0` is not. + val conjuncts = + Seq(id === streamId, streamLabel === label, streamId > 0, value === Literal("a")) + val join = lookupJoin(lookup, conjuncts.reduce(_ && _), LeftOuter) + (prepare(join), join.output, conjuncts) + } + + val (reversed, joinOutput, conjuncts) = + prepared(candidates => Array(candidates(1), candidates(0))) + assert(reversed.lookupParameters === Seq(streamLabel, streamId)) + assert(reversed.nullSafeParameters === Seq(false, false)) + assert(reversed.residualCondition === Some(conjuncts(2) && conjuncts(3))) + assert(reversed.output === joinOutput) + assert(PrepareExternalLookupJoin(reversed) === reversed) + checkError( + exception = intercept[SparkException] { reversed.copy(joinType = FullOuter).output }, 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. Removed in [e3212ca903a](https://github.com/apache/spark/commit/e3212ca903ab0d829feab6150bda53ea5ad88cfa). The check stays in `FormExternalLookupJoinSuite`. -- 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]
