sarutak commented on code in PR #60516:
URL: https://github.com/apache/spark/pull/60516#discussion_r4617751630
##########
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) {
+ private lazy val failable: AttributeSet = failableOutput(plan)
Review Comment:
Done: `reads` returns false right away when no column can fail, and one
application of the rule keeps what it finds for each plan node below a filter
in an `IdentityHashMap`, so the walk for a filter stops at the node that the
walk for the filter below it reached. The walk for the columns that can fail
goes only through the projections, filters, samples, limits, offsets, sorts,
joins, lateral joins, unions and CTEs below the filter, also from a reference
to a CTE into its definition, and into the result columns of an aggregation
with grouping keys or a serializer from objects there, each plan node once,
plus one walk over the whole plan, with its subqueries, to find the definitions
of the CTEs, only when it reaches a reference to one; the one for the foldable
columns, which goes through every operator that `FoldablePropagation` looks
through, also both sides of a join, runs only for an AND with an equality over
a column that can fail.
##########
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)
Review Comment:
Done: the check folds only the conjuncts that the constants or the foldable
columns change, skips those that `ExprUtils.canEvaluateUnconditionally`
accepts, folds a conjunct only once where both ways of putting the constants in
give the same one, and does not tag ([5]). It runs only for an AND with an
equality over a column that can fail. Where it fails, it still raises more
exceptions for such a part in each iteration of the batch than master, which
raises one in `replaceConstants`: one in each of the up to three
`replaceConstants` passes here that reach it (four in the fallback), and up to
two in the check (as rewritten and with all of the constants in), as the
condition keeps the column and the next iteration checks it again. I left that,
as it happens only for a condition that fails to fold with the constants, which
failed the query while it was optimized on 4.3.0 unless another rule removed
the failing part first.
##########
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
Review Comment:
Done: its scaladoc now says what it does with the equalities it gets, and
that the caller passes only those over columns that `columns` takes as ones
that can not fail; in the fallback those are all of them, with no column taken
as one that can fail, as on master. The fallback is explained once, in the new
`propagateInPlace`, and the scaladoc of `replaceConstantsInPlace` no longer
repeats it.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala:
##########
@@ -324,4 +324,258 @@ class ConstantPropagationSuite extends PlanTest {
val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") ===
2).analyze
comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
}
+
+ // SPARK-61437: the columns of the projection below that can fail.
+ private val strings = LocalRelation($"s".string, $"id".long, $"x".long)
+ private def castS: Expression = $"s".cast(IntegerType)
+ private def projected: LogicalPlan = strings.select($"s", $"id", $"x",
castS.as("i"))
+ private def divide(e: Expression): Expression = Divide(Literal(10.0),
e.cast(DoubleType))
+
+ private def conjuncts(plan: LogicalPlan): Seq[String] = plan match {
+ case Filter(condition, _) =>
splitConjunctivePredicates(condition).map(_.sql)
+ case other => fail(s"Expected a Filter: $other")
+ }
+
+ /** Checks the optimized plan also in the order of the conjuncts, which
`comparePlans` sorts. */
+ private def checkOrdered(child: LogicalPlan, condition: Expression,
expected: Expression)
+ : Unit = {
+ val optimized = Optimize.execute(child.where(condition).analyze)
+ val expectedPlan = child.where(expected).analyze
+ comparePlans(optimized, expectedPlan)
+ assert(conjuncts(optimized) == conjuncts(expectedPlan))
+ }
+
+ test("SPARK-61437: Do not move an equality over a column of the projection
below that can " +
+ "fail") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ // `i = 1` can fail, as the cast does, so it is not moved ahead of `id >
5`. Its constant is
+ // propagated in place, so only `i = 1` reads `i`.
+ val written = $"id" > 5L && $"i".cast(LongType) * $"id" > 0L && $"i" ===
1
+ val expected = $"id" > 5L && Literal(1L) * $"id" > 0L && $"i" === 1
+ Seq(
+ projected,
+ projected.select($"s", $"id", $"i"),
+ projected.where($"id" > 1L).select($"s", $"id", $"i"),
+ projected.sample(0.0, 0.5, withReplacement = false, 1L).select($"s",
$"id", $"i"),
+ projected.select($"s", $"id", $"i".as("j")).select($"s", $"id",
$"j".as("i"))
+ ).foreach(child => checkOrdered(child, written, expected))
+ }
+ }
+
+ test("SPARK-61437: Propagate an equality over a column that can fail in
place") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ // Into every conjunct, also one that can fail, as before SPARK-60983,
so that a conjunct
+ // that it rewrites no longer reads `i`.
+ val twoCasts = projected.select($"s", $"id", $"x", $"i", castS.as("j"))
+ val threeCasts = twoCasts.select($"s", $"id", $"x", $"i", $"j",
castS.as("k"))
+ Seq(
+ ($"id" > 5L && $"i" + 1 > 1 && $"i" === 1) -> ($"id" > 5L && $"i" ===
1),
+ (($"id" < 0L || $"i" + 1 > 3) && $"i" === 1) -> ($"id" < 0L && $"i"
=== 1),
+ (divide($"i") > 1.0 && $"i" === 1) -> ($"i" === 1),
+ ($"id" > 5L && ($"i" <=> 1) && $"i" > 0) -> ($"id" > 5L && ($"i" <=>
1)),
+ ($"id" > 5L && (Literal(1) <=> $"i") && $"i" > 0) -> ($"id" > 5L &&
(Literal(1) <=> $"i")),
+ (divide($"x") > 0.0 && $"i" > 0 && $"i" === 1) -> (divide($"x") > 0.0
&& $"i" === 1),
+ ($"i" + 1 > 1 && $"i" === 1 && divide($"x") > 0.0) -> ($"i" === 1 &&
divide($"x") > 0.0),
+ ($"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && $"i" === 1) ->
+ ($"id" > 5L && divide($"x") > 0.0 && $"i" === 1),
+ ($"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && Literal(1) === $"i")
->
+ ($"id" > 5L && divide($"x") > 0.0 && Literal(1) === $"i"),
+ ($"id" > 5L && $"i" > 0 && divide($"x") > 0.0 && ($"i" <=> 1)) ->
+ ($"id" > 5L && divide($"x") > 0.0 && ($"i" <=> 1)),
+ // The division reads `i` with the constant, so it does not fail on a
row where `id` is
+ // 8 and `i` is 8, but does on one where `id` is 1 and `i` is 2, as
before SPARK-60983.
+ (divide($"id" - $"i".cast(LongType)) > 0.0 && $"i" === 1) ->
+ (divide($"id" - 1L) > 0.0 && $"i" === 1),
+ // `id > 0` is rewritten by `id = 7`, which goes first.
+ ($"id" > 0L && divide($"x") > 0.0 && $"i" === 1 && $"i" + 1 > 1 &&
$"id" === 7L) ->
+ ($"id" === 7L && divide($"x") > 0.0 && $"i" === 1),
+ // But `id = 7` rewrites nothing here, so it stays, as on 4.3.0.
+ ($"i" + 1 > 1 && divide($"x") > 0.0 && $"i" === 1 && $"id" === 7L) ->
+ (divide($"x") > 0.0 && $"i" === 1 && $"id" === 7L)
+ ).foreach { case (condition, expected) => checkOrdered(projected,
condition, expected) }
+ Seq(
+ ($"j" > 0 && $"i" > 0 && $"j" === 2 && divide($"x") > 0.0 && $"i" ===
1) ->
+ ($"j" === 2 && divide($"x") > 0.0 && $"i" === 1),
+ ($"i" > 0 && $"k" > 5 && $"i" === 1 && $"j" + 1 > 1 && $"j" === 2) ->
+ ($"k" > 5 && $"i" === 1 && $"j" === 2),
+ // `i + 1` does not overflow on a row where `i` is the largest integer.
+ ($"i" + 1 > 0 && $"k" > 5 && $"i" === 1) -> ($"k" > 5 && $"i" === 1),
+ // `j < 5` no longer stops a row before `i = 2`, as before SPARK-60983.
+ ($"j" < 5 && $"i" > 0 && $"i" === 2 && $"j" === 1) -> ($"i" === 2 &&
$"j" === 1)
+ ).foreach { case (condition, expected) => checkOrdered(threeCasts,
condition, expected) }
+
+ // But not where the condition then fails to fold, which would fail the
query with no row,
+ // unlike in a conditional branch, which is not folded where it fails.
Then the equalities
+ // are handled as since SPARK-60983, and go first.
+ val failsToFold = $"i" === 0 && $"x".cast(DoubleType) > divide($"i")
+ checkOrdered(projected, failsToFold, failsToFold)
+ checkOrdered(projected,
+ $"id" > 5L && $"i" + 1 > 0 && $"x".cast(DoubleType) > divide($"i") &&
$"i" === 0,
+ $"i" === 0 && $"id" > 5L && $"x".cast(DoubleType) > divide($"i"))
+ // Also where the comparison folds, but the conjunct does not.
+ checkOrdered(projected,
+ $"i" === 0 && ElementAt(CreateArray(Seq(Literal(true))), ($"i" >
0).cast(IntegerType)),
+ $"i" === 0 && ElementAt(Literal.create(Seq(true),
ArrayType(BooleanType, false)),
+ ($"i" > 0).cast(IntegerType)))
+ checkOrdered(projected,
+ $"i" === 0 && If($"x" > 0L, divide($"i"), Literal(0.0)) > 0.0,
+ $"i" === 0 && If($"x" > 0L, divide(Literal(0)), Literal(0.0)) > 0.0)
+ checkOrdered(projected,
+ CaseWhen(Seq(($"id" < 0L) -> ($"x".cast(DoubleType) > divide($"i"))),
$"s".isNotNull) &&
+ $"i" === 0,
+ CaseWhen(Seq(($"id" < 0L) -> ($"x".cast(DoubleType) >
divide(Literal(0)))),
+ $"s".isNotNull) && $"i" === 0)
+ // Trying to fold it leaves no mark on a part that fails in a
conditional branch, which
+ // would keep `ConstantFolding` from failing on the same part elsewhere.
+ val byZero = Divide(Literal(10.0), Literal(0.0))
+ val sharesByZero = projected.where($"x".cast(DoubleType) > byZero &&
$"i" === 0 &&
+ If($"x" > 0L, byZero, Literal(0.0)) > $"i".cast(DoubleType)).analyze
+ intercept[ArithmeticException](Optimize.execute(sharesByZero))
+ intercept[ArithmeticException](Optimize.execute(projected
+ .where($"i" === 0 && If($"x" > 0L, byZero, Literal(0.0)) >
$"i".cast(DoubleType))
+ .select($"id", byZero.as("z")).analyze))
+ // Nor does it remove a mark that is there already.
+ byZero.setTagValue(ConstantFolding.FAILED_TO_EVALUATE, ())
+ Optimize.execute(sharesByZero)
+
+ // Not a string of a trim collation into `length`, as on 4.3.0: a row
with `u` = 'A '
+ // passes `u = 'A'`.
+ val trimmed = LocalRelation(AttributeReference("s",
StringType("UTF8_BINARY_RTRIM"))())
+ .select(Upper($"s").as("u"))
+ val lengthOfTrimmed = trimmed.where($"u" === "A" && Length($"u") ===
2).analyze
+ comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
+ }
+ }
+
+ test("SPARK-61437: A conjunct over a column that can fail can fail") {
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ // `id = 7` folds the guard `id > 0`, so it goes ahead of `i > 0`, which
can fail.
+ checkOrdered(projected, $"id" > 0L && $"i" > 0 && $"id" === 7L, $"id"
=== 7L && $"i" > 0)
+ checkOrdered(projected, $"id" > 0L && $"i" === 1 && $"id" === 7L,
+ $"id" === 7L && $"i" === 1)
+ // `id < 3` decides whether `i > 0` runs. `i > 0` counts as one that can
not fail there, as
+ // on master, so `id < 3` is rewritten, and the equality goes first,
ahead of `i > 0`.
+ checkOrdered(projected, ($"id" < 3L || $"i" > 0) && $"id" === 5L, $"id"
=== 5L && $"i" > 0)
+ // So `id > 0` is rewritten too, and becomes TRUE, also inside another
operator, so the
+ // operator folds away and `i` is not read.
+ Seq(
+ ($"id" > 0L || $"i" > 0) && $"id" === 7L,
+ ($"id" > 0L || $"x" > 0L || $"i" > 0) && $"id" === 7L
+ ).foreach(condition => checkOrdered(projected, condition, $"id" === 7L))
+ // `NullPropagation`, not in this batch, then drops the operands after
the 7, and the
+ // equality goes first until then.
+ checkOrdered(projected, (Coalesce(Seq($"id", $"x")) > 0L || $"i" > 0) &&
$"id" === 7L,
+ $"id" === 7L && (Coalesce(Seq(Literal(7L), $"x")) > 0L || $"i" > 0))
+ checkOrdered(projected, Coalesce(Seq($"id", $"i".cast(LongType))) > 0L
&& $"id" === 7L,
+ $"id" === 7L && Coalesce(Seq(Literal(7L), $"i".cast(LongType))) > 0L)
+ checkOrdered(projected, (($"id" < 0L && $"i" > 0) || $"x" > 0L) && $"id"
=== 7L,
+ $"id" === 7L && $"x" > 0L)
+
+ // Also one that reads the propagated attribute, which a collation keeps.
+ val lcase = LocalRelation($"s".string, AttributeReference("c",
StringType("UTF8_LCASE"))())
+ .select($"c", castS.as("i"))
+ checkOrdered(lcase, ($"i" > 0 || Length($"c") > 0) && $"c" === "a",
+ $"c" === "a" && ($"i" > 0 || Length($"c") > 0))
+
+ // Also under a `NOT`, with `s` and `id` not nullable.
+ val notNull = LocalRelation($"s".string.notNull, $"id".long.notNull)
+ .select($"s", $"id", castS.as("i"))
+ checkOrdered(notNull, Not($"id" > 0L && $"i" > 0 && $"id" === 7L),
+ Not($"id" === 7L) || $"i" <= 0)
+ // The cast is marked nullable (`Cast.forceNullable`), so `i = 1` is not
propagated under
+ // it, as on master.
+ checkOrdered(notNull, Not($"i" + 1 > 3 && $"i" === 1), $"i" + 1 <= 3 ||
Not($"i" === 1))
+ // `upper` is not, so the condition inside becomes FALSE, as on master.
+ val upperNotNull = notNull.select($"s", Upper($"s").as("u"))
+ comparePlans(
+ Optimize.execute(upperNotNull.where(Not(Length($"u") > 3 && $"u" ===
"X")).analyze),
+ upperNotNull.where(true).analyze)
+ // And one that becomes NULL stays NULL, which the `NOT` keeps NULL.
+ checkOrdered(upperNotNull,
+ Not(If($"u" === "X", Literal(null, StringType), $"u") === "Y" && $"u"
=== "X"),
+ Literal(null, BooleanType) || Not($"u" === "X"))
+ }
+ }
+
+ test("SPARK-61437: A condition that becomes FALSE with the constants is
FALSE") {
Review Comment:
- [1]-[4]: added `Do not propagate a zero in place where its sign can
matter` and `An equality over a column that can fail is handled as before when
the condition with all of the constants fails to fold` to
`ConstantPropagationSuite`, the FALSE cases to `A condition that becomes FALSE
with the constants is FALSE`, and a new end-to-end test in `DataFrameSuite`
with your examples, also with a BIGINT `id` and the filter pushed below the
projection, and the cases of [1] that succeed.
- The first `intercept`: as the check now folds only the conjuncts that the
constants change, it checks the `IF`, and that `intercept` alone fails when the
check tags (I ran it with the second one removed).
- `lower`: added `id > 0 AND length(l) > 0 AND id = 7`, where `id = 7` goes
first only if `l` counts as a column that can fail.
- I removed the first checks at L540, L545 and L550, which give the same
plan either way, and changed the cases at L372-378 and L399-404 to use `i *
id`, `j * id` and `i + k`, where master keeps the column and moves the
equality. Each of them now gives another plan on master.
- `collationSafeReplacement`: that is not the mutant the description meant.
The one I ran replaced the whole guard with `true`, which the trim collation
test kills; removing only `|| collationSafeReplacement` did survive, as you
say. Added `v = u AND u = 'a'`, with `u` the alias `upper(c)` and `v` of the
same collation, which kills it. Both rules now share that check.
- Nits: `twoCasts` and `threeCasts` are now defined once, the new members
are named `stringIds` and `tenDividedBy`, and the comments say "as since
SPARK-60983/SPARK-61033" or "as for any other column" instead of "as on master".
##########
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:
Thanks, confirmed: over `('0', 7, 1), ('x', 0, 0)` with whole-stage codegen,
4.3.0 returns `('0', 7)` and master fails with `CAST_INVALID_INPUT`. Fixed
along the lines you suggested: each conjunct that the constants change is
folded both as rewritten and with the constants of all of the equalities in
place, and one that fails to fold only as rewritten is replaced with what it
folds to with all of the constants in, before `moveEqualitiesFirst` gets the
in-place condition as the original. I did not limit the replacement to a
literal: what it folds to is its value on every row where the equalities hold,
and the AND is not TRUE on the other rows, so the filter keeps the same rows.
Where the replacement can fail, the equalities over the other columns that can
not fail now go first, also one whose constant a later iteration folds, so that
it runs only on the rows where those hold; one over a column that can fail
whose constant a later iteration folds stays where it is written, and its c
onstant goes in place in that iteration; it can still run on a row where the
equality over the column that can fail does not hold, as on 4.3.0. So:
- `x > 0 AND (id > 0 OR 10 / i > 1) AND i = 0 AND id = 7` becomes `id = 7
AND x > 0 AND i = 0`, which returns `('0', 7)`.
- `x > 0 AND CAST(id > 5 OR 10 / i > 1 AS BIGINT) <= x AND i = 0 AND id = 7`
does not fail to fold as rewritten, as `replaceConstants` folds the whole cast
with `id = 7` in, and becomes `id = 7 AND x > 0 AND 1 <= x AND i = 0`, which
returns `('0', 7)`.
- `((id > 10 AND 10 / i > 1) OR x > 5) AND i = 0 AND id = 7` becomes `id = 7
AND x > 5 AND i = 0`, and returns `('0', 7)` over `('0', 7, 6), ('x', 7, 0)`,
as 4.3.0 does.
- `((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`, and `CAST(id > 0 OR 10 / i > 1 AS INT) + x >
0 AND i = 0 AND id = 7` becomes `id = 7 AND x + 1 > 0 AND i = 0`, which return
`('0', 7)` over `('0', 7, 1), ('x', 7, 100)` and `('0', 7, 1), ('x', 7, -5)`,
as 4.3.0 does. So no TODO is needed at the fallback for them.
- `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: it becomes `id = 7 AND 10 / (x - id) >
0 AND x > 0 AND i = 0`.
- The fallback is taken only where a conjunct fails to fold with all of the
constants in, which fails the query while it is optimized on 4.3.0 unless a
rule before `ConstantFolding` removed the part that fails, e.g. `id > 5 AND i +
1 > 0 AND x > 10 / i AND i = 0`, which still becomes `i = 0 AND id > 5 AND x >
10 / i`. For a conjunct with an expression that can not be copied, such as the
test Python UDF (see 4591709830), it is also taken where another rule rewrites
a part that failed in a conditional branch, or where the conjunct would be
replaced and a part of it failed in such a branch, also where 4.3.0 runs the
query. I did not add a TODO for that one: it needs an expression that `clone`
can not copy, it is handled as on master there, and avoiding it would mean
tagging a part of the conjunct that the plan may share.
##########
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:
Thanks. That is right as a description of what happens, but I'd keep it: the
rows that a non-deterministic conjunct such as a seeded `rand` sees are not
something the optimizer keeps, e.g. `CombineFilters` runs conditions that can
not fail ahead of a non-deterministic one, and partition pruning and the file
scan's filters use every deterministic conjunct. Its doc, "should not change in
number and order", is to my reading about the evaluations on the rows it gets,
as those precedents already change which rows those are. Moving `id = 7` ahead
here also follows the same rule as master's own moves, which already move
equalities past a non-deterministic conjunct written after the first rewritten
one, so I would rather not add a special case for one written before 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]