spark-test commented on code in PR #60127:
URL: https://github.com/apache/spark/pull/60127#discussion_r4583076448


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala:
##########
@@ -240,41 +276,97 @@ class NameScope(
    * aggregate expressions.
    */
   private lazy val topAggregateExpressionsByAliasName: 
IdentifierMap[ArrayList[Alias]] =
-    new IdentifierMap[ArrayList[Alias]]
+    topAggregateExpressionsByAliasNameOverride.getOrElse(new 
IdentifierMap[ArrayList[Alias]])
 
   /**
-   * Sets `canResolveNameByHiddenOutput` to `true`, enabling hidden output 
resolution for this
-   * scope.
+   * Mark this scope for HAVING clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `true`,
+   * allowing resolution to use hidden output attributes and preferring them 
over main output.
+   */
+  def markScopeForHaving(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = true
+  }
+
+  /**
+   * Mark this scope for ORDER BY (Sort) clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `false`,
+   * allowing resolution to use hidden output attributes but preferring main 
output (SELECT list
+   * aliases) over hidden output (table columns). This also resets any prior 
[[markScopeForHaving]]
+   * marking when Sort sits above a HAVING clause.
+   */
+  def markScopeForSort(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = false
+  }
+
+  /**
+   * Mark this scope for hidden output resolution without preferring hidden 
output over main
+   * output. Used by [[Filter]] and [[RepartitionByExpression]] where 
attributes from hidden output
+   * need to be resolvable but main output (SELECT list aliases) takes 
precedence.
+   *
+   * For example in the following case `col1` from the `filter` clause should 
be resolvable:
+   *
+   * {{{
+   *   sql("SELECT col1, col2 FROM VALUES(1, 
2)").select("col2").filter($"col1" > 1)
+   * }}}
+   *
+   * In this case, even though `col1` is not in the main output, we should 
resolve it from the
+   * hidden one.
    */
   def markScopeForHiddenOutputResolution(): Unit = {
     canResolveNameByHiddenOutput = true
   }
 
   /**
    * Returns new [[NameScope]] which preserves all the immutable [[NameScope]] 
properties but
-   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`aggregateListAliases` and
-   * `baseAggregate` if provided. Mutable state like `lcaRegistry` is not 
preserved.
+   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`unaggregatedAccessOnlyIds` and
+   * `qualifiedAccessOnlyOutputIds` if provided. The
+   * [[QueryBlockScope]] is preserved so that query-block-scoped state 
([[Aggregate]]
+   * context, aggregate-list aliases) is shared across [[NameScope]]s of the 
same query block. The
+   * `lcaRegistry` is carried over for the same reason: an overwrite produces 
a new scope for the
+   * same query block with updated outputs, so the lateral-column-alias state 
collected during
+   * expression resolution must survive it (e.g. grouping analytics inserts an 
[[Expand]] below the
+   * [[Aggregate]] and overwrites the output before the lateral aliases are 
resolved).
+   * `topAggregateExpressionsByAliasName` is carried over for the same reason: 
it is populated
+   * while resolving the aggregate expressions and read while resolving the 
grouping expressions,
+   * and an overwrite can happen in between, so dropping it would make 
SELECT-list aliases
+   * invisible to group-by-alias resolution. The 
`canResolveNameByHiddenOutput` and
+   * `shouldPreferHiddenOutput` flags are propagated from the current scope.
    */
   def overwrite(
       output: Option[Seq[Attribute]] = None,
       hiddenOutput: Option[Seq[Attribute]] = None,
       availableAliases: Option[HashMap[ExprId, Alias]] = None,
-      aggregateListAliases: Seq[Alias] = Seq.empty,
-      baseAggregate: Option[Aggregate] = None): NameScope = {
-    new NameScope(
+      unaggregatedAccessOnlyIds: Option[HashSet[ExprId]] = None,
+      qualifiedAccessOnlyOutputIds: Option[HashSet[ExprId]] = None,
+      planIdTargetRegistry: Option[PlanIdTargetRegistry] = None): NameScope = {
+    val newScope = new NameScope(
       output = output.getOrElse(this.output),
       hiddenOutput = hiddenOutput.getOrElse(this.hiddenOutput),
-      isSubqueryRoot = isSubqueryRoot,
+      scopeType = scopeType,
       availableAliases = availableAliases.getOrElse(this.availableAliases),
-      aggregateListAliases = aggregateListAliases,
-      baseAggregate = baseAggregate,
-      planLogger = planLogger
+      queryBlockScope = queryBlockScope,
+      unaggregatedAccessOnlyIds =
+        unaggregatedAccessOnlyIds.getOrElse(this.unaggregatedAccessOnlyIds),
+      qualifiedAccessOnlyOutputIds =
+        
qualifiedAccessOnlyOutputIds.getOrElse(this.qualifiedAccessOnlyOutputIds),
+      planIdTargetRegistry = 
planIdTargetRegistry.getOrElse(this.planIdTargetRegistry),
+      planLogger = planLogger,
+      lcaRegistryOverride = Some(lcaRegistry),
+      topAggregateExpressionsByAliasNameOverride = 
Some(topAggregateExpressionsByAliasName)
     )
+    newScope.canResolveNameByHiddenOutput = this.canResolveNameByHiddenOutput

Review Comment:
   **Non-blocking (P2):** `overwrite()` copies `canResolveNameByHiddenOutput` 
and `shouldPreferHiddenOutput` into every successor scope, and 
`resolveMultipartName` now reads these scope vars instead of the per-call 
`NameResolutionParameters`. That also bypasses 
`canResolveNameByHiddenOutputInSubquery`: `NameScopeStack.resolveMultipartName` 
still passes it for outer-scope lookups, but the outer `NameScope` applies its 
own Sort or Filter mark instead.
   
   Reading the code, for `SELECT a FROM t ORDER BY (SELECT max(v) FROM s WHERE 
s.k = t.b)` the subquery resolves `t.b` from the outer scope's hidden output, 
`SubqueryExpressionResolver` records it as referenced by the Sort, and 
`SortResolver` inserts `b` below the Sort, so single-pass accepts a query that 
the fixed-point analyzer rejects (its `resolveOuterRef` only sees the Sort's 
child output). Tentative and forced single-pass modes would return that plan, 
and dual-run fails with `FIXED_POINT_FAILED_SINGLE_PASS_SUCCEEDED`. A Project 
above the marking operator can also resolve such columns from hidden output; 
that case ends in `MISSING_ATTRIBUTES` instead of `UNRESOLVED_COLUMN`.
   
   Suggested fix: set the marks only for the marking operator's own expression 
resolution, stop copying them in `overwrite()`, and keep outer-scope lookups on 
the per-call subquery parameter, as the base code did.
   
   **Verification:**
   - **Regression:** An unresolved DataFrame plan that selects col2, filters on 
col1 and then selects col1 fails single-pass resolution with the same error as 
the fixed-point analyzer.
   - **Regression:** SELECT a FROM t ORDER BY (SELECT max(v) FROM s WHERE s.k = 
t.b) fails single-pass resolution instead of resolving, so dual-run raises no 
fixedPointFailedSinglePassSucceeded.
   - **Behavior:** Filter, Sort, HAVING and DISTRIBUTE BY queries that 
reference hidden-output columns directly, and HAVING or ORDER BY-over-aggregate 
queries whose correlated subqueries reference grouping columns, still resolve 
under dual-run without mismatches.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala:
##########
@@ -240,41 +276,97 @@ class NameScope(
    * aggregate expressions.
    */
   private lazy val topAggregateExpressionsByAliasName: 
IdentifierMap[ArrayList[Alias]] =
-    new IdentifierMap[ArrayList[Alias]]
+    topAggregateExpressionsByAliasNameOverride.getOrElse(new 
IdentifierMap[ArrayList[Alias]])
 
   /**
-   * Sets `canResolveNameByHiddenOutput` to `true`, enabling hidden output 
resolution for this
-   * scope.
+   * Mark this scope for HAVING clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `true`,
+   * allowing resolution to use hidden output attributes and preferring them 
over main output.
+   */
+  def markScopeForHaving(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = true
+  }
+
+  /**
+   * Mark this scope for ORDER BY (Sort) clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `false`,
+   * allowing resolution to use hidden output attributes but preferring main 
output (SELECT list
+   * aliases) over hidden output (table columns). This also resets any prior 
[[markScopeForHaving]]
+   * marking when Sort sits above a HAVING clause.
+   */
+  def markScopeForSort(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = false
+  }
+
+  /**
+   * Mark this scope for hidden output resolution without preferring hidden 
output over main
+   * output. Used by [[Filter]] and [[RepartitionByExpression]] where 
attributes from hidden output
+   * need to be resolvable but main output (SELECT list aliases) takes 
precedence.
+   *
+   * For example in the following case `col1` from the `filter` clause should 
be resolvable:
+   *
+   * {{{
+   *   sql("SELECT col1, col2 FROM VALUES(1, 
2)").select("col2").filter($"col1" > 1)
+   * }}}
+   *
+   * In this case, even though `col1` is not in the main output, we should 
resolve it from the
+   * hidden one.
    */
   def markScopeForHiddenOutputResolution(): Unit = {
     canResolveNameByHiddenOutput = true
   }
 
   /**
    * Returns new [[NameScope]] which preserves all the immutable [[NameScope]] 
properties but
-   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`aggregateListAliases` and
-   * `baseAggregate` if provided. Mutable state like `lcaRegistry` is not 
preserved.
+   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`unaggregatedAccessOnlyIds` and
+   * `qualifiedAccessOnlyOutputIds` if provided. The
+   * [[QueryBlockScope]] is preserved so that query-block-scoped state 
([[Aggregate]]
+   * context, aggregate-list aliases) is shared across [[NameScope]]s of the 
same query block. The
+   * `lcaRegistry` is carried over for the same reason: an overwrite produces 
a new scope for the
+   * same query block with updated outputs, so the lateral-column-alias state 
collected during
+   * expression resolution must survive it (e.g. grouping analytics inserts an 
[[Expand]] below the
+   * [[Aggregate]] and overwrites the output before the lateral aliases are 
resolved).
+   * `topAggregateExpressionsByAliasName` is carried over for the same reason: 
it is populated
+   * while resolving the aggregate expressions and read while resolving the 
grouping expressions,
+   * and an overwrite can happen in between, so dropping it would make 
SELECT-list aliases
+   * invisible to group-by-alias resolution. The 
`canResolveNameByHiddenOutput` and
+   * `shouldPreferHiddenOutput` flags are propagated from the current scope.
    */
   def overwrite(
       output: Option[Seq[Attribute]] = None,
       hiddenOutput: Option[Seq[Attribute]] = None,
       availableAliases: Option[HashMap[ExprId, Alias]] = None,
-      aggregateListAliases: Seq[Alias] = Seq.empty,
-      baseAggregate: Option[Aggregate] = None): NameScope = {
-    new NameScope(
+      unaggregatedAccessOnlyIds: Option[HashSet[ExprId]] = None,
+      qualifiedAccessOnlyOutputIds: Option[HashSet[ExprId]] = None,
+      planIdTargetRegistry: Option[PlanIdTargetRegistry] = None): NameScope = {
+    val newScope = new NameScope(
       output = output.getOrElse(this.output),
       hiddenOutput = hiddenOutput.getOrElse(this.hiddenOutput),
-      isSubqueryRoot = isSubqueryRoot,
+      scopeType = scopeType,
       availableAliases = availableAliases.getOrElse(this.availableAliases),
-      aggregateListAliases = aggregateListAliases,
-      baseAggregate = baseAggregate,
-      planLogger = planLogger
+      queryBlockScope = queryBlockScope,
+      unaggregatedAccessOnlyIds =
+        unaggregatedAccessOnlyIds.getOrElse(this.unaggregatedAccessOnlyIds),
+      qualifiedAccessOnlyOutputIds =
+        
qualifiedAccessOnlyOutputIds.getOrElse(this.qualifiedAccessOnlyOutputIds),
+      planIdTargetRegistry = 
planIdTargetRegistry.getOrElse(this.planIdTargetRegistry),
+      planLogger = planLogger,
+      lcaRegistryOverride = Some(lcaRegistry),

Review Comment:
   **Nit (P3):** `lcaRegistryOverride = Some(lcaRegistry)` keeps the registry 
across every overwrite, while the base built a fresh scope whose registry 
started empty. `AliasResolver` registers every top-level alias resolved in the 
scope, so the PIVOT aggregate alias `s` and the SELECT list's own `s` are both 
registered when the Project resolves `s + 1`, and 
`LateralColumnAliasRegistryImpl` throws `AMBIGUOUS_LATERAL_COLUMN_ALIAS`.
   
   Reading the code, `SELECT 10 AS s, s + 1 AS t FROM VALUES (1, 2) AS v(x, y) 
PIVOT (sum(x) AS s FOR y IN (2))` fails in single-pass, while the fixed-point 
analyzer, which only considers aliases of the same SELECT list, resolves `s` to 
10.
   
   Suggested fix: start each Project and Aggregate list resolution with an 
empty registry (where `availableAliases` is already cleared), keeping the 
carry-over that grouping analytics needs within one Aggregate's resolution.
   
   **Verification:**
   - **Regression:** A lateral alias whose name matches a PIVOT aggregate alias 
in the same FROM clause resolves to the SELECT-list alias in single-pass and 
matches fixed-point under dual-run.
   - **Behavior:** Lateral column alias queries with GROUPING SETS, CUBE or 
ROLLUP keep resolving without dual-run mismatches.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/SortResolver.scala:
##########
@@ -158,58 +161,117 @@ class SortResolver(operatorResolver: Resolver, 
expressionResolver: ExpressionRes
     } else {
       val partiallyResolvedSort = unresolvedSort.copy(child = resolvedChild)
 
-      val (partiallyResolvedOrderExpressions, missingAttributes) =
-        resolveOrderExpressions(partiallyResolvedSort)
+      val (resolvedOrderExpressions, missingExpressions) = 
resolveSortOrder(partiallyResolvedSort)
 
-      val (resolvedOrderExpressions, missingExpressions) = resolvedChild match 
{
-        case _ @(_: Aggregate | _: Filter | _: Project)
-            if scopes.current.baseAggregate.isDefined =>
-          extractReferencedGroupingAndAggregateExpressions(
-            scopes.current.baseAggregate.get,
-            partiallyResolvedOrderExpressions
-          )
-        case other =>
-          (partiallyResolvedOrderExpressions, missingAttributes)
-      }
+      buildSort(
+        unresolvedSort = unresolvedSort,
+        resolvedChild = resolvedChild,
+        resolvedOrderExpressions = resolvedOrderExpressions,
+        missingExpressions = missingExpressions
+      )
+    }
+  }
 
-      val (resolvedOrderExpressionsWithAliasesReplaced, 
filteredMissingExpressions) =
-        tryReplaceSortOrderWithAlias(resolvedOrderExpressions, 
missingExpressions)
+  /** Resolves sort keys and extracts the hidden expressions needed to 
evaluate them. */
+  private def resolveSortOrder(sort: Sort): (Seq[SortOrder], 
Seq[NamedExpression]) = {
+    val (partiallyResolvedOrderExpressions, missingAttributes, 
hasGroupingAnalyticsExpression) =
+      resolveOrderExpressions(sort)
 
-      val resolvedChildWithMissingAttributes =
-        insertMissingExpressions(resolvedChild, filteredMissingExpressions)
+    val orderExpressionsWithGroupingAnalytics = if 
(hasGroupingAnalyticsExpression) {
+      
groupingAnalyticsResolver.handleSortOrderExpressionsWithGroupingAnalytics(
+        orderExpressions = partiallyResolvedOrderExpressions,
+        sort = sort
+      )
+    } else {
+      partiallyResolvedOrderExpressions
+    }
 
-      val isChildChangedByMissingExpressions = 
!resolvedChildWithMissingAttributes.eq(resolvedChild)
+    val currentQueryBlockScope = queryBlockScopes.current
+    sort.child match {
+      case _: Aggregate | _: Filter | _: Project

Review Comment:
   **Non-blocking (P2):** This branch treats a `Project` child as sitting on 
the aggregate whenever the query block has a base aggregate, but nothing clears 
that aggregate when a plain user-written Project is resolved above it; the base 
code dropped it at every plain Project overwrite.
   
   Reading the code, for 
`df.groupBy('a').agg(max('c')).select('a').orderBy(sum('b'))` the extractor 
turns `sum(b)` into a new aggregate alias, `insertMissingExpressions` threads 
it through the Project into the Aggregate, and the query is accepted, whereas 
the fixed-point analyzer resolves sort keys with an aggregate only directly 
below the Sort (or below a Filter on it) and fails with `UNRESOLVED_COLUMN`. 
Conversely, for 
`df.groupBy('a').agg(sum('b').as('s')).select('a').orderBy('s')` this path 
returns only the extracted grouping and aggregate expressions and drops the 
hidden-output attribute `s`, so the Sort fails with `MISSING_ATTRIBUTES`, 
although the fixed-point analyzer adds `s` back to the Project. Tentative and 
forced modes return the accepted plan, and dual-run fails in both directions.
   
   Suggested fix: clear the query block's aggregate state when 
`ProjectResolver` finishes a plain Project, as `resolveDistinct` does, so a 
Sort above it resolves against the Project output and inserts missing 
attributes as before.
   
   **Verification:**
   - **Regression:** A Sort with an aggregate key above a DataFrame select 
above an Aggregate fails single-pass resolution, and dual-run raises no 
fixedPointFailedSinglePassSucceeded.
   - **Regression:** Sorting by an aggregate alias that a DataFrame select 
dropped resolves in single-pass without a dual-run failure.
   - **Behavior:** ORDER BY and HAVING over aggregates with lateral aliases and 
window functions keep resolving without dual-run mismatches.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala:
##########
@@ -472,18 +632,31 @@ class Resolver(
    *  {{{ spark.sql("SELECT * FROM VALUES (1, 
2)").select("col1").as("q1").select("col2"); }}}
    */
   private def resolveSubqueryAlias(unresolvedSubqueryAlias: SubqueryAlias): 
LogicalPlan = {
-    val resolvedSubqueryAlias =
+    queryBlockScopes.push()

Review Comment:
   **Nit (P3):** This pushes a `QueryBlockScope` for the alias body but no 
`NameScope`, while a `NameScope` captures `queryBlockScopes.current` only when 
it is pushed. A Sort or HAVING at the top of the body resolves in the enclosing 
name scope, so the base aggregate and its aliases are registered in the body's 
block, but `tryReplaceSortOrderOrHavingConditionWithAlias` and the 
outer-reference alias rewrite read `scopes.current.queryBlockScope` and 
`outerScope.queryBlockScope`, which is the enclosing block.
   
   Reading the code, `SELECT * FROM (SELECT col1 AS a, a + 1 AS b FROM VALUES 
(1) GROUP BY col1 ORDER BY col1) sq` inserts `col1` into the lateral-alias 
Project stack instead of sorting by `a`, and `SELECT * FROM (SELECT col1 AS 
alias FROM VALUES ('a') GROUP BY col1 HAVING (SELECT col1 = 'a')) sq` keeps 
`outer(col1)` where the fixed-point analyzer uses `outer(alias)`, so dual-run 
reports a plan mismatch. Query results do not change, and without lateral 
aliases the ORDER BY case is unaffected because the grouping column is already 
mapped to its alias. With the test-only 
`preventUsingAliasesFromNonDirectChildren` setting, the conf-gated clear also 
empties the enclosing block's state instead of the derived table's.
   
   **Recommended change:** Make resolveSubqueryAlias push an Intermediate name 
scope after it pushes the new query block, and resolve the child inside it. 
Read the child's output from that scope before popping it, because popScope 
carries hidden output, available aliases, qualified-access-only IDs and plan-id 
targets to the enclosing scope but not output. Then pop it before popping the 
query block, and overwrite the enclosing scope with the alias output and 
metadata hidden output as today. Make the conf-gated aggregate-state clear in 
retainOriginalOutput act on the block the current name scope belongs to, which 
is now the right one. Add single-pass resolver tests for ORDER BY over a 
lateral-alias aggregate and for HAVING with a correlated subquery at the top of 
derived tables, with and without the prevent-aliases-from-non-direct-children 
setting.
   
   **Why this works:** With both stacks pushed together, every NameScope used 
by an operator in the alias body captures the body's QueryBlockScope, so 
scopes.current.queryBlockScope, outerScope.queryBlockScope and 
queryBlockScopes.current all denote the same block for those operators. 
popScope's existing Intermediate propagation carries hidden output, aliases, 
qualified-access-only IDs and plan-id targets back to the enclosing scope, and 
the alias output is built from the pushed scope before it is popped, so what 
the enclosing scope observes after the alias is unchanged.
   
   **Scope:** Align name scopes with query blocks at SubqueryAlias boundaries.
   
   **Compatibility:** What a SubqueryAlias exposes to its parent (output, 
metadata hidden output, plan-id targets) is unchanged.
   
   **Risks:** Operators at the top of an alias body now mark and overwrite 
their own name scope rather than the enclosing one, so state that previously 
leaked across the alias boundary (hidden-output marks, lateral alias 
registrations) no longer does; this is the intended behavior and can be rolled 
back by removing the push.
   
   **Constraints:** The popped name scope must propagate plan-id targets so 
DataFrame references through aliases keep resolving. The alias output must be 
read from the pushed scope before it is popped; after popScope the enclosing 
scope still holds its previous output.
   
   **Exclusions:**
   - Changing which state a SubqueryAlias exposes to its parent, which stays 
its output plus metadata hidden output.
   
   **Success:** SELECT * FROM (SELECT col1 AS a, a + 1 AS b FROM VALUES (1) 
GROUP BY col1 ORDER BY col1) sq resolves to the same plan as the fixed-point 
analyzer. HAVING with a correlated subquery at the top of a derived table, such 
as SELECT * FROM (SELECT col1 AS alias FROM VALUES ('a') GROUP BY col1 HAVING 
(SELECT col1 = 'a')) sq, rewrites outer references to the aggregate alias like 
the fixed-point analyzer. With the prevent-aliases-from-non-direct-children 
setting enabled, the aggregate state cleared is the derived table's own. The 
output, qualifiers and metadata hidden output that a SubqueryAlias exposes to 
its parent are unchanged.
   
   **Verification:**
   - **Regression:** ORDER BY on a grouping column of a lateral-alias aggregate 
at the top of a derived table produces no dual-run plan mismatch.
   - **Regression:** HAVING with a correlated subquery referencing a grouping 
column at the top of a derived table matches the fixed-point plan.
   - **Compatibility:** DataFrame plan-id references through aliased DataFrames 
and derived tables, and column references to derived-table output, keep 
resolving after the change.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala:
##########
@@ -240,41 +276,97 @@ class NameScope(
    * aggregate expressions.
    */
   private lazy val topAggregateExpressionsByAliasName: 
IdentifierMap[ArrayList[Alias]] =
-    new IdentifierMap[ArrayList[Alias]]
+    topAggregateExpressionsByAliasNameOverride.getOrElse(new 
IdentifierMap[ArrayList[Alias]])
 
   /**
-   * Sets `canResolveNameByHiddenOutput` to `true`, enabling hidden output 
resolution for this
-   * scope.
+   * Mark this scope for HAVING clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `true`,
+   * allowing resolution to use hidden output attributes and preferring them 
over main output.
+   */
+  def markScopeForHaving(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = true
+  }
+
+  /**
+   * Mark this scope for ORDER BY (Sort) clause resolution.
+   *
+   * Sets `canResolveNameByHiddenOutput` to `true` and 
`shouldPreferHiddenOutput` to `false`,
+   * allowing resolution to use hidden output attributes but preferring main 
output (SELECT list
+   * aliases) over hidden output (table columns). This also resets any prior 
[[markScopeForHaving]]
+   * marking when Sort sits above a HAVING clause.
+   */
+  def markScopeForSort(): Unit = {
+    canResolveNameByHiddenOutput = true
+    shouldPreferHiddenOutput = false
+  }
+
+  /**
+   * Mark this scope for hidden output resolution without preferring hidden 
output over main
+   * output. Used by [[Filter]] and [[RepartitionByExpression]] where 
attributes from hidden output
+   * need to be resolvable but main output (SELECT list aliases) takes 
precedence.
+   *
+   * For example in the following case `col1` from the `filter` clause should 
be resolvable:
+   *
+   * {{{
+   *   sql("SELECT col1, col2 FROM VALUES(1, 
2)").select("col2").filter($"col1" > 1)
+   * }}}
+   *
+   * In this case, even though `col1` is not in the main output, we should 
resolve it from the
+   * hidden one.
    */
   def markScopeForHiddenOutputResolution(): Unit = {
     canResolveNameByHiddenOutput = true
   }
 
   /**
    * Returns new [[NameScope]] which preserves all the immutable [[NameScope]] 
properties but
-   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`aggregateListAliases` and
-   * `baseAggregate` if provided. Mutable state like `lcaRegistry` is not 
preserved.
+   * overwrites `output`, `hiddenOutput`, `availableAliases`, 
`unaggregatedAccessOnlyIds` and
+   * `qualifiedAccessOnlyOutputIds` if provided. The
+   * [[QueryBlockScope]] is preserved so that query-block-scoped state 
([[Aggregate]]
+   * context, aggregate-list aliases) is shared across [[NameScope]]s of the 
same query block. The
+   * `lcaRegistry` is carried over for the same reason: an overwrite produces 
a new scope for the
+   * same query block with updated outputs, so the lateral-column-alias state 
collected during
+   * expression resolution must survive it (e.g. grouping analytics inserts an 
[[Expand]] below the
+   * [[Aggregate]] and overwrites the output before the lateral aliases are 
resolved).
+   * `topAggregateExpressionsByAliasName` is carried over for the same reason: 
it is populated
+   * while resolving the aggregate expressions and read while resolving the 
grouping expressions,
+   * and an overwrite can happen in between, so dropping it would make 
SELECT-list aliases
+   * invisible to group-by-alias resolution. The 
`canResolveNameByHiddenOutput` and
+   * `shouldPreferHiddenOutput` flags are propagated from the current scope.
    */
   def overwrite(
       output: Option[Seq[Attribute]] = None,
       hiddenOutput: Option[Seq[Attribute]] = None,
       availableAliases: Option[HashMap[ExprId, Alias]] = None,
-      aggregateListAliases: Seq[Alias] = Seq.empty,
-      baseAggregate: Option[Aggregate] = None): NameScope = {
-    new NameScope(
+      unaggregatedAccessOnlyIds: Option[HashSet[ExprId]] = None,
+      qualifiedAccessOnlyOutputIds: Option[HashSet[ExprId]] = None,
+      planIdTargetRegistry: Option[PlanIdTargetRegistry] = None): NameScope = {
+    val newScope = new NameScope(
       output = output.getOrElse(this.output),
       hiddenOutput = hiddenOutput.getOrElse(this.hiddenOutput),
-      isSubqueryRoot = isSubqueryRoot,
+      scopeType = scopeType,
       availableAliases = availableAliases.getOrElse(this.availableAliases),
-      aggregateListAliases = aggregateListAliases,
-      baseAggregate = baseAggregate,
-      planLogger = planLogger
+      queryBlockScope = queryBlockScope,
+      unaggregatedAccessOnlyIds =
+        unaggregatedAccessOnlyIds.getOrElse(this.unaggregatedAccessOnlyIds),

Review Comment:
   **Non-blocking (P2):** `overwrite()` keeps the previous 
`unaggregatedAccessOnlyIds` when it is given `None`, and 
`overwriteOutputAndExtendHiddenOutput` passes a set only for 
`GroupingModifier.GroupingAnalytics`, so the Expand-output grouping IDs stay on 
the scope after the Aggregate's output has been handed to its parent; the 
`SubqueryAlias` overwrite keeps them too.
   
   Reading the code, in `SELECT sum(a) FROM (SELECT a FROM t GROUP BY CUBE(a)) 
sq` the outer `sum(a)` resolves `a` inside an aggregate expression, 
`getCandidatesForResolution` filters out `sq.a` because its ID is in the set, 
and no pre-Expand `a` is left in hidden output, so single-pass reports 
`UNRESOLVED_COLUMN` for a query the fixed-point analyzer resolves. Dual-run 
fails with `SINGLE_PASS_FAILED_FIXED_POINT_SUCCEEDED`, and tentative mode falls 
back.
   
   Suggested fix: reset the set whenever an operator hands its output to a 
parent (an empty set for every modifier other than `GroupingAnalytics`, and at 
the `SubqueryAlias` overwrite), so only the grouping-analytics SELECT's own 
HAVING and ORDER BY see it.
   
   **Verification:**
   - **Regression:** An aggregate over a CUBE derived table resolves in 
single-pass and matches the fixed-point plan under dual-run.
   - **Behavior:** Existing HAVING and ORDER BY over grouping analytics cases 
keep resolving without dual-run mismatches.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/InsertsMetadataColumns.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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 java.util.{HashMap, HashSet}
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import org.apache.spark.sql.catalyst.expressions.{Attribute, ExprId, 
NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  ExposesMetadataColumns,
+  Join,
+  LeafNode,
+  LogicalPlan,
+  Project,
+  SubqueryAlias,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Mixed into [[Resolver]] to provide metadata column insertion into the plan 
tree. Called from
+ * [[Resolver.insertReferencedMetadataColumnsForOperator]] after each operator 
resolves.
+ *
+ * Metadata columns (e.g. `_metadata`) originate from leaf operators like 
[[LogicalRelation]] or
+ * [[DataSourceV2Relation]] and are stored in the [[NameScope]]'s hidden 
output, identified by the
+ * `__metadata_col` attribute marker ([[Attribute.isMetadataCol]]). When an 
operator's expressions
+ * reference a metadata column, this trait inserts the column into the plan 
tree below by
+ * propagating it downward through intermediate operators until reaching the 
leaf node that owns it.
+ *
+ * The propagation descends through passthrough operators (e.g. [[Filter]], 
[[Sort]]) and [[Join]]
+ * nodes, extends [[Project]] expression lists as needed, and calls
+ * [[ExposesMetadataColumns.withMetadataColumns]] on leaf nodes. [[Aggregate]] 
is a propagation
+ * barrier, matching the legacy analyzer where `Aggregate.metadataOutput` is 
`Nil`. For [[Join]],
+ * metadata columns are sent to both children - only the child whose leaf owns 
the metadata
+ * column's [[ExprId]] will actually insert it; the other child's subtree is a 
no-op.
+ *
+ * {{{
+ * -- Project: _metadata resolved from hidden output, inserted into 
LogicalRelation output.
+ * SELECT _metadata FROM nation
+ *
+ * -- Filter: _metadata.file_size resolved from hidden output in WHERE 
condition.
+ * SELECT n_nationkey FROM nation WHERE _metadata.file_size > 0
+ *
+ * -- Aggregate: _metadata referenced in grouping expression.
+ * SELECT count(*) AS cnt FROM nation GROUP BY _metadata.file_block_start
+ *
+ * -- Join: _metadata propagated to both children, only the owning leaf 
inserts it.
+ * SELECT a._metadata FROM nation a JOIN region b ON a.n_regionkey = 
b.r_regionkey
+ * }}}
+ */
+trait InsertsMetadataColumns extends SQLConfHelper {
+
+  /**
+   * Checks if the current operator's expression resolution referenced any 
metadata columns, and
+   * if so, inserts them into the resolved plan tree by propagating down to 
the leaf nodes.
+   *
+   * Following the legacy [[AddMetadataColumns]] rule: after propagating 
metadata columns into the
+   * children (which adds them to leaf outputs), if the operator's output 
schema changed (e.g. a
+   * [[Filter]] whose child now exposes `_metadata`), we wrap the operator 
with a [[Project]] that
+   * projects only the original output columns. This preserves the operator's 
output schema while
+   * making the metadata columns available internally.
+   *
+   * `referencedMetadataColumns` is populated during expression resolution by 
cross-referencing
+   * referenced attributes with [[NameScope.hiddenOutput]]. This avoids 
reading from
+   * [[NameScope.hiddenOutput]] directly, which may have already been stripped 
by operator resolvers
+   * that call [[NameScopeStack.overwriteOutputAndExtendHiddenOutput]] with
+   * `stripMetadataFromHiddenOutput = true`. `currentOutput` is the operator's 
output that the
+   * wrapping [[Project]] must preserve. `isTopLevel` is `true` when the 
operator is the plan's
+   * top-level operator (carries [[ResolverTag.TOP_LEVEL_OPERATOR]] on its 
unresolved node); when
+   * so, the wrapping [[Project]] preserves only the original output, without 
exposing the metadata
+   * columns for a (nonexistent) parent to reference.
+   */
+  protected def insertReferencedMetadataColumnsForOperator(
+      resolvedPlan: LogicalPlan,
+      referencedMetadataColumns: HashMap[ExprId, Attribute],
+      currentOutput: Seq[Attribute],
+      isTopLevel: Boolean): LogicalPlan = {
+    if (referencedMetadataColumns.isEmpty) {
+      resolvedPlan
+    } else {
+      val metadataColumns = referencedMetadataColumns.values().asScala.toSeq
+
+      val updatedChildren = resolvedPlan.children.map { child =>
+        val (updatedChild, _) = insertReferencedMetadataColumnsIntoChild(
+          operator = child,
+          metadataColumns = metadataColumns
+        )
+        updatedChild
+      }
+
+      val updatedPlan = resolvedPlan.withNewChildren(updatedChildren)
+      if (updatedPlan eq resolvedPlan) {
+        resolvedPlan
+      } else {
+        resolvedPlan match {
+          case _: Project | _: Aggregate =>
+            updatedPlan
+          case _ =>
+            val metadataColumnsToPreserve =
+              if (isTopLevel) {
+                Seq.empty
+              } else {
+                metadataColumns.map(_.markAsQualifiedAccessOnly())
+              }
+            val wrappingProject = Project(currentOutput ++ 
metadataColumnsToPreserve, updatedPlan)
+            if (metadataColumnsToPreserve.nonEmpty) {
+              wrappingProject.setTagValue(
+                InsertsMetadataColumns.PRESERVED_METADATA_COLUMN_IDS,
+                metadataColumnsToPreserve.map(_.exprId).toSet
+              )
+            }
+            wrappingProject
+        }
+      }
+    }
+  }
+
+  /**
+   * Recursively insert referenced metadata columns into the operator tree. 
Returns the modified
+   * plan and the subset of requested columns that were actually accepted by
+   * [[ExposesMetadataColumns]] leaf nodes. This allows parent operators to 
only add columns to
+   * their expression lists that are actually available from the subtree 
below, which is essential
+   * when metadata columns are sent to both sides of a [[Join]] -- only the 
side whose leaf owns
+   * the column will report it as accepted.
+   *
+   * For [[Project]], recursion always proceeds with the full
+   * `metadataColumns` to ensure the leaf's 
[[ExposesMetadataColumns.withMetadataColumns]] is
+   * called even when the metadata column is already present in the operator's 
expression list
+   * (e.g. `SELECT _metadata FROM t`). The filtering via 
[[filterColumnsNotInExpressionList]] is
+   * applied after recursion to decide what to *add* to the expression list, 
not whether to recurse.
+   */
+  protected def insertReferencedMetadataColumnsIntoChild(
+      operator: LogicalPlan,
+      metadataColumns: Seq[Attribute]): (LogicalPlan, Seq[Attribute]) = {
+    operator match {
+      case project: Project =>
+        failIfReferencingPreservedMetadataColumns(project, metadataColumns)
+
+        insertMetadataColumnsIntoOutputList(
+          operator = project,
+          expressionList = project.projectList,
+          metadataColumns = metadataColumns,
+          buildOperator = (newProjectList, newChild) =>
+            project.copy(projectList = newProjectList, child = newChild)
+        )
+      case aggregate: Aggregate =>

Review Comment:
   **Nit (P3):** `case aggregate: Aggregate => (aggregate, Seq.empty)` makes 
every Aggregate a barrier. With a lateral column alias, the resolver returns 
`Project(Project(Aggregate(...)))` with the Aggregate recorded as base 
operator, so metadata columns referenced in the aggregate's own expressions 
travel down through the lateral-alias Projects, stop at the Aggregate, and 
never reach the scan.
   
   Reading the code, `SELECT _metadata.file_name AS f, count(*) AS c, c + 1 AS 
d FROM parquet_table GROUP BY _metadata.file_name` then fails validation of the 
recorded Aggregate with `MISSING_ATTRIBUTES`; global aggregates with lateral 
aliases take the same path.
   
   Suggested fix: insert into the child of the operator's own base Aggregate, 
keep reporting no accepted columns to the Projects above it (it does not output 
them), and validate the rebuilt Aggregate.
   
   **Verification:**
   - **Regression:** A GROUP BY query and a global aggregate with a lateral 
alias and a metadata column over a file source resolve in single-pass and match 
the fixed-point plan.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/SetOperationLikeResolver.scala:
##########
@@ -408,12 +504,7 @@ class SetOperationLikeResolver(resolver: Resolver, 
expressionResolver: Expressio
           var outputChanged = false
           val newExpressions = output.zip(widenedTypes).map {
             case (attribute, widenedType) =>
-              /**
-               * Probably more correct way to compare data types here would be 
to call
-               * [[DataType.equalsStructurally]] but fixed-point [[Analyzer]] 
rule
-               * [[WidenSetOperationTypes]] uses `==`, so we do the same to 
stay compatible.
-               */
-              if (attribute.dataType == widenedType) {
+              if (DataType.equalsStructurally(attribute.dataType, 
widenedType)) {

Review Comment:
   **Nit (P3):** `DataType.equalsStructurally` ignores struct field names, 
while `WidenSetOperationTypes` casts a child exactly when a widened type exists 
and differs from the child's type (the base used `==` with a comment saying 
so). Together with the new fallback in `validateAndDeduceTypes`, which keeps 
the left child's type when `findWiderTypeForTwo` fails, this changes the casts 
in both directions. Reading the code:
   
   - `SELECT named_struct('A', 1) AS s UNION ALL SELECT named_struct('a', 2L) 
AS s` in a case-insensitive session widens to `struct<A:bigint>`; the 
fixed-point analyzer and the base single-pass code cast both children, but 
single-pass now casts only the first, so dual-run reports a plan mismatch.
   - `SELECT 1 AS x, named_struct('a', 1) AS s UNION ALL SELECT 2L AS x, 
named_struct('b', CAST(NULL AS INT)) AS s` has no wider type for `s`, so the 
fixed-point analyzer leaves it uncast, but single-pass casts the second child's 
nullable field to the left child's non-nullable one; `Cast` rejects that, and 
resolution fails with an internal error where the base threw 
`INCOMPATIBLE_COLUMN_TYPE`.
   
   Query results are unaffected whenever single-pass succeeds. Suggested fix: 
keep the widened type per column as an `Option` (`None` where the fallback 
applies today), cast only when it is `Some(dt)` and `attribute.dataType != dt`, 
and throw the fixed-point error for `None` in the recursive CTE path. Restoring 
`==` alone would also cast columns without a wider type, which match the 
fixed-point analyzer today.
   
   **Verification:**
   - **Regression:** A UNION ALL of named_struct('A', 1) and named_struct('a', 
2L) in a case-insensitive session matches the fixed-point plan under dual-run.
   - **Regression:** A UNION ALL that widens an int column next to struct 
columns with different field names resolves in single-pass and matches the 
fixed-point plan, both when the second child's nested field is nullable and the 
first's is not, and the reverse.
   - **Compatibility:** Recursive CTEs whose anchor and recursion struct types 
differ in field names behave as in the fixed-point analyzer.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/CteScope.scala:
##########
@@ -259,19 +495,58 @@ class CteScope(val isRoot: Boolean, val isOpaque: 
Boolean) {
   }
 
   /**
-   * Get a visible CTE definition by its name.
+   * Checks if a CTE with the given name exists in this scope. This is a 
simplified existence check
+   * used by [[PlanPreprocessor]] to determine if an [[UnresolvedRelation]] 
should be
+   * replaced with an [[UnresolvedCteRelationRef]].
+   */
+  def cteExists(name: String): Boolean = {
+    visibleCtes.get(name).isDefined || {
+      recursiveCteParameters.exists(params => params.cteName == name)

Review Comment:
   **Non-blocking (P2):** `params.cteName == name` here and in `getCte` is an 
exact comparison, while `visibleCtes` is a case-insensitive `IdentifierMap` and 
the fixed-point `CTESubstitution` uses the session resolver. Reading the code, 
in `WITH RECURSIVE R(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r WHERE n < 5) 
SELECT * FROM R` the reference `r` is not recognized as a self-reference, so 
single-pass fails with `TABLE_OR_VIEW_NOT_FOUND`, or reads a table named `r` if 
one exists, instead of recursing. Under an enclosing `WITH r AS (SELECT 100 AS 
n)` it binds `r` to that CTE and returns `{1}`, while the fixed-point analyzer 
shadows the outer `r` and returns `{1, 2, 3, 4, 5}`. Tentative and forced modes 
would return those wrong rows.
   
   Suggested fix: compare with the same normalization `IdentifierMap` uses, at 
both sites (here and in `getCte`).
   
   **Verification:**
   - **Regression:** A recursive CTE whose self-reference differs in case from 
its name resolves to the same recursive plan as the fixed-point analyzer under 
dual-run, with and without a same-named table.
   - **Regression:** A differently-cased recursive CTE nested under an 
enclosing CTE with the lowercase name returns the fixed-point result.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/OperatorResolutionContext.scala:
##########
@@ -127,16 +217,61 @@ class OperatorResolutionContextStack {
       case _: UnresolvedHaving => true
       case _ => current.isResolvingTreeUnderHaving
     }
+    val isResolvingSetVariableSource = unresolvedPlan match {
+      case _: SetVariable => true
+      case _ => current.isResolvingSetVariableSource
+    }
     stack.push(
       new OperatorResolutionContext(
         unresolvedPlan = Some(unresolvedPlan),
         isResolvingTreeUnderHaving = isResolvingTreeUnderHaving,
+        isResolvingSetVariableSource = isResolvingSetVariableSource,
         parameterNamesToValues = current.parameterNamesToValues,
+        resolvingLimitAll = currentContextIsResolvingLimitAll(unresolvedPlan),

Review Comment:
   **Non-blocking (P2):** `resolvingLimitAll` is derived from the parent 
context even when `isSubqueryRoot` is true, unlike the hint contexts on the 
next line, which reset at subquery roots. `createCteRelationRef` then builds 
every CTE reference inside the subquery with `isUnlimitedRecursion = true`, 
whereas `ApplyLimitAll` only follows plan children.
   
   Reading the code, with `spark.sql.cteRecursionRowLimit=50` (as in 
`cte-recursion.sql`), `WITH RECURSIVE t MAX RECURSION LEVEL 100 AS (SELECT 1 AS 
n UNION ALL SELECT n + 1 FROM t WHERE n < 60) SELECT (SELECT count(*) FROM t) 
LIMIT ALL` fails in the fixed-point analyzer with 
`RECURSION_ROW_LIMIT_EXCEEDED` but returns 60 in tentative or forced 
single-pass. Non-recursive CTEs are affected in dual-run too, e.g. `WITH t AS 
(SELECT 1 AS n) SELECT * FROM VALUES (1) AS v(c) WHERE c IN (SELECT n FROM t) 
LIMIT ALL`, because `isUnlimitedRecursion` takes part in plan comparison. The 
recursion level limit still applies.
   
   Suggested fix: at a subquery root, set `resolvingLimitAll` only when the 
root itself is a `LimitAll`.
   
   **Verification:**
   - **Regression:** A scalar subquery over a recursive CTE under LIMIT ALL 
produces a CTE reference without unlimited recursion, matching the fixed-point 
plan, and still fails with the row-limit error when the recursion exceeds it.
   - **Regression:** A non-recursive CTE referenced from an IN subquery under 
LIMIT ALL resolves to the fixed-point plan under dual-run.
   - **Behavior:** LIMIT ALL over a recursive CTE through Project, Filter and 
SubqueryAlias, and LIMIT ALL inside the subquery itself, still produce 
unlimited-recursion references.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/AsOfJoinResolver.scala:
##########
@@ -56,14 +56,19 @@ class AsOfJoinResolver(
     with JoinLikeResolver {
 
   override def resolve(unresolvedAsOfJoin: AsOfJoin): LogicalPlan = {
+    val (allowLeftRecursiveCte, allowRightRecursiveCte) =
+      getRecursiveCteAllowance(unresolvedAsOfJoin.joinType)

Review Comment:
   **Nit (P3):** The join-type-based allowance makes the right side of a `LEFT 
ASOF JOIN` reject recursive references with 
`INVALID_RECURSIVE_REFERENCE.PLACE`, but 
`ResolveWithCTE.checkIfSelfReferenceIsPlacedCorrectly` has no `AsOfJoin` case, 
so in the fixed-point analyzer both children inherit the enclosing allowance. 
Reading the code, with `spark.sql.join.asofJoin.enabled=true` (internal, off by 
default), a recursive CTE whose recursive branch is `SELECT ... FROM t LEFT 
ASOF JOIN r ...` with `r` on the right resolves in the fixed-point analyzer and 
fails in single-pass. The fixed-point analyzer's permissiveness may itself 
deserve a fix, but the two analyzers need to agree.
   
   Suggested fix: resolve both sides with `shouldDisallowRecursiveCtes = false` 
(enclosing operators still reject misplaced references), or throw 
`ExplicitlyUnsupportedResolverFeature` on the disallowed side so both modes 
fall back.
   
   **Verification:**
   - **Regression:** With spark.sql.join.asofJoin.enabled set, recursive CTEs 
that self-reference on either side of a LEFT ASOF JOIN produce no dual-run 
disagreement.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/CteDefinitionResolver.scala:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.AnalysisException
+import org.apache.spark.sql.catalyst.analysis.AnalysisErrorAt
+import org.apache.spark.sql.catalyst.plans.logical.{
+  CTERelationDef,
+  Distinct,
+  LogicalPlan,
+  Project,
+  SubqueryAlias,
+  UnionLoop,
+  UnresolvedWith,
+  WithCTE
+}
+
+/**
+ * Resolves and registers WITH definitions in declaration order with isolated 
scopes.
+ *
+ * {{{
+ * WITH t AS (SELECT 1 AS n) SELECT n FROM t
+ * }}}
+ *
+ * Registers `CTERelationDef(Project [1 AS n])` so the child can resolve to
+ * `Project [n] -> CTERelationRef`.
+ */
+private[resolver] class CteDefinitionResolver(
+    resolver: Resolver,
+    expressionResolver: ExpressionResolver) {
+  private val scopes = resolver.getNameScopes
+  private val queryBlockScopes = resolver.getQueryBlockScopes
+  private val cteRegistry = resolver.getCteRegistry
+  private val expressionIdAssigner = expressionResolver.getExpressionIdAssigner
+
+  /**
+   * Resolves and registers the definitions of a WITH clause before its child 
query.
+   *
+   * For each CTE definition, a new [[CteScope]] is pushed with:
+   *  - `cteName` and `cteId` to identify this specific CTE
+   *  - `allowRecursion` flag indicating if this is a recursive CTE
+   *  - `maxDepth` specifying iteration limit for recursive CTEs
+   *  - `isInsideRecursiveCteScope` set to true for recursive CTEs to force 
immediate inlining of
+   *  CTE definitions and prevent unnecessary stack traversals.
+   *
+   * The order in which CTE ids are allocated (via [[CTERelationDef.newId]]) 
can matter to
+   * downstream consumers that key off of [[CTERelationDef.id]] (for example, 
lineage serializes
+   * CTEs using the numeric id as the "table name").
+   *
+   * For non-recursive CTEs, we preserve the historical depth-first allocation 
behavior by
+   * allocating ids *after* resolving the CTE plan. This ensures nested WITH 
clauses inside the
+   * definition consume ids first (inner CTEs get smaller ids than their 
enclosing CTEs).
+   *
+   * For recursive CTEs, we must allocate the id up-front so that 
self-references can be
+   * represented during resolution (via `UnionLoopRef` / [[UnionLoop]]).
+   *
+   * During CTE resolution, the scope tracks whether the CTE references 
itself. If self-referenced,
+   * the CTE is validated as a properly structured recursive CTE.
+   *
+   */
+  def resolve(unresolvedWith: UnresolvedWith): Unit = {
+    for (cteRelation <- unresolvedWith.cteRelations) {
+      val cteName = cteRelation.name
+      val ctePlan = cteRelation.plan
+      val maxDepth = cteRelation.maxDepth
+      val preallocatedCteIdForRecursive: Option[Long] =
+        if (unresolvedWith.allowRecursion) Some(CTERelationDef.newId) else None
+
+      expressionIdAssigner.pushMapping()
+      queryBlockScopes.push()
+      scopes.pushScope()
+
+      val recursiveCteParams = if (unresolvedWith.allowRecursion) {
+        Some(
+          RecursiveCteParameters(
+            cteId = preallocatedCteIdForRecursive.get,
+            cteName = cteName,
+            maxDepth = maxDepth
+          )
+        )
+      } else {
+        None
+      }
+
+      cteRegistry.pushScope(
+        recursiveCteParameters = recursiveCteParams,
+        isInsideRecursiveCteScope = unresolvedWith.allowRecursion
+      )
+
+      var referencedRecursively = false
+      var recursiveReferenceIds = Set.empty[Long]
+
+      val resolvedCtePlan = try {
+        val plan = resolver.resolve(ctePlan)
+        referencedRecursively = cteRegistry.currentScope.referencedRecursively
+        recursiveReferenceIds = 
cteRegistry.currentScope.enclosingRecursiveReferenceIds
+        plan
+      } finally {
+        cteRegistry.popScope()
+        scopes.popScope()
+        queryBlockScopes.pop()
+        expressionIdAssigner.popMapping()
+      }
+
+      val cteDefinition = if (referencedRecursively) {
+        checkValidRecursiveCTE(resolvedCtePlan)
+        CTERelationDef(
+          resolvedCtePlan,
+          id = preallocatedCteIdForRecursive.get,
+          maxDepth = maxDepth,
+          materialized = cteRelation.materialized
+        )
+      } else {
+        CTERelationDef(resolvedCtePlan, materialized = 
cteRelation.materialized)

Review Comment:
   **Nit (P3):** This branch builds `CTERelationDef(resolvedCtePlan, 
materialized = ...)`, dropping the definition's `MAX RECURSION LEVEL` and 
discarding the id preallocated at line 82. The fixed-point `CTESubstitution` 
builds every definition under `WITH RECURSIVE` with `maxDepth` up front and 
keeps both when it substitutes the body. Reading the code, `WITH RECURSIVE t 
MAX RECURSION LEVEL 10 AS (SELECT 1 AS c) SELECT * FROM t` carries `maxDepth = 
Some(10)` in the fixed-point analyzer and `None` in single-pass, so dual-run 
reports a plan mismatch; only `UnionLoop` reads `maxDepth`, so results are 
unaffected.
   
   Suggested fix: pass `maxDepth` and reuse `preallocatedCteIdForRecursive` 
here as well.
   
   **Verification:**
   - **Regression:** A WITH RECURSIVE definition with MAX RECURSION LEVEL that 
does not reference itself produces no dual-run plan mismatch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ResolverGuard.scala:
##########
@@ -154,17 +183,54 @@ class ResolverGuard(
         checkSort(sort)
       case supervisingCommand: SupervisingCommand =>
         None
+      case setVariable: SetVariable =>
+        checkSetVariable(setVariable)
       case repartition: Repartition =>
         checkRepartition(repartition)
+      case unresolvedHint: UnresolvedHint =>
+        checkUnresolvedHint(unresolvedHint)
+      case resolvedHint: ResolvedHint =>
+        checkResolvedHint(resolvedHint)
       case having: UnresolvedHaving =>
         checkHaving(having)
       case sample: Sample =>
         checkSample(sample)
+      case unresolvedTVF: UnresolvedTableValuedFunction =>
+        checkUnresolvedTableValuedFunction(unresolvedTVF)
+      case unresolvedTVFAliases: UnresolvedTVFAliases =>
+        checkUnresolvedTVFAliases(unresolvedTVFAliases)
+      case nameParameterizedQuery: NameParameterizedQuery =>
+        checkNameParameterizedQuery(nameParameterizedQuery)
+      case posParameterizedQuery: PosParameterizedQuery =>
+        checkPosParameterizedQuery(posParameterizedQuery)
+      case repartitionByExpression: RepartitionByExpression =>
+        checkRepartitionByExpression(repartitionByExpression)
+      case pipeOperator: PipeOperator =>
+        checkPipeOperator(pipeOperator)
+      case pivot: Pivot =>
+        checkPivot(pivot)
+      case unpivot: Unpivot =>
+        checkUnpivot(unpivot)
+      case planWithUnresolvedIdentifier: PlanWithUnresolvedIdentifier =>
+        checkPlanWithUnresolvedIdentifier(planWithUnresolvedIdentifier)
+      case lateralJoin: LateralJoin =>
+        checkLateralJoin(lateralJoin)
+      case unresolvedBinBy: UnresolvedBinBy =>
+        checkBinBy(unresolvedBinBy)
       case _ =>
-        Some(s"${operator.getClass} operator resolution")
+        tryDelegateToGuardExtension(operator)
     }
   }
 
+  /** Try to delegate the guard check to one of the registered 
[[ResolverGuardExtension]]s. */
+  private def tryDelegateToGuardExtension(operator: LogicalPlan): 
Option[String] = {
+    guardExtensions.iterator.map(_.checkOperator(operator, 
tracker)).collectFirst {

Review Comment:
   **Nit (P3):** The iterator is lazy and `GuardExtensionResult` has only 
`Supported` and `NotSupported`, so `collectFirst` always takes the first 
extension's verdict and later extensions are never consulted. A `Supported` 
verdict also returns `None` without checking the operator's children, and the 
extension gets no handle to check them, unlike `ResolverExtension` and 
`ResolutionValidatorExtension`. With two registered extensions, the second 
one's operator is always reported unsupported by the first; an extension 
operator above an unsupported built-in operator passes the guard and fails 
later in resolution, which dual-run reports as a failure unless the error is 
`ExplicitlyUnsupportedResolverFeature`. No in-tree extension implements the 
trait today, but the API is new in this PR.
   
   Suggested fix: add an abstaining result, consult extensions in order until 
one decides (rejecting conflicting claims, as `AMBIGUOUS_RESOLVER_EXTENSION` 
does on the resolver side), and check the children of an extension-supported 
operator or give the extension a child-check callback.
   
   **Verification:**
   - **Behavior:** A guard with two extensions accepts an operator known only 
to the second extension.
   - **Regression:** A plan with an unsupported operator under an 
extension-supported operator is reported unsupported by the guard.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/FunctionResolver.scala:
##########
@@ -73,9 +81,40 @@ class FunctionResolver(
   private val traversals = expressionResolver.getExpressionTreeTraversals
   private val expressionResolutionContextStack =
     expressionResolver.getExpressionResolutionContextStack
+  private val higherOrderFunctionResolver =
+    new HigherOrderFunctionResolver(expressionResolver, functionResolution)
 
   /**
-   * Main method used to resolve an [[UnresolvedFunction]]. It resolves it in 
the following steps:
+   * In case the function is a higher order function, it delegates the 
resolution to
+   * [[HigherOrderFunctionResolver]]. Otherwise, the resolution is done in the 
[[resolveFunction]]
+   * method.
+   * Examples of higher order functions are (resolved by 
[[HigherOrderFunctionResolver]]):
+   *  - `ARRAY_SORT`
+   *  - `MAP_FILTER`
+   *  - `MAP_ZIP_WITH`
+   * Higher order functions take lambda functions as arguments (which are 
handled in the
+   * [[LambdaFunctionResolver]]).
+   * Examples of non-higher order functions are (resolved by 
[[resolveFunction]]):
+   *  - `LOWER`
+   *  - `ROUND`
+   *  - `COALESCE`
+   */
+  override def resolve(unresolvedFunction: UnresolvedFunction): Expression = {
+    val expressionInfo = functionResolution.lookupBuiltinOrTempFunction(
+      nameParts = unresolvedFunction.nameParts,
+      unresolvedFunc = Some(unresolvedFunction)
+    )
+
+    if (expressionInfo.exists(_.getGroup == "lambda_funcs")) {

Review Comment:
   **Nit (P3):** `lookupBuiltinOrTempFunction` accepts system- and 
builtin-qualified names, and the guard accepts the call, so `SELECT 
system.builtin.transform(array(1, 2), x -> x + 1)` is routed here to 
`HigherOrderFunctionResolver`. That resolver calls 
`resolveBuiltinOrTempFunction`, which returns `None` for any multi-part name, 
so, reading the code, resolution fails with `UNRESOLVED_ROUTINE` while the 
fixed-point analyzer returns `[2, 3]`.
   
   Suggested fix: resolve the builtin identifier that the qualified name maps 
to, or go through `functionResolution.resolveFunction` as the fixed-point 
analyzer does. Avoid looking up only the last name part with 
`resolveBuiltinOrTempFunction`, which would let a temporary function named 
`transform` win over an explicitly builtin-qualified call.
   
   **Verification:**
   - **Regression:** Builtin-qualified higher-order function calls resolve in 
single-pass and match the fixed-point plan under dual-run.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ResolutionValidator.scala:
##########
@@ -120,17 +129,34 @@ class ResolutionValidator {
         validateRelation(multiInstanceRelation)
       case supervisingCommand: SupervisingCommand =>
         validateSupervisingCommand(supervisingCommand)
+      case lateralJoin: LateralJoin =>
+        validateLateralJoin(lateralJoin)
+      case pipe: PipeOperator =>
+        validatePipeOperator(pipe)
+      case binBy: BinBy =>
+        validateBinBy(binBy)
+      case setVariable: SetVariable =>
+        validateSetVariable(setVariable)
+      case resolvedHint: ResolvedHint =>
+        validateResolvedHint(resolvedHint)
+      case operator =>
+        tryDelegateToValidatorExtension(operator)

Review Comment:
   **Nit (P3):** `tryDelegateToValidatorExtension` calls every extension with 
`foreach` and ignores the Boolean that `validateOperator` returns, although 
`validatePlan`'s doc says unknown operators are caught by throwing. Before this 
PR the match had no default case, so an unhandled operator failed validation. 
Now such an operator and its whole subtree pass unvalidated and its output is 
never published to the attribute scope, so the gap surfaces either silently or 
as a misleading missing-attribute error in a parent. 
`ANALYZER_SINGLE_PASS_RESOLVER_VALIDATION_ENABLED` defaults to true, so this 
applies to every single-pass mode; no in-tree operator reaches the default case 
today.
   
   Suggested fix: fail with an internal error naming the operator when no 
extension returns true, e.g. 
`validatorExtensions.exists(_.validateOperator(operator, this))` (note that 
`exists` stops at the first extension that handles it).
   
   **Verification:**
   - **Regression:** Validation of a plan with an operator unknown to the 
validator and its extensions fails with an internal error.
   - **Behavior:** An extension that returns true for its operator still 
validates it without errors.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ViewResolver.scala:
##########
@@ -98,12 +101,20 @@ class ViewResolver(
           createSparkVersion = unresolvedView.desc.createVersion)
       ) {
         checkResolverGuard(unresolvedView)
+        val planPreprocessor =
+          new PlanPreprocessor(resolver, 
resolveExpressionIdentifiersInRootScope = false)

Review Comment:
   **Nit (P3):** HybridAnalyzer's preprocessed-plan check runs with 
`resolveExpressionIdentifiersInRootScope = true` so that the guard sees the 
functions expression IDENTIFIERs name, but this view-body check runs with it 
off, leaving `ExpressionWithUnresolvedIdentifier` unexpanded; the guard then 
checks only its name and arguments. Reading the code, after `CREATE VIEW v AS 
SELECT IDENTIFIER(concat('ex', 'plode'))(array(1, 2))`, `SELECT * FROM v` 
builds `explode` during single-pass resolution, the Project stays unresolved 
and resolution throws an internal error, while the fixed-point analyzer returns 
two rows: dual-run fails, tentative mode falls back and forced mode fails. 
Guard-rejected builtins such as generators, `from_json`, `current_user` or the 
window functions are affected; UDFs and catalog functions still raise 
`ExplicitlyUnsupportedResolverFeature` in `FunctionResolver`. No session 
variable is needed.
   
   Suggested fix: run this guard-time preprocessing with root-scope 
materialization on, and turn a preprocessing failure into 
`ExplicitlyUnsupportedResolverFeature` for the view body, as HybridAnalyzer 
does.
   
   **Verification:**
   - **Regression:** Querying a persistent view and a temporary view whose 
bodies call explode through IDENTIFIER(concat(...)) returns the fixed-point 
result under dual-run.
   - **Behavior:** Views without expression IDENTIFIERs, and views that use 
IDENTIFIER for supported functions, keep resolving in single-pass.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/InsertsMetadataColumns.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * 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 java.util.{HashMap, HashSet}
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import org.apache.spark.sql.catalyst.expressions.{Attribute, ExprId, 
NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  ExposesMetadataColumns,
+  Join,
+  LeafNode,
+  LogicalPlan,
+  Project,
+  SubqueryAlias,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Mixed into [[Resolver]] to provide metadata column insertion into the plan 
tree. Called from
+ * [[Resolver.insertReferencedMetadataColumnsForOperator]] after each operator 
resolves.
+ *
+ * Metadata columns (e.g. `_metadata`) originate from leaf operators like 
[[LogicalRelation]] or
+ * [[DataSourceV2Relation]] and are stored in the [[NameScope]]'s hidden 
output, identified by the
+ * `__metadata_col` attribute marker ([[Attribute.isMetadataCol]]). When an 
operator's expressions
+ * reference a metadata column, this trait inserts the column into the plan 
tree below by
+ * propagating it downward through intermediate operators until reaching the 
leaf node that owns it.
+ *
+ * The propagation descends through passthrough operators (e.g. [[Filter]], 
[[Sort]]) and [[Join]]
+ * nodes, extends [[Project]] expression lists as needed, and calls
+ * [[ExposesMetadataColumns.withMetadataColumns]] on leaf nodes. [[Aggregate]] 
is a propagation
+ * barrier, matching the legacy analyzer where `Aggregate.metadataOutput` is 
`Nil`. For [[Join]],
+ * metadata columns are sent to both children - only the child whose leaf owns 
the metadata
+ * column's [[ExprId]] will actually insert it; the other child's subtree is a 
no-op.
+ *
+ * {{{
+ * -- Project: _metadata resolved from hidden output, inserted into 
LogicalRelation output.
+ * SELECT _metadata FROM nation
+ *
+ * -- Filter: _metadata.file_size resolved from hidden output in WHERE 
condition.
+ * SELECT n_nationkey FROM nation WHERE _metadata.file_size > 0
+ *
+ * -- Aggregate: _metadata referenced in grouping expression.
+ * SELECT count(*) AS cnt FROM nation GROUP BY _metadata.file_block_start
+ *
+ * -- Join: _metadata propagated to both children, only the owning leaf 
inserts it.
+ * SELECT a._metadata FROM nation a JOIN region b ON a.n_regionkey = 
b.r_regionkey
+ * }}}
+ */
+trait InsertsMetadataColumns extends SQLConfHelper {
+
+  /**
+   * Checks if the current operator's expression resolution referenced any 
metadata columns, and
+   * if so, inserts them into the resolved plan tree by propagating down to 
the leaf nodes.
+   *
+   * Following the legacy [[AddMetadataColumns]] rule: after propagating 
metadata columns into the
+   * children (which adds them to leaf outputs), if the operator's output 
schema changed (e.g. a
+   * [[Filter]] whose child now exposes `_metadata`), we wrap the operator 
with a [[Project]] that
+   * projects only the original output columns. This preserves the operator's 
output schema while
+   * making the metadata columns available internally.
+   *
+   * `referencedMetadataColumns` is populated during expression resolution by 
cross-referencing
+   * referenced attributes with [[NameScope.hiddenOutput]]. This avoids 
reading from
+   * [[NameScope.hiddenOutput]] directly, which may have already been stripped 
by operator resolvers
+   * that call [[NameScopeStack.overwriteOutputAndExtendHiddenOutput]] with
+   * `stripMetadataFromHiddenOutput = true`. `currentOutput` is the operator's 
output that the
+   * wrapping [[Project]] must preserve. `isTopLevel` is `true` when the 
operator is the plan's
+   * top-level operator (carries [[ResolverTag.TOP_LEVEL_OPERATOR]] on its 
unresolved node); when
+   * so, the wrapping [[Project]] preserves only the original output, without 
exposing the metadata
+   * columns for a (nonexistent) parent to reference.
+   */
+  protected def insertReferencedMetadataColumnsForOperator(
+      resolvedPlan: LogicalPlan,
+      referencedMetadataColumns: HashMap[ExprId, Attribute],
+      currentOutput: Seq[Attribute],
+      isTopLevel: Boolean): LogicalPlan = {
+    if (referencedMetadataColumns.isEmpty) {
+      resolvedPlan
+    } else {
+      val metadataColumns = referencedMetadataColumns.values().asScala.toSeq
+
+      val updatedChildren = resolvedPlan.children.map { child =>
+        val (updatedChild, _) = insertReferencedMetadataColumnsIntoChild(
+          operator = child,
+          metadataColumns = metadataColumns
+        )
+        updatedChild
+      }
+
+      val updatedPlan = resolvedPlan.withNewChildren(updatedChildren)
+      if (updatedPlan eq resolvedPlan) {
+        resolvedPlan
+      } else {
+        resolvedPlan match {
+          case _: Project | _: Aggregate =>
+            updatedPlan
+          case _ =>
+            val metadataColumnsToPreserve =

Review Comment:
   **Nit (P3):** The preserving Project uses every referenced metadata column, 
not only those the rebuilt operator outputs, and it is built whenever insertion 
changed the operator's children. Reading the code, for `SELECT * FROM a LEFT 
SEMI JOIN b ON a.id = b.id AND b._metadata.file_size > 0`, `b._metadata` is 
inserted into `b`'s scan and then re-exposed in `Project(a.* ++ b._metadata)` 
over a join that outputs only the left side, so validation fails with 
`MISSING_ATTRIBUTES`. The fixed-point analyzer adds the column to the right 
leaf and, since the join's output is unchanged, adds no Project at all.
   
   Suggested fix: preserve only metadata columns the rebuilt operator outputs, 
and wrap only when its output actually changed (`sameOutput`, as 
`AddMetadataColumns` does); otherwise `Project(currentOutput, join)` still 
differs from the fixed-point plan.
   
   **Verification:**
   - **Regression:** Left semi and left anti joins with right-side metadata in 
the condition resolve in single-pass and match the fixed-point plan under 
dual-run.
   - **Behavior:** A Filter on a metadata column below a Project that also 
selects it keeps resolving.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala:
##########
@@ -1168,34 +1377,74 @@ class NameScopeStack(
    * }
    * }}}
    *
-   * @param isSubqueryRoot Indicates that the current scope is a root of a 
subquery. This is used by
-   *   [[NameScopeStack.resolveMultipartName]] to detect the nearest outer 
scope.
+   * @param scopeType Indicates the type of this scope. See [[NameScopeType]] 
for details.
    */
-  def pushScope(isSubqueryRoot: Boolean = false): Unit = {
-    stack.push(new NameScope(isSubqueryRoot = isSubqueryRoot, planLogger = 
planLogger))
+  def pushScope(scopeType: NameScopeType = NameScopeType.Intermediate): Unit = 
{
+    stack.push(
+      new NameScope(
+        scopeType = scopeType,
+        queryBlockScope = queryBlockScopes.current,
+        planLogger = planLogger
+      )
+    )
   }
 
   /**
    * After finishing the resolution after [[pushScope]], the caller needs to 
call [[popScope]] to
    * clear the stack. We propagate `hiddenOutput`, `availableAliases` upwards 
because of name
-   * resolution by overwriting their current values with the popped ones. This 
is not done in case
-   * [[pushScope]] and [[popScope]] were called in the context of subquery 
resolution (which is
-   * indicated by `isSubqueryRoot` flag), because we don't want to overwrite 
the existing
-   * `hiddenOutput` of the main plan.
+   * resolution by overwriting their current values with the popped ones, 
together with
+   * `qualifiedAccessOnlyOutputIds` that describe `hiddenOutput`. This is only 
done for
+   * [[NameScopeType.Intermediate]] scopes, which represent operators within 
the same query block
+   * (e.g., nested [[Project]] inside [[Filter]]) whose accumulated resolution 
state must be
+   * visible to subsequent sibling operators. [[NameScopeType.SubqueryRoot]] 
and
+   * [[NameScopeType.Opaque]] scopes do not propagate any state to the parent 
because they
+   * represent independent query blocks whose internal state should not leak 
out.
    */
   def popScope(): Unit = {
     val childScope = stack.pop()
-    if (!stack.isEmpty && !childScope.isSubqueryRoot) {
+    if (!stack.isEmpty && childScope.scopeType == NameScopeType.Intermediate) {
       val currentScope = stack.pop()
       stack.push(
         currentScope.overwrite(
           hiddenOutput = Some(childScope.hiddenOutput),
-          availableAliases = Some(childScope.availableAliases)
+          availableAliases = Some(childScope.availableAliases),
+          qualifiedAccessOnlyOutputIds = 
Some(childScope.qualifiedAccessOnlyOutputIds),
+          planIdTargetRegistry = Some(childScope.planIdTargetRegistry)
         )
       )
     }
   }
 
+  /**
+   * Move existing plan-id targets through the current operator and register 
the operator's tag.
+   *
+   * The plan id is read from `unresolvedOperator` because it is the 
authoritative carrier of
+   * [[LogicalPlan.PLAN_ID_TAG]]. Some operators (e.g. NATURAL/USING joins) 
resolve into a new node
+   * that already carries its own tag, and `copyTagsFrom` will not overwrite 
it, so the resolved
+   * node may not have the plan id even though the unresolved one does.
+   */
+  def updatePlanIdTargetsForCurrentOperator(unresolvedOperator: LogicalPlan): 
Unit = {
+    val registry = current.planIdTargetRegistry
+    val planId = unresolvedOperator.getTagValue(LogicalPlan.PLAN_ID_TAG)
+    if (!registry.isEmpty || planId.isDefined) {

Review Comment:
   **Nit (P3):** `updatePlanIdTargetsForCurrentOperator` runs after every 
operator once the registry is non-empty or the operator carries a plan id, and 
it advances every recorded target through that operator; targets are only 
flagged unreachable, never removed. Spark Connect tags every relation with a 
plan id, so for a chain of N `withColumn` calls operator k updates about k 
targets of O(k) attributes each, roughly N^3/6 attribute updates in total 
(about 2*10^7 for N = 500), by the review's estimate from the code. This is 
paid during single-pass resolution even when the query has no `df(col)` 
reference, and with the default `strictDataFrameColumnResolution` the guard 
rejects every plan-id-tagged reference, so in dual-run and tentative mode the 
registry is never read at all. The default fixed-point path is unaffected.
   
   **Recommended change:** Decide once per top-level resolution whether any 
plan-id-tagged reference (UnresolvedAttribute or UnresolvedDataFrameStar 
carrying a plan id, including inside subquery and replacement expressions) can 
be resolved, and skip target registration and advancement entirely when none 
can. Compute this either with an extra linear walk over the unresolved plan's 
expressions (the plan id is a tag, not a tree pattern, so the existing 
pattern-pruned PlanPreprocessor traversal cannot find it) or, more cheaply, 
from the fact that the resolver guard ran with 
spark.sql.analyzer.strictDataFrameColumnResolution on, since the guard then 
rejects every plan-id-tagged reference; forced mode skips the guard and needs 
the walk. Compute the flag on the top-level plan before any view body is 
preprocessed and never reset it. Stop advancing targets whose attributes are 
all unreachable, but keep them for lookups. Add single-pass resolver tests and 
a micro-benchmark-style check for a de
 ep chain of plan-id-tagged projections with and without plan-id references.
   
   **Why this works:** Plans that cannot consume plan-id targets do no registry 
work, and frozen targets stop costing per-operator updates; plans with live 
plan-id references keep today's targets, so their results and errors are 
unchanged.
   
   **Scope:** Bound plan-id bookkeeping by the references that need it.
   
   **Compatibility:** Plan-id resolution results and errors are unchanged for 
every plan.
   
   **Risks:** A plan-id reference missed by the walk would fail to resolve; 
this is mitigated by walking all expressions of the top-level plan, and is 
rollback-safe by forcing maintenance on. Plans that do contain plan-id 
references, such as a deep withColumn chain followed by a df(col) reference, 
keep the current cost, because no target becomes unreachable there.
   
   **Constraints:** Targets whose attributes are still reachable must keep 
their depth and ambiguity information unchanged. Unreachable targets must stay 
visible to plan-id lookups, so fallback to name resolution and ambiguity errors 
are unchanged.
   
   **Exclusions:**
   - Changing plan-id resolution semantics or error messages.
   
   **Success:** Resolving a plan with no resolvable plan-id-tagged references 
performs no plan-id registry work. Plan-id-tagged references keep resolving to 
the same targets and errors as before, including through views.
   
   **Verification:**
   - **Behavior:** Single-pass resolution of a deep chain of plan-id-tagged 
projections without plan-id references registers no targets.
   - **Compatibility:** Existing DataFrame plan-id resolution cases, including 
spark.table on a view combined with another DataFrame's column, joins, unions 
and references that fall back to name resolution, resolve to the same 
attributes and errors as before.
   - **Regression:** Resolution time for a chain of several hundred tagged 
withColumn projections without plan-id references grows linearly with chain 
length.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/SetOperationLikeResolver.scala:
##########
@@ -450,6 +546,28 @@ class SetOperationLikeResolver(resolver: Resolver, 
expressionResolver: Expressio
     }
   }
 
+  /**
+   * Computes the [[PlanIdTargetRegistry]] that this set operation exposes to 
enclosing operators.
+   *
+   * For [[Intersect]] and [[Except]] the children's registries are merged and 
propagated upwards.
+   * The generic advance step run after this operator resolves then filters 
those targets by the
+   * merged output, which carries only the first child's expression ids, so 
only the first child's
+   * targets remain reachable. [[Union]] is a leaf for plan-id resolution: its 
children's targets
+   * are discarded, so a plan-id-tagged reference to a node beneath the union 
is not visible above
+   * it and fails with `CANNOT_RESOLVE_DATAFRAME_COLUMN`.
+   */
+  private def mergePlanIdTargetRegistry(
+      unresolvedOperator: LogicalPlan,
+      childScopes: Seq[NameScope]): PlanIdTargetRegistry = {
+    val registry = new PlanIdTargetRegistry
+    unresolvedOperator match {
+      case _: Union =>

Review Comment:
   **Nit (P3):** `mergePlanIdTargetRegistry` gives a Union an empty registry, 
so an `UnresolvedDataFrameStar` for a DataFrame below the union has no target 
above it. The fixed-point analyzer treats Union as a leaf only for column 
lookups; `resolveDataFrameStarRecursively` recurses into its children and 
accepts the star when its attributes are in the union's output. Reading the 
code, with `spark.sql.analyzer.strictDataFrameColumnResolution=false` (as some 
Connect parity suites use), `df1.union(df2).select(df1['*'])` fails in 
single-pass with `CANNOT_RESOLVE_DATAFRAME_COLUMN` but succeeds in the 
fixed-point analyzer; with the default setting the guard rejects 
`UnresolvedDataFrameStar`, so nothing diverges.
   
   Suggested fix: keep the children's targets above a Union for star resolution 
only (column lookups still see no target), and record star ambiguity per plan 
id at the set-operation boundary, because the fixed-point analyzer rejects 
`df1.union(df1).select(df1['*'])` as ambiguous; apply the same rule to 
Intersect and Except.
   
   **Verification:**
   - **Regression:** With strict DataFrame column resolution disabled, a 
DataFrame star for the first union child resolves in single-pass and matches 
the fixed-point plan.
   - **Compatibility:** A DataFrame star for the second union child, a star 
over a self-union, and a plan-id column beneath the union fail with the same 
errors as the fixed-point analyzer.



##########
sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/ResolverGuardSuite.scala:
##########
@@ -444,31 +468,486 @@ class ResolverGuardSuite extends ResolverGuardSuiteBase {
     }
   }
 
-  test("Higher-order functions are unsupported") {
+  test("Higher-order functions") {
+    checkResolverGuard("SELECT transform(array(1, 2), x -> x + 1)")
+    checkResolverGuard("SELECT filter(array(1, 2), x -> x > 1)")
+    checkResolverGuard("SELECT aggregate(array(1, 2), 0, (acc, x) -> acc + x)")
+  }
+
+  test("Metadata column star target") {
+    withTable("t") {
+      sql("CREATE TABLE t (col INT) USING parquet")
+      checkResolverGuard("SELECT _metadata.* FROM t")
+    }
+  }
+
+  test("COALESCE with star expression") {
     checkResolverGuard(
-      "SELECT transform(array(1, 2), x -> x + 1)",
-      unsupportedReason = Some("unsupported function transform")
+      "SELECT COALESCE(TA.*) FROM VALUES(1, 2) AS TA(c1, c2), VALUES('a', 'b') 
AS TB(ca, cb)"
+    )
+  }
+
+  test("CreateArray expression") {
+    checkResolverGuard("SELECT array(1, 2, 3)")
+    checkResolverGuard("SELECT array()")
+    checkResolverGuard("SELECT array(1, 2.0, '3')")
+
+    val plan = Project(
+      Seq(UnresolvedAlias(CreateArray(Seq(Literal(1), Literal(2), 
Literal(3))))),
+      OneRowRelation()
     )
+    checkResolverGuard(plan = plan, unsupportedReason = None)
+  }
+
+  test("DISTRIBUTE BY") {
     checkResolverGuard(
-      "SELECT filter(array(1, 2), x -> x > 1)",
-      unsupportedReason = Some("unsupported function filter")
+      plan = spark
+        .sql("SELECT col1, col2 FROM values(1,2) DISTRIBUTE BY col1")
+        .queryExecution
+        .logical,
+      unsupportedReason = None
+    )
+  }
+
+  test("GetMapValue") {
+    val df = Seq(Map("key" -> 1)).toDF("m").select($"m")
+    val mapAttribute = df.queryExecution.analyzed.output.head
+    val plan = Project(
+      projectList = Seq(Alias(GetMapValue(mapAttribute, Literal("key")), 
"value")()),
+      child = df.queryExecution.logical
+    )
+
+    checkResolverGuard(plan = plan, unsupportedReason = None)
+  }
+
+  test("GetStructField") {
+    val df = Seq((1, 2)).toDF("a", "b").select(struct($"a", $"b").as("s"))
+    val structAttribute = df.queryExecution.analyzed.output.head
+    val plan = Project(
+      projectList = Seq(Alias(GetStructField(structAttribute, 0, Some("a")), 
"field")()),
+      child = df.queryExecution.logical
     )
+
+    checkResolverGuard(plan = plan, unsupportedReason = None)
+  }
+
+  test("Grouping analytics") {
+    val testCases = Seq(
+      "SELECT col1 FROM VALUES(1) GROUP BY CUBE(col1)",
+      "SELECT col1 FROM VALUES(1) GROUP BY ROLLUP(col1)",
+      "SELECT col1 FROM VALUES(1) GROUP BY GROUPING SETS((col1), ())"
+    )
+
+    testCases.foreach(query => checkResolverGuard(query))
+  }
+
+  test("IDENTIFIER clause") {
+    checkResolverGuard("SELECT IDENTIFIER('c' || '1') FROM VALUES(1) AS T(c1)")
+    withTable("t1") {
+      spark.sql("CREATE TABLE t1 (c1 INT) USING parquet")
+      checkResolverGuard("SELECT * FROM IDENTIFIER('t' || '1')")
+    }
+  }
+
+  test("IDENTIFIER clause with functions") {
+    checkResolverGuard("SELECT IDENTIFIER(concat('c', '1')) FROM VALUES(1) AS 
T(c1)")
+    withTable("t1") {
+      spark.sql("CREATE TABLE t1 (c1 INT) USING parquet")
+      checkResolverGuard("SELECT * FROM IDENTIFIER(concat('t', '1'))")
+    }
+  }
+
+  test("IDENTIFIER clause with variable is supported") {
+    withTable("t1") {
+      spark.sql("CREATE TABLE t1 (c1 INT) USING csv")
+      withSessionVariable("tbl_name") {
+        spark.sql("DECLARE tbl_name STRING DEFAULT 't1'")
+        checkResolverGuard("SELECT * FROM IDENTIFIER(tbl_name)")
+      }
+    }
+    withSessionVariable("col_name") {
+      spark.sql("DECLARE col_name STRING DEFAULT 'c1'")
+      checkResolverGuard("SELECT IDENTIFIER(col_name) FROM VALUES(1) AS T(c1)")
+    }
+  }
+
+  test("IDENTIFIER expressions use standard function support checks") {
+    checkResolverGuardOnly("SELECT IDENTIFIER(max('c1')) FROM VALUES(1) AS 
T(c1)")
+    checkResolverGuardOnly("SELECT IDENTIFIER((SELECT 'c1')) FROM VALUES(1) AS 
T(c1)")
+    checkResolverGuardOnly(
+      "SELECT IDENTIFIER(WINDOW('c1', '1 minute')) FROM VALUES(1) AS T(c1)",
+      unsupportedReason = Some("unsupported function window")
+    )
+    withSqlFunction("identifier_name") {
+      sql("CREATE FUNCTION identifier_name() RETURNS STRING RETURN 'c1'")
+      checkResolverGuardOnly(
+        "SELECT IDENTIFIER(identifier_name()) FROM VALUES(1) AS T(c1)",
+        unsupportedReason = Some("non-builtin function")
+      )
+    }
+  }
+
+  test("IDENTIFIER subquery remains guard-supported") {
+    checkResolverGuardOnly("SELECT * FROM IDENTIFIER((SELECT 't'))")
+  }
+
+  test("JSON_TABLE") {
+    // JSON_TABLE is parsed into a [[Generate]] operator, which is not 
supported yet.
     checkResolverGuard(
-      "SELECT aggregate(array(1, 2), 0, (acc, x) -> acc + x)",
-      unsupportedReason = Some("unsupported function aggregate")
+      "SELECT * FROM JSON_TABLE('{\"items\":[1]}', '$.items[*]' " +
+      "COLUMNS (value INT PATH '$'))",
+      Some("class org.apache.spark.sql.catalyst.plans.logical.Generate 
operator resolution")
     )
   }
 
-  test("Star target with unsupported metadata attribute name") {
+  test("LATERAL JOIN") {
+    val lateralJoinQuery =
+      "SELECT * FROM (VALUES (1, 2)) AS t1(c1, c2) JOIN LATERAL (SELECT c1 + 
c2 AS c3) ON c2 = c3"
+    checkResolverGuard(lateralJoinQuery)
+  }
+
+  test("LIMIT ALL") {
+    checkResolverGuard(
+      """
+        WITH RECURSIVE r AS (
+          SELECT 0 AS level
+          UNION ALL
+          SELECT level + 1 FROM r WHERE level < 9
+        )
+        SELECT * FROM r LIMIT ALL;
+        """
+    )
+  }
+
+  test("Lambda variable") {
+    val testCases = Seq(
+      "SELECT array_sort(array(2, 1), (p1, p2) -> IF(p1 > p2, 1, 0))",
+      "SELECT transform(array(2, 1), x -> x * 2)",
+      "SELECT filter(array(2, 1), x -> x > 0)"
+    )
+
+    testCases.foreach(query => checkResolverGuard(query))
+  }
+
+  test("Metadata column resolution") {
     withTable("t") {
-      sql("CREATE TABLE t (col INT) USING parquet")
+      spark.sql("CREATE TABLE t (col INT) USING csv")
+      checkResolverGuard("SELECT _metadata FROM t")
+    }
+  }
+
+  test("NamePlaceholder") {
+    val query = "SELECT struct(*) FROM VALUES (1)"
+    checkResolverGuard(query)
+  }
+
+  test("Named argument expression") {
+    val query = "SELECT mask('ABCabc123', lowerChar => 'q')"
+    checkResolverGuard(query)
+  }
+
+  test("Natural join with multiple resolution passes") {
+    val df1 = Seq(1 -> "a").toDF("k", "v").as("left")
+    val df2 = Seq(1 -> "b").toDF("k", "v").as("right")
+    val dfQuery = df1
+      .join(df2, "k", "outer")
+      .withColumn("left_all", struct($"left.k"))
+      .withColumn("right_all", struct($"right.k"))
+    checkResolverGuard(
+      plan = dfQuery.queryExecution.logical,
+      unsupportedReason = Some("NaturalJoin second resolution")
+    )
+  }
+
+  test("PLAN_ID_TAG with set operation") {
+    val child = spark.sessionState.sqlParser.parsePlan(
+      "SELECT col1 FROM VALUES (1) UNION ALL SELECT col1 FROM VALUES (2)"
+    )
+    val planId: Long = 0
+    child.setTagValue(LogicalPlan.PLAN_ID_TAG, planId)
+    val attribute = UnresolvedAttribute("col1")
+    attribute.setTagValue(LogicalPlan.PLAN_ID_TAG, planId)
+    val plan = Project(Seq(attribute), child)
+
+    withSQLConf(SQLConf.STRICT_DATAFRAME_COLUMN_RESOLUTION.key -> "false") {
+      checkResolverGuard(plan, unsupportedReason = None)
+    }
+  }
+
+  test("Pivot") {
+    checkResolverGuard(
+      plan = spark
+        .sql("SELECT * FROM VALUES (2024,1) PIVOT (sum(col1) FOR col2 IN (1 AS 
q1))")
+        .queryExecution
+        .logical,
+      unsupportedReason = None
+    )
+  }
+
+  test("Unpivot") {
+    checkResolverGuard(
+      plan = spark
+        .sql("SELECT * FROM VALUES (2024,1) UNPIVOT (col1 FOR col2 IN (col1 AS 
`Jan-Mar`))")
+        .queryExecution
+        .logical,
+      unsupportedReason = None
+    )
+  }
+
+  test("Recursive CTE") {
+    val query =
+      """
+        WITH RECURSIVE r AS (
+          SELECT 0 AS level
+          UNION ALL
+          SELECT level + 1 FROM r WHERE level < 9
+        )
+        SELECT * FROM r;
+      """
+
+    checkResolverGuard(query)
+  }
+
+  test("SQL pipe aggregate with ordinals") {
+    checkResolverGuard("values (3, 4) as tab(x, y) |> aggregate sum(y) group 
by 1")
+  }
+
+  test("SQL pipe syntax") {
+    withTable("t") {
+      spark.sql("CREATE TABLE t (x INT, y STRING) USING CSV")
       checkResolverGuard(
-        "SELECT _metadata.* FROM t",
-        unsupportedReason = Some("unsupported attribute name '_metadata'")
+        """
+          | FROM t AS t_alias
+          | |> SELECT t_alias.x as tx, t_alias.y as ty
+          | |> WHERE ty = 'def'
+          | |> SELECT tx
+          |""".stripMargin
       )
     }
   }
 
+  test("Star target with columns") {
+    val df1 = Seq(1 -> "a").toDF("k", "v").as("left")
+    val df2 = df1.withColumn("left_duplicates", struct($"left.*"))
+    checkResolverGuard(plan = df2.queryExecution.logical, None)
+  }
+
+  test("Star target with except") {
+    checkResolverGuard("SELECT * EXCEPT(col2) FROM VALUES(1,2)")
+  }
+
+  test("Star with metadata target in aggregate") {
+    withTable("t") {
+      spark.sql("CREATE TABLE t (col INT) USING csv")
+      checkResolverGuard("SELECT _metadata.* FROM t GROUP BY ALL")
+    }
+  }
+
+  test("Streaming relation") {
+    withTable("t1") {
+      spark.sql("CREATE TABLE t1 USING parquet AS SELECT * FROM VALUES (1)")
+
+      checkResolverGuard(
+        "SELECT * FROM STREAM t1",
+        unsupportedReason = Some(
+          "class org.apache.spark.sql.catalyst.analysis.NamedStreamingRelation 
operator resolution"
+        )
+      )
+    }
+  }
+
+  test("TVFs resolution") {
+    checkResolverGuard("SELECT * FROM range(10)")
+    checkResolverGuard(
+      "SELECT * FROM python_worker_logs()",
+      unsupportedReason = Some("unsupported table valued function 
python_worker_logs")
+    )
+
+    val generatorTableValuedFunctions = Seq(
+      "collations" -> "SELECT * FROM collations()",
+      "explode" -> "SELECT * FROM explode(array(1,2,3))",
+      "explode_outer" -> "SELECT * FROM explode_outer(array())",
+      "inline" -> "SELECT * FROM inline(array(struct(1, 'a')))",
+      "inline_outer" -> "SELECT * FROM inline_outer(array(struct(1, 'a')))",
+      "json_tuple" -> "SELECT * FROM json_tuple('{\"a\":1}', 'a')",
+      "posexplode" -> "SELECT * FROM posexplode(array(1,2,3))",
+      "posexplode_outer" -> "SELECT * FROM posexplode_outer(array())",
+      "sql_keywords" -> "SELECT * FROM sql_keywords()",
+      "stack" -> "SELECT * FROM stack(2, 1, 2, 3)",
+      "variant_explode" -> "SELECT * FROM 
variant_explode(parse_json('[1,2,3]'))",
+      "variant_explode_outer" -> "SELECT * FROM 
variant_explode_outer(parse_json('[]'))"
+    )
+    generatorTableValuedFunctions.foreach { case (name, query) =>
+      checkResolverGuard(
+        query,
+        unsupportedReason = Some(s"generator table valued function $name")
+      )
+    }
+  }
+
+  test("table valued function with alias") {
+    checkResolverGuard("SELECT * FROM range(10) AS my_table(r)")
+  }
+
+  test("multi-part table valued function name") {
+    checkResolverGuard(
+      "SELECT * FROM catalog.schema.range(10)",
+      unsupportedReason = Some("multi-part table valued function name")
+    )
+  }
+
+  test("streaming table valued function") {
+    // Streaming TVFs are wrapped in NamedStreamingRelation for source naming 
support,
+    // so the resolver guard hits that wrapper first before the underlying TVF.
+    checkResolverGuard(
+      "SELECT * FROM STREAM range(10)",
+      unsupportedReason = Some(
+        "class org.apache.spark.sql.catalyst.analysis.NamedStreamingRelation 
operator resolution"
+      )
+    )
+  }
+
+  test("user-defined table valued function") {
+    withSqlFunction("custom_tvf") {
+      sql("CREATE FUNCTION custom_tvf() RETURNS TABLE(x INT) RETURN SELECT 1 
AS x")
+      checkResolverGuard(
+        "SELECT * FROM custom_tvf()",
+        unsupportedReason = Some("UDTF")
+      )
+    }
+  }
+
+  test("Temp variables") {
+    checkResolverGuard("SELECT 1")
+    withTempVariable("temp_variable") {
+      checkResolverGuard("SELECT temp_variable")
+      checkResolverGuard("SELECT 1")
+    }
+  }
+
+  test("Scripting variables") {
+    val compoundBody = spark.sessionState.sqlParser.parsePlan("""
+      BEGIN
+      SELECT 1;
+      END
+      """).asInstanceOf[CompoundBody]
+    withSqlScriptingContextManager(spark, compoundBody) { _ =>
+      checkResolverGuard("SELECT 1")
+      withScriptingVariable("scripting_variable", "value") {
+        checkResolverGuard("SELECT scripting_variable")
+        checkResolverGuard("SELECT 1")
+      }
+    }
+  }
+
+  test("SET VARIABLE") {
+    withSessionVariable("set_variable_target") {
+      sql("DECLARE VARIABLE set_variable_target INT DEFAULT 0")
+      checkResolverGuard("SET VAR set_variable_target = 1")
+      checkResolverGuard("SET VAR (set_variable_target) = (SELECT col1 FROM 
VALUES (2))")
+    }
+  }
+
+  test("SET VARIABLE scripting targets") {
+    val compoundBody = spark.sessionState.sqlParser.parsePlan("""
+      BEGIN
+      SELECT 1;
+      END
+      """).asInstanceOf[CompoundBody]
+    withSqlScriptingContextManager(spark, compoundBody) { _ =>
+      withScriptingVariable("set_variable_target", "value") {
+        checkResolverGuardOnly("SET VAR set_variable_target = 'other_value'")
+      }
+    }
+  }
+
+  gridTest("SET VARIABLE with an unknown target")(
+    Seq(
+      "SET VAR missing_set_variable_target = 1",
+      "SET VAR missing_set_variable_target = source_variable")) { statement =>
+    checkResolverGuardOnly(statement)
+  }
+
+  test("SET VARIABLE rejects nested raw and preprocessed CTE sources") {
+    withSessionVariable("set_variable_target") {
+      sql("DECLARE VARIABLE set_variable_target INT")
+      val parsedPlan = spark.sessionState.sqlParser.parsePlan(
+        "SET VAR (set_variable_target) = " +
+          "(SELECT value FROM " +
+          "(WITH source(value) AS (VALUES(1)) SELECT value FROM source) 
nested_source)")
+      val preprocessedPlan = new PlanPreprocessor(
+        resolver = new Resolver(spark.sessionState.catalogManager),
+        resolveExpressionIdentifiersInRootScope = 
true).substitutePlan(parsedPlan)
+      val unsupportedReason = Some("SET VARIABLE with a CTE source")
+
+      checkResolverGuard(parsedPlan, unsupportedReason)
+      checkResolverGuard(preprocessedPlan, unsupportedReason)
+    }
+  }
+
+  test("EXECUTE IMMEDIATE is unsupported") {
+    val unsupportedReason = Some(
+      "class org.apache.spark.sql.catalyst.analysis.UnresolvedExecuteImmediate 
" +
+      "operator resolution"
+    )
+    checkResolverGuard("EXECUTE IMMEDIATE 'SELECT 1'", unsupportedReason)
+    withSessionVariable("execute_immediate_target") {
+      sql("DECLARE VARIABLE execute_immediate_target INT")
+      checkResolverGuard(
+        "EXECUTE IMMEDIATE 'SELECT 1' INTO execute_immediate_target",
+        unsupportedReason
+      )
+    }
+  }
+
+  test("Positional parameters") {

Review Comment:
   **Nit (P3):** Outside legacy mode `SparkSession.sql` binds the markers in 
the parser and returns a plan without `PosParameterizedQuery`, so the first 
assertion checks a plain plan; in legacy mode the unbound `PosParameter` 
markers make the guard reject the plan. Neither path reaches what the guard 
accepts and `PosParameterizedQueryResolver` resolves: a `PosParameterizedQuery` 
over a `SupervisingCommand` such as EXPLAIN, or over a child without markers. 
No other test, golden file or Connect path produces such a plan, so the new 
resolver is untested.
   
   Suggested fix: with `spark.sql.legacy.parameterSubstitution.constantsOnly` 
enabled, check `spark.sql("EXPLAIN SELECT ?", Array(1))` (plus the DESCRIBE 
QUERY and nested EXPLAIN variants) and `spark.sql("SELECT 1", Array(1))`, and 
run the resolution cases under dual-run so the plans are compared with the 
fixed-point analyzer's.
   
   **Verification:**
   - **Behavior:** With legacy parameter substitution enabled, a 
PosParameterizedQuery over EXPLAIN and one over a query without markers are 
accepted by the guard and resolve under dual-run without a mismatch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/Resolver.scala:
##########
@@ -804,13 +1073,36 @@ class Resolver(
 
     operatorResolutionContextStack.current.baseOperator match {
       case Some(baseOperator) =>
-        validateOperatorResolution(baseOperator)
-        validateInvalidExpressions(baseOperator)
+        val baseOperatorToValidate = 
baseOperatorInResolvedPlan(resolvedOperator, baseOperator)
+        validateOperatorResolution(baseOperatorToValidate)
+        validateInvalidExpressions(baseOperatorToValidate)
       case None =>
         validateInvalidExpressions(resolvedOperator)
     }
   }
 
+  /**
+   * The [[OperatorResolutionContext.baseOperator]] recorded by an operator 
resolver is the operator
+   * as it stood before [[insertReferencedMetadataColumnsForOperator]] ran. A 
[[LateralJoin]] is
+   * resolved without wrapping itself in a [[Project]], so when a metadata 
column is referenced in
+   * its condition, insertion rebuilds it (adding the column to the left leaf) 
and wraps it in a
+   * [[Project]] - leaving the recorded base operator stale (its left lacks 
the column). Return the
+   * rebuilt [[LateralJoin]] under that wrapping [[Project]] so validation 
(missing-input and
+   * [[ValidateSubqueryExpression]], which requires the host to be a 
[[LateralJoin]]) sees it.
+   *
+   * Only [[LateralJoin]] needs this: other base operators either wrap 
themselves in a [[Project]]
+   * during resolution (e.g. [[JoinResolver]]), so insertion leaves that 
[[Project]] in place, or
+   * host subqueries that [[ValidateSubqueryExpression]] permits under a 
[[Project]].
+   */
+  private def baseOperatorInResolvedPlan(
+      resolvedOperator: LogicalPlan,
+      baseOperator: LogicalPlan): LogicalPlan = {
+    (baseOperator, resolvedOperator) match {
+      case (_: LateralJoin, Project(_, lateralJoin: LateralJoin)) => 
lateralJoin
+      case _ => baseOperator

Review Comment:
   **Nit (P3):** `retainOriginalOutput` records the Sort or Filter as base 
operator, and metadata insertion later rebuilds it under the wrapping Project, 
but only `(LateralJoin, Project(LateralJoin))` is mapped to the rebuilt node 
here. Reading the code, for `SELECT a FROM file_table ORDER BY b, 
_metadata.file_name` the inserted `_metadata` column sits below the rebuilt 
Sort, while validation still checks the old Sort, whose child lacks it, and 
throws `MISSING_ATTRIBUTES`; the fixed-point analyzer resolves the query. The 
doc above `baseOperatorInResolvedPlan` says only LateralJoin can go stale.
   
   Suggested fix: return or locate the rebuilt counterpart for every operator 
kind that records a base operator and validate it, and when insertion changed 
its output, place a Project with its pre-insertion output directly above it so 
the plan keeps the fixed-point shape.
   
   **Verification:**
   - **Regression:** A Sort and a Filter that reference both a hidden-output 
column and a metadata column resolve in single-pass and match the fixed-point 
plan under dual-run.
   - **Behavior:** Lateral joins referencing metadata in their condition keep 
passing validation.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/PlanPreprocessor.scala:
##########
@@ -0,0 +1,384 @@
+/*
+ * 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.analysis.{
+  ExpressionWithUnresolvedIdentifier,
+  IdentifierResolution,
+  NameParameterizedQuery,
+  PlanWithUnresolvedIdentifier,
+  UnresolvedRelation,
+  UnresolvedStarExceptOrReplace
+}
+import org.apache.spark.sql.catalyst.expressions.{
+  Expression,
+  NamedExpression,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  CTERelationDef,
+  LogicalPlan,
+  OneRowRelation,
+  SubqueryAlias,
+  UnresolvedWith
+}
+import org.apache.spark.sql.catalyst.trees.CurrentOrigin.withOrigin
+import org.apache.spark.sql.catalyst.trees.TreePattern.{
+  PLAN_EXPRESSION,
+  PLAN_WITH_UNRESOLVED_IDENTIFIER,
+  UNRESOLVED_IDENTIFIER,
+  UNRESOLVED_RELATION,
+  UNRESOLVED_STAR_EXCEPT_OR_REPLACE,
+  UNRESOLVED_WITH
+}
+import org.apache.spark.sql.errors.QueryErrorsBase
+
+/**
+ * The [[PlanPreprocessor]] is responsible for substituting the IDENTIFIERs 
and CTE references
+ * in the unresolved logical plan before the actual resolution starts 
(specifically before
+ * metadata resolution). This is important for SQL features like WITH (that 
could confuse
+ * [[MetadataResolver]] with extra [[UnresolvedRelation]]s) or IDENTIFIER 
(that "hides" the
+ * actual [[UnresolvedRelation]]s).
+ *
+ * We only recurse into the plan if [[PlanPreprocessor.NODES_OF_INTEREST]] are 
present. This is
+ * done so that [[PlanPreprocessor]] is fast and not invasive.
+ *
+ * With `resolveExpressionIdentifiersInRootScope`, an expression IDENTIFIER 
whose name is not
+ * resolved yet is also materialized from a name resolved in an isolated root 
scope, so the
+ * expression it builds is visible to plan checks (e.g. guards):
+ * {{{
+ * DECLARE function_name = 'my_udf';
+ * SELECT IDENTIFIER(function_name)(col1) FROM t;
+ * -- 'Project [unresolvedalias('my_udf('col1))] instead of an opaque 
IDENTIFIER placeholder
+ * }}}
+ * Columns are not visible in that scope, while resolution prefers a 
same-named column over a SQL
+ * variable, so this mode only predicts what resolution builds and must not 
feed resolution.
+ */
+class PlanPreprocessor(resolver: Resolver, 
resolveExpressionIdentifiersInRootScope: Boolean)
+    extends QueryErrorsBase
+    with ResolverMetricTracker {
+  private var cteRegistry = new CteRegistry
+
+  /**
+   * This is the main entry point to the substitution process. It takes 
`unresolvedPlan` and
+   * substitutes CTEs and IDENTIFIERs that would otherwise confuse the 
metadata resolution process.
+   *
+   * [[CteRegistry]] has to be reset for each new invocation, because CTEs in 
views are analyzed
+   * in isolation.
+   */
+  def substitutePlan(unresolvedPlan: LogicalPlan): LogicalPlan = {
+    recordProfile("substitutePlan") {
+      cteRegistry = new CteRegistry
+
+      substitute(unresolvedPlan)
+    }
+  }
+
+  private def substitute(unresolvedPlan: LogicalPlan): LogicalPlan = {
+    unresolvedPlan match {
+      case unresolvedWith: UnresolvedWith =>
+        handleWith(unresolvedWith)
+      case unresolvedRelation: UnresolvedRelation =>
+        handleUnresolvedRelation(unresolvedRelation)
+      case nameParameterizedQuery: NameParameterizedQuery
+          if nameParameterizedQuery.child.containsAnyPattern(
+            PlanPreprocessor.NODES_OF_INTEREST: _*) =>
+        handleNameParameterizedQuery(nameParameterizedQuery)
+      case planWithUnresolvedIdentifier: PlanWithUnresolvedIdentifier =>
+        handlePlanWithUnresolvedIdentifier(planWithUnresolvedIdentifier)
+      case _ =>
+        handleOperator(unresolvedPlan)
+    }
+  }
+
+  /**
+   * Handle [[UnresolvedWith]] operator. WITH clause produces unresolved 
relations in the plan,
+   * that are not actual tables or views, but are just potential 
[[CTERelationRef]]s. To correctly
+   * detect those CTE references we use the [[CteRegistry]] framework. The 
actual CTE resolution
+   * is left to the main algebraic pass in the [[Resolver]] - here we replace 
the
+   * [[UnresolvedRelation]]s with [[UnresolvedCteRelationRef]] to avoid 
issuing useless catalog
+   * RPCs later on in the [[MetadataResolver]].
+   *
+   * We need to use the [[CteRegistry]] framework, because whether the 
relation is a CTE reference
+   * or not depends on its position in the logical plan tree:
+   * {{{
+   * CREATE TABLE rel2 (col1 INT);
+   *
+   * WITH rel1 AS (
+   *   WITH rel2 AS (
+   *     SELECT 1
+   *   )
+   *   SELECT * FROM rel2 -- `rel2` is a CTE reference
+   * )
+   * SELECT * FROM rel2 -- `rel2` is a table reference
+   * }}}
+   *
+   * For each CTE definition, a scope is pushed with the CTE name to enable 
self-reference
+   * detection for recursive CTEs. During substitution, we use dummy values 
for cteId (0) since
+   * the actual ID is assigned later during resolution.
+   */
+  private def handleWith(unresolvedWith: UnresolvedWith): LogicalPlan = {
+    val cteRelationsAfterSubstitution = unresolvedWith.cteRelations.map { 
cteRelation =>
+      val cteName = cteRelation.name
+
+      val recursiveCteParams = if (unresolvedWith.allowRecursion) {
+        Some(RecursiveCteParameters(cteId = 0, cteName = cteName, maxDepth = 
None))
+      } else {
+        None
+      }
+
+      cteRegistry.pushScope(recursiveCteParameters = recursiveCteParams)
+
+      val ctePlanAfter = try {
+        substitute(cteRelation.plan).asInstanceOf[SubqueryAlias]
+      } finally {
+        cteRegistry.popScope()
+      }
+
+      cteRegistry.currentScope.registerCte(cteName, 
CTERelationDef(ctePlanAfter))
+
+      cteRelation.copy(plan = ctePlanAfter)
+    }
+
+    cteRegistry.pushScope()
+
+    val childAfterSubstitution = try {
+      substitute(unresolvedWith.child)
+    } finally {
+      cteRegistry.popScope()
+    }
+
+    val result = withOrigin(unresolvedWith.origin) {
+      unresolvedWith.copy(
+        child = childAfterSubstitution,
+        cteRelations = cteRelationsAfterSubstitution
+      )
+    }
+    result.copyTagsFrom(unresolvedWith)
+    result
+  }
+
+  /**
+   * Preprocesses a parameterized child with its named bindings in scope. This 
node survives parser
+   * substitution only in legacy constants-only mode.
+   */
+  private def handleNameParameterizedQuery(
+      nameParameterizedQuery: NameParameterizedQuery): LogicalPlan = {
+    resolver.withNameParameterizedQueryParameters(nameParameterizedQuery) {
+      handleOperator(nameParameterizedQuery)
+    }
+  }
+
+  /**
+   * Handle [[UnresolvedRelation]] operator, which could be a CTE reference. 
If that's the case, we
+   * replace it with [[UnresolvedCteRelationRef]].
+   */
+  private def handleUnresolvedRelation(unresolvedRelation: 
UnresolvedRelation): LogicalPlan = {
+    if (unresolvedRelation.multipartIdentifier.size == 1 &&
+      cteRegistry.cteExists(unresolvedRelation.multipartIdentifier.head)) {
+      val result = withOrigin(unresolvedRelation.origin) {
+        UnresolvedCteRelationRef(unresolvedRelation.multipartIdentifier.head)
+      }
+      result.copyTagsFrom(unresolvedRelation)
+      result
+    } else {
+      unresolvedRelation
+    }
+  }
+
+  /**
+   * Handles [[PlanWithUnresolvedIdentifier]] by resolving its name expression 
in an isolated root
+   * context, evaluating it, and building the named plan. The expression may 
contain functions
+   * supported by the resolver and SQL variables, but cannot reference columns.
+   */
+  private def handlePlanWithUnresolvedIdentifier(
+      planWithUnresolvedIdentifier: PlanWithUnresolvedIdentifier): LogicalPlan 
= {
+    val identifierParts = evaluateIdentifierInRootScope(
+      identifierExpression = planWithUnresolvedIdentifier.identifierExpr,
+      parentOperator = planWithUnresolvedIdentifier
+    )
+
+    val builtPlan = withOrigin(planWithUnresolvedIdentifier.origin) {
+      planWithUnresolvedIdentifier.planBuilder(
+        identifierParts,
+        planWithUnresolvedIdentifier.children
+      )
+    }
+
+    val substitutedPlan = substitute(builtPlan)
+    substitutedPlan.copyTagsFrom(planWithUnresolvedIdentifier)
+    substitutedPlan
+  }
+
+  /**
+   * Evaluates an IDENTIFIER name expression into name parts after 
substituting its subqueries and
+   * resolving it in an isolated root scope under `parentOperator`.
+   */
+  private def evaluateIdentifierInRootScope(
+      identifierExpression: Expression,
+      parentOperator: LogicalPlan): Seq[String] = {
+    val identifierExpressionAfterSubstitution =
+      
identifierExpression.transformUpWithPruning(_.containsPattern(PLAN_EXPRESSION)) 
{
+        case subqueryExpression: SubqueryExpression =>
+          substituteIdentifierSubqueryPlan(subqueryExpression)
+      }
+    val resolvedIdentifierExpression = 
resolver.resolveIdentifierExpressionRoot(
+      identifierExpression = identifierExpressionAfterSubstitution,
+      parentOperator = parentOperator
+    )
+    IdentifierResolution.evalIdentifierExpr(resolvedIdentifierExpression)
+  }
+
+  /**
+   * Handle `unresolvedOperator` generically. We use the [[CteRegistry]] 
framework to recurse into
+   * its children and subquery expressions.
+   */
+  private def handleOperator(unresolvedOperator: LogicalPlan): LogicalPlan = {
+    val operatorAfterSubstitution = unresolvedOperator match {
+      case operator
+          if !operator.containsAnyPattern(PlanPreprocessor.NODES_OF_INTEREST: 
_*) =>
+        operator
+
+      case operator if operator.children.size > 1 =>
+        val newChildren = operator.children.map { child =>
+          cteRegistry.pushScopeForMultiChildOperator(operator, child)
+
+          try {
+            substitute(child)
+          } finally {
+            cteRegistry.popScope()
+          }
+        }
+        operator.withNewChildren(newChildren)
+
+      case operator if operator.children.size == 1 =>
+        val newChildren = Seq(substitute(operator.children.head))
+        operator.withNewChildren(newChildren)
+
+      case operator =>
+        operator
+    }
+
+    substituteExpressions(operatorAfterSubstitution)
+  }
+
+  /** Materializes expression IDENTIFIERs so metadata lookup and plan checks 
can see their names. */
+  private def substituteExpressions(operator: LogicalPlan): LogicalPlan = {
+    operator.transformExpressionsWithPruning(
+      _.containsAnyPattern(
+        PLAN_EXPRESSION,
+        UNRESOLVED_IDENTIFIER,
+        UNRESOLVED_STAR_EXCEPT_OR_REPLACE
+      )
+    )(substituteExpression)
+  }
+
+  /**
+   * Substitution rule applied to an operator's expression trees. It is also 
applied explicitly to
+   * the replacement expressions of an [[UnresolvedStarExceptOrReplace]] (see
+   * [[substituteStarExceptOrReplaceReplacements]]), which are not exposed as 
children because the
+   * star is a leaf expression.
+   *
+   * An expression IDENTIFIER is materialized when its name is already 
resolved, or, with
+   * `resolveExpressionIdentifiersInRootScope`, from its name resolved under a 
[[OneRowRelation]]
+   * placeholder so the enclosing operator cannot change the name lookup.
+   */
+  private def substituteExpression: PartialFunction[Expression, Expression] = {
+    case subqueryExpression: SubqueryExpression =>
+      substituteIdentifierSubqueryPlan(subqueryExpression)
+    case expressionWithUnresolvedIdentifier: ExpressionWithUnresolvedIdentifier
+        if expressionWithUnresolvedIdentifier.identifierExpr.resolved =>
+      val identifierParts = IdentifierResolution.evalIdentifierExpr(
+        expressionWithUnresolvedIdentifier.identifierExpr
+      )
+      IdentifierResolution.buildExpressionFromIdentifierParts(
+        expressionWithUnresolvedIdentifier = 
expressionWithUnresolvedIdentifier,
+        identifierParts = identifierParts
+      )
+    case expressionWithUnresolvedIdentifier: ExpressionWithUnresolvedIdentifier
+        if resolveExpressionIdentifiersInRootScope =>
+      val identifierParts = evaluateIdentifierInRootScope(
+        identifierExpression = 
expressionWithUnresolvedIdentifier.identifierExpr,
+        parentOperator = OneRowRelation()
+      )
+      IdentifierResolution.buildExpressionFromIdentifierParts(
+        expressionWithUnresolvedIdentifier = 
expressionWithUnresolvedIdentifier,
+        identifierParts = identifierParts
+      )
+    case starExceptOrReplace: UnresolvedStarExceptOrReplace
+        if starExceptOrReplace.replacements.isDefined =>
+      substituteStarExceptOrReplaceReplacements(starExceptOrReplace)
+  }
+
+  /**
+   * Substitutes IDENTIFIERs and CTE references nested in the replacement 
expressions of an
+   * [[UnresolvedStarExceptOrReplace]] (e.g. a scalar subquery selecting from 
`IDENTIFIER(...)` or a
+   * CTE in a pipe `|> SET` target). These expressions are not children of the 
leaf star, so the
+   * operator's expression traversal does not reach them; they are transformed 
here explicitly with
+   * the same [[substituteExpression]] rule.
+   *
+   * The replacements see the enclosing CTE scopes, so a CTE reference nested 
in a replacement
+   * subquery is rewritten to an [[UnresolvedCteRelationRef]]: an outer CTE 
takes precedence over
+   * a same-named table, per standard scoping. This intentionally diverges 
from the fixed-point

Review Comment:
   **Non-blocking (P2):** This doc says the divergence from the fixed-point 
analyzer is intentional, but HybridAnalyzer can only hide a known gap when 
single-pass raises `ExplicitlyUnsupportedResolverFeature`; a different 
successful resolution is returned as is. Reading the code, with a table `t` and 
a table `t2` that has a column `c`, `WITH t AS (SELECT 2 AS x) TABLE t2 |> SET 
c = (SELECT max(x) FROM t)` reads the CTE in single-pass but table `t` in the 
fixed-point analyzer, whose CTE substitution never reaches the star's 
replacements; without a table `t`, the fixed-point analyzer fails with 
`TABLE_OR_VIEW_NOT_FOUND` while single-pass succeeds. Tentative and forced 
modes return the single-pass result, and dual-run fails.
   
   Suggested fix: when a replacement subquery names a CTE defined outside the 
replacement, raise `ExplicitlyUnsupportedResolverFeature` with a new resolution 
gap (CTEs defined inside the replacement keep working), or substitute 
replacements behind an opaque CTE scope so such names stay unresolved 
relations, as in the fixed-point analyzer.
   
   **Verification:**
   - **Regression:** WITH t AS (SELECT 2 AS x) TABLE t2 |> SET c = (SELECT 
max(x) FROM t) returns the same result as the fixed-point analyzer when a table 
t exists and fails the same way when it does not.
   - **Behavior:** A |> SET replacement subquery with its own WITH clause keeps 
resolving in single-pass without a dual-run error.



##########
sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/HybridAnalyzerSuite.scala:
##########
@@ -377,6 +390,92 @@ class HybridAnalyzerSuite extends HybridAnalyzerSuiteBase {
     )
   }
 
+  testDualRun("IDENTIFIER plans are guarded before and after preprocessing") {
+    val guardedPlans = new ArrayBuffer[LogicalPlan]
+    var planBuilderApplications = 0
+    val resolverGuardFactory =
+      new ResolverGuardFactory(spark.sessionState.catalogManager, Seq.empty) {
+        override def create(): ResolverGuard =
+          new ResolverGuard(spark.sessionState.catalogManager) {
+            override def apply(plan: LogicalPlan): ResolverGuardResult = {
+              guardedPlans += plan
+              super.apply(plan)
+            }
+          }
+      }
+    val identifierPlan = new PlanWithUnresolvedIdentifier(
+      Literal("ignored"),
+      _ => {
+        planBuilderApplications += 1
+        Project(
+          Seq(UnresolvedStar(None)),
+          LocalRelation(col1Integer)
+        )
+      }
+    )
+    assertPlansEqual(
+      new HybridAnalyzer(
+        new ValidatingAnalyzer(bridgeRelations = true),
+        resolverGuardFactory,
+        new ValidatingResolver(bridgeRelations = true),
+        new QueryPlanningTracker
+      ).apply(identifierPlan),
+      resolvedPlan
+    )
+
+    assert(guardedPlans.size == 2)
+    
assert(guardedPlans.head.exists(_.isInstanceOf[PlanWithUnresolvedIdentifier]))
+    
assert(!guardedPlans.last.exists(_.isInstanceOf[PlanWithUnresolvedIdentifier]))
+    // Once for the post-preprocessing guard check, once for each analyzer.
+    assert(planBuilderApplications == 3)
+  }
+
+  testDualRun("IDENTIFIER preprocessing failures fall back") {
+    val queryExecution = spark.sessionState.executePlan(
+      spark.sessionState.sqlParser.parsePlan("SELECT * FROM IDENTIFIER((SELECT 
't'))")
+    )
+    checkError(
+      exception = intercept[ExtendedAnalysisException] {
+        queryExecution.analyzed
+      },
+      condition = "NOT_A_CONSTANT_STRING.NOT_CONSTANT",
+      parameters = Map("name" -> "IDENTIFIER", "expr" -> "scalarsubquery()"),
+      queryContext = Array(
+        ExpectedContext(
+          objectType = "",
+          objectName = "",
+          startIndex = 25,
+          stopIndex = 36,
+          fragment = "(SELECT 't')"
+        )
+      )
+    )
+  }
+
+  testDualRun("Nested view post-preprocessing rejection returns the 
fixed-point result") {
+    withSQLConf(SQLConf.PYTHON_WORKER_LOGGING_ENABLED.key -> "true") {
+      withView("v_identifier_guard") {
+        withSQLConf(
+          SQLConf.ANALYZER_DUAL_RUN_LEGACY_AND_SINGLE_PASS_RESOLVER.key -> 
"false",
+          SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED_TENTATIVELY.key -> 
"false"
+        ) {
+          spark.sql(
+            "CREATE VIEW v_identifier_guard AS " +
+              "SELECT * FROM IDENTIFIER(concat('python_worker', '_logs'))()"
+          )
+        }
+
+        val query = spark.sql("SELECT * FROM v_identifier_guard")
+        checkAnswer(query, Seq.empty)
+        assert(
+          query.queryExecution.analyzed
+            .getTagValue(ResolverRunner.SINGLE_PASS_ANALYSIS_MARKER)

Review Comment:
   **Nit (P3):** `testDualRun` does not set 
`ANALYZER_DUAL_RUN_RETURN_SINGLE_PASS_RESULT`, and `resolveInDualRun` returns 
the fixed-point plan both when single-pass throws 
`ExplicitlyUnsupportedResolverFeature` and when the two analyzers agree. 
`SINGLE_PASS_ANALYSIS_MARKER` is set only on single-pass results, so this 
assertion passes whether or not the view body was rejected. The dual-run 
comparison still catches a different error or plan, and ViewResolverSuite's 
'View IDENTIFIER materializes an unsupported table-valued function' test checks 
the rejection itself, so only a regression in which single-pass resolves the 
body to the fixed-point plan would go unnoticed here.
   
   Suggested fix: run this test with 
`ANALYZER_DUAL_RUN_RETURN_SINGLE_PASS_RESULT` enabled so the marker assertion 
can fail, or drop the assertion.
   
   **Verification:**
   - **Regression:** With the single-pass result returned from dual-run, the 
nested-view test fails when the view-body post-preprocessing rejection is 
removed and single-pass resolves the body, and passes with the rejection in 
place.



-- 
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]

Reply via email to