You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "zhmin (via GitHub)" <gi...@apache.org> on 2023/03/27 14:06:02 UTC

[GitHub] [spark] zhmin opened a new pull request, #40567: [SPARK-42935] [SQL] Add union required distribution push down

zhmin opened a new pull request, #40567:
URL: https://github.com/apache/spark/pull/40567

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'core/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   We  indroduce a new idea to optimize exchange plan when union spark plan output partitoning can't match parent plan's required distribution.
   
   1. First introduce a new RDD, it consists of parent rdds that has the same partition size. The ith parttition corresponds to ith partition of each parent rdd.
   2. Then push the required distribution to union plan's children. If any child output partitioning matches the required distribution , we can reduce this child shuffle operation.
   
   
   ### Why are the changes needed?
   Union plan does not take full advantage of children plan output partitionings when output partitoning can't match parent plan's required distribution.
   
   
   ### Does this PR introduce _any_ user-facing change?
   No
   
   
   ### How was this patch tested?
   org.apache.spark.sql.execution.PlannerSuite
   org.apache.spark.sql.execution.exchange.UnionZipRDDSuite
   


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


[GitHub] [spark] github-actions[bot] commented on pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #40567:
URL: https://github.com/apache/spark/pull/40567#issuecomment-1633364631

   We're closing this PR because it hasn't been updated in a while. This isn't a judgement on the merit of the PR in any way. It's just a way of keeping the PR queue manageable.
   If you'd like to revive this PR, please reopen it and ask a committer to remove the Stale tag!


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


[GitHub] [spark] jaceklaskowski commented on a diff in pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "jaceklaskowski (via GitHub)" <gi...@apache.org>.
jaceklaskowski commented on code in PR #40567:
URL: https://github.com/apache/spark/pull/40567#discussion_r1153247899


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4195,6 +4195,15 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val UNION_REQUIRED_DISTRIBUTION_PUSHDOWN =
+    buildConf("spark.sql.unionRequiredDistributionPushdown.enabled")
+      .internal()
+      .doc("Enable union spark plan required children distribution pushdown. This is useful when " +

Review Comment:
   nit: Enables



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {

Review Comment:
   Why not `object`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {

Review Comment:
   nit: Replace `map(... => {...})` with `map { ... => }`



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {
+      val firstAttr = attrs.head
+      attrs.forall(_.dataType == firstAttr.dataType)
+    }).forall(_ == true)
+  }
+
+  def createNewChildrenDistribution(unionExec: UnionExec,
+                                    unionRequired: Distribution): Seq[Distribution] = {
+    unionExec.children.map(unionChild => {
+      // create output attributes map (union output exprId -> child output)
+      val attributes = unionExec.output.map(_.exprId).zip(unionChild.output).toMap
+      unionRequired match {
+        case distribution: ClusteredDistribution =>
+          val newExpressions = distribution.clustering.map(exp => exp.transformUp {
+            case attr: Attribute if attributes.contains(attr.exprId) => attributes(attr.exprId)
+          })
+          ClusteredDistribution(newExpressions, distribution.requireAllClusterKeys,
+            distribution.requiredNumPartitions)
+
+        case distribution => distribution
+      }
+    })
+  }
+
+  override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+    case operator: SparkPlan if conf.getConf(SQLConf.UNION_REQUIRED_DISTRIBUTION_PUSHDOWN) &&
+      operator.children.exists(_.isInstanceOf[UnionExec]) =>
+      val newChildren = operator.children.zipWithIndex.map {
+        case (unionExec: UnionExec, childIndex: Int) if !unionExec.outputPartitioning.
+          satisfies(operator.requiredChildDistribution(childIndex)) =>
+          val unionRequired = operator.requiredChildDistribution(childIndex)
+          unionRequired match {
+            case _: ClusteredDistribution if allChildrenSameDataType(unionExec) =>
+              val requiredChildDistribution: Seq[Distribution] =
+                createNewChildrenDistribution(unionExec, unionRequired)
+              val numPartitions = unionRequired.requiredNumPartitions
+                .getOrElse(conf.numShufflePartitions)
+              val outputPartitioning = unionRequired.createPartitioning(numPartitions)
+              UnionZipExec(unionExec.children, requiredChildDistribution,
+                outputPartitioning)
+
+            case _: Distribution => unionExec
+          }
+
+        case (child, _) => child
+      }
+      operator.withNewChildren(newChildren)
+  }
+}
+
+/**
+ * Class representing partitions of UnionZipRDD, which maintains the list of
+ * corresponding partitions of parent RDDs.
+ */
+private[spark]
+class UnionZipRDDPartition(@transient val rdds: Seq[RDD[_]],
+                           override val index: Int) extends Partition {
+  var parents: Array[Partition] = rdds.map(_.partitions(index)).toArray
+
+  override def hashCode(): Int = index
+
+  override def equals(other: Any): Boolean = super.equals(other)
+
+  @throws(classOf[IOException])
+  private def writeObject(oos: ObjectOutputStream): Unit = Utils.tryOrIOException {
+    // Update the reference to parent partition at the time of task serialization
+    parents = rdds.map(_.partitions(index)).toArray
+    oos.defaultWriteObject()
+  }
+}
+
+/**
+ * Class representing an RDD that can take multiple RDDs with same partition size and
+ * unify them into a single RDD while preserving the partition. So m RDDs with p partitions
+ * will be unified to a single RDD with p partitions, which the ith partition consists of the
+ * ith partition in each parent RDD.
+ */
+private[spark]
+class UnionZipRDD[T: ClassTag](sc: SparkContext, var rdds: Seq[RDD[T]])

Review Comment:
   nit: Can you move arguments to their own lines?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {
+      val firstAttr = attrs.head
+      attrs.forall(_.dataType == firstAttr.dataType)
+    }).forall(_ == true)
+  }
+
+  def createNewChildrenDistribution(unionExec: UnionExec,
+                                    unionRequired: Distribution): Seq[Distribution] = {
+    unionExec.children.map(unionChild => {
+      // create output attributes map (union output exprId -> child output)
+      val attributes = unionExec.output.map(_.exprId).zip(unionChild.output).toMap
+      unionRequired match {
+        case distribution: ClusteredDistribution =>
+          val newExpressions = distribution.clustering.map(exp => exp.transformUp {
+            case attr: Attribute if attributes.contains(attr.exprId) => attributes(attr.exprId)
+          })
+          ClusteredDistribution(newExpressions, distribution.requireAllClusterKeys,
+            distribution.requiredNumPartitions)
+
+        case distribution => distribution
+      }
+    })
+  }
+
+  override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+    case operator: SparkPlan if conf.getConf(SQLConf.UNION_REQUIRED_DISTRIBUTION_PUSHDOWN) &&
+      operator.children.exists(_.isInstanceOf[UnionExec]) =>
+      val newChildren = operator.children.zipWithIndex.map {
+        case (unionExec: UnionExec, childIndex: Int) if !unionExec.outputPartitioning.
+          satisfies(operator.requiredChildDistribution(childIndex)) =>
+          val unionRequired = operator.requiredChildDistribution(childIndex)
+          unionRequired match {
+            case _: ClusteredDistribution if allChildrenSameDataType(unionExec) =>
+              val requiredChildDistribution: Seq[Distribution] =
+                createNewChildrenDistribution(unionExec, unionRequired)
+              val numPartitions = unionRequired.requiredNumPartitions
+                .getOrElse(conf.numShufflePartitions)
+              val outputPartitioning = unionRequired.createPartitioning(numPartitions)
+              UnionZipExec(unionExec.children, requiredChildDistribution,
+                outputPartitioning)
+
+            case _: Distribution => unionExec
+          }
+
+        case (child, _) => child
+      }
+      operator.withNewChildren(newChildren)
+  }
+}
+
+/**
+ * Class representing partitions of UnionZipRDD, which maintains the list of
+ * corresponding partitions of parent RDDs.
+ */
+private[spark]
+class UnionZipRDDPartition(@transient val rdds: Seq[RDD[_]],
+                           override val index: Int) extends Partition {
+  var parents: Array[Partition] = rdds.map(_.partitions(index)).toArray
+
+  override def hashCode(): Int = index
+
+  override def equals(other: Any): Boolean = super.equals(other)

Review Comment:
   Is `equals` required? Doesn't do much.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {
+      val firstAttr = attrs.head
+      attrs.forall(_.dataType == firstAttr.dataType)
+    }).forall(_ == true)
+  }
+
+  def createNewChildrenDistribution(unionExec: UnionExec,
+                                    unionRequired: Distribution): Seq[Distribution] = {
+    unionExec.children.map(unionChild => {

Review Comment:
   same as above



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


[GitHub] [spark] github-actions[bot] closed pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down
URL: https://github.com/apache/spark/pull/40567


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


[GitHub] [spark] zhmin commented on a diff in pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "zhmin (via GitHub)" <gi...@apache.org>.
zhmin commented on code in PR #40567:
URL: https://github.com/apache/spark/pull/40567#discussion_r1154322505


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {
+      val firstAttr = attrs.head
+      attrs.forall(_.dataType == firstAttr.dataType)
+    }).forall(_ == true)
+  }
+
+  def createNewChildrenDistribution(unionExec: UnionExec,
+                                    unionRequired: Distribution): Seq[Distribution] = {
+    unionExec.children.map(unionChild => {
+      // create output attributes map (union output exprId -> child output)
+      val attributes = unionExec.output.map(_.exprId).zip(unionChild.output).toMap
+      unionRequired match {
+        case distribution: ClusteredDistribution =>
+          val newExpressions = distribution.clustering.map(exp => exp.transformUp {
+            case attr: Attribute if attributes.contains(attr.exprId) => attributes(attr.exprId)
+          })
+          ClusteredDistribution(newExpressions, distribution.requireAllClusterKeys,
+            distribution.requiredNumPartitions)
+
+        case distribution => distribution
+      }
+    })
+  }
+
+  override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+    case operator: SparkPlan if conf.getConf(SQLConf.UNION_REQUIRED_DISTRIBUTION_PUSHDOWN) &&
+      operator.children.exists(_.isInstanceOf[UnionExec]) =>
+      val newChildren = operator.children.zipWithIndex.map {
+        case (unionExec: UnionExec, childIndex: Int) if !unionExec.outputPartitioning.
+          satisfies(operator.requiredChildDistribution(childIndex)) =>
+          val unionRequired = operator.requiredChildDistribution(childIndex)
+          unionRequired match {
+            case _: ClusteredDistribution if allChildrenSameDataType(unionExec) =>
+              val requiredChildDistribution: Seq[Distribution] =
+                createNewChildrenDistribution(unionExec, unionRequired)
+              val numPartitions = unionRequired.requiredNumPartitions
+                .getOrElse(conf.numShufflePartitions)
+              val outputPartitioning = unionRequired.createPartitioning(numPartitions)
+              UnionZipExec(unionExec.children, requiredChildDistribution,
+                outputPartitioning)
+
+            case _: Distribution => unionExec
+          }
+
+        case (child, _) => child
+      }
+      operator.withNewChildren(newChildren)
+  }
+}
+
+/**
+ * Class representing partitions of UnionZipRDD, which maintains the list of
+ * corresponding partitions of parent RDDs.
+ */
+private[spark]
+class UnionZipRDDPartition(@transient val rdds: Seq[RDD[_]],
+                           override val index: Int) extends Partition {
+  var parents: Array[Partition] = rdds.map(_.partitions(index)).toArray
+
+  override def hashCode(): Int = index
+
+  override def equals(other: Any): Boolean = super.equals(other)

Review Comment:
   Thanks for your advice ! I have updated it.



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


[GitHub] [spark] zhmin commented on pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "zhmin (via GitHub)" <gi...@apache.org>.
zhmin commented on PR #40567:
URL: https://github.com/apache/spark/pull/40567#issuecomment-1487823925

   cc @dongjoon-hyun @cloud-fan @viirya @yaooqinn thank you


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


[GitHub] [spark] zhmin commented on a diff in pull request #40567: [SPARK-42935] [SQL] Add union required distribution push down

Posted by "zhmin (via GitHub)" <gi...@apache.org>.
zhmin commented on code in PR #40567:
URL: https://github.com/apache/spark/pull/40567#discussion_r1154322170


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/UnionDistributionPushdown.scala:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.exchange
+
+import java.io.{IOException, ObjectOutputStream}
+
+import scala.reflect.ClassTag
+
+import org.apache.spark.{OneToOneDependency, Partition, SparkContext, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, Distribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec, UnionZipExec}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Pushes parent's required distribution to [[UnionExec]] so that we can
+ * remove unnecessary shuffle exchange if any child output partitioning matches
+ * 1) the operator is UnionExec
+ * 2) the operator's output partitioning can not satisfy parent distribution
+ * 3) the operator's parent requires hashing or clustering distribution
+ * 4) the data types of operator's children output attributes are the same
+ */
+case class UnionDistributionPushdown() extends Rule[SparkPlan] {
+
+  def allChildrenSameDataType(unionExec: UnionExec): Boolean = {
+    (Seq(unionExec) ++ unionExec.children).map(_.output).transpose.map(attrs => {
+      val firstAttr = attrs.head
+      attrs.forall(_.dataType == firstAttr.dataType)
+    }).forall(_ == true)
+  }
+
+  def createNewChildrenDistribution(unionExec: UnionExec,
+                                    unionRequired: Distribution): Seq[Distribution] = {
+    unionExec.children.map(unionChild => {
+      // create output attributes map (union output exprId -> child output)
+      val attributes = unionExec.output.map(_.exprId).zip(unionChild.output).toMap
+      unionRequired match {
+        case distribution: ClusteredDistribution =>
+          val newExpressions = distribution.clustering.map(exp => exp.transformUp {
+            case attr: Attribute if attributes.contains(attr.exprId) => attributes(attr.exprId)
+          })
+          ClusteredDistribution(newExpressions, distribution.requireAllClusterKeys,
+            distribution.requiredNumPartitions)
+
+        case distribution => distribution
+      }
+    })
+  }
+
+  override def apply(plan: SparkPlan): SparkPlan = plan.transformUp {
+    case operator: SparkPlan if conf.getConf(SQLConf.UNION_REQUIRED_DISTRIBUTION_PUSHDOWN) &&
+      operator.children.exists(_.isInstanceOf[UnionExec]) =>
+      val newChildren = operator.children.zipWithIndex.map {
+        case (unionExec: UnionExec, childIndex: Int) if !unionExec.outputPartitioning.
+          satisfies(operator.requiredChildDistribution(childIndex)) =>
+          val unionRequired = operator.requiredChildDistribution(childIndex)
+          unionRequired match {
+            case _: ClusteredDistribution if allChildrenSameDataType(unionExec) =>
+              val requiredChildDistribution: Seq[Distribution] =
+                createNewChildrenDistribution(unionExec, unionRequired)
+              val numPartitions = unionRequired.requiredNumPartitions
+                .getOrElse(conf.numShufflePartitions)
+              val outputPartitioning = unionRequired.createPartitioning(numPartitions)
+              UnionZipExec(unionExec.children, requiredChildDistribution,
+                outputPartitioning)
+
+            case _: Distribution => unionExec
+          }
+
+        case (child, _) => child
+      }
+      operator.withNewChildren(newChildren)
+  }
+}
+
+/**
+ * Class representing partitions of UnionZipRDD, which maintains the list of
+ * corresponding partitions of parent RDDs.
+ */
+private[spark]
+class UnionZipRDDPartition(@transient val rdds: Seq[RDD[_]],
+                           override val index: Int) extends Partition {
+  var parents: Array[Partition] = rdds.map(_.partitions(index)).toArray
+
+  override def hashCode(): Int = index
+
+  override def equals(other: Any): Boolean = super.equals(other)

Review Comment:
   Thanks for your advice ! I have updated it.



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