HeartSaVioR commented on code in PR #60087: URL: https://github.com/apache/spark/pull/60087#discussion_r4532158932
########## 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: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [4d8b4753da3](https://github.com/apache/spark/commit/4d8b4753da3e9d7beefbc87c8fbe5d20d0b7e054): a named hint now puts its marker above a marker that it meets on the way to a relation it names. So the outer hint's options win, as `cacheOptions` documents and as with join strategy hints. Tests: two named hints in one comment give the first one's value; two chained Dataset hints give the later call's; an outer named hint wins over an inner unnamed hint on a projection of the relation. The existing precedence and placement tests still pass. ########## 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: > [!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 [4d8b4753da3](https://github.com/apache/spark/commit/4d8b4753da3e9d7beefbc87c8fbe5d20d0b7e054): a test pins option names matched without case and without the blanks around them, trimmed values, including `cache_enabled = TRUE` and `False`, and a repeat that differs only in case failing with `DUPLICATE_OPTION`. ########## 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: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in #59910 ([f407fa90d29](https://github.com/apache/spark/commit/f407fa90d293930ce62c5dec8ef7b8eee8548c0b)): the check for a lookup-only table that no lookup join reads now runs only when the plan carries `LOOKUP_ONLY_RELATION`. The "not searched" test now also runs `PrepareExternalLookupJoin`, on a batch query, a query with a subquery and a micro-batch, and asks no table for its capabilities. A lookup-only relation that no lookup join reads still fails as a batch scan, alone and next to a lookup join. -- 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]
