sarutak commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4617748623
##########
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)
Review Comment:
Thanks, confirmed: with ANSI on over a Parquet file, `x = 0.0 && CAST(x * y
AS STRING) = '-0.0'` drops the row `("-0.0", 1.0)` and returns `("-0.0", -1.0)`
on 3fe4437 and on 4.3.0, and the `pow` one drops its row too, while master is
right in all three.
Fixed, as master does it: a FLOAT or DOUBLE column whose constant is a zero,
or a column of a type with a FLOAT or DOUBLE in it, is now kept under an
operator that can tell -0.0 from 0.0, i.e. one that `ExprUtils.isTotalOperator`
does not accept and that is not arithmetic, which can fail in ANSI mode but
gives the same result, or fails, for either zero, unless master's
`replaceConstants` folds that operator, which it does where it reaches it and
every column under it gets a constant, e.g. `pow(d, 2) > 100` or `CAST(d AS
STRING) = '0.0'` as conjuncts; the rule now runs `replaceConstants` for that on
the condition as written, before the in-place replacement, so it folds in the
same places, and keeps the column e.g. in an operand that guards another one or
under a `CASE WHEN` that reads another column. One case is left as on 4.3.0:
the constant of another column that can fail, put in place, can end the
operator that guards such an operator, and a later iteration then folds it,
e.g. `
i < 0` in `(CAST(d AS STRING) = '-0.0' OR (i < 0 AND 10 / y > 1)) AND d = 0.0
AND i = 1`, which drops a -0.0 row as 4.3.0 does, where master returns it.
Keeping the constants out of such a conjunct fixes that row but fails queries
that master and 4.3.0 run (I tried it), so I left it with the fold path of
master, for after this PR. Folding such an operator, e.g. `CAST(d AS STRING) =
'0.0'`, still passes a row where `d` is -0.0, as on master and 4.3.0: keeping
`d` there would fail queries that both run, e.g. `CAST(d AS STRING) = '0.0' AND
id > 5 AND d = 0.0` over `("0.0", 7), ("x", 0)` with whole-stage codegen
(measured), so I left that with the fold path of master, for after this PR. Any
other value is equal only to itself, so `d = 1.0` still goes in everywhere, as
on 4.3.0.
Keeping the column has a cost that I don't think the rule can avoid: such a
conjunct reads the column, as written, so where 4.3.0 put the constant in and
the conjunct filtered out a row on which the column fails, the query now fails,
as on master. E.g. over the rows `("x", 1.0), ("0.0", 1.0)`, with `d` the alias
`cast(s as double)`, `CAST(d * y AS STRING) = '1.0' AND d = 0.0` returns no row
on 4.3.0 with whole-stage codegen and fails with `CAST_INVALID_INPUT` here and
on master. For `C(d, y) AND d = 0.0` with `C(0.0, y)` FALSE and `C(-0.0, y)`
TRUE, a row where `s` is 'x' and one where it is '-0.0' look the same until `d`
is computed: 4.3.0 skips both, the second one wrongly, and returning the second
one means computing `d` for the first. Keeping every FLOAT or DOUBLE column
under every operator that `ExprUtils.isTotalOperator` does not accept would
fail more queries that succeed on 4.3.0: over the same rows, `pow(d, 2) > 100
AND d = 0.0` and `10 / (d - y) > 0 AND d = 0.0` return
no row on 4.3.0 and with this PR, with whole-stage codegen, and `CAST(d * y AS
STRING) = '1.0' AND d = 2.0` returns no row on 4.3.0 and with this PR and fails
on master, while all three fail with `CAST_INVALID_INPUT` when every such
column is kept (I measured that variant too). The description now says this.
`ConstantPropagationSuite` covers these cases, and `DataFrameSuite` the ones
that succeed.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -195,14 +200,29 @@ object ConstantPropagation extends Rule[LogicalPlan] with
PredicateHelper {
(None, AttributeMap(Map(right -> (left, e))))
case a: And =>
val (newLeft, equalityPredicatesLeft) =
- traverse(a.left, replaceChildren = false, nullIsFalse)
+ traverse(a.left, replaceChildren = false, nullIsFalse, columns)
val (newRight, equalityPredicatesRight) =
- traverse(a.right, replaceChildren = false, nullIsFalse)
+ traverse(a.right, replaceChildren = false, nullIsFalse, columns)
val equalityPredicates = equalityPredicatesLeft ++
equalityPredicatesRight
val newSelf = if (equalityPredicates.nonEmpty && replaceChildren) {
val unreplaced = And(newLeft.getOrElse(a.left),
newRight.getOrElse(a.right))
- Some(moveEqualitiesFirst(
- unreplaced, replaceConstants(unreplaced, equalityPredicates),
equalityPredicates))
+ val (movable, failable) = equalityPredicates.toSeq.partition { case
(attr, _) =>
+ columns.canEvaluateUnconditionally(attr)
+ }
+ val substituted = if (failable.isEmpty) {
+ Some(unreplaced)
+ } else {
+ replaceConstantsInPlace(unreplaced, AttributeMap(failable))
+ }
+ Some(substituted match {
+ case Some(condition) if movable.isEmpty => condition
+ case Some(condition) => moveEqualitiesFirst(condition,
+ replaceConstants(condition, AttributeMap(movable)),
AttributeMap(movable), columns)
Review Comment:
Confirmed both. Fixed as you suggested: for an AND with an equality over a
column that can fail, the rule now also folds the conjuncts that the constants
change with the constants of all of the equalities in place, as 4.3.0 would
have them, with `ConstantFolding`, `SimplifyConditionals` and
`BooleanSimplification`, and the condition is FALSE where one of them becomes
FALSE, or NULL in a filter, which `ReplaceNullWithFalseInPredicate` makes FALSE
on 4.3.0. These constants include those of equalities that a later iteration
folds, e.g. `id = CAST(7 AS BIGINT)` for a BIGINT `id`, which 4.3.0 put in
during the next iteration, unless the constant is NULL, which `NullPropagation`
handles first. Both of your conditions are now pruned, as on 4.3.0, also with a
BIGINT `id`, with the filter kept above the projection or pushed below it, and
so are `CASE WHEN id > 10 THEN 10 / x END > 1` without an `ELSE`, and `(id < 7
AND 10 / x > 1) OR (id > 7 AND 10 / x > 2)` in place of the `CASE WHEN`, wh
ich takes `BooleanSimplification`. It now runs the other rules of the batch
that rewrite a filter condition too, in the batch's order, e.g.
`NullPropagation` for `CASE WHEN id > 10 THEN x END + x > 1`, which
`SimplifyConditionals` makes `NULL + x > 1`; a conjunct that only a rule that
rewrites the plan makes FALSE is not caught.
##########
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:
Confirmed all three, also over an empty table. Fixed: each conjunct that the
constants change is now folded both as rewritten and with the constants of all
of the equalities in place (see [2]), with the foldable columns of the filter's
child in, which `FoldablePropagation` collects through the projections, also
from an expression over another foldable column, and through the other
operators it looks through, also from an `Aggregate`, through an `Expand` and
from either side of a `Join`, but not a column that an outer join can make
NULL, as `FoldablePropagation` does. Where one fails to fold with all of the
constants in, the equalities are handled as on master. All three now return no
row, as on master, also over an empty table. This also covers `if(five > 0, 10
/ i, 0) > 0 AND i = 0`, with `five` the alias `lit(5)`, which the description
listed as failing while optimized, as on 4.3.0: it now returns no row, as on
master, and I removed it from that list.
The other way around (spark-test's 4593935491), a conjunct that fails to
fold only as rewritten, as `replaceConstants` does not put `id = 7` into an
operand that decides whether one that can fail runs, is now replaced with what
it folds to with all of the constants in, instead of falling back, and if that
can fail, the other equalities go first: `x > 0 AND (id > 0 OR 10 / i > 1) AND
i = 0 AND id = 7` becomes `id = 7 AND x > 0 AND i = 0`, and `((id > 10 AND 10 /
i > 1) OR 10 / x > 5) AND i = 0 AND id = 7` becomes `id = 7 AND 10 / x > 5 AND
i = 0`, which return `("0", 7)` as 4.3.0 does with whole-stage codegen. The
check also folds in the batch's order and does not fold again a part that
failed in a conditional branch once another rule takes it out of the branch, as
`ConstantFolding` skips a tagged one, so it does not fall back where the batch
would not fail. I narrowed the sentence of the description to the rules that
the check runs and the operators it looks through.
##########
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)) ||
+ conjuncts.drop(firstRewritten +
1).exists(!columns.canEvaluateUnconditionally(_)))
Review Comment:
Right. In the fallback the rule now orders the equalities exactly as master
does, with `ExprUtils.canEvaluateUnconditionally` alone, which is what the
description says. Your example no longer falls back: the rewritten condition
folds, `id = 7` folds the second conjunct to TRUE and goes first, as `i = 0`
after it can fail, and over your rows it returns `("0", 7)` with codegen on, as
master and 4.3.0. The fallback order is pinned by a test where `10 / zero`,
with `zero` the alias `lit(0.0)`, makes the condition fail to fold.
##########
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))
+ }
+
+ /**
+ * Whether [[ConstantFolding]] folds `e`, an AND in a filter condition,
without an error, which
+ * it raises for a part of `e` that becomes constant and fails, except in a
conditional branch.
+ * It tags the parts that fail in one, which can be shared with the plan, so
the tags it sets
+ * are removed.
+ */
+ private def foldsWithoutError(e: Expression): Boolean = {
+ val tagged = java.util.Collections.newSetFromMap(
+ new java.util.IdentityHashMap[Expression, java.lang.Boolean]())
+ e.foreach(n => if
(n.getTagValue(ConstantFolding.FAILED_TO_EVALUATE).isDefined) tagged.add(n))
+ try {
+ ConstantFolding.constantFolding(e)
+ true
+ } catch {
+ case NonFatal(_) => false
+ } finally {
+ e.foreach { n =>
+ if (!tagged.contains(n))
n.unsetTagValue(ConstantFolding.FAILED_TO_EVALUATE)
Review Comment:
Done, a bit differently: the check folds a copy of the conjunct, made with
`clone`, which keeps the tags, so `ConstantFolding` tags only the parts of the
copy, and the other rules carry a tag over to what they rewrite a part into, as
in the batch, e.g. `NOT (10 / 0 > 1)` into `10 / 0 <= 1`. No node of the plan
is tagged or untagged; a replacement that goes into the plan keeps the tags set
on the copy, as `ConstantFolding` would set them there. The two walks for the
tags are gone. `clone` fails for some expressions, e.g. the test Python UDF;
for a conjunct with one of those, `ConstantFolding.constantFolding` takes a
`failed` set instead, into which the check collects the parts that fail in a
conditional branch and which it then skips like tagged ones. That set misses a
part once another rule rewrites it, so such a conjunct can fail to fold where
the batch would not, and the equalities are then handled as on master.
##########
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)) ||
+ conjuncts.drop(firstRewritten +
1).exists(!columns.canEvaluateUnconditionally(_)))
if ((keepsFailable || unmasksFailable) && reordered != conjuncts) {
reordered.reduce(And)
} else {
condition
}
}
+ /**
+ * The columns of `plan` that can fail, i.e. those that a projection at its
top, or below the
+ * filters, samples and projections there, computes with a deterministic
expression that
+ * [[ExprUtils.canEvaluateUnconditionally]] rejects or that reads such a
column, or passes such a
+ * column through. Under whole-stage codegen, the projection computes a
deterministic column for a
+ * row only when a conjunct of the filter above first reads it, unless its
subexpression
+ * elimination computes it up front, and `PushPredicateThroughNonJoin`
pushes a conjunct below the
+ * projection with the expression of the column substituted. So a conjunct
over such a column can
+ * fail as that expression does. A non-deterministic column is computed on
every row the
+ * projection gets, and no filter is pushed through a projection with one,
so it does not count.
+ * Other operators are not looked through. The columns are collected once
per filter, when needed.
+ */
+ private class FailableColumns(plan: LogicalPlan) {
Review Comment:
Agreed. Your example failed the same way on 4.0.0 through 4.3.0 and master
until #60631 (SPARK-61886) fixed it in `CombineFilters` with
`PredicateHelper.failableOutput`, which SPARK-61823 added with the same notion
and SPARK-61921 extended through limits, offsets, sorts, joins and
aggregations; it returns no row on master and this PR now. This PR now counts
the columns through those operators but a global aggregation, and through
unions, lateral joins, CTEs that are not inlined and serializers from objects,
which also fixes queries above them that fail on master and succeed on 4.3.0
(the description lists the one case left). It keeps its own walk for now, for
two differences that sharing `failableOutput` would have to settle, which I'd
like to do in a follow-up:
- For `InferFiltersFromConstraints` and `CombineFilters`, counting a column
as one that can fail is the conservative side, but here the constant of an
equality over it goes in place, as on 4.3.0, which can make a conjunct fail on
a row where the equality does not hold, where moving the equality first would
not. So this PR leaves out the result columns of a global aggregation, which it
computes for its one row up front, while `failableOutput` counts them.
- `failableOutput` does not look through the other operators above, so those
queries would fail again; adding them there changes the filters that the other
two rules infer and combine.
The walk also keeps what it finds for each plan node ([7]).
--
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]