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/17 05:18:21 UTC

[GitHub] [spark] maryannxue opened a new pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

maryannxue opened a new pull request #34929:
URL: https://github.com/apache/spark/pull/34929


   <!--
   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?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   This PR adds predicate push-down and column pruning to CTEs that are not inlined as well as fixes a few potential correctness issues:
     1) Replace (previously not inlined) CTE refs with Repartition operations at the end of logical plan optimization so that WithCTE is not carried over to physical plan. As a result, we can simplify the logic of physical planning, as well as avoid a correctness issue where the logical link of a physical plan node can point to `WithCTE` and lead to unexpected behaviors in AQE, e.g., class cast exceptions in DPP/DFP.
     2) Pull (not inlined) CTE defs from subqueries up to the main query level, in order to avoid creating copies of the same CTE def during predicate push-downs and other transformations.
     3) Make CTE IDs more deterministic by starting from 0 for each query.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   Improve de-duped CTEs' performance with predicate pushdown and column pruning; fixes de-duped CTEs' correctness issues.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   No.
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   
   Added UTs.


-- 
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] SparkQA commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996491348


   Kubernetes integration test status failure
   URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/50788/
   


-- 
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] SparkQA commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996465568


   Kubernetes integration test starting
   URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/50788/
   


-- 
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] SparkQA commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996501165


   **[Test build #146315 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/146315/testReport)** for PR 34929 at commit [`841aa2a`](https://github.com/apache/spark/commit/841aa2abd7a697bc402e4321f771bf7cbba22089).
    * This patch **fails Spark unit tests**.
    * This patch merges cleanly.
    * This patch adds no public classes.


-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779665758



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
+      val cteMap = new CteMap
+      gatherPredicatesAndAttributes(plan, cteMap)
+      pushdownPredicatesAndAttributes(plan, cteMap)
+    } else {
+      plan
+    }
+  }
+
+  private def reverseMapExpressions(

Review comment:
       `restoreCTEDefAttrs`?




-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779653096



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
+      val cteMap = new CteMap
+      gatherPredicatesAndAttributes(plan, cteMap)
+      pushdownPredicatesAndAttributes(plan, cteMap)
+    } else {
+      plan
+    }
+  }
+
+  private def reverseMapExpressions(
+      input: Seq[Expression],
+      mapping: Map[Attribute, Expression]): Seq[Expression] = {
+    input.map(e => e.transform {
+      case a: Attribute =>
+        mapping.keys.find(_.semanticEquals(a)).map(mapping).getOrElse(a)
+    })
+  }
+
+  /**
+   * Gather all the predicates and referenced attributes on different points of CTE references
+   * using pattern `ScanOperation` (which takes care of determinism) and combine those predicates
+   * and attributes that belong to the same CTE definition.
+   * For the same CTE definition, if any of its references does not have predicates, the combined
+   * predicate will be a TRUE literal, which means there will be no predicate push-down.
+   */
+  private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap: CteMap): Unit = {
+    plan match {
+      case WithCTE(child, cteDefs) =>
+        cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+          gatherPredicatesAndAttributes(cteDef.child, cteMap)
+          cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty, AttributeSet.empty))
+        }
+        gatherPredicatesAndAttributes(child, cteMap)
+
+      case ScanOperation(projects, predicates, ref: CTERelationRef) =>
+        val (cteDef, precedence, preds, attrs) = cteMap(ref.cteId)
+        val mapping = ref.output.zip(cteDef.output).map{ case (r, d) => r -> d }.toMap

Review comment:
       ```suggestion
           val attrMapping = ref.output.zip(cteDef.output).map { case (r, d) => r -> d }.toMap
   ```




-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779653096



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
+      val cteMap = new CteMap
+      gatherPredicatesAndAttributes(plan, cteMap)
+      pushdownPredicatesAndAttributes(plan, cteMap)
+    } else {
+      plan
+    }
+  }
+
+  private def reverseMapExpressions(
+      input: Seq[Expression],
+      mapping: Map[Attribute, Expression]): Seq[Expression] = {
+    input.map(e => e.transform {
+      case a: Attribute =>
+        mapping.keys.find(_.semanticEquals(a)).map(mapping).getOrElse(a)
+    })
+  }
+
+  /**
+   * Gather all the predicates and referenced attributes on different points of CTE references
+   * using pattern `ScanOperation` (which takes care of determinism) and combine those predicates
+   * and attributes that belong to the same CTE definition.
+   * For the same CTE definition, if any of its references does not have predicates, the combined
+   * predicate will be a TRUE literal, which means there will be no predicate push-down.
+   */
+  private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap: CteMap): Unit = {
+    plan match {
+      case WithCTE(child, cteDefs) =>
+        cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+          gatherPredicatesAndAttributes(cteDef.child, cteMap)
+          cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty, AttributeSet.empty))
+        }
+        gatherPredicatesAndAttributes(child, cteMap)
+
+      case ScanOperation(projects, predicates, ref: CTERelationRef) =>
+        val (cteDef, precedence, preds, attrs) = cteMap(ref.cteId)
+        val mapping = ref.output.zip(cteDef.output).map{ case (r, d) => r -> d }.toMap

Review comment:
       ```suggestion
           val mapping = ref.output.zip(cteDef.output).map { case (r, d) => r -> d }.toMap
   ```




-- 
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] AmplabJenkins commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996501308


   
   Refer to this link for build results (access rights to CI server needed): 
   https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/146315/
   


-- 
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] AmplabJenkins commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996496554


   
   Refer to this link for build results (access rights to CI server needed): 
   https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/50788/
   


-- 
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] SparkQA commented on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996449332


   **[Test build #146315 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/146315/testReport)** for PR 34929 at commit [`841aa2a`](https://github.com/apache/spark/commit/841aa2abd7a697bc402e4321f771bf7cbba22089).


-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779611578



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
##########
@@ -1012,6 +1016,24 @@ class Analyzer(override val catalogManager: CatalogManager)
         // inside a view maybe resolved incorrectly.
         checkAnalysis(newChild)
         view.copy(child = newChild)
+      case view @ View(_, _, child) =>

Review comment:
       Let's add a comment before this case
   ```
   // This is DataFrame view, not SQL view. We need to reassign CTE IDs as the plan
   // is already resolved but the CTE IDs may conflict with main query.
   ```




-- 
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] AmplabJenkins removed a comment on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996501308


   
   Refer to this link for build results (access rights to CI server needed): 
   https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/146315/
   


-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779667322



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
+      val cteMap = new CteMap
+      gatherPredicatesAndAttributes(plan, cteMap)
+      pushdownPredicatesAndAttributes(plan, cteMap)
+    } else {
+      plan
+    }
+  }
+
+  private def reverseMapExpressions(
+      input: Seq[Expression],
+      mapping: Map[Attribute, Expression]): Seq[Expression] = {
+    input.map(e => e.transform {
+      case a: Attribute =>
+        mapping.keys.find(_.semanticEquals(a)).map(mapping).getOrElse(a)
+    })
+  }
+
+  /**
+   * Gather all the predicates and referenced attributes on different points of CTE references
+   * using pattern `ScanOperation` (which takes care of determinism) and combine those predicates
+   * and attributes that belong to the same CTE definition.
+   * For the same CTE definition, if any of its references does not have predicates, the combined
+   * predicate will be a TRUE literal, which means there will be no predicate push-down.
+   */
+  private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap: CteMap): Unit = {
+    plan match {
+      case WithCTE(child, cteDefs) =>
+        cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+          gatherPredicatesAndAttributes(cteDef.child, cteMap)
+          cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty, AttributeSet.empty))
+        }
+        gatherPredicatesAndAttributes(child, cteMap)
+
+      case ScanOperation(projects, predicates, ref: CTERelationRef) =>
+        val (cteDef, precedence, preds, attrs) = cteMap(ref.cteId)
+        val mapping = ref.output.zip(cteDef.output).map{ case (r, d) => r -> d }.toMap
+        val newPredicates = if (isTruePredicate(preds)) {
+          preds
+        } else {
+          val filteredPredicates = reverseMapExpressions(predicates.filter(_.find {
+            case s: SubqueryExpression => s.plan.find {
+              case r: CTERelationRef =>
+                !cteMap.contains(r.cteId) || cteMap(r.cteId)._2 >= precedence

Review comment:
       `!cteMap.contains(r.cteId)` is kind of a sanity check, as we should collect Def first before hitting its Ref. But I don't quite understand what `cteMap(r.cteId)._2 >= precedence` means.




-- 
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] AmplabJenkins removed a comment on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996496554


   
   Refer to this link for build results (access rights to CI server needed): 
   https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/50788/
   


-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779643115



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala
##########
@@ -93,25 +101,24 @@ object InlineCTE extends Rule[LogicalPlan] {
   private def inlineCTE(
       plan: LogicalPlan,
       cteMap: mutable.HashMap[Long, (CTERelationDef, Int)],
-      forceInline: Boolean): LogicalPlan = {
-    val (stripped, notInlined) = plan match {
+      notInlined: mutable.ArrayBuffer[CTERelationDef]): LogicalPlan = {
+    plan match {
       case WithCTE(child, cteDefs) =>
-        val notInlined = mutable.ArrayBuffer.empty[CTERelationDef]
         cteDefs.foreach { cteDef =>
           val (cte, refCount) = cteMap(cteDef.id)
           if (refCount > 0) {
-            val inlined = cte.copy(child = inlineCTE(cte.child, cteMap, forceInline))
+            val inlined = cte.copy(child = inlineCTE(cte.child, cteMap, notInlined))
             cteMap.update(cteDef.id, (inlined, refCount))
-            if (!forceInline && !shouldInline(inlined, refCount)) {
+            if (!shouldInline(inlined, refCount)) {
               notInlined.append(inlined)
             }
           }
         }
-        (inlineCTE(child, cteMap, forceInline), notInlined.toSeq)
+        inlineCTE(child, cteMap, notInlined)
 
       case ref: CTERelationRef =>
         val (cteDef, refCount) = cteMap(ref.cteId)
-        val newRef = if (forceInline || shouldInline(cteDef, refCount)) {
+        if (shouldInline(cteDef, refCount)) {
           if (ref.outputSet == cteDef.outputSet) {

Review comment:
       why do we compare output set, not output? is it possible that the ref and def have different output column order?




-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779673282



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/ReplaceCTERefWithRepartition.scala
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.expressions.{Alias, SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CTE, PLAN_EXPRESSION}
+
+/**
+ * Replaces CTE references that have not been previously inlined with [[Repartition]] operations
+ * which will then be planned as shuffles and reused across different reference points.
+ *
+ * Note that this rule should be called at the very end of the optimization phase to best guarantee
+ * that CTE repartition shuffles are reused.
+ */
+object ReplaceCTERefWithRepartition extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan match {
+    case _: Subquery => plan
+    case _ =>
+      replaceWithRepartition(plan, mutable.HashMap.empty[Long, LogicalPlan])
+  }
+
+  private def replaceWithRepartition(
+      plan: LogicalPlan,
+      cteMap: mutable.HashMap[Long, LogicalPlan]): LogicalPlan = plan match {
+    case WithCTE(child, cteDefs) =>
+      cteDefs.foreach { cteDef =>
+        val inlined = replaceWithRepartition(cteDef.child, cteMap)
+        val originalPlan = cteDef.originalPlanWithPredicates.map(_._1).getOrElse(cteDef.child)

Review comment:
       I think `originalPlanWithPredicates` must be none here?




-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779649059



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]

Review comment:
       nit: in other classes we always upper case CTE, how about naming it `CTEMap`?




-- 
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] SparkQA removed a comment on pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #34929:
URL: https://github.com/apache/spark/pull/34929#issuecomment-996449332


   **[Test build #146315 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/146315/testReport)** for PR 34929 at commit [`841aa2a`](https://github.com/apache/spark/commit/841aa2abd7a697bc402e4321f771bf7cbba22089).


-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779612590



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
##########
@@ -1012,6 +1016,24 @@ class Analyzer(override val catalogManager: CatalogManager)
         // inside a view maybe resolved incorrectly.
         checkAnalysis(newChild)
         view.copy(child = newChild)
+      case view @ View(_, _, child) =>
+        // Refresh CTE IDs in view's child that has been analyzed with a different AnalysisContext.

Review comment:
       ```
   // This is DataFrame view, not SQL view. We need to refresh the CTE IDs in view's child,
   // as it's already resolved but the CTE IDs may conflict with the main query.
   ```




-- 
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] cloud-fan commented on a change in pull request #34929: [SPARK-37670][SQL] Support predicate pushdown and column pruning for de-duped CTEs

Posted by GitBox <gi...@apache.org>.
cloud-fan commented on a change in pull request #34929:
URL: https://github.com/apache/spark/pull/34929#discussion_r779666326



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.expressions.{And, Attribute, AttributeSet, Expression, Literal, Or, SubqueryExpression}
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.CTE
+
+/**
+ * Infer predicates and column pruning for [[CTERelationDef]] from its reference points, and push
+ * the disjunctive predicates as well as the union of attributes down the CTE plan.
+ */
+object PushdownPredicatesAndPruneColumnsForCTEDef extends Rule[LogicalPlan] {
+
+  // CTE_id - (CTE_definition, precedence, predicates_to_push_down, attributes_to_prune)
+  private type CteMap = mutable.HashMap[Long, (CTERelationDef, Int, Seq[Expression], AttributeSet)]
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (!plan.isInstanceOf[Subquery] && plan.containsPattern(CTE)) {
+      val cteMap = new CteMap
+      gatherPredicatesAndAttributes(plan, cteMap)
+      pushdownPredicatesAndAttributes(plan, cteMap)
+    } else {
+      plan
+    }
+  }
+
+  private def reverseMapExpressions(
+      input: Seq[Expression],
+      mapping: Map[Attribute, Expression]): Seq[Expression] = {
+    input.map(e => e.transform {
+      case a: Attribute =>
+        mapping.keys.find(_.semanticEquals(a)).map(mapping).getOrElse(a)
+    })
+  }
+
+  /**
+   * Gather all the predicates and referenced attributes on different points of CTE references
+   * using pattern `ScanOperation` (which takes care of determinism) and combine those predicates
+   * and attributes that belong to the same CTE definition.
+   * For the same CTE definition, if any of its references does not have predicates, the combined
+   * predicate will be a TRUE literal, which means there will be no predicate push-down.
+   */
+  private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap: CteMap): Unit = {
+    plan match {
+      case WithCTE(child, cteDefs) =>
+        cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+          gatherPredicatesAndAttributes(cteDef.child, cteMap)
+          cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty, AttributeSet.empty))
+        }
+        gatherPredicatesAndAttributes(child, cteMap)
+
+      case ScanOperation(projects, predicates, ref: CTERelationRef) =>
+        val (cteDef, precedence, preds, attrs) = cteMap(ref.cteId)
+        val mapping = ref.output.zip(cteDef.output).map{ case (r, d) => r -> d }.toMap
+        val newPredicates = if (isTruePredicate(preds)) {
+          preds
+        } else {
+          val filteredPredicates = reverseMapExpressions(predicates.filter(_.find {
+            case s: SubqueryExpression => s.plan.find {
+              case r: CTERelationRef =>
+                !cteMap.contains(r.cteId) || cteMap(r.cteId)._2 >= precedence

Review comment:
       Can you add some comments to explain this condition?




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