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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2626,12 +2626,12 @@ object CombineFilters extends Rule[LogicalPlan] with 
PredicateHelper {
     // 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. 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`.
+    // keeps in a filter in place of the top join, or can be NULL (see 
`canBeNull`), 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), afterBarrier = 
nc.throwable)
+      val (movable, rest) = splitMovable(splitConjunctivePredicates(fc), 
Seq(grandChild),
+        afterBarrier = nc.throwable || canBeNull(nc))

Review Comment:
   **Blocking (P1):** With `afterBarrier = nc.throwable || canBeNull(nc)`, the 
right side of an EXCEPT can now stay as two stacked Filters. 
`ReplaceExceptWithFilter`, which this PR does not change, runs `CombineFilters` 
on that side and then reads only the top Filter's condition: 
`combineFilters(skipProject(right)).asInstanceOf[Filter].condition` 
(ReplaceExceptWithFilter.scala:53). Its eligibility check skips every stacked 
Filter, so the lower condition silently drops out of the rewrite. The rule runs 
in the Replace Operators batch, before Infer Filters adds any IS NOT NULL 
check, so any comparison on a nullable column counts as NULL-able there.
   
   By the review's reading of the code, with default configs (ANSI on, 
`spark.sql.optimizer.replaceExceptWithFilter` true) and a Parquet table `t(a 
INT, b INT, c INT)` holding (4, 2, 0) and (4, 2, 1), this query
   
   ```sql
   SELECT * FROM t EXCEPT SELECT * FROM (SELECT * FROM t WHERE c = 1) WHERE a / 
b > 1
   ```
   
   is rewritten to `Distinct(Filter(NOT coalesce(a / b > 1, false), t))`. It 
returns no rows instead of (4, 2, 0), and so does `t.except(t.where($"c" === 
1).where($"a" / $"b" > 1))`. On the base branch, `CombineFilters` merged `c = 1 
AND a / b > 1` first, so the whole condition was flipped. A left row with `b = 
0` and `c = 0` also fails with DIVIDE_BY_ZERO, although the query divides only 
where `c = 1`. The base branch already lost a non-deterministic or throwable 
lower filter this way; the barrier extends that to ordinary comparisons on 
nullable columns.
   
   **Recommended change:** In ReplaceExceptWithFilter, build the flipped 
condition from every Filter that CombineFilters leaves on the right side of the 
EXCEPT, not only the top one, and nest each upper condition under the ones 
below it, so that it runs only where they are TRUE. Keep leaving the EXCEPT to 
the anti-join rewrite in two cases: when any of those conditions is 
non-deterministic, as the rule already does for the top one, and when an upper 
condition calls a Python or external UDF. Add tests: optimizer tests for the 
set-operation rewrite, and an end-to-end EXCEPT test in ANSI mode.
   
   **Why this works:** Walk the right side from its top Filter down to the 
first node that is not a Filter, and collect the conditions from the bottom up. 
Fold them as If(lower, upper, false), starting from the bottom one, then wrap 
the result in Coalesce(..., false) and Not, as now. An If evaluates its true 
branch only when its predicate is TRUE, so an upper condition never runs on a 
row that a lower one drops as FALSE or NULL. A single Filter yields its own 
condition, so the rewrite of such a right side is unchanged.
   
   **Risks:** A right side whose upper filter calls a Python or external UDF 
now goes to the anti-join rewrite, which is slower than the filter rewrite that 
the base branch used for it once CombineFilters had merged the filters. For 
right sides that keep stacked filters, the left filter's condition becomes a 
nested IF instead of one conjunction. As with the current NOT COALESCE 
condition, it is not translated into data-source filters.
   
   **Constraints:** A row on which the flipped condition is NULL must stay in 
the result as a left row that the right side does not contain, as Coalesce(..., 
false) treats it now.
   
   **Exclusions:**
   - EXCEPT ALL, which RewriteExceptAll rewrites before this rule runs, is not 
changed.
   
   **Verification:**
   - **Regression:** In ANSI mode, run an EXCEPT DISTINCT over a Parquet table 
whose right side is a filter that can fail above a filter that can be NULL. It 
returns the left rows that the lower filter keeps out of the right side, and it 
does not fail on a left row where the upper condition would divide by zero but 
the lower one is FALSE or NULL. Check both the SQL form and the Dataset.except 
form.
   - **Behavior:** In the optimized plan of such an EXCEPT, the flipped 
condition contains every stacked right-side condition, and each upper one is 
evaluated only under the lower ones. A right side with a single filter, or with 
filters that CombineFilters merges, is rewritten exactly as before.
   - **Regression:** A right side with a throwable lower filter and an upper 
conjunct that can fail is rewritten with both conditions. A right side with a 
non-deterministic lower filter is not rewritten with only its top condition. On 
the base branch, both cases left conditions out.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/planning/patterns.scala:
##########
@@ -148,13 +161,16 @@ object ScanOperation extends OperationHelper {
     // placed at the beginning of `filters` list. According to the SQL 
semantic, we cannot merge
     // Filters if one or more of them are nondeterministic. This means we can 
only push down the
     // bottom-most Filter, or more following deterministic Filters if the 
bottom-most Filter is
-    // also deterministic.
+    // also deterministic, up to the first one that can fail on a row that the 
Filters below it
+    // drop as NULL (see `canCombine`).
     if (filters.isEmpty) {
       Some((fields.getOrElse(child.output), Nil, Nil, child))
     } else if (filters.head.deterministic) {
-      val filtersCanPushDown = filters.takeWhile(_.deterministic)
-        .flatMap(splitConjunctivePredicates)
-      val filtersStayUp = filters.dropWhile(_.deterministic)
+      val numCanPushDown = (1 until filters.length)
+        .find(i => !canCombine(filters.take(i), filters(i)))
+        .getOrElse(filters.length)
+      val filtersCanPushDown = 
filters.take(numCanPushDown).flatMap(splitConjunctivePredicates)
+      val filtersStayUp = filters.drop(numCanPushDown)

Review Comment:
   **Non-blocking (P2):** `filtersStayUp` can now hold deterministic filters, 
but `PrepareExternalLookupJoin` treats it as a non-deterministic remainder, 
which a lookup side never has. It ANDs the stay-up filters back into the pushed 
ones with `(lookupPlan.filtersPushDown ++ 
lookupPlan.filtersStayUp).reduceOption(And)` 
(PrepareExternalLookupJoin.scala:235-236), evaluates the result as one 
predicate, and offers lookup candidates only from `filtersPushDown` and the 
upper stages (PrepareExternalLookupJoin.scala:458-463).
   
   By the review's reading of the code, in ANSI mode, take a lookup side 
`SELECT * FROM lt WHERE a = 1 OR b = 2` with `CAST(s AS INT) > 0` above it. It 
gets the segment filter `(a = 1 OR b = 2) AND CAST(s AS INT) > 0`, which fails 
with CAST_INVALID_INPUT on a looked-up row with `a = NULL, b = 3, s = 'x'`, a 
row that the view drops. Over such a view, a pushed-down comparison such as 
`r.tenant = my_udf('acme')` is no longer offered to the connector either. A 
connector whose access path needs it then selects nothing, and planning fails 
with NO_LOOKUP_PREDICATE. On the base branch, the filters were merged, so the 
comparison was offered and pushed.
   
   **Verification:**
   - **Regression:** In ANSI mode, an external lookup join whose lookup side 
has a filter that can fail above a filter that can be NULL returns the rows of 
the written query. It does not fail on a looked-up row that the lower filter 
drops as NULL.
   - **Regression:** A connector whose access path needs a comparison that now 
stays up above such a filter still receives that comparison among the offered 
lookup predicates, so planning does not fail with NO_LOOKUP_PREDICATE.
   - **Behavior:** Only the pushed-down filters reach the source. Each stay-up 
filter is evaluated on the returned rows after them, in order.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -314,12 +314,43 @@ trait PredicateHelper extends AliasHelper with Logging {
       conditions.span(cond => cond.deterministic && !cond.throwable)
     }
     lazy val failable = 
AttributeSet.fromAttributeSets(plans.map(failableOutput))
-    val (cannotFail, stayUp) = following.partition { cond =>
-      ExprUtils.canEvaluateUnconditionally(cond) && 
!cond.references.exists(failable.contains)
-    }
+    val (cannotFail, stayUp) = following.partition(!canFail(_, failable))
     (leading ++ cannotFail, stayUp)
   }
 
+  /**
+   * Returns true if the conjunct `cond` can fail on a row: 
[[ExprUtils.canEvaluateUnconditionally]]
+   * rejects it, or it reads a column in `failable`. A filter that 
`PartitionPruning` or
+   * `InjectRuntimeFilter` adds computes its subquery once, so only its key 
counts.
+   */
+  protected def canFail(cond: Expression, failable: => AttributeSet): Boolean 
= {
+    val computed = cond match {
+      case d: DynamicPruningSubquery => d.pruningKey
+      case BloomFilterMightContain(_: ScalarSubquery, XxHash64(Seq(key), _)) 
=> key

Review Comment:
   **Non-blocking (P2):** This case matches only an unmerged bloom filter. 
`MergeSubplans` runs after `InjectRuntimeFilter` and before the 'Pushdown 
Filters from PartitionPruning' batch (SparkOptimizer.scala:94-101), and it 
rewrites a merged bloom filter's subquery to 
`GetStructField(ScalarSubquery(...), i)`. The 
`PerPartitionRuntimeFilterSubquery` placeholder has no case either. Both fall 
through to `canEvaluateUnconditionally`, which rejects any subquery, although 
the Scaladoc above says that every filter `PartitionPruning` or 
`InjectRuntimeFilter` adds is judged by its key.
   
   `BloomFilterMightContain.nullable` is always true, so a filter that holds 
one bloom filter can be NULL. Take a join on two keys with one creation side, 
whose two bloom filters `MergeSubplans` merges, such as the query of 
InjectRuntimeFilterSuite's 'Merge runtime bloom filters' test. By the review's 
reading of the code, the second bloom filter stays in a separate filter with 
default configs. `FileSourceStrategy` then receives it among the stay-up 
filters, so it is not offered as a Parquet storage filter when 
`spark.sql.parquet.storageFilterPushdown.enabled` is on. 
`DataSourceV2Strategy`'s `PhysicalOperation` stops at it, so a DSv2 scan that 
declares runtime filter attributes does not receive it for runtime filtering. 
On the base branch, both were combined into the scan filter. That test counts 
subqueries only, so it still passes.
   
   **Verification:**
   - **Behavior:** CombineFilters combines a merged runtime bloom filter, and a 
per-partition runtime filter placeholder, each with a key that cannot fail, 
into a lower filter whose condition can be NULL, including a lower filter that 
holds another runtime bloom filter. It keeps them above that filter when their 
key can fail.
   - **Regression:** Take two runtime bloom filters over one creation side on 
one scan, which MergeSubplans merges, once with and once without a scan filter 
that can be NULL below them. Both end up in one filter over the scan, among its 
pushed filters, as on the base branch. The assertion inspects the filter 
directly above the scan.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -314,12 +314,43 @@ trait PredicateHelper extends AliasHelper with Logging {
       conditions.span(cond => cond.deterministic && !cond.throwable)
     }
     lazy val failable = 
AttributeSet.fromAttributeSets(plans.map(failableOutput))
-    val (cannotFail, stayUp) = following.partition { cond =>
-      ExprUtils.canEvaluateUnconditionally(cond) && 
!cond.references.exists(failable.contains)
-    }
+    val (cannotFail, stayUp) = following.partition(!canFail(_, failable))
     (leading ++ cannotFail, stayUp)
   }
 
+  /**
+   * Returns true if the conjunct `cond` can fail on a row: 
[[ExprUtils.canEvaluateUnconditionally]]

Review Comment:
   **Nit (P3):** The description defers a more precise test: 'The check is 
conservative, so this also holds for functions that can not fail in fact'. But 
this Scaladoc says canFail returns whether the conjunct 'can fail on a row'. 
Neither it nor the comments on `canCombine` (patterns.scala:106-113), 
`CombineFilters` (Optimizer.scala:2626-2631) and `ScanOperation` 
(patterns.scala:160-165) says something else: a conjunct that cannot fail in 
fact, such as `exp(bonus) > 0`, `upper(s) = 'A'` or a CASE WHEN, also stays 
above a filter that can be NULL and loses data-source pushdown and partition 
pruning. The JDBCV2Suite comment at JDBCV2Suite.scala:1293-1294 presents the 
EXP case as a filter that can fail. A short TODO here that names the 
conservative test and its cost would keep a later change from relying on 
canFail being exact.
   
   **Verification:**
   - **Inspection:** canFail's documentation names its conservative test, gives 
an example of a conjunct that cannot fail but still stays above, and names the 
pushdown and pruning that conjunct loses. The test comment that explains the 
single-filter rewrite says the same.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2626,12 +2626,12 @@ object CombineFilters extends Rule[LogicalPlan] with 
PredicateHelper {
     // 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. 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`.
+    // keeps in a filter in place of the top join, or can be NULL (see 
`canBeNull`), 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), afterBarrier = 
nc.throwable)
+      val (movable, rest) = splitMovable(splitConjunctivePredicates(fc), 
Seq(grandChild),
+        afterBarrier = nc.throwable || canBeNull(nc))

Review Comment:
   **Blocking (P1):** When `CombineFilters` keeps `fc` above `nc` over an inner 
join, `PushPredicateThroughJoin` pushes `nc` into the join condition in the 
same `PushDownPredicates` pass, and pushes `fc` on the next pass. Its barrier 
counts only a throwable or non-deterministic join conjunct 
(Optimizer.scala:3441-3443), and `newJoinConditions ++ joinCondition` 
(Optimizer.scala:3461) puts `fc` ahead of `nc`. `ExtractEquiJoinKeys` keeps 
that order, so the join evaluates `fc AND nc` on every key-matched pair. On the 
base branch, the two filters were merged first and pushed as `nc AND fc`, which 
stops at a FALSE `nc`.
   
   By the review's reading of the code, in ANSI mode with a(k, x) = (1, 3) and 
b(k, y) = (1, 3), this query
   
   ```scala
   a.join(b, a("k") === b("k")).where(a("x") > b("y"))
     .where(lit(10) / (a("x") - b("y")) > 1)
   ```
   
   returns no rows on the base branch, but fails with DIVIDE_BY_ZERO with this 
change, because the division now runs before `a.x > b.y`. The nested SQL form, 
`SELECT * FROM (SELECT a.x, b.y FROM a JOIN b ON a.k = b.k WHERE a.x > b.y) 
WHERE 10 / (x - y) > 1`, takes the same path. ReorderJoin does not flatten a 
join of two inputs, and all of this happens before Infer Filters, so any 
comparison over nullable columns counts as NULL-able. Inner joins in streaming 
queries get the same plan.
   
   **Recommended change:** In the inner-join case of PushPredicateThroughJoin 
(Optimizer.scala:3456-3461), put a filter's movable conjuncts that can fail 
after the existing join condition, and keep the ones that cannot fail ahead of 
it. Stacked filters over an inner join then keep their written order, as on the 
base branch. Add tests: optimizer filter pushdown tests for joins, and an 
end-to-end join test in ANSI mode.
   
   **Why this works:** Split the filter's conjuncts that move into the join 
condition with canFail, as splitMovable does. Build the condition from the 
conjuncts that cannot fail, then the existing condition, then the conjuncts 
that can fail. A conjunct that cannot fail only drops rows, so moving it ahead 
is safe. A conjunct that can fail now runs only after the conditions already in 
the join, and And stops at a FALSE one. For stacked filters, the condition 
becomes `nc AND keys AND fc` instead of `fc AND nc AND keys`.
   
   **Risks:** A WHERE conjunct that can fail is now evaluated after an inner 
join's ON conditions rather than before them. That changes the order of the 
join's other condition in plans and in EXPLAIN output, and a few TPC-DS plan 
stability files may change. Rows do not change, but errors change both ways. 
Such a WHERE conjunct no longer runs on a pair where an ON condition is FALSE. 
An ON conjunct that can fail now runs before it, so a query in which a FALSE 
WHERE conjunct kept such an ON conjunct from raising, such as ON a.k = b.k AND 
10 / (a.x - b.y) > 0 with WHERE a.x + b.z > 100 in ANSI mode, on a matched pair 
where a.x equals b.y and the sum is at most 100, now fails with the ON 
conjunct's error, as its ON clause does when evaluated as written.
   
   **Constraints:** Conjuncts that cannot fail keep their current place ahead 
of the existing condition, so join keys and their pushdown do not change.
   
   **Exclusions:**
   - A lower condition that is NULL on a matched pair still lets the upper 
conjunct run. The repair that adds the NULL barrier on join paths covers that 
case.
   
   **Verification:**
   - **Regression:** Run, in ANSI mode, stacked filters over a two-input inner 
join where both conditions read both sides, and the outer one divides by an 
expression that is zero on a matched pair where the inner one is FALSE. They 
return the base branch's rows instead of failing. Check both the DataFrame 
chain and the nested SQL subquery forms.
   - **Behavior:** At the optimizer level, a filter conjunct that can fail is 
placed after an inner join's existing condition, while a conjunct that cannot 
fail keeps its place ahead of it.



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