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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,184 @@ class ConstantPropagationSuite extends PlanTest {
     val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") === 
2).analyze
     comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
   }
+
+  // SPARK-61437: the columns of the projection below that can fail.
+  private val strings = LocalRelation($"s".string, $"id".long, $"x".long)
+  private def castS: Expression = $"s".cast(IntegerType)
+  private def projected: LogicalPlan = strings.select($"s", $"id", $"x", 
castS.as("i"))
+  private def divide(e: Expression): Expression = Divide(Literal(10.0), 
e.cast(DoubleType))
+
+  private def conjuncts(plan: LogicalPlan): Seq[String] = plan match {
+    case Filter(condition, _) => 
splitConjunctivePredicates(condition).map(_.sql)
+    case other => fail(s"Expected a Filter: $other")
+  }
+
+  /** Checks the optimized plan also in the order of the conjuncts, which 
`comparePlans` sorts. */
+  private def checkOrdered(child: LogicalPlan, condition: Expression, 
expected: Expression)
+    : Unit = {
+    val optimized = Optimize.execute(child.where(condition).analyze)
+    val expectedPlan = child.where(expected).analyze
+    comparePlans(optimized, expectedPlan)
+    assert(conjuncts(optimized) == conjuncts(expectedPlan))
+  }
+
+  test("SPARK-61437: Do not move an equality over a column of the projection 
below that can " +
+      "fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // `i = 1` can fail, as the cast does, so it is not moved ahead of `id > 
5`.
+      val written = $"id" > 5L && $"i".cast(LongType) * $"id" > 0L && $"i" === 
1
+      Seq(
+        projected,
+        projected.select($"s", $"id", $"i"),
+        projected.where($"id" > 1L).select($"s", $"id", $"i"),
+        projected.sample(0.0, 0.5, withReplacement = false, 1L).select($"s", 
$"id", $"i"),
+        projected.select($"s", $"id", $"i".as("j")).select($"s", $"id", 
$"j".as("i"))
+      ).foreach(child => checkOrdered(child, written, written))
+    }
+  }
+
+  test("SPARK-61437: Propagate an equality over a column that can fail where 
it is written") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // A conjunct before it that it rewrites can pass a row it would not 
only where it would fail
+      // as well or where `i` does not fail, so `i = 1` raises no new error, 
and the conjuncts
+      // after it only run where it does not fail.
+      Seq(
+        ($"id" > 5L && $"i" + 1 > 1 && $"i" === 1) -> ($"id" > 5L && $"i" === 
1),
+        (($"id" < 0L || $"i" + 1 > 3) && $"i" === 1) -> ($"id" < 0L && $"i" 
=== 1),
+        (divide($"i") > 1.0 && $"i" === 1) -> ($"i" === 1),
+        ($"id" > 5L && ($"i" <=> 1) && $"i" > 0) -> ($"id" > 5L && ($"i" <=> 
1)),
+        ($"id" > 5L && (Literal(1) <=> $"i") && $"i" > 0) -> ($"id" > 5L && 
(Literal(1) <=> $"i")),
+        // Only the conjuncts from the first rewritten one to it count.
+        (divide($"x") > 0.0 && $"i" > 0 && $"i" === 1) -> (divide($"x") > 0.0 
&& $"i" === 1),
+        ($"i" + 1 > 1 && $"i" === 1 && divide($"x") > 0.0) -> ($"i" === 1 && 
divide($"x") > 0.0),
+        // `id > 0` is rewritten by `id = 7`, which goes first. Then `i = 1` 
is propagated too.
+        ($"id" > 0L && divide($"x") > 0.0 && $"i" === 1 && $"i" + 1 > 1 && 
$"id" === 7L) ->
+          ($"id" === 7L && divide($"x") > 0.0 && $"i" === 1)
+      ).foreach { case (condition, expected) => checkOrdered(projected, 
condition, expected) }
+    }
+  }
+
+  test("SPARK-61437: Do not propagate an equality over a column that can fail 
past a " +
+      "conjunct that can fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // The division would run on the rows that `i > 0` passes when 
rewritten, i.e. all rows.
+      val twoCasts = projected.select($"s", $"id", $"x", $"i", castS.as("j"))
+      Seq(
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && $"i" === 1,
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && Literal(1) === $"i",
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && ($"i" <=> 1),
+        $"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && (Literal(1) <=> $"i"),
+        // Without `i = 1`, `i > 0` can fail, and it comes between `j = 2` and 
`j > 0`.
+        $"j" > 0 && $"i" > 0 && $"j" === 2 && divide($"x") > 0.0 && $"i" === 1
+      ).foreach(condition => checkOrdered(twoCasts, condition, condition))
+
+      // Unless a conjunct before it becomes FALSE, or NULL, which is made 
FALSE, so no row
+      // reaches it.
+      Seq(
+        $"i" + 1 > 3 && divide($"x") > 0.0 && $"i" === 1,
+        $"i" === 1 && divide($"x") > 0.0 && $"i" === 2,
+        If($"i" === 1, Literal(null, IntegerType), $"i") > 0 && divide($"x") > 
0.0 && $"i" === 1
+      ).foreach { condition =>
+        comparePlans(Optimize.execute(projected.where(condition).analyze),
+          projected.where(false).analyze)
+      }
+      // But not NULL under a `NOT`, where the division still runs after it.
+      val upperNotNull = LocalRelation($"s".string.notNull, $"x".long.notNull)
+        .select($"x", Upper($"s").as("u"))
+      Optimize.execute(upperNotNull.where(Not(
+        If($"u" === "X", Literal(null, StringType), $"u") === "Y" && 
divide($"x") > 0.0 &&
+          $"u" === "X")).analyze) match {
+        case Filter(negated, _) => assert(negated.exists(_.isInstanceOf[If]))
+        case other => fail(s"Expected a Filter: $other")
+      }
+    }
+  }
+
+  test("SPARK-61437: A conjunct over a column that can fail can fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // `id = 7` folds the guard `id > 0`, so it goes ahead of `i > 0`, which 
can fail.
+      checkOrdered(projected, $"id" > 0L && $"i" > 0 && $"id" === 7L, $"id" 
=== 7L && $"i" > 0)
+      checkOrdered(projected, $"id" > 0L && $"i" === 1 && $"id" === 7L,
+        $"id" === 7L && $"i" === 1)
+      // `id < 3` decides whether `i > 0` runs, so it keeps `id`, and the 
equality goes first.
+      checkOrdered(projected, ($"id" < 3L || $"i" > 0) && $"id" === 5L,
+        $"id" === 5L && ($"id" < 3L || $"i" > 0))
+
+      // Also under a `NOT`, with `s` and `id` not nullable.
+      val notNull = LocalRelation($"s".string.notNull, $"id".long.notNull)
+        .select($"s", $"id", castS.as("i"))
+      checkOrdered(notNull, Not($"id" > 0L && $"i" > 0 && $"id" === 7L),
+        Not($"id" === 7L) || $"i" <= 0)
+      // The cast is marked nullable (`Cast.forceNullable`), so `i = 1` is not 
propagated under
+      // it, as on master.
+      checkOrdered(notNull, Not($"i" + 1 > 3 && $"i" === 1), $"i" + 1 <= 3 || 
Not($"i" === 1))
+      // `upper` is not, so the condition inside becomes FALSE, as on master.
+      val upperNotNull = notNull.select($"s", Upper($"s").as("u"))
+      comparePlans(
+        Optimize.execute(upperNotNull.where(Not(Length($"u") > 3 && $"u" === 
"X")).analyze),
+        upperNotNull.where(true).analyze)
+      // But one that becomes NULL is not made FALSE, which the `NOT` would 
turn into TRUE.
+      val nullInside = Optimize.execute(upperNotNull.where(Not(
+        If($"u" === "X", Literal(null, StringType), $"u") === "Y" && $"u" === 
"X")).analyze)
+      assert(!nullInside.fastEquals(upperNotNull.where(true).analyze))
+    }
+  }
+
+  test("SPARK-61437: A condition that becomes FALSE with the constants is 
FALSE") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      Seq(
+        $"id" > 5L && $"i" + 1 > 3 && $"i" === 1,
+        $"i" === 1 && $"i" + 1 > 3,
+        $"i" + 1 > 3 && Literal(1) === $"i",
+        $"i" === 1 && $"id" > 5L && $"i" === 2,
+        $"i".cast(LongType) + $"id" > 3L && $"i" === 1 && $"id" === 1L
+      ).foreach { condition =>
+        comparePlans(Optimize.execute(projected.where(condition).analyze),
+          projected.where(false).analyze)
+      }
+      comparePlans(
+        Optimize.execute(
+          projected.where(($"id" < 0L || ($"i" + 1 > 3 && $"i" === 1)) && 
$"id" > 5L).analyze),
+        projected.where($"id" < 0L && $"id" > 5L).analyze)
+    }
+  }
+
+  test("SPARK-61437: Columns that can not fail") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // A non-deterministic alias is computed on every row the projection 
gets, so it raises no
+      // new error here, and an equality over it is propagated and moved.
+      val random = strings.select($"id", $"x", Rand(1L).as("r"))
+      checkOrdered(random, $"r" > 0.0 && $"r" === 0.5, $"r" === 0.5)
+      checkOrdered(random, $"r" > 0.0 && divide($"x") > 0.0 && $"r" === 0.5,
+        $"r" === 0.5 && divide($"x") > 0.0)
+      // So is one over a column that reads it with an expression that can not 
fail.
+      val randomPlusOne = random.select($"id", ($"r" + 1.0).as("r1"))
+      checkOrdered(randomPlusOne, $"r1" > 0.0 && $"r1" === 1.5, $"r1" === 1.5)

Review Comment:
   Added `r1 > 0.0 && divide(id) > 0.0 && r1 === 1.5`, which expects `r1 = 1.5` 
first.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -318,32 +399,80 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * where an equality does not hold, with the value of the row, while a guard 
over the same
    * attribute may be folded away, e.g. `n / d > 1` for `d <> 0 AND n / d > 1 
AND d = 5`. The
    * same holds for a conjunct that can fail after one that is rewritten, as 
that one decides
-   * whether it runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. 
An equality between
-   * an attribute and a literal cannot fail, so running it first raises no 
error.
+   * whether it runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. 
A conjunct over a
+   * column of the projection below that can fail can fail too (see 
[[FailableColumns]]), e.g.
+   * `i > 0`, with `i` the alias `CAST(s AS INT)`, in ANSI mode. 
`equalityPredicates` are the
+   * equalities over a column that can not fail, which can not fail 
themselves, so running them
+   * first raises no error. The ones over a column that can fail stay where 
they are written (see
+   * [[usableEqualities]]). `keepsFailable` checks the attributes a conjunct 
reads against those
+   * of `equalityPredicates`, not those that the expressions of its columns 
read, which these
+   * equalities do not replace.
    */
   private def moveEqualitiesFirst(
       original: Expression,
       condition: Expression,
-      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Expression = {
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      columns: FailableColumns): Expression = {
     val predicates = equalityPredicates.values.map(_._2).toSet[Expression]
     val propagated = AttributeSet(equalityPredicates.keys)
     val conjuncts = splitConjunctivePredicates(condition)
     val (equalities, others) = conjuncts.partition(predicates.contains)
     val reordered = equalities ++ others
     val keepsFailable = others.exists { c =>
-      c.references.intersect(propagated).nonEmpty && 
!ExprUtils.canEvaluateUnconditionally(c)
+      c.references.intersect(propagated).nonEmpty && 
!columns.canEvaluateUnconditionally(c)
     }
-    val firstRewritten = splitConjunctivePredicates(original).zip(conjuncts)
-      .indexWhere { case (before, after) => !before.fastEquals(after) }
-    val unmasksFailable = firstRewritten >= 0 &&
-      conjuncts.drop(firstRewritten + 
1).exists(!ExprUtils.canEvaluateUnconditionally(_))
+    val first = firstRewritten(splitConjunctivePredicates(original), conjuncts)
+    val unmasksFailable = first >= 0 &&
+      conjuncts.drop(first + 1).exists(!columns.canEvaluateUnconditionally(_))
     if ((keepsFailable || unmasksFailable) && reordered != conjuncts) {
       reordered.reduce(And)
     } else {
       condition
     }
   }
 
+  /**
+   * The columns of `plan` that can fail, i.e. those that a projection at its 
top, or below the
+   * filters, samples and projections there, computes with a deterministic 
expression that
+   * [[ExprUtils.canEvaluateUnconditionally]] rejects or that reads such a 
column, or passes such
+   * a column through. Under whole-stage codegen, the projection computes a 
deterministic column
+   * for a row only when a conjunct of the filter above first reads it, unless 
subexpression
+   * elimination computes it up front, and `PushPredicateThroughNonJoin` 
pushes a conjunct below
+   * the projection with the expression of the column substituted. So a 
conjunct over such a
+   * column can fail as that expression does. A non-deterministic column is 
computed on every row
+   * the projection gets, and no filter is pushed through a projection with 
one, so it does not
+   * count. Other
+   * operators are not looked through. The columns are collected once per 
filter, when needed.

Review Comment:
   Done.



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