You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2021/12/09 16:57:02 UTC

[GitHub] [spark] attilapiros commented on a change in pull request #32298: [SPARK-34079][SQL] Merge non-correlated scalar subqueries

attilapiros commented on a change in pull request #32298:
URL: https://github.com/apache/spark/pull/32298#discussion_r765004424



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala
##########
@@ -0,0 +1,422 @@
+/*
+ * 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.ListBuffer
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.QueryPlan
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, CommonScalarSubqueries, Filter, Join, LogicalPlan, Project, Subquery}
+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.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
+ *   [[ScalarSubqueryReference]] pointing to its cached version.
+ *   The cache uses a flag to keep track of if a cache entry is a results 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 is is basically
+ *   `CreateNamedStruct(name1, attribute1, name2, attribute2, ...)` expression in new root
+ *   [[Project]] node. This expression ensures that the merged plan is a valid scalar subquery that
+ *   returns only one value.
+ * - A second traversal checks if a [[ScalarSubqueryReference]] is pointing to a merged subquery
+ *   plan or not and either keeps the reference or restores the original [[ScalarSubquery]].
+ *   If there are [[ScalarSubqueryReference]] nodes remained a [[CommonScalarSubqueries]] root node
+ *   is added to the plan with the referenced scalar subqueries.
+ * - [[PlanSubqueries]] or [[PlanAdaptiveSubqueries]] rule does the physical planning of scalar
+ *   subqueries including the ones under [[CommonScalarSubqueriesExec]] node and replaces
+ *   each [[ScalarSubqueryReference]] to their referenced physical plan in
+ *   `GetStructField(ScalarSubquery(merged plan with CreateNamedStruct() header))` form.
+ *   It is important that references pointing to the same merged subquery are replaced to the same
+ *   planned instance to make sure that each merged subquery runs only once (even without a wrapping
+ *   [[ReuseSubquery]] node).
+ *   Finally, the [[CommonScalarSubqueriesExec]] node is removed from the physical plan.
+ * - The [[ReuseExchangeAndSubquery]] rule wraps the second, third, ... instances of the same
+ *   subquery into a [[ReuseSubquery]] node, but this just a cosmetic change in the plan.
+ *
+ * Eg. the following query:
+ *
+ * SELECT
+ *   (SELECT avg(a) FROM t GROUP BY b),
+ *   (SELECT sum(b) FROM t GROUP BY b)
+ *
+ * is optimized from:
+ *
+ * Project [scalar-subquery#231 [] AS scalarsubquery()#241,
+ *          scalar-subquery#232 [] AS scalarsubquery()#242L]
+ * :  :- Aggregate [b#234], [avg(a#233) AS avg(a)#236]
+ * :  :  +- Relation default.t[a#233,b#234] parquet
+ * :  +- Aggregate [b#240], [sum(b#240) AS sum(b)#238L]
+ * :     +- Project [b#240]
+ * :        +- Relation default.t[a#239,b#240] parquet
+ * +- OneRowRelation
+ *
+ * to:
+ *
+ * CommonScalarSubqueries [scalar-subquery#250 []]
+ * :  +- Project [named_struct(avg(a), avg(a)#236, sum(b), sum(b)#238L) AS mergedValue#249]
+ * :     +- Aggregate [b#234], [avg(a#233) AS avg(a)#236, sum(b#234) AS sum(b)#238L]
+ * :        +- Project [a#233, b#234]
+ * :           +- Relation default.t[a#233,b#234] parquet
+ * +- Project [scalarsubqueryreference(0, 0, DoubleType, 231) AS scalarsubquery()#241,
+ *             scalarsubqueryreference(0, 1, LongType, 232) AS scalarsubquery()#242L]
+ *    +- OneRowRelation
+ */
+object MergeScalarSubqueries extends Rule[LogicalPlan] with PredicateHelper {
+  def apply(plan: LogicalPlan): LogicalPlan = {
+    plan match {
+      case Subquery(_: CommonScalarSubqueries, _) => plan
+      case s: Subquery => s.copy(child = extractCommonScalarSubqueries(s.child))
+      case _: CommonScalarSubqueries => plan
+      case _ => extractCommonScalarSubqueries(plan)
+    }
+  }
+
+  /**
+   * An item in the cache of merged scalar subqueries.
+   *
+   * @param elements  List of attributes that form the 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 `elements.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
+   *                  `elements.size` remains 1 after merging, but the merged flag becomes true.
+   */
+  case class Header(elements: Seq[(String, Attribute)], plan: LogicalPlan, merged: Boolean)
+
+  private def extractCommonScalarSubqueries(plan: LogicalPlan) = {
+    val cache = ListBuffer.empty[Header]
+    val newPlan = removeReferences(insertReferences(plan, cache), cache)
+    if (cache.nonEmpty) {
+      val scalarSubqueries = cache.map {
+        case Header(elements, child, _) => ScalarSubquery(createProject(elements, child))
+      }.toSeq
+      CommonScalarSubqueries(scalarSubqueries, newPlan)
+    } else {
+      newPlan
+    }
+  }
+
+  // First traversal builds up the cache and inserts `ScalarSubqueryReference`s to the plan.
+  private def insertReferences(plan: LogicalPlan, cache: ListBuffer[Header]): LogicalPlan = {
+    plan.transformAllExpressionsWithPruning(_.containsAnyPattern(SCALAR_SUBQUERY)) {
+      case s: ScalarSubquery if s.children.isEmpty =>

Review comment:
       As nondeterministic plans are skipped I think we could skip those here (as early as possible).




-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org