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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))
 
-    case _ => (Seq((plan, parentJoinType)), Seq.empty)
+    case _ => (Seq((plan, parentJoinType)), Seq.empty, Seq.empty)
+  }
+
+  /**
+   * Guards `conditions`, the ones of `plan`, a join or filter above the 
flattened `filters`. A
+   * filter removes a row on which its condition is NULL, but in the join 
condition that
+   * `ReorderJoin` puts it in, a condition above it that only reads its 
columns can follow it, and
+   * `NULL AND x` evaluates `x`. So such a condition that can fail, which 
`splitMovable` does not
+   * move after a barrier, is returned as `If(<condition of the filter>, 
<condition>, false)` for
+   * each such filter whose condition can be NULL, the lowest one outermost, 
which evaluates it only
+   * where they are TRUE, wherever it is put. A condition that also reads a 
column of a plan joined
+   * above the filter goes into a join with that plan, and is left as is, so 
that it can still be a
+   * join key, as can one that reads no column of the filter.
+   */
+  private def guard(
+      conditions: Seq[Expression],
+      filters: Seq[(Expression, LogicalPlan)],
+      plan: LogicalPlan): Seq[Expression] = if (filters.isEmpty) {
+    conditions
+  } else {
+    conditions.map { cond =>
+      val below = filters.filter { case (condition, filter) =>
+        cond.references.subsetOf(filter.outputSet) && condition.nullable
+      }
+      if (below.nonEmpty &&
+          splitMovable(Seq(cond), Seq(plan), afterBarrier = true)._2.nonEmpty) 
{

Review Comment:
   **Blocking (P1):** This check also admits a conjunct that `ReorderJoin` 
keeps in the filter above all the joins, such as `rand() < 0.5`: an empty 
reference set passes the `subsetOf` test, and `splitMovable` keeps any 
non-deterministic conjunct. That filter already runs after every flattened 
filter, so the wrapper buys nothing there, and it is not stable. When 
`PushDownPredicates` puts the lower filter back between the joins, for example 
`Filter(IN, a JOIN b)` for `(a.x + b.z) IN (SELECT y FROM s)`, the next 
`ReorderJoin` pass wraps `If(IN, rand() < 0.5, false)` once more: nothing marks 
a conjunct as already guarded, and `SimplifyConditionals` does not fold `If(c, 
If(c, x, false), false)`. Tracing the rules, `SELECT * FROM a JOIN b ON a.k = 
b.k JOIN c ON a.k = c.k WHERE (a.x + b.z) IN (SELECT y FROM s) AND rand() < 
0.5` reaches a fixed point after two iterations on the base branch, but with 
this change gains one `If` layer per iteration until 
`spark.sql.optimizer.maxIterations`, in
  both operator-optimization batches; with `spark.testing` set, `RuleExecutor` 
throws instead. `RewritePredicateSubquery` then turns each nested IN copy into 
its own `ExistenceJoin` over the joined rows, so the extra work grows with the 
data. A failable filter over a join with a throwable conjunct, with such a 
conjunct above it, loops the same way without any subquery.
   
   **Recommended change:** Make `guard` leave unwrapped every conjunct of the 
join or filter it guards that `splitMovable` keeps in place when applied to 
that plan's own conditions in written order with no barrier: a 
non-deterministic or throwable conjunct, and a conjunct that can fail written 
after one. `ReorderJoin` keeps exactly these in a filter above all the joins 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala,
 lines 113-125). There they run only on rows that passed every flattened 
filter, so they need no guard, and without the wrapper a later pass finds 
nothing to wrap again. Add join-reorder optimizer tests that run the full 
operator-optimization batches, not `ReorderJoin` alone, on both looping shapes.
   
   **Why this works:** The only guarded conjuncts that end up above a filter 
that pushdown can re-create between the joins are the ones `ReorderJoin` keeps 
above all the joins. Every other guarded conjunct goes into a join condition, 
or into a filter with no flattened filter below it, which no later pass guards 
again. Excluding the kept conjuncts in `guard`, with the same `splitMovable` 
rule that `ReorderJoin` uses, makes each pass return the plan it started from. 
Both operator-optimization batches then reach a fixed point, as they do on the 
base branch.
   
   **Compatibility:** Every conjunct that `ReorderJoin` places into a join, or 
into a filter below the top, keeps the guard it gets today.
   
   **Risks:** Conjuncts kept above all the joins lose their wrapper, so their 
plans return to the base branch's. That is safe, because the filter above the 
joins runs after every flattened filter, and no other conjunct changes.
   
   **Constraints:** The exclusion must apply `splitMovable` to the guarded 
plan's conditions in written order and with no barrier, as `ReorderJoin` does 
at 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala 
line 113. Then every conjunct that the guard leaves unwrapped is one that stays 
above all the joins. The narrowed exemption for conditions that read a plan 
joined above the filter must keep this exclusion, and the corrected scaladoc 
must describe the rule they leave together.
   
   **Verification:**
   - **Regression:** Run the full operator-optimization batches, with testing 
enabled, on the IN-subquery query with `rand() < 0.5` and on the query whose 
lower join has a throwable conjunct. Check that neither reaches the iteration 
limit, and that each kept conjunct appears once, unwrapped, above the joins.
   - **Behavior:** Check that a failable condition that `ReorderJoin` places 
into a join above a nullable filter is still wrapped in that filter's 
condition, and that the PR's end-to-end ANSI query still returns no rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))
 
-    case _ => (Seq((plan, parentJoinType)), Seq.empty)
+    case _ => (Seq((plan, parentJoinType)), Seq.empty, Seq.empty)
+  }
+
+  /**
+   * Guards `conditions`, the ones of `plan`, a join or filter above the 
flattened `filters`. A
+   * filter removes a row on which its condition is NULL, but in the join 
condition that
+   * `ReorderJoin` puts it in, a condition above it that only reads its 
columns can follow it, and
+   * `NULL AND x` evaluates `x`. So such a condition that can fail, which 
`splitMovable` does not
+   * move after a barrier, is returned as `If(<condition of the filter>, 
<condition>, false)` for
+   * each such filter whose condition can be NULL, the lowest one outermost, 
which evaluates it only
+   * where they are TRUE, wherever it is put. A condition that also reads a 
column of a plan joined
+   * above the filter goes into a join with that plan, and is left as is, so 
that it can still be a
+   * join key, as can one that reads no column of the filter.
+   */
+  private def guard(
+      conditions: Seq[Expression],
+      filters: Seq[(Expression, LogicalPlan)],
+      plan: LogicalPlan): Seq[Expression] = if (filters.isEmpty) {

Review Comment:
   **Blocking (P1):** `guard` runs for streaming plans too: streaming queries 
use the session optimizer, and neither this method nor `ReorderJoin` checks 
`isStreaming`. Take three watermarked streams in ANSI mode, with `s2.v` 
nullable, and `s1.join(s2).where(s2("v") > 0).join(s3, s1("k") === 
s3("k")).where(s1("a") + 1 === s2("b"))`. On the base branch the equality 
becomes the key of the `s1`-`s2` join. With this change it becomes `If(s2.v > 
0, s1.a + 1 = s2.b, false)`, `PushPredicateThroughJoin` pushes `s2.v > 0` to 
`s2`, `ExtractEquiJoinKeys` finds no top-level equality, and 
`StreamingJoinStrategy` throws "stream-stream join without equality predicate 
is not supported". When the join also has a plain key, the wrapped equality 
drops out of the state key schema, so restarting from a checkpoint written 
before the upgrade fails the state schema check. A wrapped event-time range 
comparison yields no state watermark, so that join's state is never evicted.
   
   **Recommended change:** Leave conditions unguarded when the plan being 
flattened is streaming, so that streaming queries get the base branch's 
conditions. Add a TODO in `guard` naming stream-stream joins as the deferred 
case, since their keys, state schema and state watermark need top-level 
conjuncts. Add streaming join tests for stream-stream joins whose failable 
equality, or event-time range comparison, is written above a nullable filter 
between the joins.
   
   **Why this works:** With no wrapper on streaming plans, 
`ExtractEquiJoinKeys` finds the same keys as on the base branch, the join's 
state key schema matches checkpoints the base branch wrote, and 
`StreamingJoinHelper` derives the same state watermark.
   
   **Compatibility:** Batch plans keep the guard, as the other repairs leave it.
   
   **Risks:** Streaming queries, stream-static joins included, keep the base 
branch's failure when a failable condition above a NULL-able filter runs on 
rows that the filter removes. It stays an explicit error, never a wrong result.
   
   **Constraints:** The check must cover every plan with a streaming input, 
because a stream-stream join anywhere in the flattened plan depends on its keys 
and conditions.
   
   **Exclusions:**
   - Streaming queries do not get the fix in this PR: as on the base branch, a 
failable condition above a NULL-able filter between their joins can still run 
on rows that the filter removes.
   
   **Verification:**
   - **Compatibility:** In ANSI mode, run an inner join of three streams with 
`s2.v > 0` between the joins and `s1.a + 1 = s2.b` above them. Check that it 
plans with that equality as a join key, and that its state key schema is the 
one the base branch writes.
   - **Behavior:** Run an inner join of three streams with an event-time range 
comparison between two of them written above a nullable filter, and check that 
the join evicts state as the watermark advances.
   - **Regression:** Check that a batch plan of the same shape still guards its 
failable conditions.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))

Review Comment:
   **Non-blocking (P2):** Recording `flattened.reduce(And)`, the filter's 
condition as already guarded, puts the guards of every lower filter into each 
filter's record, and line 313 nests every qualifying record again. A conjunct 
above k such filters therefore carries 2^(k-1) copies of filter conditions. For 
a chain `fact.join(d0, ...).where(f1).join(d1, ...).where(f2) ...` whose 
filters are nullable, can fail and read only `fact`, a model of `flatten` and 
`guard` gives about 3,000 tree nodes at 10 filters and about 3.1 million at 20, 
where the base branch keeps the conditions as written. Catalyst rules and code 
generation walk these trees, and every fact row that passes the filters 
evaluates the copies, so optimization time, driver memory, generated code and 
per-row work all grow exponentially with the chain's length.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinOptimizationSuite.scala:
##########
@@ -215,4 +215,27 @@ class JoinOptimizationSuite extends PlanTest {
       .select($"a", $"b", $"c", $"d", $"e", $"f")
     comparePlans(ReorderJoin(query.analyze), answer.analyze)
   }
+
+  test("SPARK-62226: reorder inner joins with a lower filter whose condition 
can be NULL") {

Review Comment:
   **Non-blocking (P2):** This case, like the `JoinSuite` one, has exactly one 
flattened filter below each guarded condition, so `filters` holds one element 
whenever `guard` wraps and the nested path is never reached. Changing `flatten` 
to record only the nearest filter, or `guard` to keep only the last element of 
`below`, would leave both suites green, yet in `A.join(B, k).where(fc1).join(C, 
k2).where(fc2).join(D, k3).where(10 / (A.v - B.w) > 0)`, with `fc1` NULL and 
`fc2` TRUE on a row, the division would again be evaluated on the row that 
`fc1` removes. The description states this nesting as part of the design and 
reports checking it only with a temporary suite that the PR does not include.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/JoinOptimizationSuite.scala:
##########
@@ -215,4 +215,27 @@ class JoinOptimizationSuite extends PlanTest {
       .select($"a", $"b", $"c", $"d", $"e", $"f")
     comparePlans(ReorderJoin(query.analyze), answer.analyze)
   }
+
+  test("SPARK-62226: reorder inner joins with a lower filter whose condition 
can be NULL") {
+    // The lower filter removes a row on which `b > d` is NULL, but in the 
join condition that the
+    // filter is put in, `NULL AND x` evaluates `x`. So a division above it 
that only reads its
+    // columns, which can fail in ANSI mode, is evaluated only where `b > d` 
is TRUE. A condition
+    // that can not fail, one that also reads a column of `z`, and any 
condition above a filter
+    // whose condition can not be NULL go into a join as before. Only 
ReorderJoin runs.
+    def divide(l: Expression, r: Expression): Expression =
+      Divide(l, r, NumericEvalContext(EvalMode.ANSI))
+    val z = LocalRelation($"e".int, $"f".int)
+    Seq(($"b" > $"d") -> true, $"b".isNotNull -> false).foreach { case (cond, 
nullable) =>
+      val query = testRelation.join(testRelation1, condition = Some($"a" === 
$"d"))
+        .where(cond)
+        .join(z, condition = Some($"e" === $"a" && divide($"c", $"d") > 1 && 
$"c" > 1))

Review Comment:
   **Nit (P3):** The guarded condition here, `divide($"c", $"d") > 1`, is 
rejected by `canEvaluateUnconditionally` on its own, and `$"c" > 1` reads plain 
`LocalRelation` columns, so nothing in this test depends on the plans that 
`guard` passes to `splitMovable`. If `guard` passed `Nil` instead, both new 
tests would still pass, while `q > 1` over a projected ANSI division `q = c / 
d`, above a nullable filter between the joins, would again go unguarded into 
the join condition after the filter condition.
   
   **Verification:**
   - **Regression:** Check that the new plan test passes with the PR's code, 
and fails when the guard's can-fail test ignores the flattened plans, for 
example when it passes no plans to `splitMovable`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))
 
-    case _ => (Seq((plan, parentJoinType)), Seq.empty)
+    case _ => (Seq((plan, parentJoinType)), Seq.empty, Seq.empty)
+  }
+
+  /**
+   * Guards `conditions`, the ones of `plan`, a join or filter above the 
flattened `filters`. A
+   * filter removes a row on which its condition is NULL, but in the join 
condition that
+   * `ReorderJoin` puts it in, a condition above it that only reads its 
columns can follow it, and
+   * `NULL AND x` evaluates `x`. So such a condition that can fail, which 
`splitMovable` does not
+   * move after a barrier, is returned as `If(<condition of the filter>, 
<condition>, false)` for
+   * each such filter whose condition can be NULL, the lowest one outermost, 
which evaluates it only
+   * where they are TRUE, wherever it is put. A condition that also reads a 
column of a plan joined
+   * above the filter goes into a join with that plan, and is left as is, so 
that it can still be a
+   * join key, as can one that reads no column of the filter.

Review Comment:
   **Nit (P3):** "as can one that reads no column of the filter" does not match 
the code: `cond.references.subsetOf(filter.outputSet)` holds for an empty 
reference set, so a condition that reads no column at all, such as `10 / 
(SELECT min(x) FROM t) > 0`, is wrapped above every nullable filter when it can 
fail. That is the safer behavior, since `createOrderedJoin` would otherwise put 
such a condition into the first join, below the filter's join; a maintainer who 
changed the code to match this sentence would bring that failure back. The 
sentence should say that a condition with no references is guarded too.
   
   See **Shared repair plan 2** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))
 
-    case _ => (Seq((plan, parentJoinType)), Seq.empty)
+    case _ => (Seq((plan, parentJoinType)), Seq.empty, Seq.empty)
+  }
+
+  /**
+   * Guards `conditions`, the ones of `plan`, a join or filter above the 
flattened `filters`. A

Review Comment:
   **Nit (P3):** The description lists cases this fix leaves failing, but 
nothing in the code says so. In `flatten`, the `Join` case passes `filters` up 
without the join's own condition (line 280), so a NULL-able `ON` condition of a 
lower inner join guards nothing. When `ReorderJoin` does not flatten the plan, 
as in a subquery (left to #60771), with the filter and the division as stacked 
filters over all the joins, or with a hint on the upper join, 
`PushPredicateThroughJoin` and `CombineFilters` still merge the division after 
the filter condition. A TODO in this scaladoc naming those cases would show 
readers that the fix is partial.
   
   See **Shared repair plan 2** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -262,16 +268,53 @@ object ExtractFiltersAndInnerJoins extends 
PredicateHelper {
    * flattened left-deep tree.
    */
   def flattenJoin(plan: LogicalPlan, parentJoinType: InnerLike = Inner)
-      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = plan match {
+      : (Seq[(LogicalPlan, InnerLike)], Seq[Expression]) = {
+    val (plans, conditions, _) = flatten(plan, parentJoinType)
+    (plans, conditions)
+  }
+
+  private def flatten(plan: LogicalPlan, parentJoinType: InnerLike): Flattened 
= plan match {
     case Join(left, right, joinType: InnerLike, cond, hint) if hint == 
JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(left, joinType)
+      val (plans, conditions, filters) = flattenBelow(left, joinType)
       (plans ++ Seq((right, joinType)), conditions ++
-        cond.toSeq.flatMap(splitConjunctivePredicates))
+        guard(cond.toSeq.flatMap(splitConjunctivePredicates), filters, plan), 
filters)
     case Filter(filterCondition, j @ Join(_, _, _: InnerLike, _, hint)) if 
hint == JoinHint.NONE =>
-      val (plans, conditions) = flattenBelow(j, Inner)
-      (plans, conditions ++ splitConjunctivePredicates(filterCondition))
+      val (plans, conditions, filters) = flattenBelow(j, Inner)
+      val flattened = guard(splitConjunctivePredicates(filterCondition), 
filters, plan)
+      // The top filter is added too, but no condition is above it.
+      (plans, conditions ++ flattened, filters :+ (flattened.reduce(And), 
plan))
 
-    case _ => (Seq((plan, parentJoinType)), Seq.empty)
+    case _ => (Seq((plan, parentJoinType)), Seq.empty, Seq.empty)
+  }
+
+  /**
+   * Guards `conditions`, the ones of `plan`, a join or filter above the 
flattened `filters`. A
+   * filter removes a row on which its condition is NULL, but in the join 
condition that
+   * `ReorderJoin` puts it in, a condition above it that only reads its 
columns can follow it, and
+   * `NULL AND x` evaluates `x`. So such a condition that can fail, which 
`splitMovable` does not
+   * move after a barrier, is returned as `If(<condition of the filter>, 
<condition>, false)` for
+   * each such filter whose condition can be NULL, the lowest one outermost, 
which evaluates it only
+   * where they are TRUE, wherever it is put. A condition that also reads a 
column of a plan joined
+   * above the filter goes into a join with that plan, and is left as is, so 
that it can still be a
+   * join key, as can one that reads no column of the filter.
+   */
+  private def guard(
+      conditions: Seq[Expression],
+      filters: Seq[(Expression, LogicalPlan)],
+      plan: LogicalPlan): Seq[Expression] = if (filters.isEmpty) {
+    conditions
+  } else {
+    conditions.map { cond =>
+      val below = filters.filter { case (condition, filter) =>
+        cond.references.subsetOf(filter.outputSet) && condition.nullable

Review Comment:
   **Non-blocking (P2):** This `subsetOf` test exempts every conjunct that also 
reads a plan joined above the filter, on the premise in the scaladoc that it 
goes into a join with that plan, above the filter. Join reordering does not 
keep that order: `createOrderedJoin` joins the first plan with the first plan a 
condition connects to it, and `StarSchemaDetection` orders dimensions by size. 
In ANSI mode, with `t0(k)`, `t1(k, f, v)`, `t2(k, g)` and `t3(k, w)` holding 
`(1)`, `(1, 5, 1)`, `(1, NULL)` and `(1, 1)`, `t0.crossJoin(t1).join(t2, 
t1("k") === t2("k")).where(t1("f") > t2("g")).join(t3, t0("k") === 
t3("k")).where(lit(10) / (t1("v") - t3("w")) > 0)` should return no rows. Per 
the code, `createOrderedJoin` joins `t0` with `t3` first, puts the division 
into the join with `t1`, and puts `t1.f > t2.g` into the last join, so the 
query still fails with `DIVIDE_BY_ZERO`, as on the base branch. Keeping join 
keys, the exemption's stated reason, does not cover a non-key condition like 
this d
 ivision, and no comment defers the case.
   
   **Recommended change:** In `guard`, also wrap a conjunct that can fail and 
reads columns of the filter's plans together with columns of plans joined above 
the filter, when the filter sits over two or more plans and 
`canEvaluateWithinJoin` accepts its condition and the conditions of the filters 
that guard it. The exception is an equality that can be a join key: an 
`EqualTo` or `EqualNullSafe` whose one side reads only the filter's plans and 
whose other side reads only plans joined above it. Conjuncts that read only 
plans joined above the filter stay unwrapped, as the PR states, and a conjunct 
with no references stays wrapped, as today. Add a TODO at the exemption that 
names what stays exempt, the equality keys and the conditions above a filter 
whose condition holds a subquery, and the reordered joins under which they can 
still run first. Add a join-reorder plan test in which a cross join below the 
filter makes `ReorderJoin` join the upper plan first, an end-to-end ANSI join 
test of
  that shape that returns no rows, and optimizer tests that run the full 
operator-optimization batches on a filter that pushdown re-creates between the 
joins, with such a condition above it.
   
   **Why this works:** The wrapped conjunct also reads the filter condition's 
columns. So whatever order `createOrderedJoin` or `StarSchemaDetection` 
chooses, it is placed in a join that has the filter's plans, and it is 
evaluated only where the filter condition is TRUE. An equality key stays a key, 
as the PR intends. A filter whose condition can go into a join and that sits 
over two or more plans is not re-created between the joins: `ReorderJoin` puts 
each of its conjuncts into a join, and pushdown moves only a conjunct that 
reads a single plan, into that plan. So no later pass finds the wrapped 
conjunct above the same filter again, and the batches still reach a fixed 
point. The condition of a filter over a single plan, which `flattenBelow` keeps 
as the first plan, ends up directly over that plan, below every join, so a 
conjunct that reads that plan already runs after it and needs no wrapper.
   
   **Compatibility:** Equality join keys with a plan joined above the filter, 
conditions that read only such plans, and conditions above a filter whose 
condition holds a subquery or that sits over a join kept as one plan keep 
today's plans.
   
   **Risks:** A failable non-key conjunct that reads an upper plan is now 
guarded even when the upper plan is joined after the filter's plans, where the 
base branch already evaluates it safely. The filter condition is then evaluated 
again for each joined pair, and no IS NOT NULL filters are inferred from the 
conjunct. That costs work but changes no result. Guarding the conditions that 
stay exempt above a filter whose condition holds a subquery would need the 
guard to skip a filter that already guards a condition, and the wrapped 
condition could no longer go into a join: each copy of the subquery would 
become an extra existence join, also on queries the base branch already plans 
safely. Until a separate change covers them, such queries can still fail as on 
the base branch when the joins are reordered.
   
   **Constraints:** An equality whose sides read the filter's plans and an 
upper plan respectively must stay unwrapped, so that it remains a join key. The 
selection must still exclude the conjuncts that `ReorderJoin` keeps above all 
the joins, and must still wrap a failable conjunct with no references. The 
widening must not apply above a filter that pushdown re-creates between the 
joins: one whose condition `canEvaluateWithinJoin` rejects, such as an IN 
subquery over two of the joined plans, or one over a join that `flattenBelow` 
keeps as one plan. A conjunct wrapped above such a filter stays outside it, so 
the next pass wraps it again and the batches never reach a fixed point. A model 
of these rules shows this even for a single WHERE clause with an IN subquery 
over two tables and a division over a third, which the base branch optimizes in 
two iterations.
   
   **Exclusions:**
   - An equality key between the filter's plans and a plan joined above the 
filter stays unwrapped. When reordering joins that plan first, the key can 
still be evaluated on rows the filter removes, and a TODO at the exemption 
records this.
   - Above a filter whose condition holds a subquery, a failable condition that 
also reads a plan joined above the filter stays unwrapped. When reordering 
joins that plan first, it can still be evaluated on rows the filter removes, 
and the TODO at the exemption records this.
   
   **Verification:**
   - **Regression:** In ANSI mode, run `t0.crossJoin(t1).join(t2, t1.k = 
t2.k).where(t1.f > t2.g).join(t3, t0.k = t3.k).where(10 / (t1.v - t3.w) > 0)` 
on rows where `g` is NULL and `v` equals `w`, and check that it returns no rows.
   - **Behavior:** Check that the reordered plan puts the guarded division into 
the join that receives the filter condition, and that a failable equality 
between the filter's plans and the upper plan is still a join key.
   - **Regression:** Run the full operator-optimization batches, with testing 
enabled, on `SELECT * FROM t1 JOIN t2 ON t1.k = t2.k JOIN t3 ON t1.k = t3.k 
WHERE (t1.x + t2.z) IN (SELECT y FROM s) AND 10 / (t1.v - t3.u) > 0` and on a 
query whose failable filter sits over a join with a throwable conjunct, with a 
division over `t1` and `t3` above it. Check that neither reaches the iteration 
limit and that the division is not wrapped.



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