viirya commented on code in PR #60653:
URL: https://github.com/apache/spark/pull/60653#discussion_r4622040892
##########
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:
Both join conditions here pass on master too: there, `$c` is lifted next to
`t1.k = t2.k` and kept in the join condition. So they guard against a
regression from the earlier revision, but don't reproduce the
`PushExtraPredicateThroughJoin` bug. Could you add the query from the PR
description that uses different messages (`'bad v'` / `'bad v2'`), which fails
on master? Also, `checkAnswer` would still pass if the first condition lost its
equi-join key, so asserting that the plan has no `BroadcastNestedLoopJoinExec`
would pin the factoring end to end.
##########
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:
When `e` is admitted only through `onlyCommonBefore(rhs)`, the lifted
expression is still the `lhs` copy. `semanticEquals` ignores the operand order
inside `And`/`Or`, so that copy can be the unguarded one. With ANSI on, `y = 0`
and `p = false`:
```
(p AND (x / y > 1 OR y = 0)) OR ((y = 0 OR x / y > 1) AND q)
=> (x / y > 1 OR y = 0) AND (p OR q)
```
The original evaluates to true; the rewritten predicate throws
DIVIDE_BY_ZERO. This is pre-existing on master, but the new doc comment claims
this lift is safe. The `c` vs `Not(a)` case above already handles the same
subtlety. Lifting the `rhs` copy in this case would fix it.
##########
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:
For example, in ANSI mode `(t1.a = 1 AND t1.k + 1 = t2.k) OR (t2.b = 2 AND
t1.k + 1 = t2.k)` is now kept as is, while master gives `t1.k + 1 = t2.k AND
(t1.a = 1 OR t2.b = 2)`. So the join loses its only equi-join key. See the
review body for the options.
--
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]