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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -195,9 +195,16 @@ object ExtractEquiJoinKeys extends Logging with 
PredicateHelper {
     case Join(left, right, joinType, condition, hint) =>
       logDebug(s"Considering join on: $condition")
       // Find equi-join predicates that can be evaluated before the join, and 
thus can be used
-      // as join keys.
+      // as join keys. A join computes its keys on every row of its inputs, 
ahead of the rest of
+      // its condition, so a conjunct that may not be evaluated ahead of the 
others (see
+      // `splitMovable`), e.g. one that can fail written after a throwable 
one, is not a key. It
+      // stays in the other condition, in its written order. Only the 
condition decides it, not
+      // the columns of the inputs that can fail, so that the keys do not 
change when the inputs
+      // do, e.g. when AQE replaces them with query stages: 
`NormalizeFloatingNumbers` only
+      // normalizes the keys that it finds in the optimizer.
       val predicates = condition.map(splitConjunctivePredicates).getOrElse(Nil)
-      val joinKeys = predicates.flatMap {
+      val notMovable = splitMovable(predicates, Nil)._2
+      val joinKeys = predicates.filterNot(notMovable.contains).flatMap {

Review Comment:
   Thank you. I tried it, but the optimizer removes the later copy before the 
planner sees the condition. For `CAST(a.s AS INT) = b.z AND CASE WHEN a.x < 0 
THEN raise_error('neg') ELSE true END AND CAST(a.s AS INT) = b.z`, the 
optimized join condition is `(cast(s#27 as int) = z#28) AND CASE WHEN ...`, and 
the join is `BroadcastHashJoin [cast(s#27 as int)], [z#28]`, also when the 
`CASE WHEN` reads both sides. So I kept the structural match. 
`ExtractEquiJoinKeysSuite` now checks that an equality that can fail, written 
before the throwable conjunct, stays a key, and that a throwable equality 
written first is one.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -195,9 +195,16 @@ object ExtractEquiJoinKeys extends Logging with 
PredicateHelper {
     case Join(left, right, joinType, condition, hint) =>
       logDebug(s"Considering join on: $condition")
       // Find equi-join predicates that can be evaluated before the join, and 
thus can be used
-      // as join keys.
+      // as join keys. A join computes its keys on every row of its inputs, 
ahead of the rest of
+      // its condition, so a conjunct that may not be evaluated ahead of the 
others (see
+      // `splitMovable`), e.g. one that can fail written after a throwable 
one, is not a key. It
+      // stays in the other condition, in its written order. Only the 
condition decides it, not
+      // the columns of the inputs that can fail, so that the keys do not 
change when the inputs
+      // do, e.g. when AQE replaces them with query stages: 
`NormalizeFloatingNumbers` only
+      // normalizes the keys that it finds in the optimizer.
       val predicates = condition.map(splitConjunctivePredicates).getOrElse(Nil)
-      val joinKeys = predicates.flatMap {
+      val notMovable = splitMovable(predicates, Nil)._2

Review Comment:
   Thank you. Fixed. The first conjunct may be a key again when it is 
deterministic, also when it is throwable; the conjuncts after a throwable first 
conjunct keep the rule (`splitMovable(rest, Nil, afterBarrier = 
first.throwable)`). `NormalizeNaNAndZero` and `KnownFloatingPointNormalized` 
now declare `NoThrow`, so a normalized `FLOAT` or `DOUBLE` key after it stays a 
key when the planner extracts the keys again. `ExtractEquiJoinKeysSuite` covers 
it.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala:
##########
@@ -2115,6 +2115,49 @@ class JoinSuite extends SharedSparkSession with 
AdaptiveSparkPlanHelper
       }
     }
   }
+
+  test("SPARK-62241: do not compute an equality that can fail after a 
throwable join " +
+    "condition as a join key") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTable("c1", "c3") {
+        Seq((5, "abc"), (1, "7")).toDF("x", "s").write.saveAsTable("c1")
+        Seq(7).toDF("z").write.saveAsTable("c3")
+        // The CASE WHEN is false on the row whose s is 'abc', so the cast, 
which fails on it, is
+        // not evaluated on it. A join key would be computed on every row.
+        checkAnswer(
+          sql(
+            """SELECT c1.x, c3.z FROM c1 JOIN c3 ON
+              |  CASE WHEN c1.x > 3 THEN false WHEN c1.x >= 0 THEN true ELSE 
raise_error('k') END
+              |  AND CAST(c1.s AS INT) = c3.z
+              |""".stripMargin),
+          Row(1, 7))
+      }
+    }
+  }
+
+  test("SPARK-62241: AQE keeps the join keys after a throwable join 
condition") {
+    withSQLConf(
+        SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB") {
+      withTable("c1", "c3") {
+        Seq((1, "7"), (3, "-0")).toDF("x", "s").write.saveAsTable("c1")
+        Seq((7, 1), (0, 3)).toDF("z", "w").write.saveAsTable("c3")
+        // AQE plans the sort-merge join again as a broadcast hash join once 
its inputs are query
+        // stages. The equality on `q`, a cast computed below the join, must 
have the same role
+        // there: as a key that `NormalizeFloatingNumbers` did not normalize, 
-0.0 would not
+        // match 0.0.
+        checkAnswer(

Review Comment:
   Thank you. The test now checks that the initial plan has a 
`SortMergeJoinExec` and the final plan a `BroadcastHashJoinExec`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -195,9 +195,16 @@ object ExtractEquiJoinKeys extends Logging with 
PredicateHelper {
     case Join(left, right, joinType, condition, hint) =>
       logDebug(s"Considering join on: $condition")
       // Find equi-join predicates that can be evaluated before the join, and 
thus can be used
-      // as join keys.
+      // as join keys. A join computes its keys on every row of its inputs, 
ahead of the rest of
+      // its condition, so a conjunct that may not be evaluated ahead of the 
others (see
+      // `splitMovable`), e.g. one that can fail written after a throwable 
one, is not a key. It
+      // stays in the other condition, in its written order. Only the 
condition decides it, not
+      // the columns of the inputs that can fail, so that the keys do not 
change when the inputs
+      // do, e.g. when AQE replaces them with query stages: 
`NormalizeFloatingNumbers` only
+      // normalizes the keys that it finds in the optimizer.

Review Comment:
   Thank you. I rewrote the comment to lead with that reason.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala:
##########
@@ -2115,6 +2115,49 @@ class JoinSuite extends SharedSparkSession with 
AdaptiveSparkPlanHelper
       }
     }
   }
+
+  test("SPARK-62241: do not compute an equality that can fail after a 
throwable join " +

Review Comment:
   Thank you. The test now runs Issue 1, Issue 2 and the `LEFT ANTI JOIN` form, 
with and without `spark.sql.autoBroadcastJoinThreshold=-1`.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala:
##########
@@ -2115,6 +2115,49 @@ class JoinSuite extends SharedSparkSession with 
AdaptiveSparkPlanHelper
       }
     }
   }
+
+  test("SPARK-62241: do not compute an equality that can fail after a 
throwable join " +
+    "condition as a join key") {
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      withTable("c1", "c3") {
+        Seq((5, "abc"), (1, "7")).toDF("x", "s").write.saveAsTable("c1")
+        Seq(7).toDF("z").write.saveAsTable("c3")
+        // The CASE WHEN is false on the row whose s is 'abc', so the cast, 
which fails on it, is
+        // not evaluated on it. A join key would be computed on every row.
+        checkAnswer(
+          sql(
+            """SELECT c1.x, c3.z FROM c1 JOIN c3 ON
+              |  CASE WHEN c1.x > 3 THEN false WHEN c1.x >= 0 THEN true ELSE 
raise_error('k') END
+              |  AND CAST(c1.s AS INT) = c3.z
+              |""".stripMargin),
+          Row(1, 7))
+      }
+    }
+  }
+
+  test("SPARK-62241: AQE keeps the join keys after a throwable join 
condition") {
+    withSQLConf(
+        SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+        SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+        SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10MB") {
+      withTable("c1", "c3") {
+        Seq((1, "7"), (3, "-0")).toDF("x", "s").write.saveAsTable("c1")
+        Seq((7, 1), (0, 3)).toDF("z", "w").write.saveAsTable("c3")
+        // AQE plans the sort-merge join again as a broadcast hash join once 
its inputs are query
+        // stages. The equality on `q`, a cast computed below the join, must 
have the same role
+        // there: as a key that `NormalizeFloatingNumbers` did not normalize, 
-0.0 would not
+        // match 0.0.
+        checkAnswer(
+          sql(
+            """SELECT b.x, c3.z FROM (SELECT x, CAST(s AS DOUBLE) AS q FROM 
c1) b JOIN c3
+              |ON CASE WHEN c3.z > 100 THEN raise_error('big') ELSE true END
+              |  AND b.q = CAST(c3.z AS DOUBLE) AND b.x = c3.w
+              |""".stripMargin),
+          Seq(Row(1, 7), Row(3, 0)))

Review Comment:
   Thank you. It now asserts that the initial plan has a `SortMergeJoinExec` 
and the final plan a `BroadcastHashJoinExec`. It still passes without this PR, 
where the cast equality is a key from the start; it fails if the keys depend on 
the columns of the inputs that can fail.
   



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