dongjoon-hyun commented on code in PR #60337:
URL: https://github.com/apache/spark/pull/60337#discussion_r4540714251
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -195,9 +199,8 @@ object ConstantPropagation extends Rule[LogicalPlan] with
PredicateHelper {
traverse(a.right, replaceChildren = false, nullIsFalse)
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))
+ Some(replaceConstants(
Review Comment:
**[1] Without `moveEqualitiesFirst`, some queries that succeed on released
versions and on master now fail.**
SPARK-60983 and SPARK-61033 leave a conjunct, or an operand of one, as it is
when it keeps a propagated attribute in an expression that can fail, or guards
one. `moveEqualitiesFirst` was what kept such a conjunct off the rows that the
equality drops. Without it, these conditions run as written, while released
versions rewrite them and master moves the equality first. With ANSI mode on,
each over one Parquet file:
```scala
// (n, d) = (10, 0), (10, 5)
df1.where($"n" / $"d" > 1 && $"d" === 5)
// (a, c) = (2, 0), (5, 1)
df2.where(($"a" > 3 || lit(10) / $"c" > 1) && $"a" === 5)
```
- 4.1.4 and 4.3.0 return `[10,5]` and `[5,1]`: `n / d` becomes `n / 5`, and
`a > 3` becomes `true`.
- Master returns the same rows, as it moves the equality first.
- This PR keeps `n / d`, as the division can fail and `n` is not constant,
and `a > 3`, as it guards the division, and moves nothing, so both fail with
`DIVIDE_BY_ZERO` on the first row.
I ran the released versions, and checked the failure on 4.1.4 and 4.3.0 with
`spark.sql.optimizer.excludedRules` set to `ConstantPropagation`, which leaves
the conditions as this PR does; I did not run this PR's code. So "as in
released versions" in the description does not hold for these shapes, and
`checkInOrder(notConstant, notConstant)` (`ConstantPropagationSuite.scala:239`)
now asserts the written order for the first one. As ANSI mode is on by default,
a filter like `amount / qty > 10 AND qty = 5` that starts failing after an
upgrade looks like the most visible change of this PR. Could the equalities
still go first when every conjunct they pass is deterministic, which keeps the
fix for the non-deterministic case, leaving the case of #59940 to SPARK-61437?
Otherwise, could the description list this as a change from released versions?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
Review Comment:
**[2] `InferFiltersFromConstraints` still puts derived conditions ahead of a
non-deterministic conjunct, so it can still see other rows than as written.**
This rule now leaves `x > a` before `rand(10) < 0.5` in `x > a AND rand(10)
< 0.5 AND a = 1`. But `inferConstraintsFromLiteralBindings` (SPARK-57437)
derives `x > 1` from `x > a` and `a = 1`, and `InferFiltersFromConstraints`
puts it in front of the whole condition ([`Optimizer.scala`
L2281](https://github.com/apache/spark/blob/f24daffd581f60991e085365244b4b87a9b1485e/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala#L2281)).
A row like `(x, a) = (1, 0)` then no longer reaches `rand`, so the draws of
the later rows shift. With `spark.range(0, 100, 1, 1).select($"id", $"id" % 4
as "x", $"id" % 3 as "a")` in one Parquet file and ANSI mode off:
- As written, `df.where($"x" > $"a").where(rand(10) < 0.5)` keeps 9 rows
with `a = 1`.
- 4.3.0 with `ConstantPropagation` excluded, which leaves this condition as
this PR does, returns 3.
- 4.3.0 with the rule returns 6.
The filter of the second one is:
```
((((x > 1L) AND (x IS NOT NULL)) AND (a IS NOT NULL)) AND
(((x > a) AND (rand(10L) < 0.5D)) AND (a = 1L)))
```
The new `DataFrameSuite` test passes because `a > 0` with `a = 1` derives
nothing about another column. So the goal in the description, a
non-deterministic condition seeing the rows it sees as written, also needs
`InferFiltersFromConstraints` to leave the conjuncts before such a condition
alone, e.g. by adding the inferred filters after the last non-deterministic
conjunct. Could the description say this is still open, or could it go into a
JIRA with SPARK-61437?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
+ val attributeOf: Map[Expression, Attribute] = equalityPredicates
+ .map { case (attr, (_, predicate)) => (predicate: Expression) -> attr
}.toMap
+ val constants =
+ AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr ->
lit })
+ val conjuncts = splitConjunctivePredicates(condition)
+ // `replaceInConjunct` keeps the propagated equalities, which do not fold.
+ val isContradiction = conjuncts.exists { conjunct =>
+ fold(replaceInConjunct(conjunct, constants, _ => true,
predicates)).contains(FalseLiteral)
+ }
+ if (isContradiction) {
+ FalseLiteral
+ } else {
+ val equalityAttributes = conjuncts.map(attributeOf.get)
+ // The position of the first conjunct that is the propagated equality
over each attribute,
+ // or a copy of it. Another equality over the attribute, e.g. `1 = a`
for `a = 1`, is not.
+ val firstEquality = equalityAttributes.zipWithIndex
Review Comment:
**[6] Nit: only a copy of the last equality counts as one before a conjunct,
so an earlier `1 = a` or `a <=> 1` does not give its constant.**
`attributeOf` matches with `==`, so an earlier `1 = a`, `a <=> 1`, or `a =
1` whose attribute has another qualifier is not a copy of the propagated `a =
1`, although it fixes the same value on the rows that reach the conjuncts after
it. In `1 = a AND c > a AND rand() < 0.5 AND a = 1`, `c > a` stays, where
master and released versions have `c > 1`. Could `firstEquality` take the first
`EqualTo` or `EqualNullSafe` between the attribute and an equal literal, on
either side? The `otherForm` test would then expect `1 > 0` for `a > 0`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
Review Comment:
**[3] On master, a filter with whole-stage codegen no longer drops a row at
the first NULL conjunct, so SPARK-61438 is not limited to an OR.**
SPARK-60315, which is in master only, makes the generated filter go on with
the remaining conjuncts after a NULL one when a later conjunct can raise, as
`And.eval` does (`spark.sql.legacy.filterShortCircuitOnNullConjunct` is `false`
by default). So the rows where an `EqualTo` is NULL also reach the conjuncts
after it in a top-level filter, when no `isnotnull` check drops them first,
e.g. with `spark.sql.constraintPropagation.enabled` set to `false`. With ANSI
mode on, `y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0` over `(y, x) = (NULL,
0)` then divides by zero once the middle conjunct becomes `true`, while without
the rule `coalesce(y, 0) > 0` is `false` there and stops it. I traced this from
the code and did not run it.
So L271-273 hold on branch-4.x but not on master. Could the comment, and the
description, say that on master it also applies to a top-level filter without
an `isnotnull` check on the attribute?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
+ val attributeOf: Map[Expression, Attribute] = equalityPredicates
+ .map { case (attr, (_, predicate)) => (predicate: Expression) -> attr
}.toMap
+ val constants =
+ AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr ->
lit })
+ val conjuncts = splitConjunctivePredicates(condition)
+ // `replaceInConjunct` keeps the propagated equalities, which do not fold.
+ val isContradiction = conjuncts.exists { conjunct =>
+ fold(replaceInConjunct(conjunct, constants, _ => true,
predicates)).contains(FalseLiteral)
Review Comment:
**[4] Pre-existing: folding with the constant ignores that `-0.0 = 0.0`, and
`isContradiction` now turns that into `false` for the whole condition.**
`ExprUtils.isTotalOperator` leaves out a cast of a `DOUBLE` to a `STRING`,
as it tells `-0.0` from `0.0`, which `=` treats as equal. But when every
reference of an expression is propagated, the fold arm of `replace` (L350-351)
puts the constant in whatever the expression is, and this check does the same
with all the constants. Over a Parquet file with a `DOUBLE` column `a` holding
`-0.0` and `1.0`, `where($"a" === 0.0 && $"a".cast("string") === "-0.0")`
returns `[-0.0]` without the rule and no row with it. I ran it on 4.3.0, and
from the code it is the same on master and with this PR.
So it is not from this PR, and a separate JIRA may fit better. As
`isContradiction` is a new user of that fold, though, could it and the fold arm
skip a constant that is or contains a floating-point zero?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
+ val attributeOf: Map[Expression, Attribute] = equalityPredicates
+ .map { case (attr, (_, predicate)) => (predicate: Expression) -> attr
}.toMap
+ val constants =
+ AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr ->
lit })
+ val conjuncts = splitConjunctivePredicates(condition)
+ // `replaceInConjunct` keeps the propagated equalities, which do not fold.
+ val isContradiction = conjuncts.exists { conjunct =>
+ fold(replaceInConjunct(conjunct, constants, _ => true,
predicates)).contains(FalseLiteral)
+ }
+ if (isContradiction) {
+ FalseLiteral
+ } else {
+ val equalityAttributes = conjuncts.map(attributeOf.get)
+ // The position of the first conjunct that is the propagated equality
over each attribute,
+ // or a copy of it. Another equality over the attribute, e.g. `1 = a`
for `a = 1`, is not.
+ val firstEquality = equalityAttributes.zipWithIndex
+ .collect { case (Some(attr), i) => attr.exprId -> i }
+ .groupMapReduce(_._1)(_._2)(math.min)
+ // `equalitiesAfter` holds the attributes of the equalities after the
conjunct with only
+ // conjuncts that can be evaluated unconditionally in between.
+ val (newConjuncts, _) =
conjuncts.lazyZip(equalityAttributes).lazyZip(conjuncts.indices)
+ .foldRight((List.empty[Expression], Set.empty[ExprId])) {
+ case ((conjunct, Some(attr), _), (laterConjuncts, equalitiesAfter))
=>
+ (conjunct :: laterConjuncts, equalitiesAfter + attr.exprId)
+ case ((conjunct, None, i), (laterConjuncts, equalitiesAfter)) =>
+ def canTake(attr: Attribute): Boolean =
+ firstEquality.get(attr.exprId).exists(_ < i) ||
equalitiesAfter.contains(attr.exprId)
+ val newConjunct = replaceInConjunct(conjunct, constants, canTake,
predicates)
+ val newEqualitiesAfter = if
(ExprUtils.canEvaluateUnconditionally(newConjunct)) {
+ equalitiesAfter
+ } else {
+ Set.empty[ExprId]
+ }
+ (newConjunct :: laterConjuncts, newEqualitiesAfter)
+ }
+ val newConjunctsIterator = newConjuncts.iterator
+ def rebuild(e: Expression): Expression = e match {
+ case a @ And(left, right) =>
+ val newLeft = rebuild(left)
+ val newRight = rebuild(right)
+ if ((newLeft eq left) && (newRight eq right)) a else And(newLeft,
newRight)
+ case _ => newConjunctsIterator.next()
+ }
+ rebuild(condition)
+ }
+ }
+
+ /**
+ * Replaces the attributes that `canTake` accepts with their values in
`constantsMap` in the
+ * comparisons of `conjunct`, one of the conjuncts of the condition rather
than an `And` of them,
+ * as described in [[replaceConstants]]. The equalities in `predicates` are
kept.
+ */
+ private def replaceInConjunct(
+ conjunct: Expression,
+ constantsMap: AttributeMap[Literal],
+ canTake: Attribute => Boolean,
+ predicates: Set[BinaryComparison]): Expression = {
def replaceInComparison(b: BinaryComparison): Expression = {
lazy val collationSafeReplacement = isSameCollationAttrRefComparison(b)
- def canReplace(a: Attribute): Boolean =
- constantsMap.contains(a) && (isBinaryStable(a.dataType) ||
collationSafeReplacement)
+ def canReplace(a: Attribute): Boolean = constantsMap.contains(a) &&
canTake(a) &&
+ (isBinaryStable(a.dataType) || collationSafeReplacement)
def replace(e: Expression): Expression = e match {
case a: AttributeReference if canReplace(a) => constantsMap(a)
Review Comment:
**[5] Pre-existing: replacing an attribute that is an operand of a
comparison removes the comparison's NULL short-circuit, so its other operand
can now fail.**
A comparison returns NULL without evaluating its right side when its left
side is NULL. `y > 10 / x` keeps `10 / x`, but becomes `5 > 10 / x` with `y =
5`, which evaluates the division on the rows where `y` is NULL. With ANSI mode
on, `(y = 5 AND y > 10 / x) OR b > 0` over `(y, x, b) = (NULL, 0, 0)` fails
with `DIVIDE_BY_ZERO`: `y = 5` is NULL, so the AND goes on to `5 > 10 / x`,
while as written `y > 10 / x` is NULL there. For a top-level `y > 10 / x AND y
= 5` with codegen on master, the rewritten conjunct no longer refers to `y`, so
the generated filter checks `isnotnull(y)` only after it. I traced both from
the code and did not run them.
This goes against "So that this raises no error the original condition
cannot raise" (L243), and is not quite what SPARK-61438 describes, a rewritten
conjunct deciding whether a later one runs. It predates this PR, so a separate
JIRA, or a note under SPARK-61438, may fit better. One way is to leave a
nullable attribute that is an operand of a comparison as it is when the other
operand can fail.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
Review Comment:
**[9] Nit: `predicates` holds the keys of `attributeOf`, and `firstEquality`
can be a plain map.**
With the parameter of `replaceInConjunct` widened, `predicates` could be
`attributeOf.keySet`, so the two can't drift apart. `firstEquality` could be
`equalityAttributes.zipWithIndex.reverseIterator.collect { case (Some(attr), i)
=> attr.exprId -> i }.toMap`, where the last entry, the first index, wins.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
+ val attributeOf: Map[Expression, Attribute] = equalityPredicates
+ .map { case (attr, (_, predicate)) => (predicate: Expression) -> attr
}.toMap
+ val constants =
+ AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr ->
lit })
+ val conjuncts = splitConjunctivePredicates(condition)
+ // `replaceInConjunct` keeps the propagated equalities, which do not fold.
+ val isContradiction = conjuncts.exists { conjunct =>
+ fold(replaceInConjunct(conjunct, constants, _ => true,
predicates)).contains(FalseLiteral)
+ }
+ if (isContradiction) {
+ FalseLiteral
+ } else {
+ val equalityAttributes = conjuncts.map(attributeOf.get)
+ // The position of the first conjunct that is the propagated equality
over each attribute,
+ // or a copy of it. Another equality over the attribute, e.g. `1 = a`
for `a = 1`, is not.
+ val firstEquality = equalityAttributes.zipWithIndex
+ .collect { case (Some(attr), i) => attr.exprId -> i }
+ .groupMapReduce(_._1)(_._2)(math.min)
+ // `equalitiesAfter` holds the attributes of the equalities after the
conjunct with only
+ // conjuncts that can be evaluated unconditionally in between.
+ val (newConjuncts, _) =
conjuncts.lazyZip(equalityAttributes).lazyZip(conjuncts.indices)
+ .foldRight((List.empty[Expression], Set.empty[ExprId])) {
+ case ((conjunct, Some(attr), _), (laterConjuncts, equalitiesAfter))
=>
+ (conjunct :: laterConjuncts, equalitiesAfter + attr.exprId)
+ case ((conjunct, None, i), (laterConjuncts, equalitiesAfter)) =>
+ def canTake(attr: Attribute): Boolean =
+ firstEquality.get(attr.exprId).exists(_ < i) ||
equalitiesAfter.contains(attr.exprId)
+ val newConjunct = replaceInConjunct(conjunct, constants, canTake,
predicates)
+ val newEqualitiesAfter = if
(ExprUtils.canEvaluateUnconditionally(newConjunct)) {
Review Comment:
**[8] Nit: `canEvaluateUnconditionally` walks the rewritten conjunct even
when `equalitiesAfter` is already empty.**
The result is then the empty set either way, e.g. for every conjunct before
a non-deterministic one. Could it be `if (equalitiesAfter.isEmpty ||
ExprUtils.canEvaluateUnconditionally(newConjunct))`?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -241,18 +244,105 @@ object ConstantPropagation extends Rule[LogicalPlan]
with PredicateHelper {
* condition cannot raise, an expression that can fail keeps its attributes,
unless all of them
* are replaced and the result evaluates without an error. For the same
reason, an operand of an
* AND, OR, COALESCE or IN in a conjunct is rewritten only if no operand
after it can fail, as it
- * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`. The conjuncts of
- * `condition` itself are rewritten regardless, and [[moveEqualitiesFirst]]
orders them.
+ * decides whether they run, e.g. `y < 3` in `(y < 3 OR 10 / x > 1) AND y =
5`.
+ *
+ * A conjunct decides whether the ones after it run as well, but the
conjuncts are rewritten by
+ * the rules below instead. The conjuncts keep their written order: moving
an equality ahead of a
+ * non-deterministic conjunct changes the rows that one sees, and a later
rule can turn an
+ * equality into an expression that can fail, e.g. by pushing it through a
projection that defines
+ * its attribute with a cast, which would then run on rows that the
conjuncts written before it
+ * drop. Whether a conjunct can fail is judged on it as it is when this rule
runs, and an equality
+ * in between is not checked (SPARK-61437). A conjunct takes the constants
of the equalities
+ * before it, which hold on the rows that reach it where they are not NULL.
It takes the constant
+ * of an equality after it only if every conjunct in between, as rewritten,
can be evaluated
+ * unconditionally ([[ExprUtils.canEvaluateUnconditionally]]), which rejects
e.g. an expression
+ * that can fail or is non-deterministic: not into `y > 0` in `y > 0 AND 10
/ x > 0 AND y = 1` or
+ * `y > 0 AND rand() < 0.5 AND y = 1`, nor into `d <> 0` in `d <> 0 AND n /
d > 1 AND d = 5`, with
+ * the divisions in ANSI mode. Of several equalities over the same
attribute, only the last
+ * one is propagated, together with any earlier one identical to it; the
others are rewritten
+ * like the other conjuncts.
+ *
+ * On a row where the attribute of an `EqualTo` is NULL, the equality is
NULL, so the row still
+ * reaches the conjuncts after it. There, a conjunct rewritten with its
constant, before or after
+ * it, can still decide whether a later conjunct runs, e.g. `coalesce(y, 0)
> 0` in
+ * `(y = 1 AND coalesce(y, 0) > 0 AND 10 / x > 0) OR z > 0` or in
+ * `(coalesce(y, 0) > 0 AND y = 1 AND 10 / x > 0) OR z > 0`, or `y > w` in
+ * `(y = 1 AND y > w AND rand() < 0.5) OR z > 0`, which can be FALSE instead
of NULL there once
+ * rewritten. A condition that becomes FALSE below can be NULL there, too.
Without whole-stage
+ * codegen, or under an OR, the conjuncts of a filter are evaluated this
way; with it, a filter
+ * drops a row at the first conjunct that is NULL (SPARK-61438).
+ *
+ * If a conjunct other than the propagated equalities is FALSE with the
constants of all of them,
+ * e.g. `y = 1` in `y = 1 AND 10 / x > 0 AND y = 2`, where `y = 2` is
propagated, the condition
+ * becomes FALSE, as a row that passes the equalities fails that conjunct,
so none passes the
+ * condition. This also holds under a NOT, where the attributes are not
nullable and an `EqualTo`
+ * with a NULL literal is not propagated, so the equalities are never NULL.
*/
private def replaceConstants(
condition: Expression,
equalityPredicates: AttributeMap[(Literal, BinaryComparison)]):
Expression = {
- val constantsMap = AttributeMap(equalityPredicates.map { case (attr, (lit,
_)) => attr -> lit })
val predicates = equalityPredicates.values.map(_._2).toSet
+ val attributeOf: Map[Expression, Attribute] = equalityPredicates
+ .map { case (attr, (_, predicate)) => (predicate: Expression) -> attr
}.toMap
+ val constants =
+ AttributeMap(equalityPredicates.map { case (attr, (lit, _)) => attr ->
lit })
+ val conjuncts = splitConjunctivePredicates(condition)
+ // `replaceInConjunct` keeps the propagated equalities, which do not fold.
+ val isContradiction = conjuncts.exists { conjunct =>
Review Comment:
**[7] Nit: `isContradiction` rewrites and folds every conjunct once more
before the pass below rewrites them again.**
It runs `replaceInConjunct` and `fold` over all the conjuncts with all the
constants, for every filter with an equality and in every iteration of the
batch, so the rewrite of a long condition runs twice. Could it only look at the
conjuncts that refer to a propagated attribute, or reuse the result below for a
conjunct where `canTake` accepts all of them?
--
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]