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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/merge/MergeScalarSubqueries.scala:
##########
@@ -0,0 +1,627 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.merge
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions._
+import 
org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression, 
Average, Count, Max, Min, Sum}
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, CTERelationDef, 
CTERelationRef, Filter, Join, LocalRelation, LogicalPlan, Project, 
SerializeFromObject, Subquery, WithCTE}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{SCALAR_SUBQUERY, 
SCALAR_SUBQUERY_REFERENCE, TreePattern}
+import org.apache.spark.sql.execution.ExternalRDD
+import org.apache.spark.sql.execution.datasources.FileSourceScanPlan
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * This rule tries to merge multiple non-correlated [[ScalarSubquery]]s to 
compute multiple scalar
+ * values once.
+ *
+ * The process is the following:
+ * - While traversing through the plan each [[ScalarSubquery]] plan is tried 
to merge into the cache
+ *   of already seen subquery plans. If merge is possible then cache is 
updated with the merged
+ *   subquery plan, if not then the new subquery plan is added to the cache.
+ *   During this first traversal each [[ScalarSubquery]] expression is 
replaced to a temporal
+ *   [[ScalarSubqueryReference]] reference pointing to its cached version.
+ *   The cache uses a flag to keep track of if a cache entry is a result of 
merging 2 or more
+ *   plans, or it is a plan that was seen only once.
+ *   Merged plans in the cache get a "Header", that contains the list of 
attributes form the scalar
+ *   return value of a merged subquery.
+ * - A second traversal checks if there are merged subqueries in the cache and 
builds a `WithCTE`
+ *   node from these queries. The `CTERelationDef` nodes contain the merged 
subquery in the
+ *   following form:
+ *   `Project(Seq(CreateNamedStruct(name1, attribute1, ...) AS mergedValue), 
mergedSubqueryPlan)`
+ *   and the definitions are flagged that they host a subquery, that can 
return maximum one row.
+ *   During the second traversal [[ScalarSubqueryReference]] expressions that 
pont to a merged
+ *   subquery is either transformed to a 
`GetStructField(ScalarSubquery(CTERelationRef(...)))`
+ *   expression or restored to the original [[ScalarSubquery]].
+ *
+ * Eg. the following query:
+ *
+ * SELECT
+ *   (SELECT avg(a) FROM t),
+ *   (SELECT sum(b) FROM t)
+ *
+ * is optimized from:
+ *
+ * == Optimized Logical Plan ==
+ * Project [scalar-subquery#242 [] AS scalarsubquery()#253,
+ *          scalar-subquery#243 [] AS scalarsubquery()#254L]
+ * :  :- Aggregate [avg(a#244) AS avg(a)#247]
+ * :  :  +- Project [a#244]
+ * :  :     +- Relation default.t[a#244,b#245] parquet
+ * :  +- Aggregate [sum(a#251) AS sum(a)#250L]
+ * :     +- Project [a#251]
+ * :        +- Relation default.t[a#251,b#252] parquet
+ * +- OneRowRelation
+ *
+ * to:
+ *
+ * == Optimized Logical Plan ==
+ * Project [scalar-subquery#242 [].avg(a) AS scalarsubquery()#253,
+ *          scalar-subquery#243 [].sum(a) AS scalarsubquery()#254L]
+ * :  :- Project [named_struct(avg(a), avg(a)#247, sum(a), sum(a)#250L) AS 
mergedValue#260]
+ * :  :  +- Aggregate [avg(a#244) AS avg(a)#247, sum(a#244) AS sum(a)#250L]
+ * :  :     +- Project [a#244]
+ * :  :        +- Relation default.t[a#244,b#245] parquet
+ * :  +- Project [named_struct(avg(a), avg(a)#247, sum(a), sum(a)#250L) AS 
mergedValue#260]
+ * :     +- Aggregate [avg(a#244) AS avg(a)#247, sum(a#244) AS sum(a)#250L]
+ * :        +- Project [a#244]
+ * :           +- Relation default.t[a#244,b#245] parquet
+ * +- OneRowRelation
+ *
+ * == Physical Plan ==
+ *  *(1) Project [Subquery scalar-subquery#242, [id=#125].avg(a) AS 
scalarsubquery()#253,
+ *                ReusedSubquery
+ *                  Subquery scalar-subquery#242, [id=#125].sum(a) AS 
scalarsubquery()#254L]
+ * :  :- Subquery scalar-subquery#242, [id=#125]
+ * :  :  +- *(2) Project [named_struct(avg(a), avg(a)#247, sum(a), 
sum(a)#250L) AS mergedValue#260]
+ * :  :     +- *(2) HashAggregate(keys=[], functions=[avg(a#244), sum(a#244)],
+ *                                output=[avg(a)#247, sum(a)#250L])
+ * :  :        +- Exchange SinglePartition, ENSURE_REQUIREMENTS, [id=#120]
+ * :  :           +- *(1) HashAggregate(keys=[], 
functions=[partial_avg(a#244), partial_sum(a#244)],
+ *                                      output=[sum#262, count#263L, sum#264L])
+ * :  :              +- *(1) ColumnarToRow
+ * :  :                 +- FileScan parquet default.t[a#244] ...
+ * :  +- ReusedSubquery Subquery scalar-subquery#242, [id=#125]
+ * +- *(1) Scan OneRowRelation[]
+ */
+object MergeScalarSubqueries extends Rule[LogicalPlan] {
+  def apply(plan: LogicalPlan): LogicalPlan = {
+    plan match {
+      // Subquery reuse needs to be enabled for this optimization.
+      case _ if !conf.getConf(SQLConf.SUBQUERY_REUSE_ENABLED) => plan
+
+      // This rule does a whole plan traversal, no need to run on subqueries.
+      case _: Subquery => plan
+
+      // Plans with CTEs are not supported for now.
+      case _: WithCTE => plan
+
+      case _ => extractCommonScalarSubqueries(plan)
+    }
+  }
+
+  /**
+   * An item in the cache of merged scalar subqueries.
+   *
+   * @param attributes Attributes that form the struct scalar return value of 
a merged subquery.
+   * @param plan The plan of a merged scalar subquery.
+   * @param merged A flag to identify if this item is the result of merging 
subqueries.
+   *               Please note that `attributes.size == 1` doesn't always mean 
that the plan is not
+   *               merged as there can be subqueries that are different 
([[checkIdenticalPlans]] is
+   *               false) due to an extra [[Project]] node in one of them. In 
that case
+   *               `attributes.size` remains 1 after merging, but the merged 
flag becomes true.
+   */
+  case class Header(attributes: Seq[Attribute], plan: LogicalPlan, merged: 
Boolean)
+
+  private def extractCommonScalarSubqueries(plan: LogicalPlan) = {
+    val cache = ArrayBuffer.empty[Header]
+    val planWithReferences = insertReferences(plan, cache)
+    cache.zipWithIndex.foreach { case (header, i) =>
+      cache(i) = cache(i).copy(plan =
+        if (header.merged) {
+          CTERelationDef(
+            createProject(header.attributes,
+              removePropagatedFilters(removeReferences(header.plan, cache))),
+            underSubquery = true)
+        } else {
+          removePropagatedFilters(removeReferences(header.plan, cache))
+        })
+    }
+    val newPlan = removePropagatedFilters(removeReferences(planWithReferences, 
cache))
+    val subqueryCTEs = 
cache.filter(_.merged).map(_.plan.asInstanceOf[CTERelationDef])
+    if (subqueryCTEs.nonEmpty) {
+      WithCTE(newPlan, subqueryCTEs.toSeq)
+    } else {
+      newPlan
+    }
+  }
+
+  // First traversal builds up the cache and inserts 
`ScalarSubqueryReference`s to the plan.
+  private def insertReferences(plan: LogicalPlan, cache: ArrayBuffer[Header]): 
LogicalPlan = {
+    plan.transformUpWithSubqueries {
+      case n => 
n.transformExpressionsUpWithPruning(_.containsAnyPattern(SCALAR_SUBQUERY)) {
+        case s: ScalarSubquery if !s.isCorrelated && s.deterministic =>
+          val (subqueryIndex, headerIndex) = cacheSubquery(s.plan, cache)
+          ScalarSubqueryReference(subqueryIndex, headerIndex, s.dataType, 
s.exprId)
+      }
+    }
+  }
+
+  // State of the plan merging algorithm
+  object ScanCheck extends Enumeration {
+    type ScanCheck = Value
+
+    // There is no need to check if physical plan is mergeable until we don't 
encounter `Filter`s
+    // with different predicates
+    val NO_NEED,
+
+    // We switch to this state once we encounter different `Filters` in the 
plans we want to merge.
+    // Identical logical plans is not enough to consider the plans mergeagle, 
but we also need to
+    // check physical scans to determine if partition, bucket and other pushed 
down filters are
+    // safely mergeable without performance degradation.
+    CHECKING,
+
+    DONE = Value
+    // Once the physical check is complete we use this state to finish the 
logical merge check.
+  }
+
+  import ScanCheck._
+
+  // Caching returns the index of the subquery in the cache and the index of 
scalar member in the
+  // "Header".
+  private def cacheSubquery(plan: LogicalPlan, cache: ArrayBuffer[Header]): 
(Int, Int) = {
+    val output = plan.output.head
+    cache.zipWithIndex.collectFirst(Function.unlift { case (header, 
subqueryIndex) =>
+      checkIdenticalPlans(plan, header.plan).map { outputMap =>
+        val mappedOutput = mapAttributes(output, outputMap)
+        val headerIndex = header.attributes.indexWhere(_.exprId == 
mappedOutput.exprId)
+        subqueryIndex -> headerIndex
+      }.orElse(tryMergePlans(plan, header.plan, NO_NEED).collect {
+        case (mergedPlan, outputMap, None, None) =>
+          val mappedOutput = mapAttributes(output, outputMap)
+          var headerIndex = header.attributes.indexWhere(_.exprId == 
mappedOutput.exprId)
+          val newHeaderAttributes = if (headerIndex == -1) {
+            headerIndex = header.attributes.size
+            header.attributes :+ mappedOutput
+          } else {
+            header.attributes
+          }
+          cache(subqueryIndex) = Header(newHeaderAttributes, mergedPlan, true)
+          subqueryIndex -> headerIndex
+      })
+    }).getOrElse {
+      cache += Header(Seq(output), plan, false)
+      cache.length - 1 -> 0
+    }
+  }
+
+  // If 2 plans are identical return the attribute mapping from the new to the 
cached version.
+  private def checkIdenticalPlans(
+      newPlan: LogicalPlan,
+      cachedPlan: LogicalPlan): Option[AttributeMap[Attribute]] = {
+    if (newPlan.canonicalized == cachedPlan.canonicalized) {

Review Comment:
   No this doesn't work with DSv2 sources (nor did the the original 
https://github.com/apache/spark/pull/32298).
   
   I'm planning to add DSv2 support in another follow-up PR. Probably with 
introducing an `SupportsMerge` interface that `Scan`s can implement to merge 
with another `Scan`.



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