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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -95,18 +95,38 @@ object ReorderJoin extends Rule[LogicalPlan] with 
PredicateHelper {
     }
   }
 
+  /**
+   * Returns the condition of the filter above all the joins from the 
conditions kept there, each
+   * with the index of the join or filter it is written in. That join or 
filter removes a row on
+   * which its condition is NULL, so the conditions written above it are not 
evaluated on the row,
+   * but `NULL AND x` evaluates `x`. So the kept conditions of each join or 
filter but the last are
+   * wrapped as `coalesce(<their AND>, false)`, whose FALSE skips the 
conditions after them. The
+   * kept conditions of one join or filter stay in a plain AND, as they are 
written.
+   */
+  private def keptCondition(kept: Seq[(Expression, Int)]): Option[Expression] 
= {
+    val groups = kept.groupBy(_._2).toSeq.sortBy(_._1).map(_._2.map(_._1))
+    groups.lastOption.map { last =>
+      val lower = groups.init.map(g => Coalesce(Seq(g.reduceLeft(And), 
Literal.FalseLiteral)))

Review Comment:
   **Blocking (P1):** This wrapper puts a lower join's IN, NOT IN or correlated 
EXISTS predicate in the same conjunct as the guard it was kept behind. 
`RewritePredicateSubquery`, in the later `RewriteSubquery` batch, evaluates the 
conjuncts without such a predicate first, in a `Filter` below the joins it 
builds (`subquery.scala:147-217`), so the higher join's kept conditions now run 
before this guard, and `PushPredicateThroughJoin` then moves a division among 
them into a join condition.
   
   By the review's reading of the code, with ANSI on, tb1(k, v, f) = (1, 1, 5), 
(2, 2, 5), tb2(k, g) = (1, 10), (2, 1) and tb3(v, w) = (1, 1), (2, 0), this 
query returns 2 on the base branch and in 4.3.0, but with this change it fails 
with DIVIDE_BY_ZERO on the row with k = 1, which the CASE WHEN rejects:
   
   ```sql
   SELECT t1.k FROM tb1 t1 JOIN tb2 t2 ON t1.k = t2.k
     AND CASE WHEN t1.f < 0 THEN raise_error('neg') ELSE t1.f > t2.g END
     AND t1.v IN (SELECT v FROM tb3)
   JOIN tb3 t3 ON t1.v = t3.v AND 10 / (t1.k - t3.w) > 0
   ```
   
   The PR's NULL fix has no effect on this shape, because the division runs 
ahead of the whole group. A single-column NOT IN in the same position also 
becomes a nested-loop existence join instead of the null-aware anti join the 
base branch plans, and an IN becomes an existence join plus a filter instead of 
a left semi join.
   
   **Recommended change:** In ReorderJoin.keptCondition 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:106-112),
 keep the IN, NOT IN and correlated EXISTS predicates of each lower join or 
filter, the ones SubqueryExpression.hasInOrCorrelatedExistsSubquery finds, out 
of its coalesce(<AND>, false) wrapper, as top-level conjuncts placed right 
after the wrapper in their written order. The wrapper keeps holding that join's 
or filter's other kept conditions, and one that keeps only such predicates gets 
no wrapper. Add join optimizer and end-to-end join tests for a lower ON clause 
that keeps a throwable CASE WHEN with an IN or a NOT IN predicate.
   
   **Why this works:** RewritePredicateSubquery evaluates the conjuncts without 
a subquery predicate first, in written order, in a Filter below the joins it 
builds for the others 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:150-164).
 With the predicate outside the wrapper, the wrapper is such a conjunct and is 
written before the higher groups' kept conditions, so its FALSE, whether the 
guard was FALSE or NULL, stops them through AND's short-circuit; the predicate 
is a top-level conjunct again and becomes a left semi join, a left anti join 
or, for a single-column NOT IN, a null-aware anti join, as on the base branch.
   
   **Risks:** The kept conditions of a lower join or filter that are written 
after its subquery predicate now run before the predicate, on rows it rejects, 
as they do on the base branch; inside the current wrapper they run after it. 
Reverting the change restores that order together with the failures it fixes.
   
   **Constraints:** Keep the kept filter of a query whose kept conditions come 
from one join or filter, and the wrapper of a lower join or filter without a 
subquery predicate, exactly as the PR builds them. Keep the written order of 
the conditions inside the wrapper and of the predicates placed after it.
   
   **Exclusions:**
   - Making a lower join's or filter's own IN, NOT IN or EXISTS predicate stop 
the conditions written above it needs RewritePredicateSubquery to evaluate 
those conditions after the predicate's join, and the base branch evaluates them 
before it as well, so it stays out of this fix.
   
   **Verification:**
   - **Regression:** In ANSI mode, with whole-stage codegen on and off, run a 
three-way inner join whose ON clause with t2 keeps CASE WHEN t1.f < 0 THEN 
raise_error('neg') ELSE t1.f > t2.g END and t1.v IN (SELECT v FROM tb3) and 
whose ON clause with t3 keeps 10 / (t1.k - t3.w) > 0, over tb1 = (1, 1, 5), (2, 
2, 5), tb2 = (1, 10), (2, 1) and tb3 = (1, 1), (2, 0), and again with tb2's row 
for k = 1 set to (1, NULL); check that each run returns 2, where before the fix 
the first fails with DIVIDE_BY_ZERO.
   - **Regression:** Build the physical plan of a three-way inner join whose 
lower ON clause keeps a throwable CASE WHEN and a single-column NOT IN and 
whose upper ON clause keeps an ANSI division, and check that the NOT IN is 
planned as a null-aware anti join, as on the base branch, and that the CASE 
WHEN is evaluated ahead of the division.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -95,18 +95,38 @@ object ReorderJoin extends Rule[LogicalPlan] with 
PredicateHelper {
     }
   }
 
+  /**
+   * Returns the condition of the filter above all the joins from the 
conditions kept there, each
+   * with the index of the join or filter it is written in. That join or 
filter removes a row on
+   * which its condition is NULL, so the conditions written above it are not 
evaluated on the row,
+   * but `NULL AND x` evaluates `x`. So the kept conditions of each join or 
filter but the last are
+   * wrapped as `coalesce(<their AND>, false)`, whose FALSE skips the 
conditions after them. The
+   * kept conditions of one join or filter stay in a plain AND, as they are 
written.
+   */
+  private def keptCondition(kept: Seq[(Expression, Int)]): Option[Expression] 
= {
+    val groups = kept.groupBy(_._2).toSeq.sortBy(_._1).map(_._2.map(_._1))
+    groups.lastOption.map { last =>
+      val lower = groups.init.map(g => Coalesce(Seq(g.reduceLeft(And), 
Literal.FalseLiteral)))

Review Comment:
   **Blocking (P1):** Wrapping a lower join's kept conditions in `coalesce` 
hides them from constraint inference: a `Filter`'s constraints are its 
top-level conjuncts (`basicLogicalOperators.scala:382-386`), and IS NOT NULL is 
inferred only through null-intolerant expressions 
(`QueryPlanConstraints.scala:174-203`), which `coalesce` is not. The 
description mentions the lost inferred filters, but they did more than prune: 
they dropped rows with NULL before those rows could reach the guard.
   
   By the review's reading of the code, with ANSI on, tb1(k, v, f, b) = (1, 1, 
-5, NULL), tb2(k, g) = (1, 1) and tb3(v, w) = (1, 2), this query returns no 
rows on the base branch, in 4.3.0 and with the same ON clause over a join of 
two, because `isnotnull(t1.b)` is inferred and pushed into the tb1 scan; with 
this change nothing drops the row, so the CASE WHEN raises 'neg':
   
   ```sql
   SELECT t1.k FROM tb1 t1 JOIN tb2 t2 ON t1.k = t2.k
     AND CASE WHEN t1.f < 0 THEN raise_error('neg') ELSE t1.f > t2.g END
     AND t1.b / t2.g > 0
   JOIN tb3 t3 ON t1.v = t3.v AND 10 / (t1.k - t3.w) > 0
   ```
   
   The same lost filter leaves t1.b nullable at the input of a stream-stream 
join, so a streaming query of this shape whose checkpoint predates 4.3.0, and 
so keeps `spark.sql.streaming.statefulOperator.alwaysNullableOutput.enabled` 
off, fails the state schema check when it restarts on this change: the stored 
schema has the column non-nullable, and `StateSchemaCompatibilityChecker` 
rejects making it nullable (`StateSchemaCompatibilityChecker.scala:179-180`, 
`245-246`).
   
   **Recommended change:** In Filter.validConstraints 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:382-386),
 also take the conjuncts of p for every top-level conjunct of the form 
coalesce(p, false), leaving out those with a correlated subquery as for the 
filter's own conjuncts, so the conditions ReorderJoin wraps for a lower join or 
filter give their IsNotNull and other inferred filters again. Add 
constraint-inference optimizer tests for such a filter, an end-to-end join test 
for the query whose lower join reads a NULL column, and a streaming join test 
for the same shape.
   
   **Why this works:** A filter keeps a row only when its condition is TRUE, 
and coalesce(p, false) is TRUE exactly when p is, so each conjunct of p holds 
on the filter's output. With those conjuncts among the filter's constraints, 
InferFiltersFromConstraints again adds filters such as isnotnull(t1.b), from 
t1.b / t2.g > 0, ahead of the kept filter, and PushPredicateThroughJoin pushes 
them into the scans, as on the base branch, so the rows with NULLs are dropped 
there instead of reaching the guard.
   
   **Risks:** Any filter with a top-level coalesce(p, false) conjunct, not only 
the one ReorderJoin keeps, gains p's constraints, so 
InferFiltersFromConstraints can add and push more IsNotNull and other filters 
that cannot fail, and plans can change; reverting removes them. Rows that the 
restored filters drop below the joins no longer reach a lower join's guard, so 
an error the lower join as written would raise on them is not raised, as on the 
base branch. For a streaming query whose checkpoint predates 4.3.0, a 
user-written filter with a top-level coalesce(p, false) above a stream-stream 
join can now push IsNotNull filters below the join and so make the join's input 
columns non-nullable across the restart; the state schema check accepts that 
narrowing, but the join then reads the rows it stored before the restart, which 
can hold NULL in those columns, as non-nullable.
   
   **Constraints:** Only constraints that cannot fail may become filters, as 
canBeFilter already requires 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:2496-2519).
 Keep conjuncts of p with a correlated subquery, and non-deterministic ones, 
out of the constraints, as for top-level conjuncts.
   
   **Verification:**
   - **Regression:** In ANSI mode, run a three-way inner join whose ON clause 
with t2 keeps CASE WHEN t1.f < 0 THEN raise_error('neg') ELSE t1.f > t2.g END 
and t1.b / t2.g > 0 and whose ON clause with t3 keeps 10 / (t1.k - t3.w) > 0, 
over tb1 = (1, 1, -5, NULL), tb2 = (1, 1) and tb3 = (1, 2), and check that it 
returns no rows and that its optimized plan filters tb1 on isnotnull(b) below 
the joins, where before the fix it raises the CASE WHEN's error.
   - **Behavior:** Optimize a filter whose condition is coalesce(a > 1 AND b < 
2, false) above an inner join of two relations with nullable columns, and check 
that isnotnull(a) and isnotnull(b) are inferred and pushed below the join while 
a conjunct inside the coalesce that can fail does not become a filter.
   - **Compatibility:** Run a streaming query in which tb1 and tb2 are 
streaming inputs, whose ON clause with t2 keeps CASE WHEN t1.f < 0 THEN 
raise_error('neg') ELSE t1.f > t2.g END and t1.b / t2.g > 0 and whose ON clause 
with t3 keeps 10 / (t1.k - t3.w) > 0, with 
spark.sql.streaming.statefulOperator.alwaysNullableOutput.enabled set to false 
as for a query started before 4.3.0, and check that the stream-stream join's 
input, and so its state value schema, keeps t1.b non-nullable, as on the base 
branch; before the fix it is nullable, so restarting such a query from a 
checkpoint written by an earlier release fails the state schema check.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -95,18 +95,38 @@ object ReorderJoin extends Rule[LogicalPlan] with 
PredicateHelper {
     }
   }
 
+  /**
+   * Returns the condition of the filter above all the joins from the 
conditions kept there, each
+   * with the index of the join or filter it is written in. That join or 
filter removes a row on
+   * which its condition is NULL, so the conditions written above it are not 
evaluated on the row,
+   * but `NULL AND x` evaluates `x`. So the kept conditions of each join or 
filter but the last are
+   * wrapped as `coalesce(<their AND>, false)`, whose FALSE skips the 
conditions after them. The
+   * kept conditions of one join or filter stay in a plain AND, as they are 
written.
+   */
+  private def keptCondition(kept: Seq[(Expression, Int)]): Option[Expression] 
= {
+    val groups = kept.groupBy(_._2).toSeq.sortBy(_._1).map(_._2.map(_._1))
+    groups.lastOption.map { last =>
+      val lower = groups.init.map(g => Coalesce(Seq(g.reduceLeft(And), 
Literal.FalseLiteral)))

Review Comment:
   **Blocking (P1):** Nesting the guard and the conditions kept after it in one 
conjunct changes what filter subexpression elimination does with them. 
`FilterExec`, like the generated predicate, computes each common subexpression 
right before the first top-level conjunct that contains it 
(`basicPhysicalOperators.scala:359-365`, `462-469`), and with 
`spark.sql.subexpressionElimination.skipForShortcutExpr` off by default, 
`EquivalentExpressions` counts both operands of the `AND` inside `coalesce` as 
always evaluated (`EquivalentExpressions.scala:156-172`). So a non-cheap 
subexpression that a condition kept after the guard shares with another kept 
condition is now computed before the guard.
   
   By the review's reading of the code, with ANSI on and the default codegen 
settings, tb1(k, v, f) = (1, 9, 5), tb2(k, g) = (1, 9) and tb3(v, w) = (9, 0), 
this query returns no rows on the base branch and in 4.3.0, since the CASE WHEN 
is FALSE, but with this change it computes `10 / (9 - 9)` before the CASE WHEN 
and fails with DIVIDE_BY_ZERO:
   
   ```sql
   SELECT t1.k FROM tb1 t1 JOIN tb2 t2 ON t1.k = t2.k
     AND CASE WHEN t1.f < 0 THEN raise_error('neg') ELSE t1.f > t2.g END
     AND 10 / (t1.v - t2.g) > 0
   JOIN tb3 t3 ON t1.v = t3.v AND 10 / (t1.v - t2.g) > t3.w
   ```
   
   A NULL guard hits the same failure, so the PR's own fix does not hold for 
these queries; only interpreted evaluation still returns their rows.
   
   **Recommended change:** In the subexpression elimination of a filter's 
conjuncts, in FilterExec's whole-stage code 
(sql/core/src/main/scala/org/apache/spark/sql/execution/basicPhysicalOperators.scala:517-569)
 and in the generated predicate 
(CodeGenerator.generateConjunctsWithSubexprCodes, 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/CodeGenerator.scala:2445-2491),
 count a subexpression only where its conjunct always evaluates it: analyze 
each top-level conjunct on its own and, through an AND or OR nested inside it, 
count only the first operand, as 
spark.sql.subexpressionElimination.skipForShortcutExpr does, which in the 
generated predicate means adding the conjuncts one by one rather than the whole 
predicate. Then compute each common subexpression right before the first 
conjunct that always evaluates it, and let a conjunct before that one that 
holds it in an operand it may skip compute it where it is written instead of 
reading the shared value. Add
  filter codegen tests and an end-to-end join test for the shared-division 
query.
   
   **Why this works:** A common subexpression is then computed only right 
before a conjunct that always evaluates it, so the division that the lower 
join's kept conditions share with the conditions kept above them is no longer 
computed ahead of the wrapper, however many of those conditions read it: inside 
the wrapper it runs only after the guard's AND lets it, as the base branch runs 
it only after the guard's own conjunct.
   
   **Compatibility:** Interpreted evaluation, which computes a shared 
subexpression on its first use, is unchanged.
   
   **Risks:** Filters that hold a subexpression in a later operand of a nested 
AND or OR no longer share it from there: they compute it where it is written, 
and once more before a later conjunct that always evaluates it; plans do not 
change, and reverting restores the sharing. Other predicates built by 
GeneratePredicate with several conjuncts change the same way.
   
   **Constraints:** Keep eliminating a subexpression that two top-level 
conjuncts evaluate unconditionally, and keep computing it right before the 
first of them. Keep the top-level conjuncts separate inputs to the analysis, so 
that the first-operand rule inside a conjunct does not hide the subexpressions 
of the conjuncts after it.
   
   **Verification:**
   - **Regression:** In ANSI mode, with whole-stage codegen on and off, run a 
three-way inner join whose ON clause with t2 keeps CASE WHEN t1.f < 0 THEN 
raise_error('neg') ELSE t1.f > t2.g END and 10 / (t1.v - t2.g) > 0 and whose ON 
clause with t3 keeps 10 / (t1.v - t2.g) > t3.w, over tb1 = (1, 9, 5), tb2 = (1, 
9) and tb3 = (9, 0), and again with 10 / (t1.v - t2.g) < 100 added to the ON 
clause with t3; check that each returns no rows, where before the fix 
whole-stage codegen fails with DIVIDE_BY_ZERO.
   - **Regression:** Evaluate a filter whose first conjunct is coalesce(<a 
FALSE guard> AND 10 / x > 0, false) and whose next conjuncts are 10 / x > 1 and 
10 / x < 100 on a row with x = 0, through FilterExec's whole-stage code and 
through the generated predicate, and check that the row is dropped without an 
error.
   - **Behavior:** Check, through FilterExec's whole-stage code and through the 
generated predicate, that a non-cheap subexpression that two top-level 
conjuncts always evaluate is still eliminated and computed right before the 
first of them.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinOptimizationSuite.scala:
##########
@@ -67,7 +67,7 @@ class JoinOptimizationSuite extends PlanTest {
     def testExtractCheckCross(plan: LogicalPlan,
         expected: Option[(Seq[(LogicalPlan, InnerLike)], Seq[Expression])]): 
Unit = {
       assert(
-        ExtractFiltersAndInnerJoins.unapply(plan) === expected.map(e => (e._1, 
e._2)))
+        ExtractFiltersAndInnerJoins.unapply(plan).map(e => (e._1, 
e._2.flatten)) === expected)

Review Comment:
   **Non-blocking (P2):** Comparing `e._2.flatten` leaves no test asserting the 
groups that `ExtractFiltersAndInnerJoins` now returns, and the new 
`ReorderJoin` cases have exactly two ON-clause groups that keep conditions. So 
each of these changes would pass the PR's tests: putting a filter's conjuncts 
in the group of the join below it (`patterns.scala:268`), placing a filter's 
group ahead of the join groups, wrapping all the lower groups in one 
`coalesce`, or wrapping only the first lower group. Each would bring back a 
failure for a form of the fixed query, such as the WHERE, filter-between-joins 
and four-way forms the description reports running only in a temporary suite 
that is not included.
   
   **Verification:**
   - **Regression:** Check that the new ReorderJoin cases fail when a filter's 
conditions are merged into the group of the join below it, when a filter's 
group is placed ahead of the join groups, when all lower groups share one 
coalesce wrapper, or when only the first lower group is wrapped, and that they 
pass with the PR's grouping.
   - **Behavior:** Run the WHERE, filter-between-joins and four-way forms of 
the description's tb1, tb2 and tb3 query in ANSI mode with whole-stage codegen 
on and off and check that each returns the rows the joins as written produce.
   - **Behavior:** Check that the extractor test asserts the groups of 
conditions that ExtractFiltersAndInnerJoins returns for a plan that has both 
join and filter conditions.



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