cloud-fan commented on code in PR #58856:
URL: https://github.com/apache/spark/pull/58856#discussion_r4129501265
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/HybridAnalyzer.scala:
##########
@@ -388,7 +388,8 @@ object HybridAnalyzer {
metadataResolverExtensions =
legacyAnalyzer.singlePassMetadataResolverExtensions,
externalRelationResolution = Some(relationResolution),
extendedRewriteRules = legacyAnalyzer.singlePassPostHocResolutionRules,
- tracker = Some(tracker)
+ tracker = Some(tracker),
+ hintResolutionRules = legacyAnalyzer.singlePassHintResolutionRules
Review Comment:
**Non-blocking (P2):** The propagation suite makes
singlePassHintResolutionRules distinct only while testing Analyzer cloning; no
test crosses this HybridAnalyzer construction and observes which sequence ran.
Replacing this argument with legacyAnalyzer.hintResolutionRules would therefore
leave the new execution coverage green. Please add a focused execution case
with observably different legacy and single-pass rules so the single-pass-only
rewrite must run and the legacy rewrite must not.
**Verification:**
- **Regression:** Run AnalyzerExtensionPropagationSuite with distinct legacy
and single-pass rules and verify only the single-pass rule changes the executed
plan.
- **Compile:** Compile the Catalyst test module containing the new
HybridAnalyzer execution fixture.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/HintResolutionRunner.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.resolver
+
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import org.apache.spark.sql.catalyst.analysis.ResolveHints
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
LogicalPlan, UnresolvedWith}
+import org.apache.spark.sql.catalyst.rules.{Rule, RuleExecutor}
+import org.apache.spark.sql.catalyst.trees.CurrentOrigin
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PLAN_EXPRESSION,
UNRESOLVED_WITH}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Utility wrapper on top of [[RuleExecutor]], used to apply the hint
resolution rules injected
+ * through `SparkSessionExtensions.injectHintResolutionRule` on the unresolved
plan.
+ *
+ * The fixed-point Analyzer runs these rules in its "Hints" batch, which
completes before the
+ * "Resolution" batch, so the rules always observe an unresolved plan. The
single-pass Resolver
+ * has to run them before the [[MetadataResolver]] pre-pass for the same
reason: the pre-pass
+ * resolves relation metadata eagerly (which, for path-based relations, lists
files), therefore
+ * rules that rewrite [[UnresolvedRelation]]s have to run ahead of it.
+ *
+ * The "Disable Hints" batch precedes the "Hints" batch, exactly like in the
fixed-point Analyzer,
+ * so that `spark.sql.optimizer.disableHints` keeps hiding the hints from the
injected rules.
+ *
+ * The rules are applied to a plan before its nested CTE definitions and
subquery plans. That
+ * matches the fixed-point Analyzer, whose "Hints" batch finishes before
`ResolveSubquery`
+ * re-enters the Analyzer: the containing plan observes subqueries that have
not had the batch
+ * applied yet, and a subquery created by an injected rule still receives the
batch before
+ * relation metadata is resolved. The fixed-point Analyzer covers those
subtrees through two
+ * mechanisms:
+ * - `CTESubstitution` merges the CTE definitions into the main plan in the
"Substitution" batch,
+ * which runs before the "Hints" batch, so the rules observe them as part
of the main plan;
+ * - subquery plans are resolved by `ResolveSubquery` re-entering the whole
Analyzer through
+ * `executeSameContext`, which replays every batch, "Hints" included.
+ *
+ * View bodies are covered for the same reason: the fixed-point Analyzer
resolves them by
+ * re-entering the Analyzer (`ViewResolution.resolve` is called with
`executeSameContext`), and the
+ * single-pass Resolver calls [[Resolver.lookupMetadataAndResolve]], and
therefore this runner, once
+ * per unresolved [[View]].
+ */
+class HintResolutionRunner(hintResolutionRules: Seq[Rule[LogicalPlan]])
+ extends ResolverMetricTracker
+ with SQLConfHelper {
+
+ private lazy val hintResolver = new RuleExecutor[LogicalPlan] {
+ override def batches: Seq[Batch] =
+ Seq(
+ Batch("Disable Hints", Once, new ResolveHints.DisableHints),
+ Batch(
+ "Hints",
+ FixedPoint(
+ conf.analyzerMaxIterations,
+ errorOnExceed = true,
+ maxIterationsSetting = SQLConf.ANALYZER_MAX_ITERATIONS.key
+ ),
+ hintResolutionRules: _*
+ )
+ )
+ }
+
+ /**
+ * Applies the hint resolution rules to `plan` first, then to the CTE
definitions and subquery
+ * plans that exist afterwards, including subqueries the rules just created.
No rules are
+ * injected by default, in which case the plan is returned as is and the
[[RuleExecutor]] is
+ * never constructed (`hintResolver` is lazy). That also skips the "Disable
Hints" batch, which
+ * only matters for plans that still carry an [[UnresolvedHint]] - a shape
the single-pass
+ * Resolver does not support in the first place.
+ *
+ * The recursion needs [[AnalysisHelper.allowInvokingTransformsInAnalyzer]]
to rewrite the inner
+ * plans, so the rules are invoked within its scope, like the rewrite rules
in [[PlanRewriter]].
+ */
+ def resolveWithSubqueries(plan: LogicalPlan): LogicalPlan = {
+ if (hintResolutionRules.isEmpty) {
+ plan
+ } else {
+ recordProfile("resolveWithSubqueries") {
+ AnalysisHelper.allowInvokingTransformsInAnalyzer {
+ doResolveWithSubqueries(plan)
+ }
+ }
+ }
+ }
+
+ private def doResolveWithSubqueries(plan: LogicalPlan): LogicalPlan = {
+ // The containing plan's batch runs before nested plans, matching the
fixed-point Analyzer:
+ // its "Hints" batch completes before ResolveSubquery re-enters the
Analyzer. Running the
+ // batch first also picks up subqueries that the rules themselves create.
+ val planAfterHints = hintResolver.execute(plan)
+ val planWithResolvedCteDefinitions = resolveCteDefinitions(planAfterHints)
+
+ planWithResolvedCteDefinitions.transformAllExpressionsWithPruning(
+ _.containsPattern(PLAN_EXPRESSION)
+ ) {
+ case subqueryExpression: SubqueryExpression =>
+
subqueryExpression.withNewPlan(doResolveWithSubqueries(subqueryExpression.plan))
+ }
+ }
+
+ /**
+ * [[UnresolvedWith]] does not expose its CTE definitions as children, so
the rules would not
+ * reach them on their own. This is the same reason [[MetadataResolver]]
matches
+ * [[UnresolvedWith]] explicitly.
+ *
+ * The rules are applied on the definition body, and not on its
[[SubqueryAlias]] wrapper, since
+ * [[UnresolvedCTERelation.plan]] is typed as [[SubqueryAlias]]: the result
of a rule that
+ * replaced the wrapper - any rule of the `plan => Limit(1, plan)` shape
does - could not be
+ * written back.
+ *
+ * This is a deliberate limitation of the rule contract rather than full
parity: the fixed-point
+ * Analyzer runs the "Hints" batch on
`WithCTE(CTERelationDef(SubqueryAlias(body)))`, so a rule
+ * that matches [[SubqueryAlias]] does observe the CTE aliases there. Rules
that rewrite
+ * relations, which is what this hook is used for, are unaffected.
+ */
+ private def resolveCteDefinitions(plan: LogicalPlan): LogicalPlan =
+ plan.transformDownWithPruning(_.containsPattern(UNRESOLVED_WITH)) {
+ case unresolvedWith: UnresolvedWith =>
+ val newCteRelations = unresolvedWith.cteRelations.map { cteRelation =>
+ val cteDefinition = cteRelation.plan
+ val newCteDefinition =
CurrentOrigin.withOrigin(cteDefinition.origin) {
+ cteDefinition.copy(child =
doResolveWithSubqueries(cteDefinition.child))
Review Comment:
**Non-blocking (P2):** This recursive call starts a fresh complete Hints
RuleExecutor at each CTE body after the batch already ran on the containing
plan. That is not equivalent to fixed-point analysis, where the rule receives
one WithCTE root containing all definitions. For example, an idempotent rule
that wraps only its input root in Limit(1, ...) also limits the CTE body here,
so a tentative-mode count can change from 2 to 1 and dual-run can report a
mismatch. A stable rule that performs an RPC per apply is likewise invoked once
plus once per CTE instead of once on the combined tree.
**Recommended change:** Present the containing plan and all of its CTE
definitions to the Hints RuleExecutor as one structurally equivalent whole CTE
tree, invoke the fixed-point batch once, and map the result back into the
representation consumed by the single-pass resolver without restarting the
executor at definition bodies. Keep subquery analysis re-entry separate because
it matches the fixed-point analyzer lifecycle.
**Why this works:** Replace per-definition doResolveWithSubqueries calls
with a representation or adapter whose ordinary child topology matches the
fixed-point WithCTE rule boundary. Preserve origin, tags, CTE ordering, aliases
within the accepted scope, and rule-created subquery discovery when
reconstructing the single-pass plan.
**Scope:** Rework the CTE-facing hint-rule boundary and add parity coverage
for root-sensitive and invocation-counting injected rules.
**Compatibility:** Injected hint rules still run after identifier and CTE
substitution and before metadata lookup, with the configured fixed-point
iteration bound and the existing separate re-entry for nested subqueries.
**Risks:** A temporary CTE representation can lose origin, tags, definition
ordering, or alias structure while being reconstructed. Folding subquery plans
into the same invocation would diverge from the fixed-point analyzer's separate
analysis re-entry.
**Constraints:** Each injected rule must receive one containing CTE root per
fixed-point iteration rather than one root per definition.
Containing-plan-before-subquery ordering and processing of rule-created
subqueries must remain intact. The accepted limitation around replacement of
the typed SubqueryAlias wrapper need not be broadened by this repair.
**Success:** A root-sensitive idempotent rule produces the same CTE query
result in fixed-point, tentative single-pass, and dual-run modes. A stable
injected rule is invoked once per fixed-point iteration over a containing plan
with K CTE definitions, not once plus K additional definition-root executions.
CTE definition ordering, origin and tags, and containing-plan-before-subquery
behavior are preserved.
**Verification:**
- **Behavior:** Run the root-sensitive Limit rule against a supported CTE
aggregate and assert the fixed-point-equivalent count in tentative single-pass
mode and plan parity in dual-run mode.
- **Regression:** Use an invocation-counting stable rule with multiple CTE
definitions and assert that CTE count does not multiply Rule.apply calls.
- **Compatibility:** Retain coverage for ordinary relation rewrites, nested
CTEs, existing subqueries, rule-created subqueries, disabled hints, and origin
and tag preservation.
- **Compile:** Compile Catalyst test code and SQL core test code after
changing the CTE adapter and its suites.
--
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]