sarutak commented on code in PR #60643:
URL: https://github.com/apache/spark/pull/60643#discussion_r4608994996
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala:
##########
@@ -465,6 +465,27 @@ class InferFiltersFromConstraintsSuite extends PlanTest {
projected.where(IsNotNull($"k") && $"k" > 1).where(IsNotNull($"r") &&
condition).analyze)
}
+ test("SPARK-61921: a constraint over a column that can fail through a limit,
an offset, a " +
+ "join or an aggregate is not inferred as a filter") {
+ // `i` can fail as the cast does, also through the limits, the offset and
the join, and so can
+ // the aggregate result `c`. So no constraint over either, e.g. `i > 0`
from `i = k AND k > 0`,
+ // goes ahead of the condition, while one over `m`, an aggregate function,
or over `f`, a
+ // non-deterministic result computed for every group, does.
+ val left = LocalRelation($"s".string, $"k".int)
+ .select($"k", Cast($"s", IntegerType, evalMode = EvalMode.ANSI).as("i"))
+ .limit(5)
+ .offset(1)
+ val right = LocalRelation($"g".int, $"t".string)
+ .groupBy($"g")(max($"g").as("m"),
Review Comment:
nit: `right` outputs no grouping key, so this test does not check that a
grouping key does not count. For example, it still passes when the `Aggregate`
case also returns a grouping key output as is (`case a: Attribute => Some(a)`
before `case _ => None`). How about outputting `g` too? This passes at this
head and fails with that change:
```scala
.groupBy($"g")($"g", max($"g").as("m"),
...
val condition =
$"i" === $"k" && $"k" > 0 && $"c" === $"m" && $"m" > 0 && $"f" > 0 &&
$"g" > 0
comparePlans(
InferFiltersFromConstraints(joined.where(condition).analyze),
joined.where(IsNotNull($"k") && IsNotNull($"m") && IsNotNull($"f") &&
IsNotNull($"g") &&
condition).analyze)
```
The comment above would then mention `g` too.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -249,8 +269,20 @@ trait PredicateHelper extends AliasHelper with Logging {
a.child.references.exists(below.contains)) => a.toAttribute
case a: Attribute if below.contains(a) => a
})
- case Filter(_, child) => failableOutput(child)
- case s: Sample => failableOutput(s.child)
+ case agg: Aggregate =>
+ AttributeSet(agg.aggregateExpressions.flatMap {
+ case a: Alias =>
+ val result = a.child.transform { case e: AggregateExpression =>
e.resultAttribute }
+ if (result.deterministic &&
!ExprUtils.canEvaluateUnconditionally(result)) {
+ Some(a.toAttribute)
+ } else {
+ None
+ }
+ case _ => None
+ })
+ case j: Join => failableOutput(j.left) ++ failableOutput(j.right)
+ case _: Filter | _: Sample | _: LocalLimit | _: GlobalLimit | _: Offset =>
Review Comment:
An inferred filter can still go ahead of the condition through a `Sort` that
the physical plan drops. `RemoveRedundantSorts` removes a `SortExec` whose
child already has the required ordering and distribution, and then the `Filter`
reads `q` from the projection below. With ANSI mode and whole-stage codegen,
this fails with `DIVIDE_BY_ZERO` both without and with this PR, while it
returns no row with `spark.sql.constraintPropagation.enabled=false`:
```scala
spark.range(0, 10, 1, 1).toDF()
.select($"id", (lit(10L) / ($"id" - 3)).as("q"),
$"id".cast("double").as("k"))
.orderBy($"id")
.select($"id", $"q", $"k", rand(2).as("r"))
.where($"id" > 5 && $"q" === $"k" && $"k" > 0)
.select($"id", $"r" >= 0)
```
The optimized plan still has `Sort [id ASC NULLS FIRST], true` between the
projection with `rand(2)` and the one that computes `q`, but `range` already
outputs `id` in order, so the executed plan has no sort. With
`spark.sql.execution.removeRedundantSorts=false`, the sort stays and the query
fails with constraint propagation disabled too. When I added `_: Sort` to this
case (and `Sort` to the import), the query returned no row, and
`InferFiltersFromConstraintsSuite` and the new `DataFrameSuite` test still
passed. With an order that the child does not have, e.g. `orderBy(-$"id")`, the
query fails with constraint propagation disabled too, so it is conservative
there, as for the limits. If you'd rather keep this PR as it is, could you
instead say in line 259 and in the table of the description that a `Sort` the
physical plan removes is not covered?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/predicates.scala:
##########
@@ -231,14 +232,33 @@ trait PredicateHelper extends AliasHelper with Logging {
}
/**
- * The output columns of `plan` that can fail to compute: the deterministic
columns of a
- * [[Project]] whose expression [[ExprUtils.canEvaluateUnconditionally]]
rejects or reads such a
- * column of its child, looking through [[Filter]] and [[Sample]]. A
condition over such a column
- * can fail as its expression does: under whole-stage codegen, the
projection computes a
- * deterministic column for a row only when a condition above first reads
it, and
- * `PushPredicateThroughNonJoin` pushes a condition below the projection
with the expression
- * substituted. A non-deterministic column is computed on every row the
projection gets, so it
- * does not count. Other operators are not looked through.
+ * The output columns of `plan` that can fail to compute. Under whole-stage
codegen, a
+ * projection or an aggregation computes a deterministic column for a row
only when a condition
+ * above first reads it, and `PushPredicateThroughNonJoin` pushes a
condition below a projection
+ * with the expression substituted. So a condition over such a column can
fail as its expression
+ * does. The columns are:
+ * - A deterministic column of a [[Project]] whose expression
+ * [[ExprUtils.canEvaluateUnconditionally]] rejects or reads such a
column of its child.
+ * - A result column of an [[Aggregate]] whose expression, with each
aggregate function taken
+ * as its value, is deterministic and rejected by it. Only an aggregation
with grouping keys
+ * under whole-stage codegen computes it lazily, so this is conservative
for the others,
+ * e.g. a global aggregation or an `ObjectHashAggregateExec`.
+ *
+ * These operators pass such columns of their children through:
+ * - [[Filter]] and [[Sample]].
+ * - [[LocalLimit]], [[GlobalLimit]] and [[Offset]]. A global limit or an
offset passes them
+ * through only when its input has a single partition; otherwise the
exchange below it
+ * computes every column, and this is conservative.
+ * - [[Join]], from both sides. Only the streamed side of a hash join
passes them through, so
Review Comment:
nit: I think a shuffled hash join does not hand them on, even on its
streamed side. `ShuffledHashJoinExec.inputRDDs` executes both children, so the
projection below it computes every column even without an exchange. With `/*+
SHUFFLE_HASH(b) */` instead of `BROADCAST(b)` in the third query of the
description (`range(0, 10, 1, 1)` on both sides, no exchange in the plan), the
query fails with `DIVIDE_BY_ZERO` also with
`spark.sql.constraintPropagation.enabled=false`. Maybe "The streamed side of a
broadcast hash join passes them through; a build side, a shuffled hash join or
a sort-merge join gets every column computed, so this is conservative for
them", here and in the description?
--
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]