spark-test commented on code in PR #60699:
URL: https://github.com/apache/spark/pull/60699#discussion_r4624073330


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/joinReorder/JoinReorderSuite.scala:
##########
@@ -384,4 +384,44 @@ class JoinReorderSuite extends JoinReorderPlanTestBase 
with StatsEstimationTestB
     // this can fail before the fix
     Optimize.execute(plan.analyze)
   }
+
+  private def raiseUnless(cond: Expression): Expression =
+    If(cond, Literal(true), IsNull(RaiseError(Literal("boom"))))
+
+  test("SPARK-62054: keep the conditions that may not move or are over one 
item in the top join") {
+    // The project, which prunes t2.k-1-5, keeps ReorderJoin from flattening 
the joins.
+    val overT1 = raiseUnless(nameToAttr("t1.k-1-2") > 0)
+    val overT1T3 = raiseUnless(nameToAttr("t1.v-1-10") + 
nameToAttr("t3.v-1-100") > 0)
+    val failable = nameToAttr("t1.v-1-10") / nameToAttr("t3.v-1-100") > 0

Review Comment:
   **Non-blocking (P2):** This Divide takes its eval mode from the session, so 
it can fail only when ANSI mode is on. With SPARK_ANSI_SQL_MODE=false, as in 
the scheduled 'Build / Non-ANSI' workflow, the division is total: 
PushPredicateThroughJoin and splitMovable let it move, the reorder puts it into 
the t1-t3 join, and comparePlans fails against the expected plan, which keeps 
it in the join with t2. The comment at JoinReorderSuite.scala:402-404 is then 
false as well. The sibling SPARK-61930 test pins its divisions with Divide(l, 
r, NumericEvalContext(EvalMode.ANSI)) (JoinOptimizationSuite.scala:166).
   
   **Verification:**
   - **Compatibility:** The join reorder plan test for the conditions kept in 
the top join passes with ANSI mode off as well as on.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/joinReorder/JoinReorderSuite.scala:
##########
@@ -384,4 +384,44 @@ class JoinReorderSuite extends JoinReorderPlanTestBase 
with StatsEstimationTestB
     // this can fail before the fix
     Optimize.execute(plan.analyze)
   }
+
+  private def raiseUnless(cond: Expression): Expression =
+    If(cond, Literal(true), IsNull(RaiseError(Literal("boom"))))
+
+  test("SPARK-62054: keep the conditions that may not move or are over one 
item in the top join") {
+    // The project, which prunes t2.k-1-5, keeps ReorderJoin from flattening 
the joins.
+    val overT1 = raiseUnless(nameToAttr("t1.k-1-2") > 0)
+    val overT1T3 = raiseUnless(nameToAttr("t1.v-1-10") + 
nameToAttr("t3.v-1-100") > 0)
+    val failable = nameToAttr("t1.v-1-10") / nameToAttr("t3.v-1-100") > 0
+    val originalPlan =
+      t1.join(t2, Inner, Some(nameToAttr("t1.k-1-2") === 
nameToAttr("t2.k-1-5")))
+        .select(nameToAttr("t1.k-1-2"), nameToAttr("t1.v-1-10"))
+        .join(t3, Inner, Some(nameToAttr("t1.v-1-10") === 
nameToAttr("t3.v-1-100") &&
+          overT1 && overT1T3 && failable))
+
+    // No join below the top one takes overT1, which is over t1 only, nor 
overT1T3 and the
+    // division, which may not move: overT1T3 is throwable, and the division 
can fail after it.
+    // They would otherwise be evaluated on rows that the join with t2, or 
overT1T3, removes.
+    val bestPlan =
+      t1.join(t3, Inner, Some(nameToAttr("t1.v-1-10") === 
nameToAttr("t3.v-1-100")))
+        .join(t2, Inner, Some(nameToAttr("t1.k-1-2") === 
nameToAttr("t2.k-1-5") &&
+          overT1 && overT1T3 && failable))
+        .select(nameToAttr("t1.k-1-2"), nameToAttr("t1.v-1-10"), 
nameToAttr("t3.v-1-100"))
+
+    comparePlans(Optimize.execute(originalPlan.analyze), bestPlan.analyze)

Review Comment:
   **Nit (P3):** comparePlans normalizes each join condition by sorting its 
conjuncts by hashCode (NormalizePlan.scala:201-215), so this assertion passes 
whatever order the reorder appends the remaining conditions in, for example 
with the division ahead of overT1T3, which would then run first and could 
change which error a query raises, or whether it raises one. That order is what 
the fix relies on (CostBasedJoinReorder.scala:194-200); the SPARK-61930 tests 
compare it separately with topFilterConjuncts 
(JoinOptimizationSuite.scala:130-133).
   
   **Verification:**
   - **Regression:** Placing the conditions no join took in any order other 
than their written order, after the top join's own conditions, fails the join 
reorder plan test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -288,7 +315,7 @@ object JoinReorderDP extends PredicateHelper with Logging {
 
     val onePlan = oneJoinPlan.plan
     val otherPlan = otherJoinPlan.plan
-    val joinConds = conditions
+    val joinConds = movableConds

Review Comment:
   **Blocking (P1):** Because only the movable conditions join plans here, a 
throwable condition written in a lower join's ON clause never goes into that 
join, even when the search builds a join over exactly its inputs; search 
appends it to the top join in one AND with the conditions kept in the upper 
joins. On the base branch it went into its written join whenever the search 
joined those inputs first, so a NULL from it dropped the row before any upper 
condition ran. AND evaluates its right side after a NULL left side, so that 
boundary is now lost.
   
   Reading the code, with CBO join reorder on and ANSI mode on, this query 
raises DIVIDE_BY_ZERO on a t1 row with f >= 0 that matches, on k, a t2 row 
whose g is NULL and, on v, a t3 row whose w equals k, while the written query, 
and the base branch when the search joins t1 and t2 first, return rows:
   
   ```sql
   SELECT x.k FROM (SELECT t1.k, t1.v FROM t1 JOIN t2 ON t1.k = t2.k AND
     CASE WHEN t1.f < 0 THEN raise_error('neg') ELSE t1.f > t2.g END) x
   JOIN t3 ON x.v = t3.v AND 10 / (x.k - t3.w) > 0
   ```
   
   With the other order, (t1 JOIN t3) JOIN t2, it raises too. Moving the 
appended conditions into a Filter does not help, since a Filter also evaluates 
the rest of its AND after a NULL condition. The NULL has to survive the earlier 
rules: a CASE WHEN without ELSE does not show this, because 
ReplaceNullWithFalseInPredicate gives it ELSE false in the join condition 
before the reorder runs.
   
   **Recommended change:** Make extractInnerJoins return, with each conjunct, 
the join it is written in, and when search combines the conjuncts that no join 
took, group them by that join and wrap the AND of each group whose join lies 
below the written join of a later conjunct in the combination as 
coalesce(group, false), so that a NULL from the group drops the row before the 
conditions of the enclosing joins run, as its written join did, while the 
conjuncts of one group keep that join's AND semantics. Add join tests with CBO 
join reorder on in which a condition that may not move, in a lower join's ON 
clause, is NULL on a row on which such a condition of an upper join would fail. 
The NULL has to survive the operator optimizations, as one from a comparison 
over a nullable column in a branch of a throwable CASE WHEN does, since 
ReplaceNullWithFalseInPredicate already gives a CASE WHEN without ELSE an ELSE 
false in a join condition.
   
   **Why this works:** coalesce(g, false), where g is the AND of the conjuncts 
written in one lower join, is FALSE where g is NULL, so the combined AND stops 
there, interpreted and in generated code alike, which reproduces the row drop 
of the written lower join. Where g is TRUE or FALSE, or raises, it behaves as 
g, and the AND inside it still evaluates a later conjunct of the same join 
after a NULL one, as that join's own condition does. It keeps the parts of g 
that can throw or fail, so splitMovable and PushPredicateThroughJoin still keep 
it in place, and NullPropagation keeps a coalesce whose first child can be NULL 
and whose last one is the FALSE literal.
   
   **Compatibility:** Conditions written in the same join keep that join's AND 
semantics, including raising the error of a later condition after a NULL one.
   
   **Risks:** Plans of groups with a condition that may not move in a lower 
join change: the conditions of that join appear wrapped in coalesce(..., 
false), at the cost of one more check per row. A later optimizer rule that 
rewrote coalesce(c, false) to c in a predicate, which no rule that runs after 
the Join Reorder batch does today, would lose the NULL boundary without an 
error; the regression test guards against it.
   
   **Constraints:** The conditions written in the same join are wrapped 
together, as one AND, and not one by one, so that after a NULL among them a 
later one still raises its error, as in that join's own AND. The wrapped 
conditions must still be evaluated first, so that their own errors are raised 
as before.
   
   **Exclusions:**
   - Keeping a condition that may not move in a lower join at the level of its 
written join, which would also keep that join's output filtered; the 
performance cost of evaluating it above the reordered joins follows from the 
placement the PR's description states, on a path that is off by default.
   
   **Verification:**
   - **Regression:** With ANSI mode and CBO join reorder on, a query whose 
lower join's ON clause has a throwable CASE WHEN that is NULL on a row through 
a nullable column in its ELSE, and whose upper join's ON clause has a division 
whose divisor is zero on that row, returns the written query's rows, with the 
statistics making the search join the lower join's inputs first and with the 
other order.
   - **Compatibility:** A query whose lower join's ON clause has two conditions 
that may not move, the first NULL and the second failing on the same row, which 
matches the other joins, raises the second one's error as the written query 
does, also when an upper join's ON clause has a condition that may not move.
   - **Inspection:** After the whole optimizer runs, the plan of the regression 
query still evaluates the lower join's conditions through the NULL-to-FALSE 
wrapping.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -166,30 +166,53 @@ object JoinReorderDP extends PredicateHelper with Logging 
{
     // Build filters from the join graph to be used by the search algorithm.
     val filters = JoinReorderDPFilters.buildJoinGraphInfo(conf, items, 
conditions, itemIndex)
 
+    // Only the conditions that may be evaluated ahead of the others (see 
`splitMovable`) are used
+    // to join two plans. The others, e.g. a throwable condition and a 
condition that can fail
+    // after it, are left to the top join (see below), so that they are not 
evaluated on rows that
+    // a condition before them would remove.
+    val movableConds = ExpressionSet(splitMovable(conditions.toSeq, items)._1)
+
     // Build plans for next levels until the last level has only one plan. 
This plan contains
     // all items that can be joined, so there's no need to continue.
     val topOutputSet = AttributeSet(output)
     while (foundPlans.size < items.length) {
       // Build plans for the next level.
-      foundPlans += searchLevel(foundPlans.toSeq, conf, conditions, 
topOutputSet, filters)
+      foundPlans +=
+        searchLevel(foundPlans.toSeq, conf, conditions, movableConds, 
topOutputSet, filters)
     }
 
     val durationInMs = (System.nanoTime() - startTime) / (1000 * 1000)
     logDebug(s"Join reordering finished. Duration: $durationInMs ms, number of 
items: " +
       s"${items.length}, number of plans in memo: 
${foundPlans.map(_.size).sum}")
 
-    // The last level must have one and only one plan, because all items are 
joinable.
-    assert(foundPlans.size == items.length && foundPlans.last.size == 1)
-    foundPlans.last.head._2.plan match {
+    // The last level has at most one plan, for all items. It has none if the 
join conditions
+    // used by `buildJoin` do not connect all items, e.g. when the only 
condition of a join may
+    // not move or is over one side of it. Keep the original order then.
+    assert(foundPlans.size == items.length && foundPlans.last.size <= 1)
+    if (foundPlans.last.isEmpty) return None
+
+    // Put the conditions that no join took (the ones that may not move, and 
the ones over one
+    // item or no item) into the top join, after its own conditions, in their 
written order.
+    val finalJoinPlan = foundPlans.last.head._2
+    val remainingConds = (conditions -- finalJoinPlan.joinConds).toSeq
+    def addRemainingConds(plan: LogicalPlan): LogicalPlan = plan match {
+      case p @ Project(_, j: Join) => p.copy(child = addRemainingConds(j))
+      case j: Join => j.copy(condition = (j.condition.toSeq ++ 
remainingConds).reduceOption(And))

Review Comment:
   **Blocking (P1):** Appending the remaining conditions to the top join's own 
condition here lets physical planning evaluate them out of their written order. 
ExtractEquiJoinKeys turns any equality whose two sides fall on the two children 
of this join into a join key, which a hash or sort-merge join computes on every 
input row before the rest of the condition, and the condition is a single AND, 
which goes on past a NULL from a movable condition that the search moved up to 
this join.
   
   Reading the code, with spark.sql.cbo.enabled and 
spark.sql.cbo.joinReorder.enabled on and ANSI mode on (the default), this query 
fails with CAST_INVALID_INPUT when the search joins t1 and t2 first, on a t1 
row with s = 'abc' that matches t2 on k and for which the CASE WHEN is false; 
the written query and the base branch, with the same join order, return rows:
   
   ```sql
   SELECT x.v FROM (SELECT t1.v, t1.s FROM t1 JOIN t2 ON t1.k = t2.k AND
     CASE WHEN t1.x < t2.y THEN true WHEN t1.x >= t2.y THEN false ELSE 
raise_error('n') END) x
   JOIN t3 ON x.v = t3.v AND CAST(x.s AS INT) = t3.z
   ```
   
   The CASE WHEN no longer filters the t1-t2 join, and CAST(t1.s AS INT) = t3.z 
becomes a key of the top join, so the cast runs on the row the CASE WHEN would 
have removed. Likewise, when a movable OR such as t1.a = t2.a OR t1.b = t2.b, 
which the cost model prices as a cartesian product, is joined last, a t1 row 
whose a and b are NULL reaches a raise_error written after it that the written 
query never evaluates on that row. An equality such as x.a / x.b = x.c written 
after a throwable condition becomes a key the same way; there the base branch 
failed too.
   
   **Recommended change:** In JoinReorderDP.search, put the conjuncts that no 
join took into a Filter directly above the reordered top join, in their written 
order, instead of appending them to the top join's condition at 
CostBasedJoinReorder.scala:200, and keep the final projection above that Filter 
so the group still outputs its columns in their original order; make 
CostBasedJoinReorder.reorder mark the joins under the Filter as ordered, as 
replaceWithOrderedJoin already does under a Project. Update the expected plans 
of the new join reorder plan tests to the Filter, and add join tests that run, 
with CBO join reorder on, an equality that may not move whose operands the 
reorder puts on the two children of the top join, and a movable OR condition 
that the search joins last.
   
   **Why this works:** A Filter's conjuncts are never join keys, so 
ExtractEquiJoinKeys cannot compute an equality that may not move before the 
throwable condition written before it, and the reordered top join applies all 
of its own conditions, including a movable one that is NULL, before the Filter 
sees the row. PushPredicateThroughJoin and CombineFilters leave a Filter's 
conjuncts in place from its first throwable one on, so the later optimizer 
batches keep this Filter as they keep the one ReorderJoin builds.
   
   **Compatibility:** Groups whose conditions are all movable, and groups whose 
movable conditions do not connect every input, which keep the written plan, are 
planned as before.
   
   **Risks:** An equality that may not move, which this PR's top join used as a 
join key, is evaluated in the Filter instead, so such a join matches on fewer 
keys and can do more work before the Filter removes rows; the base branch 
joined by that equality, which the PR already stopped doing. The repair adds no 
flag of its own; setting spark.sql.cbo.joinReorder.enabled to false still gives 
the written plan.
   
   **Constraints:** The Filter must hold the remaining conditions in their 
written order and see each row only after every condition of the reordered top 
join. The final projection above the Filter must still output the group's 
original columns in their original order.
   
   **Exclusions:**
   - Keeping a condition written in a lower join's ON clause at the level of 
that join, which the separate repair for conditions hoisted from lower joins 
addresses.
   
   **Verification:**
   - **Regression:** With ANSI mode and CBO join reorder on, a query whose CAST 
equality, which may not move since it is written after a throwable condition, 
falls on the two children of the reordered top join returns the written query's 
rows on data where the throwable condition removes a row whose cast would fail.
   - **Regression:** With CBO join reorder on, a query whose movable OR join 
condition is joined last returns the written query's rows when a row with NULL 
join columns would make the throwable condition written after it raise.
   - **Behavior:** The reordered plan of a group with conditions that may not 
move has them in a Filter above the top join in their written order, every join 
below is marked as ordered, and the group outputs its original columns in their 
original order.
   - **Compatibility:** Reordered groups whose conditions are all movable, and 
groups whose movable conditions do not connect every input, keep their current 
plans.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -166,30 +166,53 @@ object JoinReorderDP extends PredicateHelper with Logging 
{
     // Build filters from the join graph to be used by the search algorithm.
     val filters = JoinReorderDPFilters.buildJoinGraphInfo(conf, items, 
conditions, itemIndex)
 
+    // Only the conditions that may be evaluated ahead of the others (see 
`splitMovable`) are used
+    // to join two plans. The others, e.g. a throwable condition and a 
condition that can fail
+    // after it, are left to the top join (see below), so that they are not 
evaluated on rows that
+    // a condition before them would remove.
+    val movableConds = ExpressionSet(splitMovable(conditions.toSeq, items)._1)
+
     // Build plans for next levels until the last level has only one plan. 
This plan contains
     // all items that can be joined, so there's no need to continue.
     val topOutputSet = AttributeSet(output)
     while (foundPlans.size < items.length) {
       // Build plans for the next level.
-      foundPlans += searchLevel(foundPlans.toSeq, conf, conditions, 
topOutputSet, filters)
+      foundPlans +=
+        searchLevel(foundPlans.toSeq, conf, conditions, movableConds, 
topOutputSet, filters)
     }
 
     val durationInMs = (System.nanoTime() - startTime) / (1000 * 1000)
     logDebug(s"Join reordering finished. Duration: $durationInMs ms, number of 
items: " +
       s"${items.length}, number of plans in memo: 
${foundPlans.map(_.size).sum}")
 
-    // The last level must have one and only one plan, because all items are 
joinable.
-    assert(foundPlans.size == items.length && foundPlans.last.size == 1)
-    foundPlans.last.head._2.plan match {
+    // The last level has at most one plan, for all items. It has none if the 
join conditions
+    // used by `buildJoin` do not connect all items, e.g. when the only 
condition of a join may
+    // not move or is over one side of it. Keep the original order then.
+    assert(foundPlans.size == items.length && foundPlans.last.size <= 1)
+    if (foundPlans.last.isEmpty) return None
+
+    // Put the conditions that no join took (the ones that may not move, and 
the ones over one
+    // item or no item) into the top join, after its own conditions, in their 
written order.
+    val finalJoinPlan = foundPlans.last.head._2
+    val remainingConds = (conditions -- finalJoinPlan.joinConds).toSeq
+    def addRemainingConds(plan: LogicalPlan): LogicalPlan = plan match {
+      case p @ Project(_, j: Join) => p.copy(child = addRemainingConds(j))
+      case j: Join => j.copy(condition = (j.condition.toSeq ++ 
remainingConds).reduceOption(And))
+    }
+    val topPlan =
+      if (remainingConds.isEmpty) finalJoinPlan.plan else 
addRemainingConds(finalJoinPlan.plan)
+    val result = topPlan match {
       case p @ Project(projectList, j: Join) if projectList != output =>
-        assert(topOutputSet == p.outputSet)
+        // The project also keeps the references of the remaining conditions.
+        assert(topOutputSet.subsetOf(p.outputSet))

Review Comment:
   **Nit (P3):** No new test reaches this check with a projection wider than 
the output: in the new JoinReorderSuite and DataFrameJoinSuite tests, the 
conditions appended to the top join read only columns the query outputs, so the 
top Project already equals the output. Reverting this to the base branch's 
assert(topOutputSet == p.outputSet) leaves every test passing, while Issue 3, 
whose CASE WHEN reads sv.id although the query outputs only w.value, fails with 
INTERNAL_ERROR again.
   
   **Verification:**
   - **Regression:** With CBO join reorder on, Issue 3's query returns [20], 
and its reordered plan outputs only w.value while the condition over sv.id is 
still applied.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -166,30 +166,53 @@ object JoinReorderDP extends PredicateHelper with Logging 
{
     // Build filters from the join graph to be used by the search algorithm.
     val filters = JoinReorderDPFilters.buildJoinGraphInfo(conf, items, 
conditions, itemIndex)
 
+    // Only the conditions that may be evaluated ahead of the others (see 
`splitMovable`) are used
+    // to join two plans. The others, e.g. a throwable condition and a 
condition that can fail
+    // after it, are left to the top join (see below), so that they are not 
evaluated on rows that
+    // a condition before them would remove.
+    val movableConds = ExpressionSet(splitMovable(conditions.toSeq, items)._1)

Review Comment:
   **Nit (P3):** The inputs passed here matter only when one of them has a 
column that can fail, such as q of an input Project(k, a / b AS q) in ANSI 
mode: then a condition over q written after a throwable one must stay out of 
the joins. Every input in the new tests is a StatsTestPlan leaf or an analyzed 
table, which has no such column, so passing Nil instead of items leaves every 
test passing. The SPARK-61930 test with such a column, q in 
JoinOptimizationSuite, runs only ReorderJoin.
   
   **Verification:**
   - **Regression:** With ANSI mode and CBO join reorder on, a condition over 
an input's computed column that can fail, written after a throwable condition, 
does not join two plans and is evaluated only after that throwable condition.



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