xumingming commented on code in PR #58229:
URL: https://github.com/apache/spark/pull/58229#discussion_r4613417809


##########
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:
   You're right about the mechanism: two live refs are counted, 
`PullOutGroupingExpressions` later merges the copies, and the shuffle ends up 
with a single reader. I'd concede this is different in kind from the other 
documented costs — those trade something for reuse, this one buys nothing.
   
   Still, I'd prefer to leave it as a known limitation:
   
   - The overhead is bounded: the view body still computes once; the waste is 
one extra shuffle stage with no reuse, not a blowup.
   - The config is opt-in, and the query shape (grouping by a correlated scalar 
subquery over a multi-referenced view) is rare.
   - The suggested fix would make `countLiveRefs` replicate 
`PullOutGroupingExpressions`' semantic matching, including correlation handling 
— coupling two rules' internals for a case that may never show up in a real 
workload.
   
   Happy to revisit if it does show up in practice.



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