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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -62,40 +62,68 @@ object CostBasedJoinReorder extends Rule[LogicalPlan] with 
PredicateHelper {
       // We also need to check if costs of all items can be evaluated.
       if (items.size > 2 && items.size <= conf.joinReorderDPThreshold && 
conditions.nonEmpty &&
           items.forall(_.stats.rowCount.isDefined)) {
-        JoinReorderDP.search(conf, items, conditions, output)
+        JoinReorderDP.search(conf, items, conditions, output).getOrElse(plan)

Review Comment:
   Thank you. Confirmed: on this path, the joins of both sides of the top join 
kept their written order. Now, when `JoinReorderDP.search` returns `None`, 
`CostBasedJoinReorder.reorder` sets only the top join ordered 
(`setTopJoinOrdered`), so the joins of each of its sides are reordered by 
themselves later. The fallback test now has a side with three inputs in a 
costly written order, on the left and on the right of the top join, and checks 
that the side is reordered while the top join keeps its condition.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -62,40 +62,68 @@ object CostBasedJoinReorder extends Rule[LogicalPlan] with 
PredicateHelper {
       // We also need to check if costs of all items can be evaluated.
       if (items.size > 2 && items.size <= conf.joinReorderDPThreshold && 
conditions.nonEmpty &&
           items.forall(_.stats.rowCount.isDefined)) {
-        JoinReorderDP.search(conf, items, conditions, output)
+        JoinReorderDP.search(conf, items, conditions, output).getOrElse(plan)
       } else {
         plan
       }
-    // Set consecutive join nodes ordered.
-    replaceWithOrderedJoin(result)
+    // Set consecutive join nodes ordered, also below the filter that 
`JoinReorderDP.search` may
+    // put above them.
+    result match {
+      case p @ Project(_, f @ Filter(_, j: Join)) =>
+        p.copy(child = f.copy(child = replaceWithOrderedJoin(j)))
+      case f @ Filter(_, j: Join) =>
+        f.copy(child = replaceWithOrderedJoin(j))
+      case _ =>
+        replaceWithOrderedJoin(result)
+    }
   }
 
   /**
    * Extracts items of consecutive inner joins and join conditions.
    * This method works for bushy trees and left/right deep trees.
+   * A join below the top one whose condition has a conjunct that may not move 
(see
+   * `splitMovable`) is an item, with its condition. It removes a row on which 
its condition is
+   * NULL, so no condition above it is evaluated on the row, but `NULL AND x` 
evaluates `x`.
    */
-  private def extractInnerJoins(plan: LogicalPlan): (Seq[LogicalPlan], 
ExpressionSet) = {
+  private def extractInnerJoins(
+      plan: LogicalPlan,
+      isTop: Boolean = true): (Seq[LogicalPlan], ExpressionSet) = {
     plan match {
+      case j: Join if !isTop && hasImmovableCondition(j) =>
+        (Seq(plan), ExpressionSet())
       case Join(left, right, _: InnerLike, Some(cond), JoinHint.NONE) =>
-        val (leftPlans, leftConditions) = extractInnerJoins(left)
-        val (rightPlans, rightConditions) = extractInnerJoins(right)
+        val (leftPlans, leftConditions) = extractInnerJoins(left, isTop = 
false)
+        val (rightPlans, rightConditions) = extractInnerJoins(right, isTop = 
false)

Review Comment:
   Thank you. Added a plan test with the lower join, under a project of 
columns, on the right side of a join. It is kept as one item, and its own joins 
are reordered by themselves. The test fails when the right-side recursion of 
`extractInnerJoins` or `replaceWithOrderedJoin`, or the projection case of 
`replaceWithOrderedJoin`, falls back to its default `isTop`. Issue 6 with its 
subquery on the right returns [2].
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -166,21 +194,46 @@ 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`) join two
+    // plans. The others, e.g. a throwable condition and a condition that can 
fail after it, go
+    // into a filter above the joins (see below), so the joins keep the 
columns that they read.
+    val (movableConds, otherConds) = splitMovable(conditions.toSeq, items)
+    val joinConds = ExpressionSet(movableConds)
+
     // 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)
+    val topOutputSet = AttributeSet(output ++ otherConds.flatMap(_.references))
     while (foundPlans.size < items.length) {
       // Build plans for the next level.
-      foundPlans += searchLevel(foundPlans.toSeq, conf, conditions, 
topOutputSet, filters)
+      foundPlans += searchLevel(foundPlans.toSeq, conf, joinConds, 
topOutputSet, filters)

Review Comment:
   Thank you. Fixed as suggested.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/CostBasedJoinReorder.scala:
##########
@@ -166,21 +194,46 @@ 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`) join two
+    // plans. The others, e.g. a throwable condition and a condition that can 
fail after it, go
+    // into a filter above the joins (see below), so the joins keep the 
columns that they read.
+    val (movableConds, otherConds) = splitMovable(conditions.toSeq, items)
+    val joinConds = ExpressionSet(movableConds)
+
     // 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)
+    val topOutputSet = AttributeSet(output ++ otherConds.flatMap(_.references))
     while (foundPlans.size < items.length) {
       // Build plans for the next level.
-      foundPlans += searchLevel(foundPlans.toSeq, conf, conditions, 
topOutputSet, filters)
+      foundPlans += searchLevel(foundPlans.toSeq, conf, joinConds, 
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 
conditions that may
+    // join two plans 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)

Review Comment:
   Thank you. Fixed as suggested. The comment above the check of the last level 
also says now that only the top join is kept in place when it has no plan.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/joinReorder/JoinReorderSuite.scala:
##########
@@ -384,4 +384,91 @@ 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"))))
+
+  // A division in ANSI mode, where it can fail.
+  private def divide(l: Expression, r: Expression): Expression =
+    Divide(l, r, NumericEvalContext(EvalMode.ANSI))
+
+  // The conjuncts of the top filter in their written order, which 
`comparePlans` does not check.
+  private def topFilterConjuncts(plan: LogicalPlan): Seq[Expression] =
+    normalizeExprIds(plan).collectFirst { case Filter(condition, _) => 
condition }
+      .map(splitConjunctivePredicates(_).map(_.canonicalized)).getOrElse(Nil)
+
+  test("SPARK-62054: put the conditions that no join may take in a filter 
above the joins") {
+    // The project, which prunes t2.k-1-5, keeps ReorderJoin from flattening 
the joins. No join
+    // takes overT1, which is over t1 only, nor overT1T3 and the conditions 
after it, which may
+    // not move: overT1T3 is throwable, the division can fail, and so can `q`, 
which overQ reads.
+    // They would otherwise be evaluated on rows that the join with t2, or 
overT1T3, removes. The
+    // filter is above all the joins, so none of them is a join key, and it 
reads columns that the
+    // query does not output.

Review Comment:
   Thank you. Fixed as suggested.
   



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