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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -176,11 +178,18 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
     condition match {
       case _ if !condition.containsAllPatterns(LITERAL, BINARY_COMPARISON) =>
         (None, AttributeMap.empty)
+      // An `EqualTo` with a NULL literal is NULL on every row, also when the 
attribute is not
+      // nullable, so under a `NOT`, where `safeToReplace` relies on the 
equalities not being NULL,
+      // replacing the attribute could change another conjunct, e.g. from TRUE 
to FALSE or from
+      // FALSE to NULL, and so the `NOT` from NULL to TRUE or from TRUE to 
NULL. Where a NULL counts
+      // as FALSE, such an `AND` is never TRUE whatever the attribute is 
replaced with, so it is
+      // still propagated there. An `EqualNullSafe` with a NULL literal is 
never NULL, so it is
+      // propagated in both cases, under a `NOT` only over an attribute that 
is not nullable.
       case e @ EqualTo(left: AttributeReference, right: Literal)
-        if safeToReplace(left, nullIsFalse) =>
+        if safeToReplace(left, nullIsFalse) && (nullIsFalse || right.value != 
null) =>

Review Comment:
   Thanks, done in 887abc32bdb and 57db67cc7cb. `safeToReplace` now takes the 
equality and checks `nullIsFalse || !(ar.nullable || e.nullable)`, so the four 
cases call it the same way, and the explanation moved into its comment. Since 
`e.nullable` now covers `ar.nullable` for an `EqualTo`, `ar.nullable` is only 
needed for an `EqualNullSafe` over a nullable attribute under a `NOT`, and no 
test in `ConstantPropagationSuite` or `DataFrameSuite` pinned that, so I added 
an assertion for it; a `safeToReplace` with only `!e.nullable` fails it. 
Changing that behavior is left out of this PR, as you said.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3032,6 +3032,43 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61704: ConstantPropagation does not propagate an EqualTo with a 
NULL literal " +
+      "under a NOT") {
+    // `NullPropagation` would turn `id = NULL` into a NULL literal first, so 
it is excluded. Under
+    // the `NOT`, `id = NULL` is NULL on every row, so a row passes only where 
the other conjunct is
+    // FALSE. Each condition gives the result that it gives with the default 
rules. The NULL is a
+    // `typedLit`: with `lit(null).cast("bigint")`, the first query returns 
the right rows also
+    // without this fix.
+    val df = spark.range(4, 7, 1, 1).toDF()
+    val nullLong = typedLit[java.lang.Long](null)
+    Seq("true", "false").foreach { ansi =>

Review Comment:
   Done: the loop is gone and the three queries moved into the ANSI block. With 
the fix, they return the same rows with ANSI mode on and off (`[4, 6]`, `[4, 
6]` and `[4, 5]`).
   



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3032,6 +3032,43 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61704: ConstantPropagation does not propagate an EqualTo with a 
NULL literal " +
+      "under a NOT") {
+    // `NullPropagation` would turn `id = NULL` into a NULL literal first, so 
it is excluded. Under
+    // the `NOT`, `id = NULL` is NULL on every row, so a row passes only where 
the other conjunct is
+    // FALSE. Each condition gives the result that it gives with the default 
rules. The NULL is a
+    // `typedLit`: with `lit(null).cast("bigint")`, the first query returns 
the right rows also
+    // without this fix.
+    val df = spark.range(4, 7, 1, 1).toDF()
+    val nullLong = typedLit[java.lang.Long](null)
+    Seq("true", "false").foreach { ansi =>
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi,
+          SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> NullPropagation.ruleName) {
+        // Propagating the NULL made the condition TRUE for id 5 ...
+        checkAnswer(df.where(!($"id" === nullLong && ($"id" + 0 <=> 5))), 
Seq(Row(4L), Row(6L)))
+        // ... also from a projection below ...
+        checkAnswer(
+          df.select($"id", nullLong as "n").where(!($"id" === $"n" && ($"id" + 
0 <=> 5)))

Review Comment:
   Right, it reaches `ConstantPropagation` as the same `Filter`, so it catches 
nothing the first query does not. I kept it only as the end-to-end example of 
the "NULL from a projection below" case of the description; with the loop gone 
it runs once, and its comment now says that pushing the filter through the 
`Project` replaces `n` with the NULL, so `ConstantPropagation` sees the same 
condition as for the first query. I can drop it if you prefer. The plan change 
log shows `Filter NOT ((id#0L = null) AND ((id#0L + cast(0 as bigint)) <=> 
cast(5 as bigint)))` over the `Range` after `PushDownPredicates`, as you said.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,50 @@ class ConstantPropagationSuite extends PlanTest {
     val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") === 
2).analyze
     comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
   }
+
+  test("SPARK-61704: Do not propagate an EqualTo with a NULL literal under a 
NOT") {
+    val nullInt = Literal(null, IntegerType)
+    Seq(true, false).foreach { ansi =>
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi.toString) {
+        // `d = NULL` is NULL on every row, so the condition under the `NOT` 
is NULL or FALSE.
+        // Replacing `d` with NULL would make `d + 0 <=> 5` FALSE, and the 
condition FALSE where it
+        // is NULL, or `d > b` NULL, and the condition NULL where it is FALSE. 
Also below an `OR`.
+        Seq(
+          Not(columnD === nullInt && (columnD + 0 <=> 5)),
+          Not(nullInt === columnD && (columnD + 0 <=> 5)),
+          Not(columnD === nullInt && columnD > columnB),

Review Comment:
   Done: dropped L338 and `columnD === Literal(1)`, with a comment pointing to 
the SPARK-30447 test for the latter. Every mutant is still killed without them, 
including one that rejects the attribute-left `EqualTo` under a `NOT` (the 
SPARK-30447 test fails), and one where the `Or` case passes `nullIsFalse = 
true` down, which fails at the `Or` assertion.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,50 @@ class ConstantPropagationSuite extends PlanTest {
     val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") === 
2).analyze
     comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
   }
+
+  test("SPARK-61704: Do not propagate an EqualTo with a NULL literal under a 
NOT") {
+    val nullInt = Literal(null, IntegerType)
+    Seq(true, false).foreach { ansi =>

Review Comment:
   Done. Without the loop, every mutant the description lists still fails the 
new `ConstantPropagationSuite` test, both with the default ANSI mode and with 
`SPARK_ANSI_SQL_MODE=false`, except the one that rejects the attribute-left 
`EqualTo` under a `NOT`, which the SPARK-30447 test fails (see [5]).
   



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameSuite.scala:
##########
@@ -3032,6 +3032,43 @@ class DataFrameSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61704: ConstantPropagation does not propagate an EqualTo with a 
NULL literal " +
+      "under a NOT") {
+    // `NullPropagation` would turn `id = NULL` into a NULL literal first, so 
it is excluded. Under
+    // the `NOT`, `id = NULL` is NULL on every row, so a row passes only where 
the other conjunct is
+    // FALSE. Each condition gives the result that it gives with the default 
rules. The NULL is a
+    // `typedLit`: with `lit(null).cast("bigint")`, the first query returns 
the right rows also
+    // without this fix.
+    val df = spark.range(4, 7, 1, 1).toDF()
+    val nullLong = typedLit[java.lang.Long](null)
+    Seq("true", "false").foreach { ansi =>
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> ansi,
+          SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> NullPropagation.ruleName) {
+        // Propagating the NULL made the condition TRUE for id 5 ...
+        checkAnswer(df.where(!($"id" === nullLong && ($"id" + 0 <=> 5))), 
Seq(Row(4L), Row(6L)))
+        // ... also from a projection below ...
+        checkAnswer(
+          df.select($"id", nullLong as "n").where(!($"id" === $"n" && ($"id" + 
0 <=> 5)))
+            .select($"id"),
+          Seq(Row(4L), Row(6L)))
+        // ... and NULL for the ids 4 and 5.
+        checkAnswer(df.where(!($"id" === nullLong && $"id" > 5)), Seq(Row(4L), 
Row(5L)))
+      }
+    }
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> NullPropagation.ruleName) {
+      // The division runs on id 4 and fails, as it does with the default 
rules. Propagating the
+      // NULL folded it away, so that no row was returned.
+      val e = intercept[SparkArithmeticException] {
+        df.where(!($"id" === nullLong && lit(10L) / ($"id" - 4) > 0)).collect()
+      }
+      assert(e.getCondition === "DIVIDE_BY_ZERO")
+      // Outside a `NOT` it is still propagated, so the division over `id - 4` 
is folded with NULL
+      // and does not run, as before.
+      checkAnswer(df.where(lit(10L) / ($"id" - 4) > 0 && $"id" === nullLong), 
Seq.empty)

Review Comment:
   I kept it for the contrast at run time: with the same `typedLit` NULL and 
the same division, the division is folded away outside a `NOT` and runs under 
it. It notices a guard that also applies outside a `NOT` only on the 
attribute-left side, as you said; `ConstantPropagationSuite` checks both sides.
   



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