You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "holdenk (via GitHub)" <gi...@apache.org> on 2025/11/03 18:24:03 UTC

[PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   ### What changes were proposed in this pull request?
   
   Changes the filter pushDown optimizer to not push down past projections of the same element if we reasonable expect that computing that element is likely to be expensive.
   
   This is a more complex alternative to https://github.com/apache/spark/pull/45802 which also moves parts of projections down so that the filters can move further down.
   
   This introduces an "expectedCost" mechanism which we may or may not want. Previous filter ordering work used filter pushdowns as an approximation of expression cost but here we need more granularity. As an alternative we could introduce a flag for expensive rather than numeric operations. Another alternative would be seeing if the predicate can be "converted" as a proxy for cheap.
   
   ### Future Work / What else remains to do?
   
   Right now if a cond is expensive and it references something in the projection we don't push-down. We could probably do better and gate this on if the thing we are reference is expensive rather than the condition it's self. We could do this as a follow up item or as part of this PR.
   
   ### Why are the changes needed?
   
   Currently Spark may double compute expensive operations (like json parsing, UDF eval, etc.) as a result of filter pushdown past projections.
   
   ### Does this PR introduce _any_ user-facing change?
   
   SQL optimizer change may impact some user queries, results should be the same and hopefully a little faster.
   
   ### How was this patch tested?
   
   New tests were added to the FilterPushDownSuite, and the initial problem of double evaluation was confirmed with a github gist 
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   No


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Sounds like a plan, I'll work on simplifying this code.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Gentle ping @cloud-fan WDYT?


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   > Just wondering if we have a consesus on the best way to go about this @zml1206 / @cloud-fan ? I'm thinking based on the > 1 year since with change it might be more complicated than we originally thought. I can re-explore as well is @zml1206 is busy but we could also go for the simpler solution in the meantime since double UDF evaluation is bad.
   
   Sorry for the late reply. The first issue we encountered was nested expansion of filter expressions causing the plan to become too large, resulting in driver out-of-memory errors. Performance was also an issue. This pr seems to only address part of the performance problem.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Awesome, I'll rework this then :)


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2704983095


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2048,23 +2048,116 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases)

Review Comment:
   we return `cond` instead of `replaced`, which indicates that the new function `replaceAliasWhileTracking` is not necessary for this new simply version.
   
   I think we can make it very simple:
   ```
   val (stayUp, pushDown) = splitConjunctivePredicates(condition).partition { predicate =>
     replaceAlias(predicate, aliasMap).expensive
   }
   (stayUp, pushDown) match {
     case (_, Nil) =>
       // Nothing to push down, keep the same filter.
       filter
     case (Nil, _) =>
       // Push all
       project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
     case _ =>
       Filter(
         stayUp.reduce(And),
         project.copy(
           child = Filter(replaceAlias(pushDown.reduce(And), aliasMap), grandChild)
         )
       )
   }
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,125 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 3: Filter references expensive to compute references.

Review Comment:
   Fair



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838234573


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,97 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      if (!SQLConf.get.avoidDoubleFilterEval) {
+        // If the user is ok with double evaluation of projections short circuit
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      } else {
+        // Break up the filter into its respective components by &&s.
+        val splitCondition = splitConjunctivePredicates(condition)
+        // Find the different aliases each component of the filter uses.
+        val usedAliasesForCondition = splitCondition.map { cond =>
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+        // Split the filter's components into cheap and expensive while keeping track of
+        // what each references from the projection.
+        val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+          .partition { case (cond, used, replaced) =>
+            if (!SQLConf.get.avoidDoubleFilterEval) {

Review Comment:
   no need to check this config anyway, it's handled at the beginning now.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838237162


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,125 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation

Review Comment:
   nit: it's more explicit to do `val correctAnswer = originalQuery`



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,190 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)

Review Comment:
   It's a good point, we currentl re-calculate replaced again further downstream when we need 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2567036287


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   It's really hard to review this new optimization, I have a few suggestions:
   1. optimizer rules should be orthogonal. I think "push down cheap filters only" and "split project" are two optimizations and should be put in two rules.
   2. add some code comments at the beginning to explain the algorithm. It's not easy for me to figure out the algorithm from the concrete code as it's a bit complicated.
   
   The algorithm in my mind:
   1. match plan pattern `Filter` -> `Project`
   2. find all expensive predicates (after `splitConjunctivePredicates`)
   3. for each expensive predicate, find the indexes of the referenced expensive expressions in the Project list.
   
   For example:
   ```
   Filter c1 + c3 > 0 AND c2 > 0
     Project expr1 AS c1, expr2 AS c2, expr3 as c3
   ```
   assume all expressions are expensive, then the first predicate has indexes [1, 3], and the second has indexes [2].
   
   The goal is to filter as much data before we evaluating expensive expressions, so a perfect solution should consider both predicate selectivity and expression eval cost, then decide how to split the `Project`. For simplicity the assumption is predicate are all selective, and expressions are equally expensive. Then we should run predicates that reference less expensive expressions:
   ```
   Filter c1 + c3 > 0
     Project expr1 AS c1, c2, expr3 as c3
       Filter c2 > 0
         Project expr2 AS c2
   ```
   
   Catalyst optimizer can run many iterations, so we don't need to finalize the plan in one shot. For this example:
   ```
   Filter c1 > 0 AND c2 > 0 AND c3 > 0
     Project expr1 AS c1, expr2 AS c2, expr3 as c3
   ```
   we can split the Project into 3
   ```
   Filter c3 > 0
     Project c1, c2, expr3 as c3
       Filter c2 > 0
         Project c1, expr2 AS c2
           Filter c1 > 0
             Project expr1 AS c1
   ```
   
   For each iteration, we only need to split a Project into two, and wait for the next iteration to keep splitting until there is no need to split.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   
   CC @cloud-fan do you have thoughts / cycles?
   
   


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2566977827


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -404,6 +404,15 @@ abstract class Expression extends TreeNode[Expression] {
     } else {
       ""
     }
+
+  /**
+   * Mark if an expression is likely to be expensive.
+   * The current only consumer of this is the pushdown optimizer.
+   * By default an expression is expensive if any of it's children are expensive.
+   */
+  def expensive: Boolean = hasExpensiveChild
+
+  protected lazy val hasExpensiveChild: Boolean = children.map(_.expensive).exists(_ == true)

Review Comment:
   ```suggestion
     protected lazy val hasExpensiveChild: Boolean = children.exists(_.expensive)
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -83,6 +83,27 @@ abstract class StringRegexExpression extends BinaryExpression
       matches(regex, input1.asInstanceOf[UTF8String].toString)
     }
   }
+
+  override def expensive: Boolean = _expensiveRegex

Review Comment:
   Good catch.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2525685446


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -404,6 +405,16 @@ abstract class Expression extends TreeNode[Expression] {
     } else {
       ""
     }
+
+  /**
+   * A developer API for marking if an expression is likely to be expensive.
+   * The current only consumer of this is the pushdown optimizer.
+   * By default an expression is expensive if any of it's children are expensive.
+   */
+  @DeveloperApi

Review Comment:
   We never add such annotation to catalyst plans/expressions, as they are very internal and we guarantee no binary compatibility.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -404,6 +405,16 @@ abstract class Expression extends TreeNode[Expression] {
     } else {
       ""
     }
+
+  /**
+   * A developer API for marking if an expression is likely to be expensive.
+   * The current only consumer of this is the pushdown optimizer.
+   * By default an expression is expensive if any of it's children are expensive.
+   */
+  @DeveloperApi
+  def expensive: Boolean = _expensive
+
+  private lazy val _expensive: Boolean = children.map(_.expensive).exists(_ == true)

Review Comment:
   ```suggestion
     private lazy val hasExpensiveChild: Boolean = children.exists(_.expensive)
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeCreator.scala:
##########
@@ -650,6 +650,7 @@ case class StringToMap(text: Expression, pairDelim: Expression, keyValueDelim: E
     pairDelim = newSecond,
     keyValueDelim = newThird
   )
+

Review Comment:
   unnecessary change



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   To discuss https://github.com/apache/spark/pull/46143#discussion_r2643476999 further:
   
   > Yes that's true, but given your previous statement around how adding projections is not free I don't think that's the right way to structure this.
   
   That's why my initial suggestion was to not do this optimization at all. We just create a single `Filter` and place it above the `Project`. By doing so we avoid the expensive expression duplication caused by filter pushdown, but all expressions in `Project` now need to be evaluated against the full input. I'm not sure how serious this issue is, and my proposal is to help simplify the algorithm given you are doing this optimization. I'm more than happier if you agree to drop this optimization and simplify the code.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {

Review Comment:
   Pretty much, makes sure we handle the split correctly though.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838239392


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,125 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 3: Filter references expensive to compute references.
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 1: Multiple filters that don't reference any projection aliases - all should be pushed
+  test("SPARK-47672: Case 1 - multiple filters not referencing projection aliases") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .where($"a" > 5 && $"b" < 10)

Review Comment:
   The analyzer can add missing columns into `Project`, but for test shall we explicitly select column `a` and `b` for clarity?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   +CC @shardulm94


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -404,6 +404,16 @@ abstract class Expression extends TreeNode[Expression] {
     } else {
       ""
     }
+
+  /**
+   * A _very rough_ indication of the expected cost of evaluating an expression.
+   * This can be used by the optimizer to decide if an element should be double
+   * evaluated for pre-emptive row filtering, in ordering filter expression, etc.
+   * This is an internal API and may go away at any time.
+   */
+  protected[spark] def expectedCost: Int = _expectedCost

Review Comment:
   Sure that makes sense to me.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643476999


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild
+          } else {
+            // We have at least one filter that we can split the projection around.
+            // We're going to now add projections one at a time for the expensive components for
+            // each group of filters. We'll keep track of what we added for the previous filter(s)
+            // so we don't double add anything.

Review Comment:
   A different view to look at this problem and design the algorithm: A `Project` with N named expressions can at most be split into N `Projects`. e.g. `Project(expr1 AS c1, expr2 AS c2, expr3 AS c3)` can be split into
   ```
   Project(c1, c2, expr3 AS c2)
     Project(leaf.output, c1, expr2 AS c2)
       Project(leaf.output, expr1 AS c1)
         leaf
   ```
   
   Each condition references a subset or all of the N named expressions, let's group the conditions by the number of referenced named expressions, `group1` means only reference one named expression, and so on.
   
   For conditions in `group1`, we rank the named expressions by "how many conditions can be evaluated with it" and pick the best, let's say it's `e1`, we create the first `Project` to evaluate `e1`, and move conditions that can't be evaluated to `group2`.
   
   For conditions in `group2`, again we rank the rest of the named expressions (exclude `e1`) by "how many conditions can be evaluated with it" and pick the best. For named expressions with the same rank, we sort by ref count and pick the best, let's say it's `e2`, and we repeat the same process and repeat it for `group3`, `group4`, ..., `groupN`.
   
   This algorithm tries to run as many filters earlier 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   I'm planning on merging on Wednesday if no objections.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2848063501


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -258,6 +239,23 @@ class FilterPushdownSuite extends PlanTest {
     comparePlans(optimized, correctAnswer)
   }
 
+  // Case 3: Filter references expensive to compute references.
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation

Review Comment:
   `correctAnswer` is the same as `originalQuery`?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,190 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)

Review Comment:
   I reworked it in 511068eef464183268b0a397d8a237f642827b16 now we avoid double computing the replacements.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828799667


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 1: Multiple filters that don't reference any projection aliases - all should be pushed
+  test("SPARK-47672: Case 1 - multiple filters not referencing projection aliases") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .where($"c" > 5 && $"d" < 10)

Review Comment:
   `c` and `d` do reference projection aliases, shall we use `.select($"a", $"b", ...)`?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   @cloud-fan updated to *just* fix the regression.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2491790363


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -404,6 +404,16 @@ abstract class Expression extends TreeNode[Expression] {
     } else {
       ""
     }
+
+  /**
+   * A _very rough_ indication of the expected cost of evaluating an expression.
+   * This can be used by the optimizer to decide if an element should be double
+   * evaluated for pre-emptive row filtering, in ordering filter expression, etc.
+   * This is an internal API and may go away at any time.
+   */
+  protected[spark] def expectedCost: Int = _expectedCost

Review Comment:
   I think this is very hard to pick an integer value as the cost. Shall we just add a bool flag `isExpensive`?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828764227


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          val replaced = replaceAlias(cond, aliasMap)
+          (cond, AttributeMap.empty[Alias], replaced)
+        } else {
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used, replaced) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (!used.exists(_._2.child.expensive)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      // Short circuit if we do not have any cheap filters return the original filter as is.
+      if (cheapWithUsed.isEmpty) {
+        f
+      } else {
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._3)
+        // Make a base instance which has all of the cheap filters pushed down.
+        // For all filter which do not reference any expensive aliases then
+        // just push the filter while resolving the non-expensive aliases.
+        val combinedCheapFilter = cheap.reduce(And)
+        val baseChild: LogicalPlan = Filter(combinedCheapFilter, child = grandChild)
+        // Take our projection and place it on top of the pushed filters.
+        val topProjection = project.copy(child = baseChild)
+
+        // If we pushed all the filters we can return the projection
+        val result = if (expensiveWithUsed.isEmpty) {
+          topProjection
+        } else {
+          // Finally add any filters which could not be pushed
+          val remainingConditions = expensiveWithUsed.map(_._1).toSeq

Review Comment:
   ```suggestion
             val remainingConditions = expensiveWithUsed.map(_._1)
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 1: Multiple filters that don't reference any projection aliases - all should be pushed
+  test("SPARK-47672: Case 1 - multiple filters not referencing projection aliases") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .where($"c" > 5 && $"d" < 10)

Review Comment:
   Oh yeah good point.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   I _might_ explore splitting the rule in another branch (I'll link it if I do), but I think it's probably the wrong thing to do.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -468,6 +468,14 @@ object SQLConf {
     .booleanConf
     .createWithDefault(true)
 
+  val AVOID_DOUBLE_FILTER_EVAL =
+    buildConf("spark.sql.optimizer.avoidDoubleFilterEval")
+    .doc("When true avoid pushing expensive (UDF, etc.) filters down if it could result in" +
+        "double evaluation. This was the behaviour prior to 3.X.")
+    .version("4.1.0")

Review Comment:
   I'll update this to 4.2



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   @zml1206 it will _reduce_ the amount of duplication but it does not completely remove it. For plan size issues that's probably better handled in a seperate PR (we can add more heuristics around when to copy and when not to copy an expression) WDYT?


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2704971473


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2048,23 +2048,116 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases)
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (!used.exists(_._2.child.expensive)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      // Short circuit if we do not have any cheap filters return the original filter as is.
+      if (cheapWithUsed.isEmpty) {
+        f
+      } else {
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        // For all filter which do not reference any expensive aliases then
+        // just push the filter while resolving the non-expensive aliases.
+        val combinedCheapFilter = cheap.reduce(And)
+        val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+        val baseChild: LogicalPlan = Filter(resolvedCheapFilter, child = grandChild)
+        // Insert a last projection to match the desired column ordering and
+        // evaluate any stragglers and select the already computed columns.

Review Comment:
   hmm why is this needed if we only push a Filter through a Project?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,117 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))

Review Comment:
   I think we can simplify it a little bit, but we don't want to just call .expensive on the result of replacing the alias because if a filter has an expensive condition, but the condition is not an alias from the projection, we still want to push.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643311099


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)

Review Comment:
   the conditions were produced by `replaceAliasWhileTracking`, the attributes should have been replaced by the projection expressions already.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Hi @cloud-fan looks like the "with" suggestion ended up being more complicated than originally suggested( see https://github.com/apache/spark/pull/46499#issuecomment-2124277717 ). In the interest of progress and avoiding double evaluation of a lot of really expensive things we don't need I intend to update this PR and merge it. We can still circle back to the with approach eventually.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838234229


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,97 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      if (!SQLConf.get.avoidDoubleFilterEval) {
+        // If the user is ok with double evaluation of projections short circuit
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      } else {
+        // Break up the filter into its respective components by &&s.
+        val splitCondition = splitConjunctivePredicates(condition)
+        // Find the different aliases each component of the filter uses.
+        val usedAliasesForCondition = splitCondition.map { cond =>

Review Comment:
   how about `originalAndRewrittenConditionsWithUsedAlias`



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838236834


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,125 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 3: Filter references expensive to compute references.
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation

Review Comment:
   nit: it's more explicit to do `val correctAnswer = originalQuery`



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2838235922


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,125 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 3: Filter references expensive to compute references.

Review Comment:
   nit: it's weird to put case 3 first



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2525726304


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,20 +156,122 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections but push components that can be") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+      .where($"a" > 5 && $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"b", $"e", $"e".rlike("magic") as "f")
+      .where($"f")

Review Comment:
   I get the purpose here is to reduce the input to other expensive functions in the same Project. But splitting a Project has overhead as well (more operator, more overhead), and in most cases the benefit of filter pushdown is to reduce IO for shuffle/scan, shall we defer this optimization? Then the impl can be much simpler: https://github.com/apache/spark/pull/46143/files#r2525714854



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   A followup SGTM, at least we can fix the perf regression first.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643311099


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)

Review Comment:
   the conditions were produced by `replaceAliasWhileTracking`, the attributes should have been replaced by the projection expressions already.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643301796


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {

Review Comment:
   how is this possible? The filter condition can't be None.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   @cloud-fan I did some exploring around seperating out the logic a little bit and it's still kind of rough: https://github.com/holdenk/spark/tree/SPARK-47672-avoid-double-eval-from-filter-pushdown-split-projection-refactor-attempt I will give a bit more thought on improving the docs but splitting the rule logic up doesn't really help (although feel free to take alook at this branch and see if you would prefer 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828801019


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 1: Multiple filters that don't reference any projection aliases - all should be pushed
+  test("SPARK-47672: Case 1 - multiple filters not referencing projection aliases") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .where($"c" > 5 && $"d" < 10)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    // Both filters on c and d should be pushed down since they just reference
+    // simple aliases (c->a, d->b) which are inexpensive
+    val correctAnswer = testStringRelation
+      .where($"a" > 5 && $"b" < 10)
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 2: Multiple filters with inexpensive references - all should be pushed

Review Comment:
   do we have a test case for the mixed cases?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828758300


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/AliasHelper.scala:
##########
@@ -65,6 +65,30 @@ trait AliasHelper {
     })
   }
 
+  /**
+   * Replace all attributes, that reference an alias, with the aliased expression.
+   * Tracks which aliases were replaced and returns them.
+   */
+  protected def replaceAliasWhileTracking(
+      expr: Expression,
+      aliasMap: AttributeMap[Alias]): (Expression, AttributeMap[Alias]) = {
+    // Use transformUp to prevent infinite recursion when the replacement expression
+    // redefines the same ExprId,
+    var replaced = AttributeMap.empty[Alias]
+    val newExpr = trimAliases(expr.transformUp {
+      case a: Attribute =>
+        // If we replace an alias add it to replaced
+        val newElem = aliasMap.get(a)
+        newElem match {
+          case None => a
+          case Some(b) =>
+            replaced += (a, b)

Review Comment:
   we should skip this operation if the AttributeMap already contains `a`. It does not change the result but is more efficient.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828782566


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          val replaced = replaceAlias(cond, aliasMap)
+          (cond, AttributeMap.empty[Alias], replaced)
+        } else {
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used, replaced) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (!used.exists(_._2.child.expensive)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      // Short circuit if we do not have any cheap filters return the original filter as is.
+      if (cheapWithUsed.isEmpty) {
+        f
+      } else {
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._3)
+        // Make a base instance which has all of the cheap filters pushed down.
+        // For all filter which do not reference any expensive aliases then
+        // just push the filter while resolving the non-expensive aliases.
+        val combinedCheapFilter = cheap.reduce(And)
+        val baseChild: LogicalPlan = Filter(combinedCheapFilter, child = grandChild)
+        // Take our projection and place it on top of the pushed filters.
+        val topProjection = project.copy(child = baseChild)
+
+        // If we pushed all the filters we can return the projection
+        val result = if (expensiveWithUsed.isEmpty) {
+          topProjection
+        } else {
+          // Finally add any filters which could not be pushed
+          val remainingConditions = expensiveWithUsed.map(_._1).toSeq
+          Filter(remainingConditions.reduce(And), topProjection)
+        }
+        result

Review Comment:
   ```suggestion
           if (expensiveWithUsed.isEmpty) {
             topProjection
           } else {
             // Finally add any filters which could not be pushed
             val remainingConditions = expensiveWithUsed.map(_._1).toSeq
             Filter(remainingConditions.reduce(And), topProjection)
           }
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828781055


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          val replaced = replaceAlias(cond, aliasMap)
+          (cond, AttributeMap.empty[Alias], replaced)
+        } else {
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used, replaced) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (!used.exists(_._2.child.expensive)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      // Short circuit if we do not have any cheap filters return the original filter as is.
+      if (cheapWithUsed.isEmpty) {
+        f
+      } else {
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._3)
+        // Make a base instance which has all of the cheap filters pushed down.
+        // For all filter which do not reference any expensive aliases then
+        // just push the filter while resolving the non-expensive aliases.
+        val combinedCheapFilter = cheap.reduce(And)
+        val baseChild: LogicalPlan = Filter(combinedCheapFilter, child = grandChild)

Review Comment:
   ```suggestion
           val baseChild = Filter(combinedCheapFilter, child = grandChild)
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          val replaced = replaceAlias(cond, aliasMap)
+          (cond, AttributeMap.empty[Alias], replaced)
+        } else {
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used, replaced) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (!used.exists(_._2.child.expensive)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      // Short circuit if we do not have any cheap filters return the original filter as is.
+      if (cheapWithUsed.isEmpty) {
+        f
+      } else {
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._3)
+        // Make a base instance which has all of the cheap filters pushed down.
+        // For all filter which do not reference any expensive aliases then
+        // just push the filter while resolving the non-expensive aliases.
+        val combinedCheapFilter = cheap.reduce(And)
+        val baseChild: LogicalPlan = Filter(combinedCheapFilter, child = grandChild)
+        // Take our projection and place it on top of the pushed filters.
+        val topProjection = project.copy(child = baseChild)
+
+        // If we pushed all the filters we can return the projection
+        val result = if (expensiveWithUsed.isEmpty) {
+          topProjection
+        } else {
+          // Finally add any filters which could not be pushed
+          val remainingConditions = expensiveWithUsed.map(_._1).toSeq
+          Filter(remainingConditions.reduce(And), topProjection)
+        }
+        result

Review Comment:
   Sure



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -258,6 +239,23 @@ class FilterPushdownSuite extends PlanTest {
     comparePlans(optimized, correctAnswer)
   }
 
+  // Case 3: Filter references expensive to compute references.
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation

Review Comment:
   True, let me simplify



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643357598


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {

Review Comment:
   These two should only differ in size, shall we just do `used.size == aliasMap.size` which is much cheaper than comparing two maps.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643339957


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have

Review Comment:
   This seems not sensible to me. Shall we sort by the map size, and then the name? If a condition references less project attributes, it should be placed lower in the tree, to delay the projection expression evaluation as much 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2656426813


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,190 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)

Review Comment:
   Seems like you don't use `replaced` anywere or am I missing something?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643293864


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {

Review Comment:
   ```suggestion
             } else if (!used.exists(_._2.child.expensive)) {
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   > That's why my initial suggestion was to not do this optimization at all. We just keep the `Filter` above the `Project`. By doing so we avoid the expensive expression duplication caused by filter pushdown, but all expressions in `Project` now need to be evaluated against the full input. I'm not sure how serious this issue is, and I was just trying to help simplify the algorithm given you are doing this optimization. I'm more than happier if you agree to drop this optimization and simplify the code.
   
   So just always leave up complex filters and don't don't attempt to split them if needed? I think that's sub-optimal for fairly self evident reasons *but* if you still find the current implementation too complex I could move it into a follow-on PR so there's less to review here and we *just* fix the perf regression introduced in 3.0


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2566978298


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -83,6 +83,27 @@ abstract class StringRegexExpression extends BinaryExpression
       matches(regex, input1.asInstanceOf[UTF8String].toString)
     }
   }
+
+  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
+
+  lazy val _expensiveRegex = {

Review Comment:
   ```suggestion
     private lazy val _expensiveRegex = {
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   While starting to get the context back @cloud-fan I think the cost based mechanism is the way to instead of just blacklisting UDFS. For example: `sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/CallMethodViaReflection.scala` is fairly "UDF like" but is not its self a UDF. Similarly, someone might write their own custom expression; regexes can also be fairly expensive, and so on. I can start with making this feature configurable while we discuss what we don't want to double eval.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Just wondering if we have a consesus on the best way to go about this @zml1206 / @cloud-fan ? I'm thinking based on the > 1 year since with change it might be more complicated than we originally thought. I can re-explore as well is @zml1206 is busy but we could also go for the simpler solution in the meantime since double UDF evaluation is bad.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Hi @holdenk , we tried very hard to solve this issue efficiently but failed. The idea was to let filter carry a project list and push them down together, but when we push through Project/Aggregate which also contains a project list, we may still hit expression duplication and need to make a decision based on cost.
   
   Sorry I should have moved back to this PR earlier. I think we can simplify it a bit as we will likely never have a practical cost model for Spark expressions. Let's just avoid UDF expression (extends marker expression `UserDefinedExpression`) duplication during a filter pushdown and add a config to enable 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2525688625


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -83,6 +83,27 @@ abstract class StringRegexExpression extends BinaryExpression
       matches(regex, input1.asInstanceOf[UTF8String].toString)
     }
   }
+
+  override def expensive: Boolean = _expensiveRegex

Review Comment:
   ```suggestion
     override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2525714854


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,117 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))

Review Comment:
   The new impl looks overly complicated. I think we only need to split the predicates and push down the part that won't trigger double eval. e.g.
   ```
   val (stayUp, pushDown) = splitConjunctivePredicates(condition).partition { predicate =>
     replaceAlias(predicate, aliasMap).expensive
   }
   (stayUp, pushDown) match {
     case (_, Nil) =>
       // Nothing to push down, keep the same filter.
       filter
     case (Nil, _) =>
       // Push all
       project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
     case _ =>
       Filter(
         stayUp.reduce(And),
         project.copy(
           child = Filter(replaceAlias(pushDown.reduce(And), aliasMap), grandChild)
         )
       )
   }
   ```



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643322333


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {

Review Comment:
   If we don't swap anything, the returned `usedAliases` must be empty, I think we can directly return `(cond, usedAliases)` here, to save this expression tree comparison.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   So adding more iterations to the optimizer isn't free, there's a reason we have logic to prune optimizer rule application. I'll write a more detailed comment describing the over-arching logic though. After that comment I intend to merge it since it's been open since **2024**.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2656430693


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild
+          } else {
+            // We have at least one filter that we can split the projection around.
+            // We're going to now add projections one at a time for the expensive components for
+            // each group of filters. We'll keep track of what we added for the previous filter(s)
+            // so we don't double add anything.

Review Comment:
   > let's group the conditions by the number of referenced named expressions, `group1` means only reference one named expression, and so on.
   > ...
   > For conditions in group1, we rank the named expressions by "how many conditions can be evaluated with it" and pick the best
   
   This seems like a good heuristics to me to split the projections around.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828790021


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {

Review Comment:
   what does "move a projection" mean?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {

Review Comment:
   Oh yeah the description made more sense before when we would move projections around, I'll drop 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   > Sorry for the late response to this project. I think the `With` approach is not that complicated and I'm fixing the nested `With` limitation here: #49093 . After this is merged, I can followup with the actual pushdown implementation if @zml1206 can't continue his work.
   
   Recently I reviewed this logic. If possible, I can continue pushdown work after merging #49093, thank you. @cloud-fan 


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2566979148


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it

Review Comment:
   we should guarantee it for the root plan, as optimizer shouldn't change the query result schema.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2567036287


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   It's really hard to review this new optimization, I have a few suggestions:
   1. optimizer rules should be orthogonal. I think "push down cheap filters only" and "split project" are two optimizations and should be put in two rules.
   2. add some code comments at the beginning to explain the algorithm. It's not easy for me to figure out the algorithm from the concrete code as it's a bit complicated.
   
   The algorithm in my mind:
   1. match plan pattern `Filter` -> `Project`
   2. find all expensive predicates (after `splitConjunctivePredicates`)
   3. for each expensive predicate, find the indexes of the referenced expensive expressions in the Project list.
   
   For example:
   ```
   Filter c1 + c3 > 0 AND c2 > 0
     Project expr1 AS c1, expr2 AS c2, expr3 as c3
   ```
   assume all expressions are expensive, then the first predicate has indexes [1, 3], and the second has indexes [2].
   
   The goal is to filter as much data before we evaluating expensive expressions, so a perfect solution should consider both predicate selectivity and expression eval cost, then decide how to split the `Project`. For simplicity the assumption is predicate are all selective, and expressions are equally expensive. Then we should run predicates that reference less expensive expressions:
   ```
   Filter c1 + c3 > 0
     Project expr1 AS c1, c2, expr3 as c3
       Filter c2 > 0
         Project expr2 AS c2
   ```
   
   Catalyst optimizer can run many iterations, so we don't need to finalize the plan in one shot. For this example:
   ```
   Filter c1 > 0 AND c2 > 0 AND c3 > 0
     Project expr1 AS c1, expr2 AS c2, expr3 as c3
   ```
   we can split the Project into 3
   ```
   Filter c3 > 0
     Project c1, c2, expr3 as c3
       Filter c2 > 0
         Project c1, expr2 AS c2
           Filter c1 > 0
             Project expr1 AS c1
   ```
   
   For each iteration, we only need to split a Project into two, and push down predicates that reference the same set of expressions (same indexes), and wait for the next iteration to keep splitting until there is no need to split.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #46143: [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown
URL: https://github.com/apache/spark/pull/46143


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #46143: [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown
URL: https://github.com/apache/spark/pull/46143


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,117 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))

Review Comment:
   Ah yes I remember now, we still would probably want to push a filter + a projection through in the case where we have an filter condition referencing an expensive alias because we could potentially eliminate some additional projections being computed by filtering on it before computing the rest of aliases. e.g. `filter(expensive_regex_ref1) -> project(expensive_regex_ref1, expensive_regex_ref2)` we want to get `project(expensive_regex_ref2) -> filter(expensive_regex_ref1) -> project(expensive_regex_ref1)`



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,97 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      if (!SQLConf.get.avoidDoubleFilterEval) {
+        // If the user is ok with double evaluation of projections short circuit
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      } else {
+        // Break up the filter into its respective components by &&s.
+        val splitCondition = splitConjunctivePredicates(condition)
+        // Find the different aliases each component of the filter uses.
+        val usedAliasesForCondition = splitCondition.map { cond =>
+          // Here we get which aliases were used in a given filter so we can see if the filter
+          // referenced an expensive alias v.s. just checking if the filter is expensive.
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases, replaced)
+        }
+        // Split the filter's components into cheap and expensive while keeping track of
+        // what each references from the projection.
+        val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+          .partition { case (cond, used, replaced) =>
+            if (!SQLConf.get.avoidDoubleFilterEval) {

Review Comment:
   Oh good catch, my bad.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828793884


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {

Review Comment:
   Is this just a more complicated case of the test `SPARK-47672: Make sure that we handle the case where everything is expensive`?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/AliasHelper.scala:
##########
@@ -65,6 +65,30 @@ trait AliasHelper {
     })
   }
 
+  /**
+   * Replace all attributes, that reference an alias, with the aliased expression.
+   * Tracks which aliases were replaced and returns them.
+   */
+  protected def replaceAliasWhileTracking(
+      expr: Expression,
+      aliasMap: AttributeMap[Alias]): (Expression, AttributeMap[Alias]) = {
+    // Use transformUp to prevent infinite recursion when the replacement expression
+    // redefines the same ExprId,
+    var replaced = AttributeMap.empty[Alias]
+    val newExpr = trimAliases(expr.transformUp {
+      case a: Attribute =>
+        // If we replace an alias add it to replaced
+        val newElem = aliasMap.get(a)
+        newElem match {
+          case None => a
+          case Some(b) =>
+            replaced += (a, b)

Review Comment:
   Good call



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2686892337


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,190 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)

Review Comment:
   The latest version still doesn't use `replaced`. Do you want to keep `replaceAliasWhileTracking()` in its current form for some reason?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643476999


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild
+          } else {
+            // We have at least one filter that we can split the projection around.
+            // We're going to now add projections one at a time for the expensive components for
+            // each group of filters. We'll keep track of what we added for the previous filter(s)
+            // so we don't double add anything.

Review Comment:
   A different view to look at this problem and design the algorithm: A `Project` with N named expressions can at most be split into N `Projects`. e.g. `Project(expr1 AS c1, expr2 AS c2, expr3 AS c3)` can be split into
   ```
   Project(c1, c2, expr3 AS c2)
     Project(leaf.output, c1, expr2 AS c2)
       Project(leaf.output, expr1 AS c1)
         leaf
   ```
   
   Each condition references a subset or all of the N named expressions, let's group the conditions by the number of referenced named expressions, `group1` means only reference one named expression, and so on.
   
   For conditions in `group1`, we rank the named expressions by "how many conditions can be evaluated with it" and pick the best, let's say it's `e1`, we create the first `Project` to evaluate `e1`, and move conditions that can't be evaluated to `group2`.
   
   For conditions in `group2`, again we rank the rest of the named expressions (exclude `e1`) by "how many conditions can be evaluated with it" and pick the best. For named expressions with the same rank, we pick the one that gets referenced the most times by conditions, let's say it's `e2`, and we repeat the same process and repeat it for `group3`, `group4`, ..., `groupN`.
   
   This algorithm tries to run as many filters earlier 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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643362333


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild

Review Comment:
   where do we add the expensive filters back?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2643359750


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {

Review Comment:
   This is impossible to happen, right?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -83,6 +83,27 @@ abstract class StringRegexExpression extends BinaryExpression
       matches(regex, input1.asInstanceOf[UTF8String].toString)
     }
   }
+
+  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
+
+  private lazy val _expensiveRegex = {
+    // A quick heuristic for expensive a pattern is.
+    left match {
+      case StringLiteral(str) =>
+        // If we have a clear start limited back tracking required.
+        if (str.startsWith("^") || str.startsWith("\\b")) {
+          false
+        } else if (str.contains("+")) {
+          // Greedy matching can be tricky.

Review Comment:
   Fair point, we can extend that



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Sorry for the late response to this project. I think the `With` approach is not that complicated and I fixed the nested `With` limitation here: https://github.com/apache/spark/pull/49093 . After this is merged, I can followup with the actual pushdown implementation if @zml1206 can't continue his work.


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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2686858040


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/regexpExpressions.scala:
##########
@@ -83,6 +83,27 @@ abstract class StringRegexExpression extends BinaryExpression
       matches(regex, input1.asInstanceOf[UTF8String].toString)
     }
   }
+
+  override def expensive: Boolean = hasExpensiveChild || _expensiveRegex
+
+  private lazy val _expensiveRegex = {
+    // A quick heuristic for expensive a pattern is.
+    left match {
+      case StringLiteral(str) =>
+        // If we have a clear start limited back tracking required.
+        if (str.startsWith("^") || str.startsWith("\\b")) {
+          false
+        } else if (str.contains("+")) {
+          // Greedy matching can be tricky.

Review Comment:
   Out of curiosity, why only `+` is considered expensive? Why `*` and `{m,n}` are not?



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2828678277


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {

Review Comment:
   If `avoidDoubleFilterEval` is false we can just return `project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))`, to make sure the legacy code path is exactly the same as before.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2048,23 +2048,116 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          (cond, usedAliases)

Review Comment:
   So the whiletracking API is giving us back the `usedAliases` which we are returning and `replaceAlias` does not. If we just look at if the substituted expression is expensive rather than the alias we'll incorrectly leave up a filter which does an expensive regex over a projected inexpesnive column. I'll write this in the comments though.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2059,23 +2059,100 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we do not push it.
+    // Note that a given filter may contain parts (sepereated by logical ands) from all cases.
+    // We handle each part separately according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {

Review Comment:
   Sure



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,17 +156,137 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Do double evaluation when configured") {
+    withSQLConf(SQLConf.AVOID_DOUBLE_FILTER_EVAL.key -> "false") {
+      val originalQuery = testStringRelation
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+        .where($"a" > 5 && $"f")
+        .analyze
+
+      val optimized = Optimize.execute(originalQuery)
+
+      val correctAnswer = testStringRelation
+        .where($"a" > 5 && $"e".rlike("magic"))
+        .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
         .analyze
 
+      comparePlans(optimized, correctAnswer)
+    }
+  }
+
+  test("SPARK-47672: Make sure that we handle the case where everything is expensive") {
+    val originalQuery = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"e".rlike("magic") as "f")
+      .where($"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Ensure filter pushdown without alias reference does not move a projection.") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .where($"a" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"e".rlike("magic") as "f", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+
+  test("SPARK-47672: Inexpensive filter pushdown should not move projections") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"b" + $"a")
+      .where($"c" > 5)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a" as "c", $"b" + $"a")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections can't push past certain items") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f")
+      .where($"a" > 5 || $"f")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 1: Multiple filters that don't reference any projection aliases - all should be pushed
+  test("SPARK-47672: Case 1 - multiple filters not referencing projection aliases") {
+    val originalQuery = testStringRelation
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .where($"c" > 5 && $"d" < 10)
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    // Both filters on c and d should be pushed down since they just reference
+    // simple aliases (c->a, d->b) which are inexpensive
+    val correctAnswer = testStringRelation
+      .where($"a" > 5 && $"b" < 10)
+      .select($"a" as "c", $"e".rlike("magic") as "f", $"b" as "d")
+      .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  // Case 2: Multiple filters with inexpensive references - all should be pushed

Review Comment:
   Added



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -152,20 +156,122 @@ class FilterPushdownSuite extends PlanTest {
   test("can't push without rewrite") {
     val originalQuery =
       testRelation
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
         .where($"e" === 1)
         .analyze
 
     val optimized = Optimize.execute(originalQuery.analyze)
     val correctAnswer =
       testRelation
         .where($"a" + $"b" === 1)
-        .select($"a" + $"b" as "e")
+        .select($"a" + $"b" as "e", $"a" - $"b" as "f")
+        .analyze
+
+    comparePlans(optimized, correctAnswer)
+  }
+
+  test("SPARK-47672: Avoid double evaluation with projections but push components that can be") {
+    val originalQuery = testStringRelation
+      .select($"a", $"e".rlike("magic") as "f", $"e".rlike("notmagic") as "j", $"b")
+      .where($"a" > 5 && $"f")
+      .analyze
+
+    val optimized = Optimize.execute(originalQuery)
+
+    val correctAnswer = testStringRelation
+      .where($"a" > 5)
+      .select($"a", $"b", $"e", $"e".rlike("magic") as "f")
+      .where($"f")

Review Comment:
   We could reduce how often we introduce this extra projection by only doing it if there is expensive element being computed. It does make the code even more complex, but I think that saving the extra expensive evals is worth the occasional introduction of a new projection node.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {

Review Comment:
   True, in my head I was thinking like case/switch where you want all of the cases but we can just drop this.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have

Review Comment:
   We don't really have a good idea of how expensive the different references is here, I think trying to sort on set size would give us a false sense of optimization -- it's why I'm intentionally sorting on just the name so we have stable sort order for testing.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {

Review Comment:
   That's true -- I think I added this check back when I did the tracking compute seperately before I inlined it in one pass, good call



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild

Review Comment:
   So we add them back in two steps 3A and 3B, this case is only 3B so we add the expensive filter on top of the final project.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {

Review Comment:
   This one can happen, so if we only have expensive filters *but* they use every alias added in the projection we get this case. I'll add that as comment for clarity.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {
+              false
+            } else {
+              true
+            }
+        }
+        if (toSplit.isEmpty && cheap.isEmpty) {
+          // Nothing to push or split, short circuit (all filters are case 3B).
+          f
+        } else {
+          val expensiveFiltersDone = if (toSplit.isEmpty) {
+            // If we can't split anymore (no 3A), but we did have cheap filters
+            // pushed we still need to add the expensive filters back on top.
+            baseChild
+          } else {
+            // We have at least one filter that we can split the projection around.
+            // We're going to now add projections one at a time for the expensive components for
+            // each group of filters. We'll keep track of what we added for the previous filter(s)
+            // so we don't double add anything.

Review Comment:
   Yes that's true, but given your previous statement around how adding projections is not free I don't think that's the right way to structure this.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2047,23 +2047,198 @@ object PushDownPredicates extends Rule[LogicalPlan] {
  * Pushes [[Filter]] operators through many operators iff:
  * 1) the operator is deterministic
  * 2) the predicate is deterministic and the operator will not change any of rows.
+ * 3) We don't add double evaluation OR double evaluation would be cheap OR we're configured to.
  *
- * This heuristic is valid assuming the expression evaluation cost is minimal.
  */
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering, this is important as we shouldn't change the schema
+  // , even the positional one, during optimization.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
+    // Projections are a special case because the filter _may_ contain references to fields added in
+    // the projection that we wish to copy. We shouldn't blindly copy everything
+    // since double evaluation all operations can be expensive (unless the broken behavior is
+    // enabled by the user). The double filter eval regression was added in Spark 3 fixed in 4.2.
+    // The _new_ default algorithm works as follows:
+    // Provided filters are broken up based on their &&s for separate evaluation.
+    // We track which components of the projection are used in the filters.
+    //
+    // 1) The filter does not reference anything in the projection: pushed
+    // 2) Filter which reference _inexpensive_ items in projection: pushed and reference resolved
+    //    resulting in double evaluation, but only of inexpensive items -- worth it to filter
+    //    records sooner.
+    // (Case 1 & 2 are treated as "cheap" predicates)
+    // 3) When an a filter references expensive to compute references we
+    //    check to see if we should split the projection into multiple parts w/ the filter
+    //    in between. This allows us to avoid double evaluating expensive references.
+    //  3a) If the filter references everything in the projection we can't split it any further.
+    //      so we leave the filter and projection as is.
+    //  3b) If the filter does not reference the entire projection then we can potentially reduce
+    //     the amount of computation but splitting the projection around the filter.
+    // Case 3 is treated as an "expensive" predicate.
+    // Note that a given filter may contain parts from all cases. We handle each part separately
+    // according to the logic above.
+    // Additional restriction:
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
+      // All of the aliases in the projection
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Break up the filter into its respective components by &&s.
+      val splitCondition = splitConjunctivePredicates(condition)
+      // Find the different aliases each component of the filter uses.
+      val usedAliasesForCondition = splitCondition.map { cond =>
+        // If the legacy double evaluation behavior is enabled we just say
+        // every filter is "free."
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          (cond, AttributeMap.empty[Alias])
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          // Didn't swap anything? empty list :)
+          if (cond == replaced) {
+            (cond, AttributeMap.empty[Alias])
+          } else {
+            (cond, usedAliases)
+          }
+        }
+      }
+      // Split the filter's components into cheap and expensive while keeping track of
+      // what each references from the projection.
+      val (cheapWithUsed, expensiveWithUsed) = usedAliasesForCondition
+        .partition { case (cond, used) =>
+        if (!SQLConf.get.avoidDoubleFilterEval) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          // Didn't use anything? We're good
+          if (used.isEmpty) {
+            true
+          } else if (used.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            false
+          }
+        }
+      }
+      if (cheapWithUsed.isEmpty && expensiveWithUsed.isEmpty) {
+        // Short circuit, we don't have anything to push OR split
+        f
+      } else {
+        // Handle all of the cheap filters (part 1 & 2).
+        val cheap: Seq[Expression] = cheapWithUsed.map(_._1)
+        // Make a base instance which has all of the cheap filters pushed down.
+        val baseChild: LogicalPlan = if (!cheap.isEmpty) {
+          // For all filter which do not reference any expensive aliases then
+          // just push the filter while resolving the non-expensive aliases.
+          val combinedCheapFilter = cheap.reduce(And)
+          val resolvedCheapFilter = replaceAlias(combinedCheapFilter, aliasMap)
+          Filter(resolvedCheapFilter, child = grandChild)
+        } else {
+          // If we don't have any inexpensive filters to push it's "just" the grandchild.
+          grandChild
+        }
+        // Handle any Case 3 filters
+        // We group the expensive components by the aliases used, since if they use the same
+        // aliases we can introduce them together.
+        val grouped = expensiveWithUsed.groupBy(_._2)
+        // Sort by the name of the head expensive alias so we have
+        // a consistent order for testing. It's possible we could do something
+        // smarter here if we build a better cost based heuristic.
+        val expensiveByUsed = grouped.view
+          .mapValues(_.map(_._1).toList).toList.sortBy(_._1.head._2.name)
+        // For each expensive alias figure out if they're in case 3A or 3B
+        val (toSplit, leaveAsIs) = expensiveByUsed.partition {
+          case (used, expensive) =>
+            // We can't split these filters from this projection since they
+            // have a 1:1 mapping with all of the aliases.
+            if (used == aliasMap) {

Review Comment:
   Good call



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #46143:
URL: https://github.com/apache/spark/pull/46143#discussion_r2618463096


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   OK I'm fine with a single rule, but we need better code comment as the algorithm will be more complicated.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it

Review Comment:
   Gotcha, I'll update the comment to match.



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2053,17 +2053,124 @@ object PushDownPredicates extends Rule[LogicalPlan] {
 object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelper {
   def apply(plan: LogicalPlan): LogicalPlan = plan transform applyLocally
 
+  // Match the column ordering. It's not something we guarantee but seems like it
+  // could be useful especially for folks writing out to "raw" files.
+  private def matchColumnOrdering(original: Seq[NamedExpression], updated: Seq[NamedExpression]):
+      Seq[NamedExpression] = {
+    val nameToIndex = original.map(_.name).zipWithIndex.toMap
+    val response = updated.toArray
+    updated.foreach { e =>
+      val idx = nameToIndex(e.name)
+      response(idx) = e
+    }
+    response.toSeq
+  }
+
   val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
     // SPARK-13473: We can't push the predicate down when the underlying projection output non-
     // deterministic field(s).  Non-deterministic expressions are essentially stateful. This
     // implies that, for a given input row, the output are determined by the expression's initial
     // state and all the input rows processed before. In another word, the order of input rows
     // matters for non-deterministic expressions, while pushing down predicates changes the order.
     // This also applies to Aggregate.
-    case Filter(condition, project @ Project(fields, grandChild))
+    case f @ Filter(condition, project @ Project(fields, grandChild))
       if fields.forall(_.deterministic) && canPushThroughCondition(grandChild, condition) =>
       val aliasMap = getAliasMap(project)
-      project.copy(child = Filter(replaceAlias(condition, aliasMap), grandChild))
+      // Projection aliases that the filter references
+      val expensiveFilterAliasesBuf = mutable.ArrayBuffer.empty[Alias]
+      // Projection aliases that are not used in the filter, so we don't need to push
+      var leftBehindAliases: Map[ExprId, Alias] = aliasMap.baseMap.values.map {
+        kv => (kv._2.exprId, kv._2)
+      }.toMap
+      val (cheap, expensive) = splitConjunctivePredicates(condition).partition { cond =>
+        if (!SQLConf.get.avoidDoubleFilterEvail) {
+          // If we are always pushing through short circuit the check.
+          true
+        } else {
+          val (replaced, usedAliases) = replaceAliasWhileTracking(cond, aliasMap)
+          if (cond == replaced) {
+          // If nothing changes then our alias is cheap
+            true
+          } else if (usedAliases.iterator.map(_._2.child.expensive).forall(_ == false)) {
+            // If it's cheap we can push it because it might eliminate more data quickly and
+            // it may also be something which could be evaluated at the storage layer.
+            // We may wish to improve this heuristic in the future.
+            true
+          } else {
+            // This is an expensive replacement so we see resolve it
+            usedAliases.iterator.foreach {
+              e: (Attribute, Alias) =>
+              if (leftBehindAliases.contains(e._2.exprId)) {
+                leftBehindAliases = leftBehindAliases.removed(e._2.exprId)
+                expensiveFilterAliasesBuf += e._2
+              }
+            }
+            false
+          }
+        }
+      }
+
+      val expensiveFilterAliases = expensiveFilterAliasesBuf.toArray.toSeq
+      val expensiveLeftBehindAliases: Map[ExprId, Alias] = leftBehindAliases.filter {
+        kv => kv._2.child.expensive
+      }
+
+      if (expensiveFilterAliases.isEmpty) {
+        // If the filter does not reference any expensive aliases then we
+        // just push the filter while resolving the non-expensive aliases.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else if (leftBehindAliases.isEmpty) {
+        // If there are no left behind aliases then we've used all of the aliases in our filter.
+        // We don't need to introduce any more projections since we already have the "minimal"
+        // projection for our expensive conditions, but we might be able to move the "cheap"
+        // conditions.
+        if (!cheap.isEmpty) {
+          val expensiveFilterCond = expensive.reduce(And)
+          // Replace the aliases in the cheap filter since we are pushing them down.
+          val cheapFilterCond = replaceAlias(cheap.reduce(And), aliasMap)
+          Filter(expensiveFilterCond, project.copy(child = Filter(cheapFilterCond, grandChild)))
+        } else {
+          f
+        }
+      } else if (expensiveLeftBehindAliases.isEmpty) {
+        // If there are no expensive left behind aliases then introducing
+        // a new projection might not be worth the overhead.
+        project.copy(child = Filter(replaceAlias(condition, aliasMap), child = grandChild))
+      } else {
+        // If we're here then we have a filter with an expensive alias along with
+        // some left behind aliases which are also expensive to compute. In this case we will
+        // add a new projection which computes the expensive aliases needed for the filter then
+        // filter and then the final top level projection with the remaining aliases.
+        val projectionReferences = project.references.toSeq
+
+        val expensiveCondition = expensive.reduce(And)
+
+        // If we don't have any cheap conditions we do:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections
+        // If we do we go:
+        // non-expensive-filter-used Project -> Filter -> Used Expensive Projections -> Cheap Filter
+        val filterChild = if (cheap.isEmpty) {
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases))
+        } else {
+          val cheapCondition = replaceAlias(cheap.reduce(And), aliasMap)
+          project.copy(
+            projectList = (projectionReferences ++ expensiveFilterAliases),
+            child = Filter(cheapCondition, grandChild))
+        }
+
+
+        // Our top level projection is going to be the existing projection minus the
+        // leftBehindAliases + all of the output fields which we've effectively pushed down.
+        val pushedAliasNames = project.output.filter(
+          a => !leftBehindAliases.contains(a.exprId)).toSeq
+        val remainingAliasesToEval = leftBehindAliases.iterator.map(_._2).toSeq
+        val topLevelProjection = project.copy(
+          projectList = matchColumnOrdering(fields, pushedAliasNames ++ remainingAliasesToEval),
+          child = Filter(expensiveCondition, child = filterChild)
+        )
+        topLevelProjection
+      }

Review Comment:
   Great, I'll work on adding more comments to explain the algorithm more clearly :)



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


Re: [PR] [SPARK-47672][SQL] Avoid double eval from filter pushDown w/ projection pushdown [spark]

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

   Assuming this still passes CI (fingers crossed), that I've updated the docs and simplified the flow of the optimization rule a little bit, I intend to merge this next week.


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