spark-test commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4529925129
########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,497 @@ +/* + * 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, + LookupKeyComparison, 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)) { Review Comment: **Nit (P3):** This rejection pass is gated on `DATA_SOURCE_V2_RELATION`, which every DSv2 read carries, so for a query with no lookup join, no `EXTERNAL_LOOKUP` hint and no lookup-only table, every optimizer run still visits every node and calls `Table.capabilities()` on each DSv2 relation. The rule is non-excludable and runs in the early scan push-down batch, before `V2ScanRelationPushDown` turns relations into scans, so the walk covers batch queries such as `spark.table("cat.db.events").where($"id" > 0)`, each subquery plan, and each micro-batch of a stream-static join over a DSv2 table. The base branch does no such walk in the optimizer. Plans and results are unchanged and the cost is small, but it falls on queries that don't use lookup joins. `LOOKUP_ONLY_RELATION` answers the same question without a walk: `DataSourceV2Relation` and `ExternalLookupRelation` set it with the same `isLookupOnly` check that this pass throws on, so gating on `prepared.containsPattern(LOOKUP_ONLY_RELATION)` keeps the same plans and errors. The tests 'a query without a lookup-only table or the hint is not searched for lookup joins' and 'a query without a lookup-only table is not searched for lookup joins' assert that the tables are not asked for their capabilities around the analysis check and the join formation, but neither runs this rule, so they don't see the walk. The pass comes from #59910 (3fb277cfa7c), so the gate may belong there. **Verification:** - **Regression:** Applying PrepareExternalLookupJoin to ordinary plans over a table that supports both batch reads and external lookups, written without the hint as a batch query, a query with a subquery and a stream-static join's micro-batch plan, makes no call to that table's capabilities() once the plans' pattern bits are computed. - **Behavior:** A lookup-only relation that no lookup join reads, alone or beside a prepared lookup join, still fails PrepareExternalLookupJoin with UNSUPPORTED_FEATURE.TABLE_OPERATION naming the table. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupHint, + ExternalLookupHintCacheOptions, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. The + * marker keeps only the options that the hint sets. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_BYTES_OPTION = "cache_max_bytes" + private val CACHE_TTL_OPTION = "cache_ttl" + private val SUPPORTED_OPTIONS = + Set(CACHE_ENABLED_OPTION, CACHE_MAX_BYTES_OPTION, CACHE_TTL_OPTION) + private val POSITIVE_SIZE = "a positive size, such as 64k, 16m, or 1g" + private val NON_NEGATIVE_DURATION = + "a non-negative duration, such as 500ms, 5s, or 10m; a number without a unit is in milliseconds" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = ExternalLookupHintCacheOptions() + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case attr: UnresolvedAttribute => + relationNames += attr.nameParts + case other => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other))) + } + if (relationNames.isEmpty) { + ExternalLookupHint(child, cacheOptions) + } else { + // As with join strategy hints, a name marks every relation that it matches. `matched` only + // tells which names matched nothing. + val matched = mutable.HashSet.empty[Seq[String]] + def matches(identifier: Seq[String]): Boolean = { + val names = relationNames.filter { name => + ResolveHints.matchedIdentifier(name, identifier, conf.resolver) + } + matched ++= names + names.nonEmpty + } + // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: a name matches an + // unaliased (possibly multipart) table or an alias, and does not reach into a view, + // a WITH clause, or an aliased subquery. + def applyHint(plan: LogicalPlan): LogicalPlan = plan match { + case relation: UnresolvedRelation if matches(relation.multipartIdentifier) => + ExternalLookupHint(relation, cacheOptions) + case alias: SubqueryAlias + if matches(alias.identifier.qualifier :+ alias.identifier.name) => + ExternalLookupHint(alias, cacheOptions) + case _: View | _: UnresolvedWith | _: SubqueryAlias => plan + case _ => plan.mapChildren(applyHint) + } + val rewritten = applyHint(child) + // As with join strategy hints, a name may be repeated. + val missing = relationNames.distinct.filterNot(matched.contains) + if (missing.nonEmpty) { + throw QueryCompilationErrors.invalidExternalLookupHintError( + "RELATION_NOT_FOUND", Map("relations" -> missing.map(toSQLId).mkString(", "))) + } + rewritten + } + } + + private def parseOption( + option: String, + cacheOptions: ExternalLookupHintCacheOptions, + seenOptions: mutable.Set[String]): ExternalLookupHintCacheOptions = { + val separator = option.indexOf('=') + if (separator <= 0 || separator == option.length - 1) { + throw QueryCompilationErrors.invalidExternalLookupOptionError(option, "INVALID_OPTION_FORMAT") + } + val name = option.substring(0, separator).trim.toLowerCase(Locale.ROOT) Review Comment: **Nit (P3):** This line and the next trim an option's name and value and lowercase the name, and the `cache_enabled` value is lowercased below, so `'CACHE_TTL = 5s'`, `'Cache_Max_Bytes=8k'` and `'cache_enabled = TRUE'` are accepted and `'cache_ttl=1s'` with `'CACHE_TTL=2s'` is reported as a duplicate. Every hint option in `ExternalLookupJoinSuite` is lowercase with no space around `=`, including the error cases of 'external lookup hint rejects duplicate and malformed options', so removing the name's trim or lowercasing, the value's trim, or the `cache_enabled` lowercasing would make such hints fail analysis while every test still passes. The failure would be loud, and no result changes. `Utils.byteStringAsBytes` and `Utils.timeStringAsMs` trim their input themselves, so only a `cache_enabled` value written with spaces around `=` shows whether this line trims values. Cases like that, an uppercase option name, `TRUE` and `False` values, and a duplicate that differs only in case woul d pin the accepted spellings. **Verification:** - **Regression:** Removing the trimming or the lowercasing of option names, the trimming of option values, or the lowercasing of the cache_enabled value makes a hint test fail: an uppercase or space-padded option name and a space-padded or uppercase TRUE or FALSE value must resolve to the written cache options, and a repeat that differs only in case must fail as a duplicate. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala: ########## @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.analysis + +import java.util.Locale + +import scala.collection.mutable +import scala.util.control.NonFatal + +import org.apache.spark.sql.catalyst.expressions.{Expression, StringLiteral} +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupHint, + ExternalLookupHintCacheOptions, LogicalPlan, SubqueryAlias, UnresolvedHint, UnresolvedWith, View} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.util.Utils + +/** + * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its parameters are + * relation names and cache options: + * - A relation name is an identifier, or a string that does not contain `=`. As with join + * strategy hints, a hint without relation names marks the plan it is attached to, and a hint + * with relation names marks each named relation. + * - A cache option is a string of the form `key=value`, such as `'cache_ttl=5s'`. It overrides a + * `spark.sql.join.externalLookup.cache.*` configuration for the joins that the hint marks. The + * marker keeps only the options that the hint sets. + */ +object ResolveExternalLookupHint extends Rule[LogicalPlan] with QueryErrorsBase { + private val HINT_NAME = "EXTERNAL_LOOKUP" + private val CACHE_ENABLED_OPTION = "cache_enabled" + private val CACHE_MAX_BYTES_OPTION = "cache_max_bytes" + private val CACHE_TTL_OPTION = "cache_ttl" + private val SUPPORTED_OPTIONS = + Set(CACHE_ENABLED_OPTION, CACHE_MAX_BYTES_OPTION, CACHE_TTL_OPTION) + private val POSITIVE_SIZE = "a positive size, such as 64k, 16m, or 1g" + private val NON_NEGATIVE_DURATION = + "a non-negative duration, such as 500ms, 5s, or 10m; a number without a unit is in milliseconds" + + override def apply(plan: LogicalPlan): LogicalPlan = + plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), ruleId) { + case UnresolvedHint(name, parameters, child) + if name.toUpperCase(Locale.ROOT) == HINT_NAME => + resolveHint(parameters, child) + } + + private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): LogicalPlan = { + val relationNames = mutable.ArrayBuffer.empty[Seq[String]] + var cacheOptions = ExternalLookupHintCacheOptions() + val seenOptions = mutable.HashSet.empty[String] + // The Dataset API, PySpark and Spark Connect pass a relation name as a string, as they do for + // join strategy hints. A relation whose name contains `=` is named with an identifier. + def addString(value: String): Unit = + if (value.contains('=')) { + cacheOptions = parseOption(value, cacheOptions, seenOptions) + } else { + relationNames += UnresolvedAttribute.parseAttributeName(value) + } + parameters.foreach { + case StringLiteral(value) => addString(value) + case attr: UnresolvedAttribute => + relationNames += attr.nameParts + case other => + throw QueryCompilationErrors.invalidExternalLookupHintError( + "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other))) + } + if (relationNames.isEmpty) { + ExternalLookupHint(child, cacheOptions) + } else { + // As with join strategy hints, a name marks every relation that it matches. `matched` only + // tells which names matched nothing. + val matched = mutable.HashSet.empty[Seq[String]] + def matches(identifier: Seq[String]): Boolean = { + val names = relationNames.filter { name => + ResolveHints.matchedIdentifier(name, identifier, conf.resolver) + } + matched ++= names + names.nonEmpty + } + // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: a name matches an + // unaliased (possibly multipart) table or an alias, and does not reach into a view, + // a WITH clause, or an aliased subquery. + def applyHint(plan: LogicalPlan): LogicalPlan = plan match { + case relation: UnresolvedRelation if matches(relation.multipartIdentifier) => + ExternalLookupHint(relation, cacheOptions) Review Comment: **Nit (P3):** A named hint marks the relation or alias itself, and the default case below descends through any marker already above it. Hints resolve bottom-up and `withHints` nests the first-listed hint outermost, so when two `EXTERNAL_LOOKUP` hints name the same relation, the outer one puts its marker beneath the inner one's. For ```sql SELECT /*+ EXTERNAL_LOOKUP(r, 'cache_ttl=5s'), EXTERNAL_LOOKUP(r, 'cache_ttl=10s') */ ... FROM s JOIN r ON s.id = r.id ``` the lookup side becomes `ExternalLookupHint(ExternalLookupHint(r, 5s), 10s)`, and `cacheOptions`, which lets the outermost marker win, gives the join `cache_ttl=10s`. Two chained Dataset `.hint("external_lookup", "r", ...)` calls likewise keep the earlier call's options. `cacheOptions` documents that an outer hint wins 'as with join strategy hints', and for those `ResolveJoinStrategyHints` merges the outer hint into the `ResolvedHint` already on the relation and lets it win with a warning, as the hints docs show for `/*+ BROADCAST(t1), MERGE(t1, t2) */`. So an outer `cache_enabled=false` or a smaller `cache_max_bytes` is silently replaced by the inner hint's value; rows are unaffected. The test 'of several hints on one lookup side, an outer hint's cache option wins' only covers a hint over a view that carries its own hint, which stacks the other way. Placing a named hint's marker above any marker it meets on the way to the named relation would restore the documented rule. **Verification:** - **Regression:** A stream join whose lookup relation is named by two EXTERNAL_LOOKUP hints in one SQL hint comment, the first setting cache_ttl=5s and the second cache_ttl=10s, plans its lookup join with a 5 second TTL, and two chained Dataset hints that name the relation's alias plan it with the later hint's value. - **Regression:** When an inner hint without relation names marks a projection of the lookup relation, an outer hint that names the relation and sets a conflicting option has its value applied to the join. - **Compatibility:** The existing precedence cases keep their results: an outer hint naming a view whose definition carries its own hint overrides that hint's option and inherits the options it leaves unset, stacked unnamed hints let the outer one win, a name that matches no relation still fails with RELATION_NOT_FOUND, and an option-only hint above a join or a set operation still fails with NOT_ON_LOOKUP_SIDE. -- 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]
