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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -316,34 +401,89 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
    * Moves the equalities ahead of the other conjuncts of `condition`, the 
rewritten `original`, if
    * one that can fail still refers to a propagated attribute. Such a conjunct 
also runs on rows
    * where an equality does not hold, with the value of the row, while a guard 
over the same
-   * attribute may be folded away, e.g. `n / d > 1` for `d <> 0 AND n / d > 1 
AND d = 5`. The
-   * same holds for a conjunct that can fail after one that is rewritten, as 
that one decides
-   * whether it runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. 
An equality between
-   * an attribute and a literal cannot fail, so running it first raises no 
error.
+   * attribute may be folded away, e.g. `n / d > 1` for `d <> 0 AND n / d > 1 
AND d = 5`. The same
+   * holds for a conjunct that can fail after one that is rewritten, as that 
one decides whether it
+   * runs, e.g. `10 / x > 0` for `y > 0 AND 10 / x > 0 AND y = 1`. A conjunct 
over a column of the
+   * projection below that can fail can fail too (see [[FailableColumns]]), 
e.g. `i > 0`, with `i`
+   * the alias `CAST(s AS INT)`, in ANSI mode. The first rewritten conjunct 
counts too, not only the
+   * ones after it, if it reads such a column, as [[replaceConstants]] 
rewrites its operands as if
+   * the column could not fail, e.g. `id < 3` in `(id < 3 OR i > 0) AND id = 
7`.
+   * `equalityPredicates` are the equalities over a column that can not fail, 
which can not fail
+   * themselves, so running them first raises no error. The ones over a column 
that can fail stay
+   * where they are written (see [[replaceConstantsInPlace]]), and `original` 
has their constants
+   * already, unless the condition fails to fold with them, where 
`equalityPredicates` are all of
+   * the equalities, as since SPARK-60983. `keepsFailable` checks the 
attributes a conjunct reads
+   * against those of `equalityPredicates`, not those that the expressions of 
its columns read,
+   * which these equalities do not replace.
    */
   private def moveEqualitiesFirst(
       original: Expression,
       condition: Expression,
-      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Expression = {
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)],
+      columns: FailableColumns): Expression = {
     val predicates = equalityPredicates.values.map(_._2).toSet[Expression]
     val propagated = AttributeSet(equalityPredicates.keys)
     val conjuncts = splitConjunctivePredicates(condition)
     val (equalities, others) = conjuncts.partition(predicates.contains)
     val reordered = equalities ++ others
     val keepsFailable = others.exists { c =>
-      c.references.intersect(propagated).nonEmpty && 
!ExprUtils.canEvaluateUnconditionally(c)
+      c.references.intersect(propagated).nonEmpty && 
!columns.canEvaluateUnconditionally(c)
     }
     val firstRewritten = splitConjunctivePredicates(original).zip(conjuncts)
       .indexWhere { case (before, after) => !before.fastEquals(after) }
-    val unmasksFailable = firstRewritten >= 0 &&
-      conjuncts.drop(firstRewritten + 
1).exists(!ExprUtils.canEvaluateUnconditionally(_))
+    val unmasksFailable = firstRewritten >= 0 && 
(columns.reads(conjuncts(firstRewritten)) ||

Review Comment:
   **Non-blocking (P2):** Whenever the first rewritten conjunct reads a column 
that can fail, this sends the equalities over the other columns to the front, 
also when the rewrite unmasks nothing because the operand over that column 
comes before the rewritten one; the column-aware keepsFailable at L430 does the 
same for a conjunct that ExprUtils accepts but that reads such a column. A 
non-deterministic conjunct written before the equalities then runs on fewer 
rows. By the review's reading of the code, `rand(42) < 0.5 AND (i > 0 OR id > 
3) AND id = 7` becomes `id = 7 AND rand(42) < 0.5`, while master keeps 
`rand(42) < 0.5 AND id = 7`, so the seeded rand is drawn only for rows with 
`id` 7 and returns another set of rows, with no error, and a side-effecting 
non-deterministic UDF runs fewer times. Here `i > 0` comes before the rewritten 
operand, so the OR reads `i` as written and nothing needed to move. Master 
already moves equalities past a non-deterministic conjunct written after the fi
 rst rewritten one, as in `y > 0 AND rand() < 0.5 AND y = 1`; this widens the 
inputs that get it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60516#discussion_r4581795950).
   
   **Recommended change:** When moveEqualitiesFirst moves the equalities, place 
them after every non-deterministic conjunct that comes before all the conjuncts 
the move protects, that is, before the first rewritten conjunct and before the 
first conjunct that can fail and still reads a propagated attribute, instead of 
at the very front; the protected conjuncts stay behind them. Cover it with 
ConstantPropagation plan tests that check the order of the conjuncts with a 
non-deterministic conjunct written before the equalities.
   
   **Why this works:** A non-deterministic conjunct that comes before every 
conjunct the move protects needs no protection from it, as the rewrite did not 
change what guards it, so keeping it ahead of the equalities keeps its written 
number and order of evaluations, while every protected conjunct still runs only 
on the rows the equalities keep.
   
   **Scope:** Keep the non-deterministic conjuncts that need no protection 
ahead of the moved equalities.
   
   **Risks:** The base branch's own moves change too where a non-deterministic 
conjunct comes before the first protected one, e.g. `rand() < 0.5 AND y > 0 AND 
10 / x > 0 AND y = 1` now becomes `rand() < 0.5 AND y = 1 AND 10 / x > 0`, so 
deterministic conjuncts written before such a non-deterministic one run on 
every row, as written, rather than only on the rows the equalities keep.
   
   **Constraints:** A conjunct written after the first rewritten one, 
non-deterministic or not, stays behind the equalities, so a guard the rewrite 
folded away still protects it. The fallback's checks, as the fallback repair 
sets them, decide whether to move; this repair decides only where the 
equalities go.
   
   **Exclusions:**
   - A non-deterministic conjunct that the move protects, one written after the 
first rewritten conjunct, still runs on fewer rows than written, as on the base 
branch, because keeping it ahead could raise an error that the written 
condition does not.
   
   **Success:** `rand(42) < 0.5 AND (i > 0 OR id > 3) AND id = 7` over a column 
`i` of the projection that can fail keeps `rand(42) < 0.5` first. `rand(42) < 
0.5 AND (i > 0 OR length(c) > 0) AND c = 'a'`, with `c` a UTF8_LCASE string, 
keeps `rand(42) < 0.5` first and `c = 'a'` ahead of the OR. Conditions without 
a non-deterministic conjunct, the PR's target queries among them, keep their 
plans.
   
   **Verification:**
   - **Regression:** ConstantPropagation plan checks with ANSI mode on and with 
the order of the conjuncts show that the two conditions above keep the seeded 
rand first, and that `rand() < 0.5 AND y > 0 AND 10 / x > 0 AND y = 1` becomes 
`rand() < 0.5 AND y = 1 AND 10 / x > 0`.
   - **Compatibility:** A plan check shows that a non-deterministic conjunct 
written after the first rewritten one, as in `y > 0 AND rand() < 0.5 AND y = 
1`, still goes behind the moved equality.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -236,6 +256,68 @@ object ConstantPropagation extends Rule[LogicalPlan] with 
PredicateHelper {
   private def safeToReplace(ar: AttributeReference, nullIsFalse: Boolean) =
     !ar.nullable || nullIsFalse
 
+  /**
+   * Replaces the attributes of `equalityPredicates` with their constants in 
the comparisons of
+   * `condition` other than those equalities, where they are written, as 
before SPARK-60983, or
+   * returns None if `condition` would then fail to fold. These are the 
equalities over a column of
+   * the projection below that can fail (see [[FailableColumns]]), e.g. `i = 
1` with `i` the alias
+   * `CAST(s AS INT)`. Such an equality can fail, so it can not go first, as 
it would compute the
+   * column on rows that the conjuncts before it filter out. A comparison that 
it rewrites no longer
+   * reads the column, so the conditions read the column in no more places 
than written. A rewritten
+   * conjunct can fail on a row where the equality does not hold, e.g. `10 / 
(id - 1)` for
+   * `10 / (id - i) > 0 AND i = 1` on a row where `id` is 1 and `i` is 2, a 
conjunct after one that
+   * the constant folds away can run on such a row, e.g. `10 / x > 0` for
+   * `i > 0 AND 10 / x > 0 AND i = 1`, and a rewritten conjunct can pass a row 
on to another such
+   * equality that the written one stops, e.g. `j < 5` for `j < 5 AND i = 2 
AND j = 1`, as before
+   * SPARK-60983. A condition that would fail to fold, outside of a 
conditional branch, e.g. with
+   * `id > 10 / 0` for `i = 0 AND id > 10 / i`, failed the query before 
SPARK-60983, unless a rule
+   * before [[ConstantFolding]] removed the part that fails, e.g. 
[[FoldablePropagation]], so the
+   * caller then handles its equalities as since SPARK-60983. As before, an 
attribute whose type is
+   * not binary stable is replaced only in a comparison with an attribute of 
the same type (see
+   * [[isSameCollationAttrRefComparison]]), one outside of a comparison, e.g. 
in `i IN (1, 2)`, is
+   * kept, and one in the correlation of a subquery in a comparison is 
replaced.
+   */
+  private def replaceConstantsInPlace(
+      condition: Expression,
+      equalityPredicates: AttributeMap[(Literal, BinaryComparison)]): 
Option[Expression] = {
+    val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit, 
_)) => attr -> lit })
+    val predicates = equalityPredicates.values.map(_._2).toSet
+    def replaceInComparison(b: BinaryComparison): Expression = {
+      lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
+      b transform {
+        case a: AttributeReference
+          if isBinaryStable(a.dataType) || collationSafeReplacement =>
+          constantsMap.getOrElse(a, a)
+      }
+    }
+    val rewritten = 
condition.transformWithPruning(_.containsPattern(BINARY_COMPARISON)) {
+      case b: BinaryComparison if !predicates.contains(b) => 
replaceInComparison(b)
+    }
+    Some(rewritten).filter(r => r.fastEquals(condition) || 
foldsWithoutError(r))

Review Comment:
   **Non-blocking (P2):** This decides the fallback on the condition with only 
the constants of the equalities over a column that can fail, but 4.3.0 put 
every constant in at once, so another equality's constant could make an 
enclosing OR, AND or IN fold whole and skip the part that fails. For example, 
with ANSI mode on, INT columns `id` and `x` and the filter kept above the 
projection, `x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 AND id = 7` fails to 
fold here, as `10 / 0 > 1` is folded on its own. The rule then falls back, 
moves `i = 0` first and, by the review's reading of the code, raises 
CAST_INVALID_INPUT on ('x', 0, 0), while 4.3.0 folds `7 > 0 OR 10 / 0 > 1` to 
TRUE, keeps the written order and returns ('0', 7). Such conditions keep the 
failure this PR fixes, although the comments at the fallback say that they 
failed before SPARK-60983. With a BIGINT `id`, 4.3.0 too puts in only the 
constant of `i` during the first pass and fails, so that variant is not 
affected.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60516#discussion_r4591709813), 
[2](https://github.com/apache/spark/pull/60516#pullrequestreview-5927871431).
   
   **Recommended change:** Take the fallback only where the conjuncts that fail 
to fold do not become literals with every constant in place, and run it with 
master's checks. When the condition with the in-place constants fails to fold, 
put the constants of the other equalities into each conjunct that fails, 
through the same guarded substitution, and fold it without changing shared 
tags, as the mixed-equality check does. When each such conjunct then folds to a 
literal without an error, as on 4.3.0, replace it with that literal and 
continue on the in-place path with master's handling of the other equalities, 
passing the in-place condition from before the replacement to 
moveEqualitiesFirst as the original, so that a replaced conjunct counts as 
rewritten and the other equalities go ahead of the conjuncts it unmasks. 
Otherwise handle every equality as master does, calling moveEqualitiesFirst 
with no column counted as able to fail, so its checks are master's, and add a 
TODO there that name
 s the conditions 4.3.0 runs but that still fall back: those whose conjunct 
that fails to fold becomes, with every constant in place, a value that still 
reads another column. Correct the comments at the fallback and in 
replaceConstantsInPlace's scaladoc to say when the fallback is taken. Cover the 
shapes with ConstantPropagation plan tests that check the order of the 
conjuncts and with end-to-end DataFrame filter tests.
   
   **Why this works:** A conjunct that folds to a literal with every constant 
in place has that value on every row on which the equalities hold, and a 
literal is never evaluated, so the replacement raises no error and keeps the 
rows the filter returns, while master's handling still moves the other 
equalities ahead of each conjunct that the replacement unmasks or that still 
reads them and can fail. So a condition whose failing conjuncts all fold away 
is no longer failed while it is optimized, keeps the in-place handling of the 
equality over the column that can fail, and gives the other equalities master's 
handling, not 4.3.0's; and every condition that still falls back is judged with 
master's checks, so it keeps the written order wherever they do.
   
   **Scope:** Replace each conjunct that fails to fold with the literal it 
folds to with every constant in place, fall back only when one does not become 
a literal, and run the fallback with master's checks.
   
   **Compatibility:** Conditions that take the in-place path today keep their 
plans, and so do the conditions that fall back because 4.3.0 failed to optimize 
them, such as `id > 5 AND i + 1 > 0 AND x > 10 / i AND i = 0`.
   
   **Risks:** A condition that falls back today and whose failing conjuncts all 
fold to literals now takes the in-place path, so its equality over the column 
that can fail stays where it is written, with the cases of SPARK-60983 and 
SPARK-61033 that the PR accepts for such an equality, as on 4.3.0; the other 
equalities keep master's handling. The extra substitution and fold run only for 
conditions that fail the current check.
   
   **Constraints:** Put the other constants in and fold exactly as the 
mixed-equality check does, through the guarded substitution and without 
changing shared tags, and run that check first, so that a conjunct that becomes 
FALSE is handled there. Replace a conjunct only with a literal, so that the 
other equalities' constants never stay under an operator that master's handling 
keeps them out of, and keep every other conjunct as the in-place step left it. 
Keep the success path's column-aware checks. The placement repair's change to 
where the equalities go applies to the fallback too; this repair changes only 
which checks decide whether they move.
   
   **Exclusions:**
   - A part that only a later rule, such as FoldablePropagation or 
SimplifyConditionals, makes constant and that then fails while the query is 
optimized stays as on 4.3.0, as the PR accepts.
   - A condition whose conjunct that fails to fold becomes, with every constant 
in place, a value that still reads another column, e.g. `CAST(id > 0 OR 10 / i 
> 1 AS INT) + x > 0 AND i = 0 AND id = 7`, still falls back to master's 
handling, which moves every equality first, although 4.3.0 does not compute `i` 
on the rows that `1 + x > 0` drops; covering it would leave the other 
equalities' constants under an operator that master's handling keeps them out 
of, and the TODO at the fallback names it.
   
   **Success:** Over INT columns `id` and `x` and a column `i` of the 
projection that can fail, `x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 AND id = 
7` no longer falls back, keeps `x > 0` ahead of `i = 0`, and returns ('0', 7) 
over the rows ('0', 7, 1) and ('x', 0, 0). `x > 0 AND CAST(id > 5 OR 10 / i > 1 
AS INT) = 1 AND i = 0 AND id = 7` no longer falls back, keeps `x > 0` ahead of 
`i = 0`, and returns ('0', 7) over the same rows. `x > 0 AND CAST(id > 5 OR 10 
/ i > 1 AS INT) <= x AND i = 0 AND id = 7` still falls back and keeps master's 
order `x > 0 AND 1 <= x AND i = 0 AND id = 7`, so it returns ('0', 7) over the 
same rows. `10 / (x - id) > 0 AND x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 
AND id = 7` puts `id = 7` ahead of the division, so it raises no error on the 
row ('0', 8, 7). `id > 5 AND i + 1 > 0 AND x > 10 / i AND i = 0`, which 4.3.0 
failed to optimize, still becomes `i = 0 AND id > 5 AND x > 10 / i`.
   
   **Verification:**
   - **Regression:** ConstantPropagation plan checks with ANSI mode on, INT 
columns `id` and `x` and the order of the conjuncts show that the OR condition 
and the cast-of-OR condition compared with `= 1` keep `x > 0` ahead of `i = 0`, 
that the cast-of-OR condition compared with `<= x` becomes `x > 0 AND 1 <= x 
AND i = 0 AND id = 7`, that the division condition puts `id = 7` ahead of `10 / 
(x - id) > 0`, and that `id > 5 AND i + 1 > 0 AND x > 10 / i AND i = 0` still 
becomes `i = 0 AND id > 5 AND x > 10 / i`.
   - **Regression:** End-to-end ANSI-mode DataFrame queries over one Parquet 
file with INT columns `id` and `x` and the rows ('0', 7, 1) and ('x', 0, 0), 
with the filter kept above the projection by a non-deterministic column read 
above it, return ('0', 7) for the three conditions that start with `x > 0` 
instead of raising CAST_INVALID_INPUT, and the division condition over the row 
('0', 8, 7) returns no row and raises no error.
   - **Inspection:** The comments at the fallback and in 
replaceConstantsInPlace's scaladoc say that the fallback is taken only where a 
conjunct that fails to fold does not become a literal with every constant in 
place and that it judges the conjuncts with master's checks, and a TODO at the 
fallback names the conditions 4.3.0 runs that still take 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