HeartSaVioR commented on code in PR #60055: URL: https://github.com/apache/spark/pull/60055#discussion_r4520075481
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala: ########## @@ -0,0 +1,341 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.plans.logical + +import org.apache.spark.SparkException +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, BinaryComparison, + Cast, EqualNullSafe, EqualTo, Expression, ExprUtils, ExternalUserDefinedFunction, GreaterThan, + GreaterThanOrEqual, LessThan, LessThanOrEqual, NamedExpression, PythonUDF, SubqueryExpression} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, LeftOuter, LeftSemi} +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, IntegralType, 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 Lookup-side attributes still required above this join. They are + * part of this node's references, so column pruning keeps them on the lookup side. + * `ColumnPruning` narrows them to what the parent reads, and `PrepareExternalLookupJoin` prunes + * the lookup scan to them. + */ +case class ExternalLookupJoin( + left: LogicalPlan, + right: LogicalPlan, + joinType: JoinType, + condition: Option[Expression], + requiredLookupOutput: Seq[Attribute]) extends BinaryNode { + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN) + + override def output: Seq[Attribute] = joinType match { + case Inner => left.output ++ right.output + case LeftOuter => left.output ++ right.output.map(_.withNullability(true)) + case LeftSemi | LeftAnti => left.output + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + // As an ordinary join's: a semi or anti join returns at most its stream rows, and the other join + // types get the product of both sides' sizes. + override def stats: Statistics = joinType match { + case LeftSemi | LeftAnti => left.stats + case _ => super.stats + } + + override def maxRows: Option[Long] = joinType match { + case LeftSemi | LeftAnti => left.maxRows + case _ => None + } + + override protected def withNewChildrenInternal( + newLeft: LogicalPlan, + newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right = newRight) +} + +/** + * The join-condition and lookup-side shapes that an external lookup join can run. Analysis, + * lookup planning and the optimizer rules for lookup joins share them. + */ +object ExternalLookupJoinShapes { + /** + * A lookup candidate: a comparison of a lookup column with a value, written with the lookup + * column on the left. `predicateName` is the name of the DSv2 `Predicate` that is offered to the + * connector for it: the SQL operator of the comparison, as `V2ExpressionBuilder` names it. + */ + case class LookupComparison( + lookupField: Attribute, + parameter: Expression, + predicateName: String, + nullSafe: Boolean) + + /** + * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, `<=>`, `<`, `<=`, `>` + * or `>=` between a bare lookup column and a value, in either operand order. When the lookup + * column is written on the right, the comparison is rebuilt with it on the left, so + * `s.ts < t.event_time` is offered as `event_time > ?`. + * + * The value is the other operand, which Spark evaluates for each stream row to fill the + * comparison's parameter. It may read only stream columns, and it may read none, as a literal + * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a parameter. + * + * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets Spark offer the + * comparison. A comparison on another column is an ordinary conjunct. + * + * @param streamOutput The output of the join's left side, the stream side. + * @param lookupOutput The output of the join's right side, the lookup side. + */ + def lookupComparison( + conjunct: Expression, + streamOutput: AttributeSet, + lookupOutput: AttributeSet): Option[LookupComparison] = { + def isLookupComparison(lookupField: Attribute, parameter: Expression): Boolean = + lookupOutput.contains(lookupField) && parameter.references.subsetOf(streamOutput) + conjunct match { + case comparison: BinaryComparison if isLookupOperator(comparison) => + val nullSafe = comparison.isInstanceOf[EqualNullSafe] + Seq(comparison, withOperandsSwapped(comparison)).collectFirst { + case candidate @ BinaryComparison(lookupField: Attribute, parameter) + if isLookupComparison(lookupField, parameter) && + isOfferedOn(comparison, lookupField, parameter) => + LookupComparison(lookupField, parameter, candidate.sqlOperator, nullSafe) + } + case _ => None + } + } + + private def isLookupOperator(comparison: BinaryComparison): Boolean = comparison match { + case _: EqualTo | _: EqualNullSafe | _: LessThan | _: LessThanOrEqual | _: GreaterThan | + _: GreaterThanOrEqual => true + case _ => false + } + + /** + * Whether Spark offers the comparison on this lookup column, with this parameter. + * + * Spark evaluates every parameter on every stream row, before the other join conditions. That + * is safe for an equality, as a hash join evaluates its keys on every row too. A range is a + * join condition, which a join evaluates only after its keys match, so its parameter must be + * one that cannot fail, as `cannotFail` decides. + */ + private def isOfferedOn( + comparison: BinaryComparison, + lookupField: Attribute, + parameter: Expression): Boolean = comparison match { + case _: EqualTo | _: EqualNullSafe => ExternalLookupKeyTypes.supportsEquality(lookupField) + case _ => + ExternalLookupKeyTypes.supportsRange(lookupField.dataType) && cannotFail(parameter) + } + + /** + * Whether a range parameter cannot fail: ExprUtils.canEvaluateUnconditionally accepts it, or it + * is a widening numeric cast of such a value. Analysis adds such a cast when the stream side has + * a narrower type than the lookup column, as an INT column compared with a BIGINT key. + */ + private def cannotFail(parameter: Expression): Boolean = parameter match { + case cast: Cast => + isTotalNumericWidening(cast.child.dataType, cast.dataType) && + ExprUtils.canEvaluateUnconditionally(cast.child) + case _ => ExprUtils.canEvaluateUnconditionally(parameter) + } + + /** + * Whether a cast converts every value of its source type: an integral type to a wider one, or + * an integral type or DECIMAL to a DECIMAL with room for all of its digits. `Cast.canUpCast` + * is not enough: it also accepts casts that fail on some values, as a far-future DATE overflows + * a TIMESTAMP, and 9999999999999999999 as DECIMAL(19, 0) exceeds BIGINT under ANSI. + */ + private def isTotalNumericWidening(from: DataType, to: DataType): Boolean = (from, to) match { + case (from: IntegralType, to: IntegralType) => from.defaultSize < to.defaultSize + case (from: IntegralType, to: DecimalType) => to.isWiderThan(from) + case (from: DecimalType, to: DecimalType) => to.isWiderThan(from) + case _ => false + } + + /** The same comparison with its operands swapped, so that `a < b` becomes `b > a`. */ + private def withOperandsSwapped(comparison: BinaryComparison): BinaryComparison = + comparison match { + case EqualTo(left, right) => EqualTo(right, left) + case EqualNullSafe(left, right) => EqualNullSafe(right, left) + case LessThan(left, right) => GreaterThan(right, left) + case LessThanOrEqual(left, right) => GreaterThanOrEqual(right, left) + case GreaterThan(left, right) => LessThan(right, left) + case GreaterThanOrEqual(left, right) => LessThanOrEqual(right, left) + } + + /** + * Whether a lookup-side projection or filter can evaluate `expression` on the lookup results, + * inside the join. Python and external UDFs and subqueries are planned as separate operators, + * which a lookup-side stage cannot contain. A non-deterministic expression is not allowed + * either: the join evaluates a stage on each returned row, so one stored row could get + * different values for different stream rows, which a read of the table never does. + */ + def canEvaluateInLookupStage(expression: Expression): Boolean = Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Thanks, fixed in [715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf): a lookup-side stage accepts `CurrentBatchTimestamp`, and `PrepareExternalLookupJoin` lowers it with `toLiteral`, next to `ReplaceUpdateFieldsExpression`. Tests cover `current_timestamp()` and `current_date()` through `start()` and a micro-batch. On master, the startup column pruning of SPARK-60734 now leaves lookup sides alone too, so they also pass with `spark.sql.streaming.v2ColumnPruning.enabled` ([4bc87c4843a](https://github.com/apache/spark/commit/4bc87c4843aa239cec21df938b2a9733b6e64c32)). ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinExec.scala: ########## @@ -0,0 +1,232 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.joins + +import org.apache.spark.SparkException +import org.apache.spark.rdd.RDD +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{And, Attribute, AttributeMap, AttributeSet, + BoundReference, EqualNullSafe, EqualTo, Expression, ExprUtils, GreaterThan, GreaterThanOrEqual, + LessThan, LessThanOrEqual, PredicateHelper} +import org.apache.spark.sql.catalyst.plans.{JoinType, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.ExternalLookupTransform +import org.apache.spark.sql.catalyst.plans.physical.Partitioning +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan} +import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode} +import org.apache.spark.sql.execution.datasources.v2.SupportsCustomDriverMetrics +import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.util.Utils + +/** + * Executes synchronous, parameterized external lookup joins without a shuffle. Each task joins + * its input rows in batches, through an [[ExternalLookupJoinEvaluatorFactory]]. + */ +case class ExternalLookupJoinExec( + tableName: String, + lookupParameters: Seq[Expression], + lookupInput: Seq[Attribute], + lookupOutput: Seq[Attribute], + lookupTransforms: Seq[ExternalLookupTransform], + nullSafeParameters: Seq[Boolean], + lookupKeys: Seq[Attribute], + lookupKeyPredicates: Seq[String], + joinType: JoinType, + residualCondition: Option[Expression], + @transient scan: Scan, + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + child: SparkPlan) extends UnaryExecNode with SupportsCustomDriverMetrics with PredicateHelper { + + // The connector's value rows follow the read schema, which `lookupInput` describes, and the + // lookup-side stages turn them into rows of `transformedLookup`. The lookup columns keep their + // analyzed order, and take the types and nullability of those rows. In `lookupInput`, the + // nullability at every nested level combines the table's and the read schema's: a field is NOT + // NULL when either says so. + private lazy val transformedLookup = lookupTransforms.lastOption.map(_.output) + .getOrElse(lookupInput) + private lazy val inputByLookupOutput = + AttributeMap(transformedLookup.map(attr => attr -> attr)) + private lazy val lookupColumns = lookupOutput.map(inputByLookupOutput) + + override def output: Seq[Attribute] = joinType match { + case LeftOuter => child.output ++ lookupColumns.map(_.withNullability(true)) + case LeftSemi | LeftAnti => child.output + case _ => child.output ++ lookupColumns + } + + // Each task joins its input rows where they are, so the stream side's partitioning holds. + override def outputPartitioning: Partitioning = child.outputPartitioning + + // The conjuncts of the residual condition that read only stream columns, and the rest. A stream + // row that fails the first cannot match, so the join checks them on each stream row before the + // lookup, and does not request the row's key. The join then evaluates them for rows without a + // match too, and before the conjuncts written ahead of them, so only conjuncts that can never + // fail are checked early: those that ExprUtils.canEvaluateUnconditionally accepts, as for the + // streamed side of other joins. `Expression.throwable` is not enough, because most expressions + // that can fail, such as an ANSI cast, do not report it. A conjunct that reads no column stays + // with the rest: the optimizer has already folded it if it could. + private def splitResidualCondition: (Option[Expression], Option[Expression]) = { + val (streamConjuncts, joinedConjuncts) = + residualCondition.toSeq.flatMap(splitConjunctivePredicates).partition { conjunct => + conjunct.references.nonEmpty && conjunct.references.subsetOf(child.outputSet) && + ExprUtils.canEvaluateUnconditionally(conjunct) + } + (streamConjuncts.reduceOption(And), joinedConjuncts.reduceOption(And)) + } + + // Spark does not trust the connector to evaluate the selected lookup predicates as Spark does, + // so it checks them itself on each row that the connector returns. The check reads that row + // after the parameter row of its request, and compares lookup key i with parameter i as its + // selected predicate does. + private def lookupKeyCheck: Option[Expression] = lookupParameters.indices.map { index => + val parameter = lookupParameters(index) + val parameterValue = BoundReference(index, parameter.dataType, parameter.nullable) + val keyOrdinal = lookupInput.indexWhere(_.exprId == lookupKeys(index).exprId) + val key = lookupInput(keyOrdinal) + val keyValue = BoundReference(lookupParameters.length + keyOrdinal, key.dataType, key.nullable) + lookupKeyPredicates(index) match { + case "=" => EqualTo(keyValue, parameterValue) + case "<=>" => EqualNullSafe(keyValue, parameterValue) + case "<" => LessThan(keyValue, parameterValue) 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 [715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf): a source option makes the connector select ranges but return rows outside them. All four operators are tested, in both written orders. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,498 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.datasources.v2 + +import java.util.{Collections, IdentityHashMap} + +import scala.annotation.tailrec +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeMap, + AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, PythonUDF} +import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression +import org.apache.spark.sql.catalyst.planning.ScanOperation +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, ExternalLookupJoin, + ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, Filter, LogicalPlan, + PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, EXTERNAL_LOOKUP_JOIN} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability} +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference} +import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate} +import org.apache.spark.sql.connector.read.{LookupParameter, SupportsExternalLookup, + SupportsPushDownRequiredColumns} +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.execution.datasources.DataSourceStrategy +import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, StructType} + +/** Finalizes an optimized external lookup side immediately before ordinary V2 scan preparation. */ +object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper + with QueryErrorsBase { + override def apply(plan: LogicalPlan): LogicalPlan = { + val prepared = plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) { + case join: ExternalLookupJoin if provablyEmpty(join) => emptyJoinResult(join) + case join: ExternalLookupJoin => prepare(join) + } + // Prepared lookup joins no longer contain their lookup relation, so a lookup-only table that + // is still read here cannot run. + if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) { + prepared.foreach { node => + ExternalLookupRelations.lookupOnlyTable(node).foreach { table => + throw QueryCompilationErrors.unsupportedBatchReadError(table) + } + } + } + prepared + } + + // The optimizer folds `WHERE false` on the lookup side into an empty relation, and a condition + // such as `s.id = r.id AND false` into `false`. Such a join needs no connector call. + private def provablyEmpty(join: ExternalLookupJoin): Boolean = + join.right.maxRows.contains(0L) || (join.condition match { + case Some(Literal(value, BooleanType)) => value == null || value == false + case _ => false + }) + + private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = { + val nullLookupColumns = join.right.output.map { attr => + Alias(Literal(null, attr.dataType), attr.name)(attr.exprId) + } + val unmatched = Project(join.left.output ++ nullLookupColumns, join.left) + join.joinType match { + case LeftOuter => unmatched + case LeftAnti => join.left + // The stream side is kept under a false filter rather than replaced by an empty relation, + // so that its sources, watermarks and stateful operators still run in every micro-batch. + // PruneFilters decides whether a streaming subplan may be pruned. + case LeftSemi => Filter(Literal.FalseLiteral, join.left) + case _ => Filter(Literal.FalseLiteral, unmatched) + } + } + + private def prepare(join: ExternalLookupJoin): LogicalPlan = { + // Analysis already rejects a lookup side with a stage that cannot be evaluated, or with another + // operator; this is a fallback. + val hasUnevaluableStage = join.right.exists { + case node @ (_: Project | _: Filter) => + !node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) + case _ => false + } + // The lookup-side stages are built here, and no later rule reaches them. withField and + // dropFields values cannot be evaluated until ReplaceUpdateFieldsExpression, in the + // optimizer's last batch, lowers them, so the same rule lowers them now. + val lookupPlan = (if (hasUnevaluableStage) None else { + extractLookupPlan(ReplaceUpdateFieldsExpression(join.right)) + }).getOrElse { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN") + } + val relation = lookupPlan.relation + val tableName = relation.table.name() + val supportsRead = relation.table match { + case table: SupportsRead + if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => table + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> toSQLId(tableName))) + } + val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates) + // A Python or external UDF over lookup columns cannot run in the residual. The rules that move + // one out of a join condition match only Join and run later, so this rule does it: an inner + // join evaluates the conjunct in a filter above the join, and other join types are rejected. + if (join.joinType != Inner) { + conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach { + case _: ExternalUserDefinedFunction => + throw QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType) + case _ => + throw QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType) + } + } + val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, index) => + ExternalLookupJoinShapes.lookupComparison( + conjunct, join.left.outputSet, join.right.outputSet).flatMap { comparison => + tableColumn(comparison.lookupField, lookupPlan).map { column => + OfferedLookupPredicate( + comparison.parameter, column, index, comparison.predicateName, comparison.nullSafe) + } + } + } + if (offeredCandidates.isEmpty) { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName))) + } + + val scanBuilder = supportsRead.newScanBuilder(relation.options) + val lookupBuilder = scanBuilder match { + case builder: SupportsExternalLookup => builder + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "SCAN_BUILDER", Map("table" -> toSQLId(tableName))) + } + // A column is offered under the table's name for it. Under case-insensitive analysis, the + // condition may spell it in another case, as `ID` for `id`, with the same exprId; filter + // pushdown renames it the same way, with DataSourceStrategy.normalizeExprs. + val columnNames = AttributeMap(relation.output.map(attr => attr -> attr.name)) + // Filters are pushed before the lookup predicates are selected, as + // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the columns of a scan. + // Unlike a batch scan, Spark evaluates every pushed filter again on the returned rows, not only + // the ones that the source rejects, so a source that accepts a filter but applies it in another + // way, or not at all, cannot change the result. + PushDownUtils.pushFilters( + scanBuilder, + DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, relation.output), + partitionFields = None) + val offeredPredicates = offeredCandidates.map { candidate => + new V2Predicate(candidate.predicateName, Array[V2Expression]( + FieldReference.column(columnNames(candidate.projectedField)), + new LookupParameter(candidate.parameter.dataType))) + }.toArray + // A copy, so a connector that reorders the array in place cannot break the identity mapping. + val selectedPredicates = selectedCandidates(tableName, offeredPredicates, offeredCandidates, + lookupBuilder.selectLookupPredicates(offeredPredicates.clone())) + val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet + // As a hash join matches its keys before it evaluates its other conditions, the residual + // evaluates the equalities between the two sides first, together with the conjuncts that + // cannot fail. A conjunct that can fail then runs only for rows that pass them. Each group + // keeps the written order. + val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect { + case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct + }.partition(lookupSideUDF(join, _).isEmpty) + val (residualFirst, residualRest) = residualConjuncts.partition { conjunct => + isJoinKeyEquality(join, conjunct) || ExprUtils.canEvaluateUnconditionally(conjunct) + } + // A conjunction evaluates its next conjunct after a NULL, so a NULL in the first group reads + // as false: a hash join never matches a NULL key either. A row matches only when the whole + // condition is true, so this changes no result. + val residual = if (residualRest.isEmpty) residualFirst else { + residualFirst.map { conjunct => + if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) else conjunct + } ++ residualRest + } + + // The prepared join replaces the analyzed one, so it keeps the analyzed lookup attributes in + // their analyzed order; execution projects the lookup results into them. It keeps only those + // required above the join: the ones that a parent projection reads, to which ColumnPruning has + // narrowed `requiredLookupOutput` during operator optimization, and the ones that `joinFilter` + // reads. `joinFilter` holds the conjuncts with a Python or external UDF over lookup columns, + // which an inner join evaluates in a filter above it; other join types reject them above. + val requiredAbove = join.joinType match { + case LeftSemi | LeftAnti => AttributeSet.empty + case _ => AttributeSet(join.requiredLookupOutput ++ joinFilter.flatMap(_.references)) + } + val lookupOutput = join.right.output.filter(requiredAbove.contains) + val residualLookupReferences = + residual.flatMap(_.references).filter(join.right.outputSet.contains) + // The columns are pruned only now, once the lookup predicates are selected. A column that a + // selected lookup predicate reads is kept, because Spark checks the predicate itself on every + // row that the connector returns. V2ScanRelationPushDown.pruneColumns prunes a scan the same + // way, through PushDownUtils.pruneColumns, which this rule cannot call: it can pass + // nested-pruned columns, while a lookup scan receives only whole top-level columns, and it + // binds the read schema by the resolver, while a lookup scan binds it by exact name. + val (prunedUpperStages, requiredBySegment) = + pruneLookupTransforms(lookupOutput ++ residualLookupReferences, lookupPlan.upperStages) + val segmentFields = + lookupPlan.fields.filter(field => requiredBySegment.contains(field.toAttribute)) + val segmentFilter = + (lookupPlan.filtersPushDown ++ lookupPlan.filtersStayUp).reduceOption(And) + val requiredColumns = relation.output.filter( + (AttributeSet(segmentFields.flatMap(_.references)) ++ + segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++ + AttributeSet(selectedPredicates.map(_.projectedField))).contains) + // As V2ScanRelationPushDown does above a scan: the filters, then a projection when it computes + // more than the columns it selects. Execution reads a selected column by its id. + val segmentStages = segmentFilter.map(ExternalLookupFilter(_, relation.output)).toSeq ++ + Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) { + ExternalLookupProject(segmentFields, relation.output) + } + scanBuilder match { + case builder: SupportsPushDownRequiredColumns => + builder.pruneColumns(requiredColumns.toStructType) + case _ => + } + + def nonNull[T](value: T, method: String): T = Option(value).getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> method)) + } + val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()") + // Fields bind to table columns by exact name, as in `PushDownUtils.toOutputAttrs`. CHAR and + // VARCHAR are read as STRING, and nullability, including nested nullability, does not count + // for the match. The value-row attributes take the read schema's type, where a column, nested + // field, array element or map value is nullable only when both the table and the read schema + // allow nulls: the join fails the task on a null that either rules out, because Spark relied + // on the table's nullability while it optimized the query. + val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema( + nonNull(scan.readSchema(), "Scan.readSchema()")) + val columnsByName = relation.output.groupBy(_.name) + val lookupInput = readSchema.fields.map { field => + columnsByName.getOrElse(field.name, Nil).find { attr => + DataType.equalsIgnoreNullability(attr.dataType, field.dataType) + }.map { attr => + attr.withDataType(withStricterNullability(attr.dataType, field.dataType)) + .withNullability(attr.nullable && field.nullable) + }.getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> toSQLId(Seq(field.name)))) + } + }.toSeq + lookupInput.groupBy(_.name).collectFirst { + case (name, fields) if fields.size > 1 => name + }.foreach { name => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name)))) + } + val readExprIds = lookupInput.map(_.exprId).toSet + requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { attr => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "MISSING_SCAN_FIELD", Map("field" -> toSQLId(Seq(attr.name)))) + } + val externalLookup = nonNull(scan.toExternalLookup(), "Scan.toExternalLookup()") + val maxParameterRowsPerRequest = externalLookup.maxParameterRowsPerRequest() + if (maxParameterRowsPerRequest <= 0) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, + "NON_POSITIVE_MAX_PARAMETER_ROWS", + Map("value" -> maxParameterRowsPerRequest.toString)) + } + val readerFactory = + nonNull(externalLookup.createReaderFactory(), "ExternalLookup.createReaderFactory()") + // With a range selected, one stored row can match several parameter rows of one request, and + // the source would have to return it once for each of them, with each ordinal. Spark cannot + // detect a missing one, so it sends one parameter row per request then. + val selectsRange = selectedPredicates.exists { predicate => + Set("<", "<=", ">", ">=").contains(predicate.predicateName) + } + val parameterRowsPerRequest = if (selectsRange) 1 else maxParameterRowsPerRequest + + val prepared = PreparedExternalLookupJoin( + join.left, + tableName, + scan, + readerFactory, + parameterRowsPerRequest, + lookupInput, + lookupOutput, + rebindLookupTransforms(segmentStages ++ prunedUpperStages, lookupInput), + selectedPredicates.map(_.parameter), + selectedPredicates.map(_.nullSafe), + selectedPredicates.map(_.projectedField), + selectedPredicates.map(_.predicateName), + join.joinType, + residual.reduceOption(And)) + joinFilter.reduceOption(And).map(Filter(_, prepared)).getOrElse(prepared) + } + + /** + * The read schema's type of a column, where a nested field, array element or map value is + * nullable only when the table's type allows nulls there too. The two types differ only in + * nullability. + */ + private def withStricterNullability(tableType: DataType, readType: DataType): DataType = + (tableType, readType) match { + case (table: StructType, read: StructType) => + StructType(table.fields.zip(read.fields).map { case (tableField, readField) => + readField.copy( + dataType = withStricterNullability(tableField.dataType, readField.dataType), + nullable = tableField.nullable && readField.nullable) + }) + case (table: ArrayType, read: ArrayType) => + ArrayType( + withStricterNullability(table.elementType, read.elementType), + table.containsNull && read.containsNull) + case (table: MapType, read: MapType) => + MapType( + withStricterNullability(table.keyType, read.keyType), + withStricterNullability(table.valueType, read.valueType), + table.valueContainsNull && read.valueContainsNull) + case _ => readType + } + + /** A Python or external UDF in the conjunct that reads lookup columns. */ + private def lookupSideUDF(join: ExternalLookupJoin, conjunct: Expression): Option[Expression] = + conjunct.find { e => + (PythonUDF.isScalarPythonUDF(e) || e.isInstanceOf[ExternalUserDefinedFunction]) && + !e.references.subsetOf(join.left.outputSet) + } + + /** + * An equality between an expression over the stream side and one over the lookup side, each + * reading a column, which a hash join would use as a join key. + */ + private def isJoinKeyEquality(join: ExternalLookupJoin, conjunct: Expression): Boolean = { + def readsOnly(expression: Expression, plan: LogicalPlan): Boolean = + expression.references.nonEmpty && expression.references.subsetOf(plan.outputSet) + def betweenSides(first: Expression, second: Expression): Boolean = + (readsOnly(first, join.left) && readsOnly(second, join.right)) || + (readsOnly(first, join.right) && readsOnly(second, join.left)) + conjunct match { + case EqualTo(first, second) => betweenSides(first, second) + case EqualNullSafe(first, second) => betweenSides(first, second) + case _ => false + } + } + + /** + * Maps the connector's selection back to the offered candidates, in the connector's order, which + * defines the fields of each request parameter row. Selections are matched by object identity + * rather than by equality, so two candidates of the same shape, for example the same lookup field + * compared with two different join-side values, remain distinguishable. + */ + private def selectedCandidates( + tableName: String, + offered: Array[V2Predicate], + candidates: Seq[OfferedLookupPredicate], + selected: Array[V2Predicate]): Seq[OfferedLookupPredicate] = { + if (selected == null) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError(tableName, "NULL_RESULT", + Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")) + } + if (selected.isEmpty) { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "NO_LOOKUP_PREDICATE", Map("table" -> toSQLId(tableName))) + } + val candidateByPredicate = new IdentityHashMap[V2Predicate, OfferedLookupPredicate]() + offered.zip(candidates).foreach { case (predicate, candidate) => + candidateByPredicate.put(predicate, candidate) + } + val seen = Collections.newSetFromMap(new IdentityHashMap[V2Predicate, java.lang.Boolean]()) + selected.toSeq.map { predicate => + // A null element is not an offered instance either. + val candidate = Option(predicate).map(candidateByPredicate.get).orNull + if (candidate == null) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "UNOFFERED_SELECTED_PREDICATE", + Map("predicate" -> Option(predicate).map(_.describe()).getOrElse("null"))) + } + if (!seen.add(predicate)) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "DUPLICATE_SELECTED_PREDICATE", Map("predicate" -> predicate.describe())) + } + candidate + } + } + + private case class OfferedLookupPredicate( + parameter: Expression, + projectedField: Attribute, + conjunctIndex: Int, + predicateName: String, + nullSafe: Boolean) + + /** + * A lookup side, split the way V2ScanRelationPushDown.pruneColumns splits a scan. The segment + * over the relation is what ScanOperation collapses into one projection and its filters, with + * aliases substituted. The stages above it are the projections and filters that ScanOperation + * cannot collapse, such as a projection whose costly expression a stage above reads more than + * once, in evaluation order. + */ + private case class LookupPlan( + relation: DataSourceV2Relation, + fields: Seq[NamedExpression], + filtersStayUp: Seq[Expression], + filtersPushDown: Seq[Expression], + upperStages: Seq[ExternalLookupTransform]) + + /** The lookup side below its topmost operator at which ScanOperation reaches the relation. */ + @tailrec + private def extractLookupPlan( + plan: LogicalPlan, + upperStages: List[ExternalLookupTransform] = Nil): Option[LookupPlan] = plan match { + case ScanOperation(fields, filtersStayUp, filtersPushDown, LookupRelation(relation)) => + Some(LookupPlan(relation, fields, filtersStayUp, filtersPushDown, upperStages)) + // The walk goes down from the join, so each stage is evaluated before those found earlier. + case Project(projectList, child) => + extractLookupPlan(child, ExternalLookupProject(projectList, child.output) :: upperStages) 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 [715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf), with your example: the stages don't collapse, the key resolves through the alias, and columns are pruned across the stages down to the read schema. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,498 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.datasources.v2 + +import java.util.{Collections, IdentityHashMap} + +import scala.annotation.tailrec +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeMap, + AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, PythonUDF} +import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression +import org.apache.spark.sql.catalyst.planning.ScanOperation +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, ExternalLookupJoin, + ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, Filter, LogicalPlan, + PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, EXTERNAL_LOOKUP_JOIN} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability} +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference} +import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate} +import org.apache.spark.sql.connector.read.{LookupParameter, SupportsExternalLookup, + SupportsPushDownRequiredColumns} +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.execution.datasources.DataSourceStrategy +import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, StructType} + +/** Finalizes an optimized external lookup side immediately before ordinary V2 scan preparation. */ +object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper + with QueryErrorsBase { + override def apply(plan: LogicalPlan): LogicalPlan = { + val prepared = plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) { + case join: ExternalLookupJoin if provablyEmpty(join) => emptyJoinResult(join) + case join: ExternalLookupJoin => prepare(join) + } + // Prepared lookup joins no longer contain their lookup relation, so a lookup-only table that + // is still read here cannot run. + if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) { + prepared.foreach { node => + ExternalLookupRelations.lookupOnlyTable(node).foreach { table => + throw QueryCompilationErrors.unsupportedBatchReadError(table) + } + } + } + prepared + } + + // The optimizer folds `WHERE false` on the lookup side into an empty relation, and a condition + // such as `s.id = r.id AND false` into `false`. Such a join needs no connector call. + private def provablyEmpty(join: ExternalLookupJoin): Boolean = + join.right.maxRows.contains(0L) || (join.condition match { + case Some(Literal(value, BooleanType)) => value == null || value == false + case _ => false + }) + + private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = { + val nullLookupColumns = join.right.output.map { attr => + Alias(Literal(null, attr.dataType), attr.name)(attr.exprId) + } + val unmatched = Project(join.left.output ++ nullLookupColumns, join.left) + join.joinType match { + case LeftOuter => unmatched + case LeftAnti => join.left + // The stream side is kept under a false filter rather than replaced by an empty relation, + // so that its sources, watermarks and stateful operators still run in every micro-batch. + // PruneFilters decides whether a streaming subplan may be pruned. + case LeftSemi => Filter(Literal.FalseLiteral, join.left) + case _ => Filter(Literal.FalseLiteral, unmatched) + } + } + + private def prepare(join: ExternalLookupJoin): LogicalPlan = { + // Analysis already rejects a lookup side with a stage that cannot be evaluated, or with another + // operator; this is a fallback. + val hasUnevaluableStage = join.right.exists { + case node @ (_: Project | _: Filter) => + !node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) + case _ => false + } + // The lookup-side stages are built here, and no later rule reaches them. withField and + // dropFields values cannot be evaluated until ReplaceUpdateFieldsExpression, in the + // optimizer's last batch, lowers them, so the same rule lowers them now. + val lookupPlan = (if (hasUnevaluableStage) None else { + extractLookupPlan(ReplaceUpdateFieldsExpression(join.right)) + }).getOrElse { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN") + } + val relation = lookupPlan.relation + val tableName = relation.table.name() + val supportsRead = relation.table match { + case table: SupportsRead + if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => table + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> toSQLId(tableName))) + } + val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates) + // A Python or external UDF over lookup columns cannot run in the residual. The rules that move + // one out of a join condition match only Join and run later, so this rule does it: an inner + // join evaluates the conjunct in a filter above the join, and other join types are rejected. + if (join.joinType != Inner) { + conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach { + case _: ExternalUserDefinedFunction => + throw QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType) + case _ => + throw QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType) + } + } + val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, index) => + ExternalLookupJoinShapes.lookupComparison( + conjunct, join.left.outputSet, join.right.outputSet).flatMap { comparison => + tableColumn(comparison.lookupField, lookupPlan).map { column => + OfferedLookupPredicate( + comparison.parameter, column, index, comparison.predicateName, comparison.nullSafe) + } + } + } + if (offeredCandidates.isEmpty) { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName))) + } + + val scanBuilder = supportsRead.newScanBuilder(relation.options) + val lookupBuilder = scanBuilder match { + case builder: SupportsExternalLookup => builder + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "SCAN_BUILDER", Map("table" -> toSQLId(tableName))) + } + // A column is offered under the table's name for it. Under case-insensitive analysis, the + // condition may spell it in another case, as `ID` for `id`, with the same exprId; filter + // pushdown renames it the same way, with DataSourceStrategy.normalizeExprs. + val columnNames = AttributeMap(relation.output.map(attr => attr -> attr.name)) + // Filters are pushed before the lookup predicates are selected, as + // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the columns of a scan. + // Unlike a batch scan, Spark evaluates every pushed filter again on the returned rows, not only + // the ones that the source rejects, so a source that accepts a filter but applies it in another + // way, or not at all, cannot change the result. + PushDownUtils.pushFilters( + scanBuilder, + DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, relation.output), + partitionFields = None) + val offeredPredicates = offeredCandidates.map { candidate => + new V2Predicate(candidate.predicateName, Array[V2Expression]( + FieldReference.column(columnNames(candidate.projectedField)), + new LookupParameter(candidate.parameter.dataType))) + }.toArray + // A copy, so a connector that reorders the array in place cannot break the identity mapping. + val selectedPredicates = selectedCandidates(tableName, offeredPredicates, offeredCandidates, + lookupBuilder.selectLookupPredicates(offeredPredicates.clone())) + val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet + // As a hash join matches its keys before it evaluates its other conditions, the residual + // evaluates the equalities between the two sides first, together with the conjuncts that + // cannot fail. A conjunct that can fail then runs only for rows that pass them. Each group + // keeps the written order. + val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect { + case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct + }.partition(lookupSideUDF(join, _).isEmpty) + val (residualFirst, residualRest) = residualConjuncts.partition { conjunct => + isJoinKeyEquality(join, conjunct) || ExprUtils.canEvaluateUnconditionally(conjunct) + } + // A conjunction evaluates its next conjunct after a NULL, so a NULL in the first group reads + // as false: a hash join never matches a NULL key either. A row matches only when the whole + // condition is true, so this changes no result. + val residual = if (residualRest.isEmpty) residualFirst else { + residualFirst.map { conjunct => + if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) else conjunct + } ++ residualRest + } + + // The prepared join replaces the analyzed one, so it keeps the analyzed lookup attributes in + // their analyzed order; execution projects the lookup results into them. It keeps only those + // required above the join: the ones that a parent projection reads, to which ColumnPruning has + // narrowed `requiredLookupOutput` during operator optimization, and the ones that `joinFilter` + // reads. `joinFilter` holds the conjuncts with a Python or external UDF over lookup columns, + // which an inner join evaluates in a filter above it; other join types reject them above. + val requiredAbove = join.joinType match { + case LeftSemi | LeftAnti => AttributeSet.empty + case _ => AttributeSet(join.requiredLookupOutput ++ joinFilter.flatMap(_.references)) + } + val lookupOutput = join.right.output.filter(requiredAbove.contains) + val residualLookupReferences = + residual.flatMap(_.references).filter(join.right.outputSet.contains) + // The columns are pruned only now, once the lookup predicates are selected. A column that a + // selected lookup predicate reads is kept, because Spark checks the predicate itself on every + // row that the connector returns. V2ScanRelationPushDown.pruneColumns prunes a scan the same + // way, through PushDownUtils.pruneColumns, which this rule cannot call: it can pass + // nested-pruned columns, while a lookup scan receives only whole top-level columns, and it + // binds the read schema by the resolver, while a lookup scan binds it by exact name. + val (prunedUpperStages, requiredBySegment) = + pruneLookupTransforms(lookupOutput ++ residualLookupReferences, lookupPlan.upperStages) + val segmentFields = + lookupPlan.fields.filter(field => requiredBySegment.contains(field.toAttribute)) + val segmentFilter = + (lookupPlan.filtersPushDown ++ lookupPlan.filtersStayUp).reduceOption(And) + val requiredColumns = relation.output.filter( + (AttributeSet(segmentFields.flatMap(_.references)) ++ + segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++ + AttributeSet(selectedPredicates.map(_.projectedField))).contains) + // As V2ScanRelationPushDown does above a scan: the filters, then a projection when it computes + // more than the columns it selects. Execution reads a selected column by its id. + val segmentStages = segmentFilter.map(ExternalLookupFilter(_, relation.output)).toSeq ++ + Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) { + ExternalLookupProject(segmentFields, relation.output) + } + scanBuilder match { + case builder: SupportsPushDownRequiredColumns => + builder.pruneColumns(requiredColumns.toStructType) + case _ => + } + + def nonNull[T](value: T, method: String): T = Option(value).getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> method)) + } + val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()") + // Fields bind to table columns by exact name, as in `PushDownUtils.toOutputAttrs`. CHAR and + // VARCHAR are read as STRING, and nullability, including nested nullability, does not count + // for the match. The value-row attributes take the read schema's type, where a column, nested + // field, array element or map value is nullable only when both the table and the read schema + // allow nulls: the join fails the task on a null that either rules out, because Spark relied + // on the table's nullability while it optimized the query. + val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema( + nonNull(scan.readSchema(), "Scan.readSchema()")) + val columnsByName = relation.output.groupBy(_.name) + val lookupInput = readSchema.fields.map { field => + columnsByName.getOrElse(field.name, Nil).find { attr => + DataType.equalsIgnoreNullability(attr.dataType, field.dataType) + }.map { attr => + attr.withDataType(withStricterNullability(attr.dataType, field.dataType)) + .withNullability(attr.nullable && field.nullable) + }.getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> toSQLId(Seq(field.name)))) + } + }.toSeq + lookupInput.groupBy(_.name).collectFirst { + case (name, fields) if fields.size > 1 => name + }.foreach { name => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name)))) + } + val readExprIds = lookupInput.map(_.exprId).toSet + requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { attr => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "MISSING_SCAN_FIELD", Map("field" -> toSQLId(Seq(attr.name)))) + } + val externalLookup = nonNull(scan.toExternalLookup(), "Scan.toExternalLookup()") + val maxParameterRowsPerRequest = externalLookup.maxParameterRowsPerRequest() + if (maxParameterRowsPerRequest <= 0) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, + "NON_POSITIVE_MAX_PARAMETER_ROWS", + Map("value" -> maxParameterRowsPerRequest.toString)) + } + val readerFactory = + nonNull(externalLookup.createReaderFactory(), "ExternalLookup.createReaderFactory()") + // With a range selected, one stored row can match several parameter rows of one request, and + // the source would have to return it once for each of them, with each ordinal. Spark cannot + // detect a missing one, so it sends one parameter row per request then. + val selectsRange = selectedPredicates.exists { predicate => 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. Right. Fixed in [715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf): only a range whose parameter reads a stream column forces one parameter row per request. One helper decides this for planning and for the physical join, and #60087 uses the same rule for the cache. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,498 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.datasources.v2 + +import java.util.{Collections, IdentityHashMap} + +import scala.annotation.tailrec +import scala.collection.mutable + +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeMap, + AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils, + ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, PythonUDF} +import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression +import org.apache.spark.sql.catalyst.planning.ScanOperation +import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, LeftSemi} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, ExternalLookupJoin, + ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, Filter, LogicalPlan, + PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, EXTERNAL_LOOKUP_JOIN} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability} +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference} +import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate} +import org.apache.spark.sql.connector.read.{LookupParameter, SupportsExternalLookup, + SupportsPushDownRequiredColumns} +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.execution.datasources.DataSourceStrategy +import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, StructType} + +/** Finalizes an optimized external lookup side immediately before ordinary V2 scan preparation. */ +object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper + with QueryErrorsBase { + override def apply(plan: LogicalPlan): LogicalPlan = { + val prepared = plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) { + case join: ExternalLookupJoin if provablyEmpty(join) => emptyJoinResult(join) + case join: ExternalLookupJoin => prepare(join) + } + // Prepared lookup joins no longer contain their lookup relation, so a lookup-only table that + // is still read here cannot run. + if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) { + prepared.foreach { node => + ExternalLookupRelations.lookupOnlyTable(node).foreach { table => + throw QueryCompilationErrors.unsupportedBatchReadError(table) + } + } + } + prepared + } + + // The optimizer folds `WHERE false` on the lookup side into an empty relation, and a condition + // such as `s.id = r.id AND false` into `false`. Such a join needs no connector call. + private def provablyEmpty(join: ExternalLookupJoin): Boolean = + join.right.maxRows.contains(0L) || (join.condition match { + case Some(Literal(value, BooleanType)) => value == null || value == false + case _ => false + }) + + private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = { + val nullLookupColumns = join.right.output.map { attr => + Alias(Literal(null, attr.dataType), attr.name)(attr.exprId) + } + val unmatched = Project(join.left.output ++ nullLookupColumns, join.left) + join.joinType match { + case LeftOuter => unmatched + case LeftAnti => join.left + // The stream side is kept under a false filter rather than replaced by an empty relation, + // so that its sources, watermarks and stateful operators still run in every micro-batch. + // PruneFilters decides whether a streaming subplan may be pruned. + case LeftSemi => Filter(Literal.FalseLiteral, join.left) + case _ => Filter(Literal.FalseLiteral, unmatched) + } + } + + private def prepare(join: ExternalLookupJoin): LogicalPlan = { + // Analysis already rejects a lookup side with a stage that cannot be evaluated, or with another + // operator; this is a fallback. + val hasUnevaluableStage = join.right.exists { + case node @ (_: Project | _: Filter) => + !node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) + case _ => false + } + // The lookup-side stages are built here, and no later rule reaches them. withField and + // dropFields values cannot be evaluated until ReplaceUpdateFieldsExpression, in the + // optimizer's last batch, lowers them, so the same rule lowers them now. + val lookupPlan = (if (hasUnevaluableStage) None else { + extractLookupPlan(ReplaceUpdateFieldsExpression(join.right)) + }).getOrElse { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN") + } + val relation = lookupPlan.relation + val tableName = relation.table.name() + val supportsRead = relation.table match { + case table: SupportsRead + if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => table + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> toSQLId(tableName))) + } + val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates) + // A Python or external UDF over lookup columns cannot run in the residual. The rules that move + // one out of a join condition match only Join and run later, so this rule does it: an inner + // join evaluates the conjunct in a filter above the join, and other join types are rejected. + if (join.joinType != Inner) { + conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach { + case _: ExternalUserDefinedFunction => + throw QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType) + case _ => + throw QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType) + } + } + val offeredCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, index) => + ExternalLookupJoinShapes.lookupComparison( + conjunct, join.left.outputSet, join.right.outputSet).flatMap { comparison => + tableColumn(comparison.lookupField, lookupPlan).map { column => + OfferedLookupPredicate( + comparison.parameter, column, index, comparison.predicateName, comparison.nullSafe) + } + } + } + if (offeredCandidates.isEmpty) { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName))) + } + + val scanBuilder = supportsRead.newScanBuilder(relation.options) + val lookupBuilder = scanBuilder match { + case builder: SupportsExternalLookup => builder + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "SCAN_BUILDER", Map("table" -> toSQLId(tableName))) + } + // A column is offered under the table's name for it. Under case-insensitive analysis, the + // condition may spell it in another case, as `ID` for `id`, with the same exprId; filter + // pushdown renames it the same way, with DataSourceStrategy.normalizeExprs. + val columnNames = AttributeMap(relation.output.map(attr => attr -> attr.name)) + // Filters are pushed before the lookup predicates are selected, as + // V2ScanRelationPushDown.pushDownFilters pushes them before it prunes the columns of a scan. + // Unlike a batch scan, Spark evaluates every pushed filter again on the returned rows, not only + // the ones that the source rejects, so a source that accepts a filter but applies it in another + // way, or not at all, cannot change the result. + PushDownUtils.pushFilters( + scanBuilder, + DataSourceStrategy.normalizeExprs(lookupPlan.filtersPushDown, relation.output), + partitionFields = None) + val offeredPredicates = offeredCandidates.map { candidate => + new V2Predicate(candidate.predicateName, Array[V2Expression]( + FieldReference.column(columnNames(candidate.projectedField)), + new LookupParameter(candidate.parameter.dataType))) + }.toArray + // A copy, so a connector that reorders the array in place cannot break the identity mapping. + val selectedPredicates = selectedCandidates(tableName, offeredPredicates, offeredCandidates, + lookupBuilder.selectLookupPredicates(offeredPredicates.clone())) + val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet + // As a hash join matches its keys before it evaluates its other conditions, the residual + // evaluates the equalities between the two sides first, together with the conjuncts that + // cannot fail. A conjunct that can fail then runs only for rows that pass them. Each group + // keeps the written order. + val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect { + case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct + }.partition(lookupSideUDF(join, _).isEmpty) + val (residualFirst, residualRest) = residualConjuncts.partition { conjunct => + isJoinKeyEquality(join, conjunct) || ExprUtils.canEvaluateUnconditionally(conjunct) + } + // A conjunction evaluates its next conjunct after a NULL, so a NULL in the first group reads + // as false: a hash join never matches a NULL key either. A row matches only when the whole + // condition is true, so this changes no result. + val residual = if (residualRest.isEmpty) residualFirst else { + residualFirst.map { conjunct => + if (conjunct.nullable) Coalesce(Seq(conjunct, Literal.FalseLiteral)) else conjunct + } ++ residualRest + } + + // The prepared join replaces the analyzed one, so it keeps the analyzed lookup attributes in + // their analyzed order; execution projects the lookup results into them. It keeps only those + // required above the join: the ones that a parent projection reads, to which ColumnPruning has + // narrowed `requiredLookupOutput` during operator optimization, and the ones that `joinFilter` + // reads. `joinFilter` holds the conjuncts with a Python or external UDF over lookup columns, + // which an inner join evaluates in a filter above it; other join types reject them above. + val requiredAbove = join.joinType match { + case LeftSemi | LeftAnti => AttributeSet.empty + case _ => AttributeSet(join.requiredLookupOutput ++ joinFilter.flatMap(_.references)) + } + val lookupOutput = join.right.output.filter(requiredAbove.contains) + val residualLookupReferences = + residual.flatMap(_.references).filter(join.right.outputSet.contains) + // The columns are pruned only now, once the lookup predicates are selected. A column that a + // selected lookup predicate reads is kept, because Spark checks the predicate itself on every + // row that the connector returns. V2ScanRelationPushDown.pruneColumns prunes a scan the same + // way, through PushDownUtils.pruneColumns, which this rule cannot call: it can pass + // nested-pruned columns, while a lookup scan receives only whole top-level columns, and it + // binds the read schema by the resolver, while a lookup scan binds it by exact name. + val (prunedUpperStages, requiredBySegment) = + pruneLookupTransforms(lookupOutput ++ residualLookupReferences, lookupPlan.upperStages) + val segmentFields = + lookupPlan.fields.filter(field => requiredBySegment.contains(field.toAttribute)) + val segmentFilter = + (lookupPlan.filtersPushDown ++ lookupPlan.filtersStayUp).reduceOption(And) + val requiredColumns = relation.output.filter( + (AttributeSet(segmentFields.flatMap(_.references)) ++ + segmentFilter.map(_.references).getOrElse(AttributeSet.empty) ++ + AttributeSet(selectedPredicates.map(_.projectedField))).contains) + // As V2ScanRelationPushDown does above a scan: the filters, then a projection when it computes + // more than the columns it selects. Execution reads a selected column by its id. + val segmentStages = segmentFilter.map(ExternalLookupFilter(_, relation.output)).toSeq ++ + Option.when(!segmentFields.forall(_.isInstanceOf[Attribute])) { + ExternalLookupProject(segmentFields, relation.output) + } + scanBuilder match { + case builder: SupportsPushDownRequiredColumns => + builder.pruneColumns(requiredColumns.toStructType) + case _ => + } + + def nonNull[T](value: T, method: String): T = Option(value).getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> method)) + } + val scan = nonNull(scanBuilder.build(), "ScanBuilder.build()") + // Fields bind to table columns by exact name, as in `PushDownUtils.toOutputAttrs`. CHAR and + // VARCHAR are read as STRING, and nullability, including nested nullability, does not count + // for the match. The value-row attributes take the read schema's type, where a column, nested + // field, array element or map value is nullable only when both the table and the read schema + // allow nulls: the join fails the task on a null that either rules out, because Spark relied + // on the table's nullability while it optimized the query. + val readSchema = CharVarcharUtils.replaceCharVarcharWithStringInSchema( + nonNull(scan.readSchema(), "Scan.readSchema()")) + val columnsByName = relation.output.groupBy(_.name) + val lookupInput = readSchema.fields.map { field => + columnsByName.getOrElse(field.name, Nil).find { attr => + DataType.equalsIgnoreNullability(attr.dataType, field.dataType) + }.map { attr => + attr.withDataType(withStricterNullability(attr.dataType, field.dataType)) + .withNullability(attr.nullable && field.nullable) + }.getOrElse { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "UNKNOWN_SCAN_FIELD", Map("field" -> toSQLId(Seq(field.name)))) + } + }.toSeq + lookupInput.groupBy(_.name).collectFirst { + case (name, fields) if fields.size > 1 => name + }.foreach { name => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "DUPLICATE_SCAN_FIELD", Map("field" -> toSQLId(Seq(name)))) + } + val readExprIds = lookupInput.map(_.exprId).toSet + requiredColumns.find(attr => !readExprIds.contains(attr.exprId)).foreach { attr => + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, "MISSING_SCAN_FIELD", Map("field" -> toSQLId(Seq(attr.name)))) + } + val externalLookup = nonNull(scan.toExternalLookup(), "Scan.toExternalLookup()") + val maxParameterRowsPerRequest = externalLookup.maxParameterRowsPerRequest() + if (maxParameterRowsPerRequest <= 0) { + throw QueryCompilationErrors.invalidDataSourceExternalLookupError( + tableName, + "NON_POSITIVE_MAX_PARAMETER_ROWS", + Map("value" -> maxParameterRowsPerRequest.toString)) + } + val readerFactory = + nonNull(externalLookup.createReaderFactory(), "ExternalLookup.createReaderFactory()") + // With a range selected, one stored row can match several parameter rows of one request, and + // the source would have to return it once for each of them, with each ordinal. Spark cannot + // detect a missing one, so it sends one parameter row per request then. + val selectsRange = selectedPredicates.exists { predicate => + Set("<", "<=", ">", ">=").contains(predicate.predicateName) + } + val parameterRowsPerRequest = if (selectsRange) 1 else maxParameterRowsPerRequest 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 [715364e7feb](https://github.com/apache/spark/commit/715364e7feb368a24073954e6c43a9ce3a8e9ecf): when a range forces one parameter row per request, a batch takes all the stream rows of one key, and ends at the second distinct key. So three identical rows now send one request. The connector contract is unchanged. -- 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]
