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


##########
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:
   Thank you. You are right: a conjunct appended to the condition of the top 
join could be a join key, or be evaluated after a NULL from a movable condition 
that the reorder joined last. Both reproduced with the cost-based join reorder 
(CAST_INVALID_INPUT and USER_RAISED_EXCEPTION). As you recommended, 
`JoinReorderDP.search` now puts the conjuncts that no join took into a filter 
above the reordered joins, in their written order, with the project that keeps 
the output above it, and `CostBasedJoinReorder.reorder` sets the joins below 
the filter ordered. The plan test checks the filter and the order of its 
conjuncts, and the new `DataFrameJoinSuite` test runs the movable `OR` case. 
The CAST equality case is now planned as written, because the lower join with 
the `CASE WHEN` is kept as one item (see the next thread).
   



##########
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:
   Thank you. Confirmed: with the cost-based join reorder, the query fails with 
DIVIDE_BY_ZERO, also on `master`. Instead of wrapping the conjuncts of each 
lower join in `coalesce(group, false)`, this now follows SPARK-62069 (#60711), 
which fixed the same problem in `ReorderJoin` and moved away from the 
`coalesce` approach during its review. `extractInnerJoins` keeps a join below 
the top one whose condition has a conjunct that may not move (see 
`splitMovable`) as one item, with its condition, so the join still removes a 
row on which its condition is NULL before any condition above it is evaluated. 
The joins in that join are reordered by themselves. The new plan test and the 
new `DataFrameJoinSuite` test cover this.
   



##########
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:
   Thank you. Fixed. The divisions in the plan test are built with 
`NumericEvalContext(EvalMode.ANSI)`, as in the SPARK-61930 test, and the new 
end-to-end test sets `spark.sql.ansi.enabled=true`. The new tests pass with 
`SPARK_ANSI_SQL_MODE=false`, and the end-to-end tests still fail there without 
this fix.
   



##########
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:
   Thank you. Fixed. The plan test also compares the conjuncts of the filter in 
their written order (`topFilterConjuncts`, as in `JoinOptimizationSuite`), so 
it fails when they are in another order.
   



##########
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:
   Thank you. The relaxed assertion is gone. The conjuncts that no join took 
are in a filter now, and the joins keep the columns that they read, so the 
check of the top project is the same as in `master`. The filter of the plan 
test reads columns that the query does not output, and the test fails when the 
joins do not keep them. Issue 3 returns [20].
   



##########
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:
   Thank you. Fixed. The plan test has an input with a column that can fail, 
`q`, computed by a division in ANSI mode, and a condition over it written after 
a throwable one. The test fails when no inputs are passed to `splitMovable`.
   



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