spark-test commented on code in PR #59909: URL: https://github.com/apache/spark/pull/59909#discussion_r4520014564
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala: ########## @@ -0,0 +1,132 @@ +/* + * 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, Expression} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter} +import org.apache.spark.sql.catalyst.trees.TreePattern.{EXTERNAL_LOOKUP_JOIN, TreePattern} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, CharType, DataType, + DateType, DecimalType, IntegerType, LongType, ShortType, StringType, TimestampNTZType, + TimestampType, VarcharType} + +/** + * A lookup join retained through ordinary expression and operator optimization. + * + * @param requiredLookupOutput Every output attribute of the lookup side. They are all part of this + * node's references, so column pruning never puts a projection over the lookup relation, which + * preparation needs directly under the join. A narrower list would let it do so. + */ +case class ExternalLookupJoin( + left: LogicalPlan, + right: LogicalPlan, + joinType: JoinType, + condition: Option[Expression], + requiredLookupOutput: Seq[Attribute]) extends BinaryNode { + + final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN) + + override def output: Seq[Attribute] = joinType match { + case Inner => left.output ++ right.output + case LeftOuter => left.output ++ right.output.map(_.withNullability(true)) + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + override protected def withNewChildrenInternal( + newLeft: LogicalPlan, + newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right = newRight) +} + +/** A lookup join after its optimized lookup side has been converted to an external operation. */ +case class PreparedExternalLookupJoin( + child: LogicalPlan, + @transient scan: Scan, + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + lookupInput: Seq[Attribute], + lookupOutput: Seq[Attribute], + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + joinType: JoinType, + residualCondition: Option[Expression]) extends UnaryNode { + + override def output: Seq[Attribute] = joinType match { + case Inner => child.output ++ lookupOutput + case LeftOuter => child.output ++ lookupOutput.map(_.withNullability(true)) + case other => throw SparkException.internalError(s"Unexpected external lookup join type $other") + } + + override def references: AttributeSet = + AttributeSet(lookupParameters.flatMap(_.references)) ++ + residualCondition.map(_.references.intersect(child.outputSet)) + .getOrElse(AttributeSet.empty) + + override protected def withNewChildInternal(newChild: LogicalPlan): PreparedExternalLookupJoin = + copy(child = newChild) + + // Connector descriptions may contain secrets, so the scan and the reader factory are not shown. + // The physical node renders a redacted description of them. + override protected def stringArgs: Iterator[Any] = + Iterator(joinType, lookupParameters, residualCondition, child) + + // The join keeps the size estimate it had before preparation, as an ordinary join's: the product + // of the stream side's size and the lookup side's, Spark's default size for a table it cannot + // scan. The stream side's size alone would ignore the lookup columns and the rows that a stream + // row can match. + override def stats: Statistics = statsCache.getOrElse { + statsCache = Some(Statistics(sizeInBytes = + Seq(child.stats.sizeInBytes, BigInt(conf.defaultSizeInBytes)).filter(_ > 0L).product)) + statsCache.get + } +} + +/** + * The types of lookup columns on which Spark offers a comparison to the connector as a lookup + * candidate. The connector evaluates a selected candidate in its store, so Spark offers only types + * whose values a store compares as Spark does. A comparison on any other type stays in Spark's + * residual condition. + */ +object ExternalLookupKeyTypes { + /** + * Whether Spark offers `=` on the lookup column `column`, by its declared type: integral types, + * BOOLEAN, DECIMAL, DATE, TIMESTAMP, TIMESTAMP_NTZ, BINARY, and STRING and VARCHAR whose + * collation compares bytes, such as UTF8_BINARY. FLOAT and DOUBLE are not offered, because + * stores treat NaN and -0.0 in different ways, nor CHAR, which Spark pads on read, nor strings + * with another collation, nor complex types, nor any other type. VARCHAR is not offered under + * `spark.sql.charVarchar.standardSemantics.enabled` either, because Spark then trims trailing Review Comment: **Nit (P3):** Under `spark.sql.charVarchar.standardSemantics.enabled`, Spark does not trim every trailing blank of a VARCHAR value on read. `CharVarcharUtils.addPaddingForScan` applies `varcharTypeReadSideCheck`, which delegates to `varcharTypeWriteSideCheck`: a value within the declared length comes back unchanged, and a longer value loses only the trailing blanks past the length, then fails if it is still too long. Reading that code, `'ab '` in a `VARCHAR(5)` column reads back as `'ab '`, and only an over-length stored value changes, such as `'ab'` followed by three blanks in a `VARCHAR(3)` column, which reads as `'ab '`. The exclusion itself is right, because a store that compares such a stored value as written could miss a row that Spark's equality matches. The reason as written suggests a much broader mismatch, though, which matters when #60055 extends the same rule to `<=>`. The comment above the standard-semantics case in `PrepareExternalLookupJoinSuite` repeats it. A wording that matches the check: under standard semantics, Spark trims the trailing blanks past the declared length from a longer value on read, and fails if the value is still too long, so a store that compares such a stored value could miss a row. This extends an [existing discussion](https://github.com/apache/spark/pull/59909#discussion_r4510643001). **Verification:** - **Inspection:** In both the key-type rule's documentation and the test comment, the stated reason for not offering VARCHAR under standard CHAR/VARCHAR semantics matches the read-side check: a value within its declared length reads unchanged, and only a longer value loses the trailing blanks past the length, or fails to read if it is still too long. - **Compatibility:** The key-type rule still offers no equality on VARCHAR under standard semantics and still offers it on a byte-comparing VARCHAR otherwise, so the existing key-type expectations hold unchanged. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala: ########## @@ -0,0 +1,489 @@ +/* + * 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.SparkThrowable +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, + BindReferences, Coalesce, Expression, Literal, Predicate => CatalystPredicate} +import org.apache.spark.sql.catalyst.optimizer.ColumnPruning +import org.apache.spark.sql.catalyst.plans.{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) } + + // A conjunct of the residual's first group, read as false when it is NULL. + private def orFalse(conjunct: Expression): Expression = + Coalesce(Seq(conjunct, Literal.FalseLiteral)) + + /** + * Whether Spark offers `code = ?` on a lookup column `code` of the given type. The connector + * selects only `id = ?`, so Spark evaluates the code equality either way. + */ + private def offeredCodeCandidate(codeType: String): Boolean = { + 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))) + assert(prepared.residualCondition === Some(codesEqual), codeType) + offeredCandidates match { + case Seq("id = ?") => false + case Seq("id = ?", "code = ?") => true + case other => fail(s"Unexpected candidates for $codeType: $other") + } + } + + 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", + "VARCHAR(3)") + val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", Review Comment: **Nit (P3):** The VARCHAR branch of `ExternalLookupKeyTypes.supportsEquality` offers `=` only when `varchar.supportsBinaryEquality` holds. That check keeps a case- or accent-insensitive VARCHAR key away from a store that compares bytes, which would return fewer rows than Spark's equality matches, and Spark's re-check of returned rows cannot restore them. No case in this test reaches the check: the collated STRING types match the `StringType` case, and every VARCHAR column in both suites uses the default collation. Dropping `&& varchar.supportsBinaryEquality` therefore keeps both suites green, while `code = ?` would then be offered on a `VARCHAR(3) COLLATE UTF8_LCASE` column. A collated VARCHAR here pairs with the `VARCHAR(3)` in `offeredTypes` and pins both outcomes: ```suggestion val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3) COLLATE UTF8_LCASE", ``` **Verification:** - **Regression:** With the collation check removed from the VARCHAR branch of the key-type rule, the key-type test fails, because a case-insensitive VARCHAR lookup column is then offered an equality. - **Behavior:** With the rule unchanged, the key-type test passes: a VARCHAR lookup column with a case-insensitive collation gets no equality offer, and a VARCHAR with the default collation still gets one. -- 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]
