peter-toth commented on code in PR #58229:
URL: https://github.com/apache/spark/pull/58229#discussion_r4591114012


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)
+      }
+    }
+  }
+
+  // References reachable from the query root, per definition. A reference 
inside a
+  // definition counts only when that definition is itself live, matching 
`InlineCTE`.
+  // The visited set stops a recursive CTE from being walked forever.
+  private def countLiveRefs(plan: LogicalPlan): Map[Long, Int] = {
+    // The region of a reference is its innermost enclosing definition's id, or
+    // ROOT_REGION at the query root.
+    val ROOT_REGION = -1L
+    val outgoing = mutable.HashMap.empty[Long, mutable.ArrayBuffer[Long]]
+
+    def walk(p: LogicalPlan, region: Long): Unit = {
+      p match {
+        case d: CTERelationDef => walk(d.child, d.id)
+        case r: CTERelationRef =>
+          outgoing.getOrElseUpdate(region, mutable.ArrayBuffer.empty) += 
r.cteId
+        case _ => p.children.foreach(walk(_, region))
+      }
+      p.subqueries.foreach(walk(_, region))
+    }
+    walk(plan, ROOT_REGION)
+
+    val liveRefCounts = mutable.HashMap.empty[Long, Int].withDefaultValue(0)
+    val visitedDefs = mutable.HashSet.empty[Long]
+    val pending = mutable.Queue.empty[Long] ++=
+      outgoing.getOrElse(ROOT_REGION, mutable.ArrayBuffer.empty)
+    while (pending.nonEmpty) {
+      val target = pending.dequeue()
+      liveRefCounts(target) += 1
+      if (visitedDefs.add(target)) {
+        pending ++= outgoing.getOrElse(target, mutable.ArrayBuffer.empty)
+      }
+    }
+    liveRefCounts.toMap
+  }
+
+  // Re-analysis mints a fresh id for each inner `CTERelationDef`, so equal 
bodies would
+  // otherwise canonicalize apart. Rewriting ids to appearance ordinals lets 
them compare
+  // equal: the same shape is walked in the same order, so genuinely different 
wiring keeps
+  // different ordinals. Recursive CTEs also re-mint `UnionLoop.id`, 
`UnionLoopRef.loopId`,
+  // and `UnionLoop.outputAttrIds`; those are not rewritten, so WITH RECURSIVE 
bodies stay
+  // distinct and are never converted.
+  private def normalizeCteIds(plan: LogicalPlan): LogicalPlan = {
+    val ids = mutable.HashMap.empty[Long, Long]
+    plan.transformUpWithSubqueries {
+      case d: CTERelationDef => d.copy(id = ids.getOrElseUpdate(d.id, 
ids.size))
+      case r: CTERelationRef => r.copy(cteId = ids.getOrElseUpdate(r.cteId, 
ids.size))
+    }
+  }
+
+  // Canonicalization drops `ResolvedHint`, so the hint check cannot come from 
the body
+  // comparison; compare them here.
+  private def hintsOf(v: View): Seq[HintInfo] =
+    v.child.collectWithSubqueries { case h: ResolvedHint => h.hints }
+
+  // Deterministic and non-streaming alone do not cover a seedless `Sample`: 
it has no
+  // expressions, so `deterministic` is true, but `SampleExec` draws a fresh 
seed per
+  // physical node. One shared definition would make every reference read one 
sample.
+  private def qualifies(occs: Seq[View]): Boolean = {
+    val first = occs.head
+    occs.length >= 2 && occs.forall { v =>
+      v.resolved &&
+        v.child.deterministic &&
+        !v.child.isStreaming &&
+        v.child.collectWithSubqueries { case s: Sample if s.seed.isEmpty => s 
}.isEmpty &&
+        !hasMainRegionSort(v.child) &&
+        hintsOf(v) == hintsOf(first) &&
+        v.desc.viewSQLConfigs == first.desc.viewSQLConfigs &&
+        schemasAlign(first, v)
+    }
+  }
+
+  // The added shuffle drops any order the body's main plan exposes, including 
sorts
+  // reachable through `children`: under LIMIT/OFFSET, in inner views, in WITH
+  // definitions, and in set-operation branches. Sorts inside subquery 
expressions can
+  // choose which rows the body produces, but they do not order its output, 
and they are
+  // not reachable through `children`.
+  private def hasMainRegionSort(plan: LogicalPlan): Boolean =
+    plan.isInstanceOf[Sort] || plan.children.exists(hasMainRegionSort)
+
+  /**
+   * Resolution renews a view's attributes and preserves column order, name, 
type, and
+   * nullability. A mismatch would zip occurrences against the wrong columns 
and silently
+   * change results.
+   */
+  private def schemasAlign(first: View, other: View): Boolean =
+    first.output.length == other.output.length &&
+      first.output.zip(other.output).forall { case (l, r) =>
+        l.name == r.name && l.dataType == r.dataType && l.nullable == 
r.nullable
+      }
+
+  // The extracted hint list is top-down; foldRight re-nests it in that order 
above the
+  // reference.
+  private def withBodyHints(hints: Seq[HintInfo], site: LogicalPlan): 
LogicalPlan =
+    hints.foldRight(site)((h, acc) => ResolvedHint(acc, h))
+
+  /**
+   * Places definitions where `CTESubstitution` would: into an existing 
top-level
+   * `WithCTE`, onto a `CTEInChildren` command, or in a wrapping `WithCTE`. 
Subquery
+   * expressions resolve against that top-level scope. Only the top-level pass 
attaches
+   * definitions; `apply` returns early for `Subquery` roots.
+   */
+  private def attachDefs(plan: LogicalPlan, newDefs: Seq[CTERelationDef]): 
LogicalPlan =
+    plan match {
+      case WithCTE(child, cteDefs) => WithCTE(child, newDefs ++ cteDefs)
+      case cmd: LogicalPlan with CTEInChildren => cmd.withCTEDefs(newDefs)
+      case other => WithCTE(other, newDefs)

Review Comment:
   **Finding 17.** The definitions land in a `WithCTE` at the root. When the 
query or a view body keeps a CTE non-inlined in a nested `WithCTE`, 
`PushdownPredicatesAndPruneColumnsForCTEDef` then crashes with 
`NoSuchElementException: key not found`.
   
   Measured on this head, AQE on and off, with parquet tables `t`, `t2` and 
`small`:
   
   ```sql
   CREATE VIEW v1 AS SELECT id, k FROM t WHERE k < 8;
   CREATE VIEW v2 AS SELECT id, k FROM t2 WHERE k < 6;
   CREATE VIEW vm2 AS WITH c AS MATERIALIZED (SELECT id FROM small)
     SELECT id, k FROM v1 WHERE id IN (SELECT id FROM c);
   
   -- (a)
   WITH c AS MATERIALIZED (SELECT id FROM small)
   SELECT a.id FROM v1 a JOIN v1 b ON a.id = b.id
   JOIN (SELECT id FROM v2 WHERE id IN (SELECT id FROM c)) x ON a.id = x.id
   JOIN (SELECT id FROM v2 WHERE id IN (SELECT id FROM c)) y ON a.id = y.id;
   
   -- (b)
   SELECT a.id FROM v2 a JOIN v2 b ON a.id = b.id
   JOIN vm2 x ON a.id = x.id JOIN vm2 y ON a.id = y.id
   JOIN (SELECT * FROM v1 WHERE id IN (SELECT id FROM small)) z ON z.id = a.id;
   ```
   
   - With the config off, every action returns the same rows.
   - With it on, `count()` and `limit(20)` on (a), and every action on (b), 
fail with `key not found: 0`.
   - `collect()` on (a) still works, because there the user's `WITH` is the 
root and line 244 merges both into one `WithCTE`.
   
   The cause is in 
`PushdownPredicatesAndPruneColumnsForCTEDef.gatherPredicatesAndAttributes`. It 
numbers each definition by its index inside its own `WithCTE` (`:68-70`), and 
the forward-reference check at `:90` compares those numbers across scopes. So a 
predicate that reads an inner `c` (index 0) is pushed into an outer definition 
(index 1), outside `c`'s scope, and the lookup at `:75` throws on the next pass.
   
   This is not new. With the config off, nested `MATERIALIZED` CTEs fail the 
same way on master, with `key not found: 2`:
   
   ```sql
   WITH u0 AS MATERIALIZED (SELECT id FROM t2),
        u AS MATERIALIZED (SELECT id, k FROM t2 WHERE k < 6)
   SELECT (WITH c AS MATERIALIZED (SELECT id FROM small)
           SELECT count(*) FROM u WHERE id > (SELECT min(id) FROM c)) x,
          (WITH c AS MATERIALIZED (SELECT id FROM small)
           SELECT max(id) FROM u WHERE id > (SELECT min(id) FROM c)) y
   FROM u0 LIMIT 1
   ```
   
   The conversion makes it reachable from plain view queries. Numbering the 
definitions in visiting order fixes both:
   
   ```scala
         case WithCTE(child, cteDefs) =>
           cteDefs.foreach { cteDef =>
             gatherPredicatesAndAttributes(cteDef.child, cteMap)
             cteMap.put(cteDef.id, (cteDef, cteMap.size, Seq.empty, 
AttributeSet.empty))
           }
   ```
   
   A definition visited later is either a later sibling, which is a real 
forward reference, or one in a nested scope, which the earlier definition 
cannot see. Both must be excluded. With this change, (a), (b) and the master 
query work. `ConvertViewToMaterializedCTESuite`, 
`ConvertViewToMaterializedCTEQuerySuite`, `CTEInlineSuite*` and 
`PushdownPredicatesForCTEDefStalenessSuite` pass.
   
   Since the base crash is older than this PR, could you file a SPARK ticket 
for it, so that its fix can be tracked and backported on its own? (a) and (b) 
would make good tests here.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)
+      }
+    }
+  }
+
+  // References reachable from the query root, per definition. A reference 
inside a
+  // definition counts only when that definition is itself live, matching 
`InlineCTE`.
+  // The visited set stops a recursive CTE from being walked forever.
+  private def countLiveRefs(plan: LogicalPlan): Map[Long, Int] = {
+    // The region of a reference is its innermost enclosing definition's id, or
+    // ROOT_REGION at the query root.
+    val ROOT_REGION = -1L
+    val outgoing = mutable.HashMap.empty[Long, mutable.ArrayBuffer[Long]]
+
+    def walk(p: LogicalPlan, region: Long): Unit = {
+      p match {
+        case d: CTERelationDef => walk(d.child, d.id)
+        case r: CTERelationRef =>
+          outgoing.getOrElseUpdate(region, mutable.ArrayBuffer.empty) += 
r.cteId
+        case _ => p.children.foreach(walk(_, region))
+      }
+      p.subqueries.foreach(walk(_, region))
+    }
+    walk(plan, ROOT_REGION)
+
+    val liveRefCounts = mutable.HashMap.empty[Long, Int].withDefaultValue(0)
+    val visitedDefs = mutable.HashSet.empty[Long]
+    val pending = mutable.Queue.empty[Long] ++=
+      outgoing.getOrElse(ROOT_REGION, mutable.ArrayBuffer.empty)
+    while (pending.nonEmpty) {
+      val target = pending.dequeue()
+      liveRefCounts(target) += 1
+      if (visitedDefs.add(target)) {
+        pending ++= outgoing.getOrElse(target, mutable.ArrayBuffer.empty)
+      }
+    }
+    liveRefCounts.toMap
+  }
+
+  // Re-analysis mints a fresh id for each inner `CTERelationDef`, so equal 
bodies would
+  // otherwise canonicalize apart. Rewriting ids to appearance ordinals lets 
them compare
+  // equal: the same shape is walked in the same order, so genuinely different 
wiring keeps
+  // different ordinals. Recursive CTEs also re-mint `UnionLoop.id`, 
`UnionLoopRef.loopId`,
+  // and `UnionLoop.outputAttrIds`; those are not rewritten, so WITH RECURSIVE 
bodies stay
+  // distinct and are never converted.
+  private def normalizeCteIds(plan: LogicalPlan): LogicalPlan = {
+    val ids = mutable.HashMap.empty[Long, Long]
+    plan.transformUpWithSubqueries {
+      case d: CTERelationDef => d.copy(id = ids.getOrElseUpdate(d.id, 
ids.size))
+      case r: CTERelationRef => r.copy(cteId = ids.getOrElseUpdate(r.cteId, 
ids.size))
+    }
+  }
+
+  // Canonicalization drops `ResolvedHint`, so the hint check cannot come from 
the body
+  // comparison; compare them here.
+  private def hintsOf(v: View): Seq[HintInfo] =
+    v.child.collectWithSubqueries { case h: ResolvedHint => h.hints }
+
+  // Deterministic and non-streaming alone do not cover a seedless `Sample`: 
it has no
+  // expressions, so `deterministic` is true, but `SampleExec` draws a fresh 
seed per
+  // physical node. One shared definition would make every reference read one 
sample.
+  private def qualifies(occs: Seq[View]): Boolean = {
+    val first = occs.head
+    occs.length >= 2 && occs.forall { v =>
+      v.resolved &&
+        v.child.deterministic &&
+        !v.child.isStreaming &&
+        v.child.collectWithSubqueries { case s: Sample if s.seed.isEmpty => s 
}.isEmpty &&
+        !hasMainRegionSort(v.child) &&
+        hintsOf(v) == hintsOf(first) &&
+        v.desc.viewSQLConfigs == first.desc.viewSQLConfigs &&
+        schemasAlign(first, v)
+    }
+  }
+
+  // The added shuffle drops any order the body's main plan exposes, including 
sorts
+  // reachable through `children`: under LIMIT/OFFSET, in inner views, in WITH
+  // definitions, and in set-operation branches. Sorts inside subquery 
expressions can
+  // choose which rows the body produces, but they do not order its output, 
and they are
+  // not reachable through `children`.
+  private def hasMainRegionSort(plan: LogicalPlan): Boolean =
+    plan.isInstanceOf[Sort] || plan.children.exists(hasMainRegionSort)

Review Comment:
   **Finding 18.** The added shuffle drops the body's partitioning as well as 
its order, and only the order is guarded. `DISTRIBUTE BY`, `REPARTITION` and 
`REBALANCE` put the rows of one key into one partition, and `TRANSFORM` and 
other per-partition consumers rely on that.
   
   Measured on this head with `spark.sql.shuffle.partitions=8` and partition 
coalescing off, AQE on and off:
   
   ```sql
   CREATE TEMP VIEW v(a, b) AS SELECT id % 3, id FROM range(0, 600) DISTRIBUTE 
BY id % 3;
   
   SELECT TRANSFORM(a) USING 'sort -u' AS (k STRING) FROM v
   UNION ALL
   SELECT TRANSFORM(a) USING 'sort -u' AS (k STRING) FROM v
   ```
   
   - With the config off it returns 6 rows.
   - With it on it returns 48, since each of the 8 round-robin partitions holds 
all three keys.
   - With coalescing on, both return 6 at this size, because the small 
round-robin partitions merge back into one.
   
   The column list puts the view's `Project` above the 
`RepartitionByExpression`. So `ReplaceCTERefWithRepartition` finds no 
repartition at the top, and it adds the round-robin one above the hash one. 
Treating repartitions like sorts returns the 6 rows with the config on, and 
both suites pass:
   
   ```suggestion
     private def hasMainRegionSort(plan: LogicalPlan): Boolean = plan match {
       case _: Sort | _: RepartitionOperation | _: RebalancePartitions => true
       case _ => plan.children.exists(hasMainRegionSort)
     }
   ```
   
   The name, the comment above and the config doc would then cover 
repartitioning too. The query above would make a good test.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1071,6 +1071,28 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val CONVERT_VIEW_TO_MATERIALIZED_CTE =
+    buildConf("spark.sql.optimizer.convertViewToMaterializedCTE.enabled")
+      .doc("When true, multiple references to the same view are rewritten into 
one " +
+        "materialized CTE, so the view's plan runs once (through exchange 
reuse) " +
+        "instead of once per reference. Enable it for queries that repeatedly 
read an " +
+        "expensive view. Each reference gains a shuffle of the view's output, 
and " +
+        "per-reference pushdown, dynamic partition pruning, and 
scalar-subquery " +
+        "merging no longer reach the view body, so it can also make queries 
slower; " +

Review Comment:
   **Finding 16.** This says that scalar-subquery merging no longer reaches the 
view body. `MergeSubplans` returns any plan that contains a CTE unchanged 
(`MergeSubplans.scala:164`). So with a converted view no scalar subquery of the 
query is merged, not only the ones over the view. Your 
[reply](https://github.com/apache/spark/pull/58229#discussion_r4572564041) says 
so too:
   
   ```suggestion
           "expensive view. Each reference gains a shuffle of the view's 
output, " +
           "per-reference pushdown and dynamic partition pruning no longer 
reach the view " +
           "body, and scalar-subquery merging is off for the whole query, so it 
can also " +
           "make queries slower; " +
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)
+      }
+    }
+  }
+
+  // References reachable from the query root, per definition. A reference 
inside a
+  // definition counts only when that definition is itself live, matching 
`InlineCTE`.
+  // The visited set stops a recursive CTE from being walked forever.
+  private def countLiveRefs(plan: LogicalPlan): Map[Long, Int] = {
+    // The region of a reference is its innermost enclosing definition's id, or
+    // ROOT_REGION at the query root.
+    val ROOT_REGION = -1L
+    val outgoing = mutable.HashMap.empty[Long, mutable.ArrayBuffer[Long]]
+
+    def walk(p: LogicalPlan, region: Long): Unit = {
+      p match {
+        case d: CTERelationDef => walk(d.child, d.id)
+        case r: CTERelationRef =>
+          outgoing.getOrElseUpdate(region, mutable.ArrayBuffer.empty) += 
r.cteId
+        case _ => p.children.foreach(walk(_, region))
+      }
+      p.subqueries.foreach(walk(_, region))
+    }
+    walk(plan, ROOT_REGION)
+
+    val liveRefCounts = mutable.HashMap.empty[Long, Int].withDefaultValue(0)
+    val visitedDefs = mutable.HashSet.empty[Long]
+    val pending = mutable.Queue.empty[Long] ++=
+      outgoing.getOrElse(ROOT_REGION, mutable.ArrayBuffer.empty)
+    while (pending.nonEmpty) {
+      val target = pending.dequeue()
+      liveRefCounts(target) += 1
+      if (visitedDefs.add(target)) {
+        pending ++= outgoing.getOrElse(target, mutable.ArrayBuffer.empty)
+      }
+    }
+    liveRefCounts.toMap
+  }
+
+  // Re-analysis mints a fresh id for each inner `CTERelationDef`, so equal 
bodies would
+  // otherwise canonicalize apart. Rewriting ids to appearance ordinals lets 
them compare
+  // equal: the same shape is walked in the same order, so genuinely different 
wiring keeps
+  // different ordinals. Recursive CTEs also re-mint `UnionLoop.id`, 
`UnionLoopRef.loopId`,
+  // and `UnionLoop.outputAttrIds`; those are not rewritten, so WITH RECURSIVE 
bodies stay
+  // distinct and are never converted.
+  private def normalizeCteIds(plan: LogicalPlan): LogicalPlan = {
+    val ids = mutable.HashMap.empty[Long, Long]
+    plan.transformUpWithSubqueries {
+      case d: CTERelationDef => d.copy(id = ids.getOrElseUpdate(d.id, 
ids.size))
+      case r: CTERelationRef => r.copy(cteId = ids.getOrElseUpdate(r.cteId, 
ids.size))
+    }
+  }
+
+  // Canonicalization drops `ResolvedHint`, so the hint check cannot come from 
the body
+  // comparison; compare them here.
+  private def hintsOf(v: View): Seq[HintInfo] =
+    v.child.collectWithSubqueries { case h: ResolvedHint => h.hints }

Review Comment:
   **Finding 23.** This compares hints as a flat list, so it misses where each 
one sits. It is the comparison I suggested for finding 14 at 
[r4480461857](https://github.com/apache/spark/pull/58229#discussion_r4480461857),
 and it is too weak.
   
   Measured on this head over parquet tables `a` and `b`, with broadcast joins 
off:
   
   ```scala
   sql("CREATE TEMP VIEW v AS SELECT /*+ BROADCAST(a) */ a.id FROM a JOIN b ON 
a.id = b.id")
   val held = spark.table("v")
   sql("CREATE OR REPLACE TEMP VIEW v AS SELECT /*+ BROADCAST(b) */ a.id FROM a 
JOIN b ON a.id = b.id")
   held.union(spark.table("v"))
   ```
   
   - Both bodies hold one `ResolvedHint(BROADCAST)`, so the lists are equal.
   - With the config off, the two joins carry `leftHint=broadcast` and 
`rightHint=broadcast`.
   - With it on, both carry `leftHint=broadcast`, so the replaced view's 
`BROADCAST(b)` is gone. The rows don't change.
   
   Pairing each hint with the subtree it sits on keeps the config-off hints, 
since the example then does not convert. Both suites pass with it:
   
   ```suggestion
     private def hintsOf(v: View): Seq[(HintInfo, LogicalPlan)] =
       v.child.collectWithSubqueries {
         case h: ResolvedHint => (h.hints, 
normalizeCteIds(h.child).canonicalized)
       }
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {

Review Comment:
   **Finding 25.** This branch cannot run. Line 86 returns when 
`qualifiedIdentifiers` is empty, and each qualified identifier has at least two 
occurrences. The bottom-up rewrite visits all of them, a nested one included, 
before a later occurrence's body is dropped. So `cteDefs` is never empty here, 
and the `else` body can be the method's tail.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)
+      }
+    }
+  }
+
+  // References reachable from the query root, per definition. A reference 
inside a
+  // definition counts only when that definition is itself live, matching 
`InlineCTE`.
+  // The visited set stops a recursive CTE from being walked forever.
+  private def countLiveRefs(plan: LogicalPlan): Map[Long, Int] = {
+    // The region of a reference is its innermost enclosing definition's id, or
+    // ROOT_REGION at the query root.
+    val ROOT_REGION = -1L
+    val outgoing = mutable.HashMap.empty[Long, mutable.ArrayBuffer[Long]]
+
+    def walk(p: LogicalPlan, region: Long): Unit = {
+      p match {
+        case d: CTERelationDef => walk(d.child, d.id)
+        case r: CTERelationRef =>
+          outgoing.getOrElseUpdate(region, mutable.ArrayBuffer.empty) += 
r.cteId
+        case _ => p.children.foreach(walk(_, region))
+      }
+      p.subqueries.foreach(walk(_, region))
+    }
+    walk(plan, ROOT_REGION)
+
+    val liveRefCounts = mutable.HashMap.empty[Long, Int].withDefaultValue(0)
+    val visitedDefs = mutable.HashSet.empty[Long]
+    val pending = mutable.Queue.empty[Long] ++=
+      outgoing.getOrElse(ROOT_REGION, mutable.ArrayBuffer.empty)
+    while (pending.nonEmpty) {
+      val target = pending.dequeue()
+      liveRefCounts(target) += 1
+      if (visitedDefs.add(target)) {
+        pending ++= outgoing.getOrElse(target, mutable.ArrayBuffer.empty)
+      }
+    }
+    liveRefCounts.toMap
+  }
+
+  // Re-analysis mints a fresh id for each inner `CTERelationDef`, so equal 
bodies would
+  // otherwise canonicalize apart. Rewriting ids to appearance ordinals lets 
them compare
+  // equal: the same shape is walked in the same order, so genuinely different 
wiring keeps
+  // different ordinals. Recursive CTEs also re-mint `UnionLoop.id`, 
`UnionLoopRef.loopId`,
+  // and `UnionLoop.outputAttrIds`; those are not rewritten, so WITH RECURSIVE 
bodies stay
+  // distinct and are never converted.
+  private def normalizeCteIds(plan: LogicalPlan): LogicalPlan = {
+    val ids = mutable.HashMap.empty[Long, Long]
+    plan.transformUpWithSubqueries {
+      case d: CTERelationDef => d.copy(id = ids.getOrElseUpdate(d.id, 
ids.size))
+      case r: CTERelationRef => r.copy(cteId = ids.getOrElseUpdate(r.cteId, 
ids.size))
+    }
+  }
+
+  // Canonicalization drops `ResolvedHint`, so the hint check cannot come from 
the body
+  // comparison; compare them here.
+  private def hintsOf(v: View): Seq[HintInfo] =
+    v.child.collectWithSubqueries { case h: ResolvedHint => h.hints }
+
+  // Deterministic and non-streaming alone do not cover a seedless `Sample`: 
it has no
+  // expressions, so `deterministic` is true, but `SampleExec` draws a fresh 
seed per
+  // physical node. One shared definition would make every reference read one 
sample.
+  private def qualifies(occs: Seq[View]): Boolean = {
+    val first = occs.head
+    occs.length >= 2 && occs.forall { v =>
+      v.resolved &&
+        v.child.deterministic &&
+        !v.child.isStreaming &&
+        v.child.collectWithSubqueries { case s: Sample if s.seed.isEmpty => s 
}.isEmpty &&

Review Comment:
   **Finding 19.** The recursive-CTE exclusion only comes from SQL views 
re-analyzing their body, which re-mints the loop ids. A DataFrame temp view 
stores its analyzed plan, so its occurrences share `UnionLoop.id`, 
`UnionLoopRef.loopId` and `outputAttrIds`. They canonicalize equal and convert.
   
   Measured on this head, AQE on and off:
   
   ```scala
   spark.sql("WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r) 
SELECT * FROM r")
     .createOrReplaceTempView("rv")
   sql("(SELECT * FROM rv LIMIT 5) UNION ALL (SELECT * FROM rv LIMIT 5)")
   ```
   
   - With the config off it returns 10 rows.
   - With it on it fails with `RECURSION_LEVEL_LIMIT_EXCEEDED`. The `LIMIT` now 
sits above the reference and no longer reaches the `UnionLoop`, so the shared 
definition recurses up to the level limit.
   - The same view created with `CREATE TEMP VIEW ... AS WITH RECURSIVE ...` 
returns 10 rows either way.
   
   The comment at lines 179-181 and the config doc say that such bodies are 
never converted. The catalyst test `does not convert views whose body contains 
a recursive CTE` mints different loop ids per occurrence, so it cannot catch 
this. An explicit check returns the 10 rows with the config on, and both suites 
pass:
   
   ```suggestion
           v.child.collectWithSubqueries { case s: Sample if s.seed.isEmpty => 
s }.isEmpty &&
           v.child.collectWithSubqueries { case u: UnionLoop => u }.isEmpty &&
   ```
   
   The comment, the config doc and the test could then name this check instead 
of the id re-minting. The query above would make a good end-to-end test.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)

Review Comment:
   **Finding 22.** `countLiveRefs` counts two live references here, but only 
one evaluation runs. These are the two queries of this PR's `grouping by a 
correlated scalar subquery over a converted view` test:
   - `SELECT a, (SELECT sum(d) FROM vr WHERE a = c) sum_d FROM l l1 GROUP BY 1, 
2`
   - the same with the subquery spelled out in the `GROUP BY`
   
   The select-list copy and the `GROUP BY` copy each hold an occurrence of 
`vr`, so the definition is materialized. `PullOutGroupingExpressions` runs 
later in `FinishAnalysis` and replaces the select-list copy with the grouping 
alias, so one subquery runs. On this head both queries plan one round-robin 
repartition that nothing reuses, where the config off plans none. The test's 
`assert(countRepartitions(query) > 0)` pins that shuffle. This is the part of 
finding 7 
([r4093602482](https://github.com/apache/spark/pull/58229#discussion_r4093602482))
 that is still open.
   
   One way is to count semantically equal subquery expressions once in 
`countLiveRefs`, since that is what `PullOutGroupingExpressions` matches them 
by. I haven't measured that change.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {
+          case Some((cteDef, bodyHints)) =>
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+
+          case None =>
+            // `forceSkipInline` is set below, once live references are 
counted.
+            val (hintFreeBody, bodyHints) =
+              EliminateResolvedHint.extractHintsFromPlan(v.child)
+            val cteDef = CTERelationDef(hintFreeBody)
+            defByGroup.put(v.desc.identifier, (cteDef, bodyHints))
+            cteDefs += cteDef
+            withBodyHints(bodyHints, CTERelationRef(
+              cteDef.id,
+              _resolved = true,
+              output = v.output,
+              isStreaming = false,
+              maxRows = cteDef.maxRows))
+        }
+    }
+
+    if (cteDefs.isEmpty) {
+      plan
+    } else {
+      // Two or more live references can share the added shuffle, so 
materialize only
+      // those. A dropped occurrence body, or a reference inside an 
unreferenced user
+      // CTE, can leave fewer; keep those inlinable and let `InlineCTE` 
flatten them.
+      val newDefIds = cteDefs.map(_.id).toSet
+      val withDefs = attachDefs(rewritten, cteDefs.toSeq)
+      val liveRefCounts = countLiveRefs(withDefs)
+      withDefs.transformUpWithSubqueries {
+        case d: CTERelationDef if newDefIds.contains(d.id) =>
+          d.copy(forceSkipInline = liveRefCounts.getOrElse(d.id, 0) >= 2)
+      }
+    }
+  }
+
+  // References reachable from the query root, per definition. A reference 
inside a
+  // definition counts only when that definition is itself live, matching 
`InlineCTE`.
+  // The visited set stops a recursive CTE from being walked forever.
+  private def countLiveRefs(plan: LogicalPlan): Map[Long, Int] = {
+    // The region of a reference is its innermost enclosing definition's id, or
+    // ROOT_REGION at the query root.
+    val ROOT_REGION = -1L
+    val outgoing = mutable.HashMap.empty[Long, mutable.ArrayBuffer[Long]]
+
+    def walk(p: LogicalPlan, region: Long): Unit = {
+      p match {
+        case d: CTERelationDef => walk(d.child, d.id)
+        case r: CTERelationRef =>
+          outgoing.getOrElseUpdate(region, mutable.ArrayBuffer.empty) += 
r.cteId
+        case _ => p.children.foreach(walk(_, region))
+      }
+      p.subqueries.foreach(walk(_, region))
+    }
+    walk(plan, ROOT_REGION)
+
+    val liveRefCounts = mutable.HashMap.empty[Long, Int].withDefaultValue(0)
+    val visitedDefs = mutable.HashSet.empty[Long]
+    val pending = mutable.Queue.empty[Long] ++=
+      outgoing.getOrElse(ROOT_REGION, mutable.ArrayBuffer.empty)
+    while (pending.nonEmpty) {
+      val target = pending.dequeue()
+      liveRefCounts(target) += 1
+      if (visitedDefs.add(target)) {
+        pending ++= outgoing.getOrElse(target, mutable.ArrayBuffer.empty)
+      }
+    }
+    liveRefCounts.toMap
+  }
+
+  // Re-analysis mints a fresh id for each inner `CTERelationDef`, so equal 
bodies would
+  // otherwise canonicalize apart. Rewriting ids to appearance ordinals lets 
them compare
+  // equal: the same shape is walked in the same order, so genuinely different 
wiring keeps
+  // different ordinals. Recursive CTEs also re-mint `UnionLoop.id`, 
`UnionLoopRef.loopId`,
+  // and `UnionLoop.outputAttrIds`; those are not rewritten, so WITH RECURSIVE 
bodies stay
+  // distinct and are never converted.
+  private def normalizeCteIds(plan: LogicalPlan): LogicalPlan = {
+    val ids = mutable.HashMap.empty[Long, Long]
+    plan.transformUpWithSubqueries {
+      case d: CTERelationDef => d.copy(id = ids.getOrElseUpdate(d.id, 
ids.size))
+      case r: CTERelationRef => r.copy(cteId = ids.getOrElseUpdate(r.cteId, 
ids.size))
+    }
+  }
+
+  // Canonicalization drops `ResolvedHint`, so the hint check cannot come from 
the body
+  // comparison; compare them here.
+  private def hintsOf(v: View): Seq[HintInfo] =
+    v.child.collectWithSubqueries { case h: ResolvedHint => h.hints }
+
+  // Deterministic and non-streaming alone do not cover a seedless `Sample`: 
it has no
+  // expressions, so `deterministic` is true, but `SampleExec` draws a fresh 
seed per
+  // physical node. One shared definition would make every reference read one 
sample.
+  private def qualifies(occs: Seq[View]): Boolean = {
+    val first = occs.head
+    occs.length >= 2 && occs.forall { v =>
+      v.resolved &&
+        v.child.deterministic &&

Review Comment:
   **Finding 20.** Unconverted, each reference prunes and filters its own copy 
of the body before it computes a column. Converted, the definition computes 
every column that some reference reads, over the OR of the references' filters 
(`PushdownPredicatesAndPruneColumnsForCTEDef`). So an expression that can fail 
runs on rows that no reference reading it sees.
   
   Measured on this head with ANSI on, AQE on and off:
   
   ```sql
   CREATE TABLE bad USING parquet AS
     SELECT id, CASE WHEN id = 99 THEN 'abc' ELSE CAST(id AS STRING) END AS s 
FROM range(0, 100);
   CREATE VIEW vbad AS SELECT id, CAST(s AS INT) AS n FROM bad;
   
   SELECT id FROM vbad WHERE id > 50 UNION ALL SELECT n FROM vbad WHERE id < 5
   ```
   
   - With the config off it returns 54 rows.
   - With it on it fails with `CAST_INVALID_INPUT`. The definition computes `n` 
for `id > 50 OR id < 5`, which includes `id = 99`. Only the first branch reads 
that row, and it never reads `n`.
   - A view computing `100 / (id - 99)` fails the same way with 
`DIVIDE_BY_ZERO`.
   
   An explicit `WITH c AS MATERIALIZED (...)` with the same body fails the same 
way with the config off. So this is how a materialized CTE behaves, but here it 
applies to plain views. The config doc promises that "a view is not converted 
when conversion could change results". I see two ways out:
   - Decline bodies whose expressions can fail. Under ANSI that covers casts, 
division and overflow-checked arithmetic, so it narrows the conversion a lot.
   - Keep the scope, and say in the config doc that the body is evaluated over 
everything the references read, so it can fail where the unconverted query does 
not.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ConvertViewToMaterializedCTE.scala:
##########
@@ -0,0 +1,248 @@
+/*
+ * 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.optimizer
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.TableIdentifier
+import org.apache.spark.sql.catalyst.expressions.{
+  InputFileBlockLength, InputFileBlockStart, InputFileName}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Rewrites multiple references to the same view into one `CTERelationDef` 
with multiple
+ * `CTERelationRef`s, so the view's underlying plan is computed once (through 
exchange
+ * reuse at the physical layer) instead of once per reference. The conversion 
trades that
+ * recomputation for the shuffle `ReplaceCTERefWithRepartition` adds at each 
reference.
+ * It is off by default ([[SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE]]) and 
does nothing
+ * when exchange reuse is disabled, since the added shuffles would then not be 
shared.
+ *
+ * It runs first in `FinishAnalysis`, while `View` nodes are still present, so 
a definition
+ * body taken from a subquery occurrence is cleaned by the rules that run next 
on the main
+ * plan (`Optimizer.scala`).
+ *
+ * Which occurrences of one view may convert, and why hint differences and 
seedless
+ * samples disqualify a body, is defined on `qualifies` and its helpers below.
+ *
+ * A view is analyzed by itself when created, so an outer reference that does 
not resolve
+ * inside the body fails view analysis and never reaches this rule. 
Correlations internal
+ * to the body resolve within the converted definition.
+ */
+object ConvertViewToMaterializedCTE extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val conf = SQLConf.get
+    if (!conf.getConf(SQLConf.CONVERT_VIEW_TO_MATERIALIZED_CTE) || 
!conf.exchangeReuseEnabled) {
+      return plan
+    }
+    // FinishAnalysis re-runs the rule batch on Subquery roots and requires 
the result
+    // to stay a Subquery; the top-level pass already covers views inside 
subqueries.
+    if (plan.isInstanceOf[Subquery]) return plan
+    val occurrences = plan.collectWithSubqueries { case v: View => v }
+    if (occurrences.length < 2) return plan
+
+    // input_file_name() and friends read the scanning task's current file 
block, which is
+    // gone above the added shuffle. Leave the whole plan unchanged so they 
keep running on
+    // the scan.
+    val readsInputFile = plan.collectFirstWithSubqueries {
+      case p if p.expressions.exists(_.exists {
+        case _: InputFileName | _: InputFileBlockStart | _: 
InputFileBlockLength => true
+        case _ => false
+      }) => true
+    }.nonEmpty
+    if (readsInputFile) return plan
+
+    // The rewrite below matches occurrences by view name (`desc.identifier`). 
Convert a
+    // name only when every occurrence of it qualifies and shares one 
canonical body: a
+    // captured Dataset can hold a view body that was replaced after another 
occurrence
+    // captured it, and such an occurrence must not be rebound to the new 
definition.
+    // Inner CTE ids are re-minted on each re-analysis; `normalizeCteIds` 
removes that
+    // noise before the bodies are compared.
+    val qualifiedIdentifiers = occurrences
+      .groupBy(_.desc.identifier)
+      .collect {
+        case (identifier, occs)
+          if qualifies(occs) && occs.map(occ =>
+            normalizeCteIds(occ.child).canonicalized).distinct.length == 1 => 
identifier
+      }
+      .toSet
+    if (qualifiedIdentifiers.isEmpty) return plan
+
+    // transformUp visits nested views first, so each definition is appended 
before the
+    // definitions that reference it. Every occurrence becomes a bare 
reference with its
+    // own output attributes, so duplicated expressions that contained the 
same view stay
+    // equal; later CTE rules rebind the attributes to the definition by 
position.
+    val cteDefs = mutable.ArrayBuffer.empty[CTERelationDef]
+    val defByGroup = mutable.HashMap.empty[TableIdentifier, (CTERelationDef, 
Seq[HintInfo])]
+
+    val rewritten = plan.transformUpWithSubqueries {
+      case v: View if qualifiedIdentifiers.contains(v.desc.identifier) =>
+        // Hints at the top of the body bind to the consuming join, but
+        // `EliminateResolvedHint` cannot walk into a `CTERelationDef`. Build 
the
+        // definition from the hint-free body and re-attach those hints above 
every
+        // reference. `qualifies` has already required the occurrences' hints 
to match.
+        defByGroup.get(v.desc.identifier) match {

Review Comment:
   **Finding 24.** Since every occurrence became a bare reference with `output 
= v.output`, both branches build the same reference. Building the definition on 
first use removes the copy:
   
   ```scala
           val (cteDef, bodyHints) = 
defByGroup.getOrElseUpdate(v.desc.identifier, {
             // `forceSkipInline` is set below, once live references are 
counted.
             val (hintFreeBody, hints) = 
EliminateResolvedHint.extractHintsFromPlan(v.child)
             val d = CTERelationDef(hintFreeBody)
             cteDefs += d
             (d, hints)
           })
           withBodyHints(bodyHints, CTERelationRef(
             cteDef.id,
             _resolved = true,
             output = v.output,
             isStreaming = false,
             maxRows = cteDef.maxRows))
   ```
   



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