peter-toth commented on code in PR #60711:
URL: https://github.com/apache/spark/pull/60711#discussion_r4647144781
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -260,16 +260,36 @@ object ExtractFiltersAndInnerJoins extends
PredicateHelper {
def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
: (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
case Join(left, right, joinType: InnerLike, cond, hint) if hint ==
JoinHint.NONE =>
- val (plans, conditions) = flattenJoin(left, joinType)
+ val (plans, conditions) = flattenBelow(left, joinType)
(plans ++ Seq((right, joinType)), conditions ++
cond.toSeq.flatMap(splitConjunctivePredicates))
case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if
hint == JoinHint.NONE =>
- val (plans, conditions) = flattenJoin(j)
+ val (plans, conditions) = flattenBelow(j, Inner)
(plans, conditions ++ splitConjunctivePredicates(filterCondition))
case _ => (Seq((plan, parentJoinType)), Seq.empty)
}
+ /**
+ * [[flattenJoin]] below the top join or filter, where a join or filter with
a condition that
+ * may not move (see `PredicateHelper.splitMovable`) is one of the plans,
with its condition. It
+ * removes a row on which its condition is NULL, so no condition above it is
evaluated on the row.
+ */
+ private def flattenBelow(plan: LogicalPlan, parentJoinType: InnerLike)
+ : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+ val condition = plan match {
+ case j: Join => j.condition
+ case f: Filter => Some(f.condition)
+ case _ => None
+ }
+ if (condition.exists(c =>
+ splitMovable(splitConjunctivePredicates(c),
plan.children)._2.nonEmpty)) {
+ (Seq((plan, parentJoinType)), Seq.empty)
Review Comment:
**Finding 1.** The doc above ("no condition above it is evaluated on the
row") holds while this plan is the first input, since `createOrderedJoin`
builds the left-deep tree from `input.head`. The star-schema path in
`ReorderJoin` can move it:
- Here the kept plan gets `parentJoinType`, so under an explicit `CROSS
JOIN` it is `(plan, Cross)`.
- `StarSchemaDetection.reorderStarJoins` only looks at the `Inner` plans
(`StarSchemaDetection.scala:326`). So the kept join no longer makes
`findStarJoins` bail out on an input that is not a base table, and a star plan
comes back.
- `starJoinPlan ++ rest` then puts the kept join after the fact and
dimension tables. Every condition written above it is movable now, so a
division in a dimension's `ON` clause runs in the fact-dimension join, on rows
that the kept join would remove.
With ANSI on, `spark.sql.cbo.starSchemaDetection=true`,
`spark.sql.cbo.enabled=false`, `spark.sql.cbo.planStats.enabled=true`, and
`ANALYZE TABLE ... COMPUTE STATISTICS FOR ALL COLUMNS` on every table:
```sql
-- sa(k, f): (1, 5), (2, 5) sb(k, g): (1, NULL), (2, 1)
sd1(c): (1)
-- sd2(id, x): (1, 1), (2, 1), (3, 0) sd3(id, v): (1, 1), (2, 2), (3,
3)
-- sf(id, a, d2, d3, v): (1, 1, 1, 1, 7), (2, 2, 2, 2, 7), (3, 99, 1, 3, 3),
(4, 1, 2, 1, 8),
-- (5, 2, 1, 2, 9), (6, 50, 1, 1, 4), (7, 51, 2, 2, 5), (8, 52, 1, 1, 6),
(9, 53, 2, 2, 7),
-- (10, 54, 1, 1, 8)
SELECT sf.id FROM sa JOIN sb ON sa.k = sb.k AND
CASE WHEN sa.f < 0 THEN raise_error('neg') ELSE sa.f > sb.g END
CROSS JOIN sd1
JOIN sf ON sf.a = sa.k
JOIN sd2 ON sf.d2 = sd2.id
JOIN sd3 ON sf.d3 = sd3.id AND 10 / (sf.v - sd3.v) > 0
WHERE sd2.x > 0
```
- Master returns `[2], [5]`. This head fails with `DIVIDE_BY_ZERO` on the
`sf` row with `a = 99`, which matches no `sa` row.
- With `JOIN sd1` instead of `CROSS JOIN sd1`, both return `[2], [5]`. The
kept join is then an `Inner` input, and `findStarJoins` bails out.
Giving the kept plan the `Inner` type does the same for the `CROSS JOIN`
form:
```suggestion
(Seq((plan, Inner)), Seq.empty)
```
With it, the query returns `[2], [5]`, the new `JoinSuite` test passes, and
`JoinOptimizationSuite`, `StarJoinReorderSuite`,
`StarJoinCostBasedReorderSuite` and `JoinReorderSuite` pass.
`createOrderedJoin` does not read the join type of the first input when there
are more than two, so the joins it builds keep their types. A
`JoinOptimizationSuite` case for this shape would pin it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2625,9 +2625,13 @@ object CombineFilters extends Rule[LogicalPlan] with
PredicateHelper {
val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = {
// Combines the conjuncts of the outer condition that may be evaluated
ahead of the others
// (see `splitMovable`) into the inner filter, and keeps the rest in a
filter above it. The
- // inner condition must be deterministic.
+ // inner condition must be deterministic. When it is throwable, e.g. one
that `ReorderJoin`
+ // keeps in a filter in place of the top join, only the outer conjuncts
that can not fail are
+ // combined: the inner filter drops a row on which its condition is NULL,
but `NULL AND x`
+ // evaluates `x`.
case Filter(fc, nf @ Filter(nc, grandChild)) if nc.deterministic =>
- val (movable, rest) = splitMovable(splitConjunctivePredicates(fc),
Seq(grandChild))
+ val (movable, rest) = splitMovable(
+ splitConjunctivePredicates(fc), Seq(grandChild), afterBarrier =
nc.throwable)
Review Comment:
**Finding 3.** This keeps the two filters apart in the logical plan, but
physical planning merges them again over a file scan. `ScanOperation` collects
every adjacent deterministic `Filter` (`patterns.scala:155`), and
`FileSourceStrategy` evaluates their conjuncts in one `FilterExec`, so `NULL
AND x` still evaluates `x`. With the tables of the new `JoinSuite` test, in
ANSI mode:
```sql
SELECT * FROM (SELECT k FROM tb2
WHERE CASE WHEN k < 0 THEN raise_error('neg') ELSE k > g END) s
WHERE 10 / (s.k - 1) > 0
```
It fails with `DIVIDE_BY_ZERO` on the row whose `g` is NULL, here and on
master. The filter that `ReorderJoin` keeps sits over a join, so the shapes of
this PR are fine. Could you file a ticket for the scan path?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -97,6 +97,10 @@ object ReorderJoin extends Rule[LogicalPlan] with
PredicateHelper {
def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
_.containsPattern(INNER_LIKE_JOIN), ruleId) {
+ // `ExtractFiltersAndInnerJoins` does not flatten a lower join or filter
with a condition that
+ // may not move (see `splitMovable`), so such conditions are only in the
top join or filter.
+ // They stay in a filter above all the joins, which takes the place of the
top join or filter.
+ // `CombineFilters` does not combine a condition that can fail from a
filter above into it.
case p @ ExtractFiltersAndInnerJoins(input, conditions)
if input.size > 2 && conditions.nonEmpty =>
Review Comment:
**Finding 2.** With a lower join kept as one plan, a chain of three joins
has only two inputs left. So this case no longer matches, and nothing rebuilds
the upper join's condition in written order. `PushPredicateThroughJoin` then
merges the `WHERE` conjunct into the join condition ahead of the `ON`
conjuncts, so a division in the `WHERE` clause runs on a row that a division in
the `ON` clause rejects:
```sql
-- qa4(k, z): (1, 1) qa3(w): (2) qa1(k): (1)
SELECT * FROM qa4 t4 JOIN qa3 t3
ON CASE WHEN t3.w < 0 THEN raise_error('neg3') ELSE t3.w > t4.z END
AND 10 / (t3.w - t4.z) > 0
JOIN qa1 t1 ON 10 / (t1.k - t3.w) > 0 AND t1.k = t4.k
WHERE 10 / (t1.k - t4.z) > 0
```
In ANSI mode, with AQE on and off:
- Master returns no rows.
- This head fails with `DIVIDE_BY_ZERO`. The top join's condition is `(10 /
(k - z) > 0) AND (10 / (k - w) > 0) AND (k = k)`.
Master is right here only because its `ReorderJoin` keeps everything after
the `CASE WHEN` in one filter, in written order:
- The same kind of `ON` and `WHERE` divisions over a join of two, `qa4 t4
JOIN qa1 t1 ON 10 / (t1.k - t4.k - 1) > 0 AND t1.k = t4.k WHERE 10 / (t1.k -
t4.z) > 0`, fail on master too.
- With a plain `t3.w > t4.z` instead of the `CASE WHEN`, master and this
head both return no rows.
So this looks like the `PushPredicateThroughJoin` ordering you plan to
handle separately
([r4631291389](https://github.com/apache/spark/pull/60711#discussion_r4631291389)),
which this PR now reaches with one more shape. Could the ticket for it include
this query?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -260,16 +260,36 @@ object ExtractFiltersAndInnerJoins extends
PredicateHelper {
def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
: (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
case Join(left, right, joinType: InnerLike, cond, hint) if hint ==
JoinHint.NONE =>
- val (plans, conditions) = flattenJoin(left, joinType)
+ val (plans, conditions) = flattenBelow(left, joinType)
(plans ++ Seq((right, joinType)), conditions ++
cond.toSeq.flatMap(splitConjunctivePredicates))
case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if
hint == JoinHint.NONE =>
- val (plans, conditions) = flattenJoin(j)
+ val (plans, conditions) = flattenBelow(j, Inner)
(plans, conditions ++ splitConjunctivePredicates(filterCondition))
case _ => (Seq((plan, parentJoinType)), Seq.empty)
}
+ /**
+ * [[flattenJoin]] below the top join or filter, where a join or filter with
a condition that
Review Comment:
**Finding 5.** The docs above still describe the old contract:
- The `flattenJoin` scaladoc (line 255) says it flattens all inner joins
next to each other and returns "the entire list of join conditions".
- The object doc (lines 238-250) shows every lower filter and join being
collected.
A sentence in each that points at this exception would keep them accurate.
--
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]