spark-test commented on code in PR #60699:
URL: https://github.com/apache/spark/pull/60699#discussion_r4651262387
##########
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:
**Non-blocking (P2):** When `search` returns None here, `.getOrElse(plan)`
hands the written plan to `replaceWithOrderedJoin(result)` at line 77, which
marks every flattened join of the group as ordered, the joins inside the top
join's two sides included (lines 121-126), so the rule's pass never reorders
those sides. Only the top join has to stay where it is written, because its
linking condition may not move; every condition inside each side may move, so
each side could be reordered by itself, as the rule already does for a lower
join kept as one item (lines 118-120).
Reading the code, with `spark.sql.cbo.enabled` and
`spark.sql.cbo.joinReorder.enabled` on, `SELECT x.k FROM (SELECT a.k, b.j, c.m
FROM a JOIN b ON a.k = b.k JOIN c ON b.j = c.j) x JOIN d ON CASE WHEN x.m > d.m
THEN true WHEN x.m = d.m THEN false ELSE raise_error('e') END` takes this path:
only `a.k = b.k` and `b.j = c.j` may join plans, no plan reaches `d`, and `a
JOIN b JOIN c` keeps its written order, while the base branch reordered all
four inputs. Without the subquery's pruning projection, ReorderJoin moves the
CASE into a filter and this rule still reorders `{a, b, c}`. Results stay
correct, but a written order that joins large inputs first keeps the
intermediate rows that a cost-based order of the side avoids. The new test
'keep the order if the join conditions do not connect all items' has a side of
two inputs, which the search cannot reorder anyway, so it passes either way.
**Verification:**
- **Regression:** With cost-based join reordering on, a query whose top join
links its two sides only by a throwable condition, and whose left side joins
three or more inputs in a costly written order, keeps the top join and its
condition in place and has the joins of that side reordered by cost, and so
does a second query with that side on the right of the top join.
- **Behavior:** Both queries return the rows of the written query and raise
no error that the written query does not raise.
##########
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:
**Nit (P3):** Only this explicit `isTop = false` keeps a right-side lower
join whose condition has a conjunct that may not move as one item, and only the
one at line 123, together with the `isTop` that the projection case at line 126
passes on, leaves such a join unmarked so that its own joins are reordered
later. Every new test puts such a join on the left, though: the lower join of
the plan test 'keep a lower join with a condition that may not move as one
item' is the left child of the join with t5, and Issue 6's subquery in
DataFrameJoinSuite is the left side of the join with t3. A right child reaches
this rule unchanged, because `ExtractFiltersAndInnerJoins` flattens only left
children.
Reading the code, if this line fell back to the default `isTop`, Issue 6's
query with its subquery joined on the right, `SELECT x.k FROM t3 JOIN (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 ON x.v = t3.v AND 10 / (x.k - t3.w)
> 0`, would have the CASE and the division in the filter above the joins, where
the NULL CASE still lets the division run, and would fail with DIVIDE_BY_ZERO
instead of returning [2], with no test failing. A regression at line 123 or 126
would only keep the kept join's own joins in their written order, which no test
notices either.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60699#discussion_r4624073321).
**Verification:**
- **Regression:** With cost-based join reordering and ANSI mode on, Issue
6's query with its subquery written as the right side of the join with t3
returns [2], and the test fails when the right-side recursion of
extractInnerJoins falls back to its default isTop.
- **Regression:** With cost-based join reordering on, when a lower join kept
as one item has three or more inputs of its own in a costly written order and
is written under a projection that keeps only columns as the right child of a
join, its own joins are still reordered by themselves, and the test fails when
either the right-side recursion of replaceWithOrderedJoin or its projection
case falls back to its default isTop.
##########
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:
**Nit (P3):** This call now passes only the conditions that may join two
plans, and the `topOutputSet` built at line 205 also holds the columns that the
conditions that may not move read, but `buildJoin`'s Scaladoc at lines 312-313
still says `@param conditions The overall set of join conditions.` and `@param
topOutput The output attributes of the final plan.` The conditions that may not
move are not in `buildJoin`'s `conditions`, so its `remainingConds` never
covers them, and their columns survive the pruning projects only through
`topOutput` (line 364); docs that call `topOutput` the final plan's output
invite trimming it back to the output, which would prune columns the filter
above the joins reads. For example: `@param conditions The conditions that may
join two plans.` and `@param topOutput The attributes needed above the joins:
the final output and the columns that the conditions that may not move read.`
**Verification:**
- **Inspection:** buildJoin's parameter docs match the values that search
passes through searchLevel: only the conditions that may join two plans, and
the output together with the columns that the conditions that may not move read.
##########
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:
**Nit (P3):** `overT1T3` is `raiseUnless(...)`, that is `If(cond,
Literal(true), IsNull(RaiseError(Literal("boom"))))`: `If` takes its else
branch on FALSE or NULL and `RaiseError` always throws, so `overT1T3` is TRUE
or raises, and it removes no row. What its place before `failable` and `overQ`
protects is which error a row raises: evaluated first, the division in
`failable` could raise DIVIDE_BY_ZERO on a row on which `overT1T3` raises
'boom'. A wording that matches the expressions:
```suggestion
// They would otherwise be evaluated on rows that the join with t2
removes, or on which
// overT1T3 raises its error. 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.
```
**Verification:**
- **Inspection:** The comment of the filter test describes overT1T3 as
raising its error, not as removing rows, and matches the conditions the test
builds.
##########
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:
**Nit (P3):** With this assertion relaxed to at most one plan and the return
for an empty last level at line 219, the comment above the level loop at lines
203-204 is stale: it still says the loop builds levels "until the last level
has only one plan. This plan contains all items that can be joined", while
lines 215-217 say that the last level may have none. For example, reword lines
203-204 to "Build plans for the next levels up to the last one, which has at
most one plan, for all items."
**Verification:**
- **Inspection:** The comments in JoinReorderDP.search agree that the last
level has at most one plan, and none when the conditions that may join two
plans do not connect all items.
--
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]