sarutak commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4589529350


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -195,14 +201,18 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
         (None, AttributeMap(Map(right -> (left, e))))
       case a: And =>
         val (newLeft, equalityPredicatesLeft) =
-          traverse(a.left, replaceChildren = false, nullIsFalse)
+          traverse(a.left, replaceChildren = false, nullIsFalse, columns)
         val (newRight, equalityPredicatesRight) =
-          traverse(a.right, replaceChildren = false, nullIsFalse)
+          traverse(a.right, replaceChildren = false, nullIsFalse, columns)
         val equalityPredicates = equalityPredicatesLeft ++ 
equalityPredicatesRight
         val newSelf = if (equalityPredicates.nonEmpty && replaceChildren) {
           val unreplaced = And(newLeft.getOrElse(a.left), 
newRight.getOrElse(a.right))
-          Some(moveEqualitiesFirst(
-            unreplaced, replaceConstants(unreplaced, equalityPredicates), 
equalityPredicates))
+          val usable = usableEqualities(unreplaced, equalityPredicates, 
nullIsFalse, columns)
+          val movable = usable.filter { case (attr, _) => 
columns.canEvaluateUnconditionally(attr) }

Review Comment:
   Thanks. I measured this with ANSI on, one Parquet file, and the filter kept 
above the projection by `rand`. Both examples hold. Placing the equality right 
before the first conjunct that reads its column fixes `i + 1 > 0 AND w > 5 AND 
i = 1` with whole-stage codegen, but not `10 / (id - i) > 0 AND i = 1`: there 
the equality goes first, so `i` is computed for it before the check that `id` 
is not NULL, which FilterExec generates right before the first conjunct that 
reads `id`. Over the rows ("1", 7), ("8", 8), ("x", NULL), that plan fails with 
`CAST_INVALID_INPUT` on ("x", NULL) with codegen on and off, while 4.3.0 
returns ("1", 7) with codegen on.
   
   Both queries succeed on 4.3.0 because it replaces `i` with the constant in 
every other comparison, in place, and does not move the equality: `10 / (id - 
1) > 0 AND i = 1` and `w > 5 AND i = 1`. So I changed the rule to do that for 
an equality over a column that can fail, instead of withholding its constant, 
unless the condition would then fail to fold outside of a conditional branch, 
e.g. with `id > 10 / 0` for `i = 0 AND id > 10 / i`, which failed the query 
while optimized on 4.3.0 unless a rule before `ConstantFolding` removed the 
part that fails; then it handles the equalities as on master. I measured 40 
conditions (the PR's queries, the ones in this review, and the SPARK-60983 / 
SPARK-61033 shapes over such a column) on 4.3.0, master and this PR, with the 
filter kept above and pushed below, codegen on and off: all that succeed on 
4.3.0 succeed with this PR, except one, which fails on master as well: `(id > 0 
OR i BETWEEN 1 AND 100) AND id = 7` once the filter is pushed below t
 he projection, where SPARK-61033 keeps `id > 0` and FilterExec's subexpression 
elimination computes the cast ahead of the OR. I will handle that one 
separately. The cost is that the SPARK-60983 case comes back for such a column, 
as on 4.3.0, e.g. `10 / (id - i) > 0 AND i = 1` fails on the row ("2", 1), and 
so do the OR case of SPARK-61033, e.g. `(i < 3 OR 10 / w > 1) AND i = 5` on a 
row with `i` = 1 and `w` = 0, a guard that the constant folds away, e.g. `id > 
5 AND i > 0 AND 10 / w > 0 AND i = 1` on a row with `i` = -1 and `w` = 0, and a 
conditional branch that divides by zero with the constant once a later rule 
makes its condition constant, e.g. `if(five > 0, 10 / i, 0) > 0 AND i = 0` with 
`five` the alias `lit(5)`, fails while optimized; the description now says so.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +246,71 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * The equalities of `condition` whose constants can be propagated. An 
equality over a column
+   * that can fail (see [[FailableColumns]]), e.g. `i = 1` with `i` the alias 
`CAST(s AS INT)` of
+   * the projection below, can not go first, as it would compute that column 
on rows the conjuncts
+   * before it filter out. So it stays where it is written. A conjunct after 
it can take its
+   * constant, as after any other equality (for the rows where the equality is 
NULL, see
+   * SPARK-61438). A conjunct before it that is rewritten with its constant 
can pass a row that it
+   * would not, but only one where it would fail as well, or one where the 
column does not fail,
+   * so the equality itself raises no new error there (but for a row where the 
column is NULL,
+   * which goes on past the equality, see SPARK-61438). A conjunct that can 
fail between them
+   * could, though, e.g. `10 / x > 0` for `i > 0 AND 10 / x > 0 AND i = 1`, so 
such an equality
+   * is not propagated then, unless a conjunct before that one is FALSE, so 
that no row reaches
+   * it, or NULL where a NULL counts as FALSE, which the caller then makes 
FALSE. For simplicity,
+   * this counts from the first conjunct that is rewritten at all, with any 
constant; the next run
+   * of the rule sees that conjunct as rewritten already. Such an equality is 
not moved even where
+   * moving it would keep a conjunct before it from failing as written, e.g. 
`10 / (id - i) > 0`
+   * in `10 / (id - i) > 0 AND i = 1`.
+   */
+  private def usableEqualities(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): AttributeMap[(Literal, BinaryComparison)] = {
+    val conjuncts = splitConjunctivePredicates(condition).toIndexedSeq
+    @tailrec
+    def usable(
+        equalities: AttributeMap[(Literal, BinaryComparison)])
+      : AttributeMap[(Literal, BinaryComparison)] = {
+      lazy val rewritten =
+        splitConjunctivePredicates(replaceConstants(condition, equalities, 
columns)).toIndexedSeq
+      lazy val first = firstRewritten(conjuncts, rewritten)
+      lazy val stop = rewritten.indexWhere { c =>
+        fold(c).exists(l => l.value == false || (l.value == null && 
nullIsFalse))
+      }
+      val unsafe = equalities.filter { case (attr, (_, equality)) =>
+        !columns.canEvaluateUnconditionally(attr) && {
+          val at = conjuncts.indexWhere(_ eq equality)
+          val end = if (stop >= 0) math.min(stop, at) else at

Review Comment:
   With the constant now propagated into the other comparisons in place, `i + 1 
> 3` becomes FALSE wherever it is, and the filter is pruned; so does a conjunct 
that becomes NULL, which `ReplaceNullWithFalseInPredicate` makes FALSE, e.g. 
`nullif(i, 1) > 0` after the division. Added `i > 0 AND 10 / x > 0 AND i + 1 > 
3 AND i = 1`, the same with the contradiction after the equality, `i > 0 AND j 
> 5 AND i > 10 AND i = 1`, and `i > 0 AND k > 5 AND j < 0 AND i = 1 AND j = 2` 
to the plan tests, and `i > 0 AND 10 / (id - 3) > 0 AND i + 1 > 3 AND i = 1`, 
the same with `i + 1 > 3` last, and the same with `nullif(i, 1) > 0` in place 
of `i + 1 > 3` to the end-to-end test, which now also checks that the filter is 
pruned.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -289,12 +367,15 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Rewrites the operands of `e`, which short-circuits, with `f`. An operand 
decides whether the
    * ones after it run, so it is rewritten only if none of those, as 
rewritten, can fail.
    */
-  private def replaceOperands(e: Expression, f: Expression => Expression): 
Expression = {
+  private def replaceOperands(
+      e: Expression,
+      f: Expression => Expression,
+      columns: FailableColumns): Expression = {
     val (newChildren, _) = e.children.foldRight((List.empty[Expression], 
false)) {
       case (child, (laterChildren, laterCanFail)) =>
         val newChild = if (laterCanFail) child else f(child)
         (newChild :: laterChildren,
-          laterCanFail || !ExprUtils.canEvaluateUnconditionally(newChild))
+          laterCanFail || !columns.canEvaluateUnconditionally(newChild))

Review Comment:
   Fixed, differently: `replaceOperands` no longer counts a column of the 
projection below as one that can fail, so it rewrites `id > 0` as on master, 
and a rewritten conjunct that still reads such a column now makes the 
equalities over the other columns go first, as one that can fail after it does. 
An equality over such a column itself is not moved. So, with the filter kept 
above the projection, `(id > 0 OR i > 0) AND id = 7` optimizes to `id = 7`, and 
so does `(id > 0 OR x > 0 OR i > 0) AND id = 7`, where the operand that ends 
the inner OR is nested. Once the filter is pushed below the projection, 
SPARK-61033 keeps `id > 0` before `cast(s as int) > 0`, as on master. 
`coalesce(id, i) > 0 AND id = 7` becomes `id = 7 AND coalesce(7, i) > 0` in the 
rule's test batch, and `id = 7` with the full optimizer. Added these to the 
plan tests, and an end-to-end test over ("1", 7), ("x", 7) that checks that the 
filter reads only `id` and returns both rows. With the filter kept above the 
projecti
 on, `(id < 3 OR i > 0) AND id = 7` now becomes `id = 7 AND i > 0`: `i` is then 
computed only on the rows where `id` is 7, a subset of the rows on which the 
written OR reads it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +246,71 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * The equalities of `condition` whose constants can be propagated. An 
equality over a column
+   * that can fail (see [[FailableColumns]]), e.g. `i = 1` with `i` the alias 
`CAST(s AS INT)` of
+   * the projection below, can not go first, as it would compute that column 
on rows the conjuncts
+   * before it filter out. So it stays where it is written. A conjunct after 
it can take its
+   * constant, as after any other equality (for the rows where the equality is 
NULL, see
+   * SPARK-61438). A conjunct before it that is rewritten with its constant 
can pass a row that it
+   * would not, but only one where it would fail as well, or one where the 
column does not fail,
+   * so the equality itself raises no new error there (but for a row where the 
column is NULL,
+   * which goes on past the equality, see SPARK-61438). A conjunct that can 
fail between them
+   * could, though, e.g. `10 / x > 0` for `i > 0 AND 10 / x > 0 AND i = 1`, so 
such an equality
+   * is not propagated then, unless a conjunct before that one is FALSE, so 
that no row reaches
+   * it, or NULL where a NULL counts as FALSE, which the caller then makes 
FALSE. For simplicity,
+   * this counts from the first conjunct that is rewritten at all, with any 
constant; the next run
+   * of the rule sees that conjunct as rewritten already. Such an equality is 
not moved even where
+   * moving it would keep a conjunct before it from failing as written, e.g. 
`10 / (id - i) > 0`
+   * in `10 / (id - i) > 0 AND i = 1`.
+   */
+  private def usableEqualities(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      nullIsFalse: Boolean,
+      columns: FailableColumns): AttributeMap[(Literal, BinaryComparison)] = {
+    val conjuncts = splitConjunctivePredicates(condition).toIndexedSeq
+    @tailrec
+    def usable(
+        equalities: AttributeMap[(Literal, BinaryComparison)])
+      : AttributeMap[(Literal, BinaryComparison)] = {
+      lazy val rewritten =
+        splitConjunctivePredicates(replaceConstants(condition, equalities, 
columns)).toIndexedSeq
+      lazy val first = firstRewritten(conjuncts, rewritten)

Review Comment:
   That logic is gone with the change above: an equality over such a column is 
now propagated into the other comparisons in place, unless the condition would 
then fail to fold, so `u > 0 AND w > 5 AND u = 1 AND v + 1 > 1 AND v = 2` 
optimizes to `w > 5 AND u = 1 AND v = 2`. Added it to the plan tests, with `u`, 
`w` and `v` named `i`, `k` and `j` there.



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3075,6 +3075,95 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61437: ConstantPropagation judges a filter condition by what the 
aliases of the " +
+    "projection below stand for") {
+    withTempPath { dir =>
+      // `i` fails on the row ("x", 0), which `id > 0` and `id > 5` filter 
out. One file, so that
+      // the scan does not skip that row by the statistics of a file of its 
own.
+      Seq(("1", 7L), ("x", 0L)).toDF("s", 
"id").coalesce(1).write.parquet(dir.getCanonicalPath)
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+        def projected: DataFrame = spark.read.parquet(dir.getCanonicalPath)
+          .select($"s", $"id", $"s".cast("int").as("i"))
+        // Whether the filter is above the projection that computes `i`.
+        def filtersAboveI(df: DataFrame): Boolean = 
df.queryExecution.optimizedPlan.exists {
+          case Filter(_, child) => child.exists {
+            case p: Project => p.projectList.exists(_.name == "i")
+            case _ => false
+          }
+          case _ => false
+        }
+        val conditions = Seq(
+          $"id" > 5 && $"i" * $"id" > 0 && $"i" === 1,
+          $"id" > 5 && $"i" > 0 && lit(10) / ($"id" - 3) > 0 && $"i" === 1,
+          // `id = 7` folds `id > 0`, and goes first, as `i > 0` and `i = 1` 
can fail.
+          $"id" > 0 && $"i" > 0 && $"id" === 7,
+          $"id" > 0 && $"i" === 1 && $"id" === 7)
+        withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "true") {
+          conditions.foreach { condition =>
+            // With `r` read, the filter stays above the projection, and so it 
does above a
+            // sample. The projection computes `i` only for the rows that 
reach a condition
+            // reading it.
+            Seq(
+              projected.select($"*", rand(1).as("r")).where(condition)
+                .select($"s", $"id", $"r" >= 0),
+              projected.sample(0.999, 1).where(condition).select($"s", $"id", 
lit(true))
+            ).foreach { df =>
+              assert(filtersAboveI(df))
+              checkAnswer(df, Row("1", 7L, true))
+            }
+          }
+          // As on master, `i = 1` simplifies the other conditions, so `i` is 
not computed
+          // for the row ("x", 0).
+          Seq(
+            $"i" + 1 > 3 && $"i" === 1,
+            $"i" === 1 && $"i" + 1 > 3,
+            ($"id" < 0 || $"i" + 1 > 3) && $"i" === 1,
+            nullif($"i", lit(1)) > 0 && $"i" === 1,
+            // Also with a division in between, so `i` is propagated, and no 
row computes it.
+            $"i" + 1 > 3 && lit(10) / ($"id" - 3) > 0 && $"i" === 1,
+            $"i" === 1 && lit(10) / ($"id" - 3) > 0 && $"i" === 2,
+            nullif($"i", lit(1)) > 0 && lit(10) / ($"id" - 3) > 0 && $"i" === 1
+          ).foreach { condition =>
+            checkAnswer(
+              projected.select($"*", rand(1).as("r")).where(condition)
+                .select($"s", $"id", $"r" >= 0),
+              Seq.empty)
+          }
+          // Nor the division by zero for the row ("0", 8).
+          withTempPath { zero =>
+            Seq(("1", 7L), ("0", 8L)).toDF("s", 
"id").coalesce(1).write.parquet(zero.toString)
+            val df = spark.read.parquet(zero.toString)
+              .select($"s", $"id", $"s".cast("int").as("i"), rand(1).as("r"))
+              .where(lit(10) / $"i" > 1 && $"i" === 1).select($"s", $"id", 
$"r" >= 0)
+            assert(filtersAboveI(df))
+            checkAnswer(df, Row("1", 7L, true))
+          }
+          // `id < 3` decides whether `i > 0` runs. Without the subexpression 
elimination path of
+          // `FilterExec`, which computes `i` up front for the `i > 0` that
+          // `InferFiltersFromConstraints` infers from it.
+          
withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_FILTER_EXEC_ENABLED.key -> 
"false") {

Review Comment:
   Right, the case now passes at the default too. The test now runs it with 
FilterExec's subexpression elimination on and off, and the comment no longer 
names that path.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to