dongjoon-hyun commented on code in PR #60653:
URL: https://github.com/apache/spark/pull/60653#discussion_r4622439861


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -644,6 +652,26 @@ object BooleanSimplification extends Rule[LogicalPlan] 
with PredicateHelper {
     case not: Not => simplifyNot(not)
   }
 
+  /**
+   * Returns the operands of `lhs` that are also in `rhs` and are to be 
evaluated ahead of the other
+   * operands, in their order in `lhs`. One that can fail, as
+   * [[ExprUtils.canEvaluateUnconditionally]] decides, is returned only if, in 
`lhs` or in `rhs`,
+   * only the ones returned before it come before it. Otherwise, evaluating it 
ahead would also run
+   * it on rows where an operand before it decides the result of both `lhs` 
and `rhs`.
+   */
+  private def commonFactors(lhs: Seq[Expression], rhs: Seq[Expression]): 
Seq[Expression] = {
+    lhs.filter(e => 
rhs.exists(e.semanticEquals)).foldLeft(Seq.empty[Expression]) { (common, e) =>
+      def onlyCommonBefore(operands: Seq[Expression]): Boolean =
+        operands.takeWhile(!_.semanticEquals(e)).forall(o => 
common.exists(o.semanticEquals))
+      if (ExprUtils.canEvaluateUnconditionally(e) ||
+          onlyCommonBefore(lhs) || onlyCommonBefore(rhs)) {
+        common :+ e

Review Comment:
   Thank you, good catch. Lifting the `rhs` copy would break the mirrored case, 
though. In `(p AND (y = 0 OR x / y > 1)) OR ((x / y > 1 OR y = 0) AND q)` with 
`p = true` and `y = 0`, the original returns true from the left branch without 
dividing, while the `rhs` copy divides first. So a throwable common factor is 
now extracted through the prefix check only when it is the same expression in 
both operands (`rhs.contains(e)`), and the doc comment says so.
   
   Since a common factor that can fail without being throwable is now extracted 
as on master (see the reply on the join key), your division example stays as on 
master. The new test uses `(e || r)` and `(r || e)` with `raise_error` instead.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -607,16 +614,17 @@ object BooleanSimplification extends Rule[LogicalPlan] 
with PredicateHelper {
     case or @ (left Or right) =>
       // 1. Split left and right to get the conjunctive predicates,
       //    i.e.  lhs = (a && b), rhs = (a && c)
-      // 2. Find the common predict between lhsSet and rhsSet, i.e. common = 
(a)
+      // 2. Find the common predict between lhsSet and rhsSet, i.e. common = 
(a). One that can
+      //    fail is left out where the formula evaluates it on more rows, see 
`commonFactors`.
       // 3. Remove common predict from lhsSet and rhsSet, i.e. ldiff = (b), 
rdiff = (c)
       // 4. If common is non-empty, apply the formula to get the optimized 
predicate:
       //    common && (ldiff || rdiff)
-      // 5. Else if common is empty, split left and right to get the 
conjunctive predicates.
+      // 5. Else, split left and right to get the conjunctive predicates.
       // for example lhs = (a || b), rhs = (a || c) => all = (a, b, a, c), 
distinct = (a, b, c)
       // optimized predicate: (a || b || c)
       val lhs = splitConjunctivePredicates(left)
       val rhs = splitConjunctivePredicates(right)
-      val common = lhs.filter(e => rhs.exists(e.semanticEquals))
+      val common = commonFactors(lhs, rhs)

Review Comment:
   Thank you. I took the second option: only a throwable common factor is kept 
in place, as `PushPredicateThroughJoin` does for a conjunct, so `t1.k + 1 = 
t2.k` is extracted as on master and stays the join key. The two rewrites where 
`c` is not nullable still use `ExprUtils.canEvaluateUnconditionally`, since 
they move no common factor out of an OR. The PR description is updated.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -2021,6 +2021,35 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61938: do not evaluate an expression that can fail ahead of its 
guard") {
+    val df = spark.range(3).toDF()
+    val all = Seq(Row(0L), Row(1L), Row(2L))
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      val d = "10 / (id - 1) > 1"
+      checkAnswer(df.where(s"(id < 5 OR $d) AND id >= 5"), Seq.empty)
+      checkAnswer(df.where(s"(id >= 5 AND $d) OR id < 5"), all)
+    }
+    val r = "raise_error('boom') IS NULL"
+    // Subexpression elimination evaluates a duplicated raise_error ahead of 
its guards by itself.
+    withSQLConf(SQLConf.SUBEXPRESSION_ELIMINATION_ENABLED.key -> "false") {
+      checkAnswer(df.where(s"(id < 5 OR $r) AND (id > -5 OR $r)"), all)
+      checkAnswer(df.where(s"(id > 5 AND $r) OR (id < -5 AND $r)"), Seq.empty)
+    }
+    // The check runs only on the joined rows, and t1.k = 3 has no match.
+    withTempView("t1", "t2") {
+      spark.range(4).selectExpr("id AS k", "id % 2 AS a",
+        "CASE WHEN id = 3 THEN -1 ELSE 1 END AS 
v").createOrReplaceTempView("t1")
+      spark.range(3).selectExpr("id AS k", "id AS 
b").createOrReplaceTempView("t2")
+      val c = "CASE WHEN t1.v < 0 THEN raise_error('bad v') ELSE TRUE END"
+      Seq(
+        s"(t1.k = t2.k AND $c AND t1.a = 1) OR (t1.k = t2.k AND $c AND t2.b = 
2)",
+        s"t1.k = t2.k AND ((t1.a = 1 AND $c) OR (t2.b = 2 AND $c))").foreach { 
cond =>

Review Comment:
   Thank you. I added the join with `'bad v'` and `'bad v2'`, which fails on 
master, and a check that none of the three joins is planned as a 
`BroadcastNestedLoopJoinExec`.
   



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