spark-test commented on code in PR #59979:
URL: https://github.com/apache/spark/pull/59979#discussion_r4577157146
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2883,6 +2889,84 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case _ => false
}
+ // Splits `conds`, the conjuncts of a filter on top of `aggregate`, into the
ones to push below
+ // it, rewritten in terms of the aggregate's child, and the ones that stay
above it. A conjunct
+ // can be pushed if it is deterministic and, after alias expansion, only
reads the aggregate's
+ // child (that is, grouping keys and constants). Expressions above the
aggregate see its
+ // float/double grouping keys normalized (see NormalizeFloatingNumbers: -0.0
becomes 0.0 and every
+ // NaN becomes one canonical NaN), so a pushed conjunct reads them
normalized too, wherever the
+ // raw value could change its result. If the form of the keys the aggregate
outputs may still
+ // change (with grouped-agg pandas UDFs, see
NormalizeFloatingNumbers.mayChangeKeyForm), a
+ // conjunct that normalizing would change stays above it instead, where it
reads whatever the
+ // final plan outputs. Streaming aggregates keep the previous behavior, with
conjuncts pushed
+ // below them unnormalized: rules can still replace them with a Project of
the raw keys (see
+ // NormalizeFloatingNumbers.readsNormalizedKeys), and keeping a conjunct
above one could separate
+ // two aggregates that RemoveRedundantAggregates would merge, adding a
stateful operator. The CTE
+ // rule PushdownPredicatesAndPruneColumnsForCTEDef uses this too, to find
the filters it pushed.
+ private[optimizer] def pushBelowAggregate(
Review Comment:
**Non-blocking (P2):** This normalizes the conjuncts
`PushPredicateThroughNonJoin` moves below an Aggregate, but its sibling
`PushDownLeftSemiAntiJoin` (whose Scaladoc calls it a variant of this rule)
still moves LEFT SEMI and LEFT ANTI joins below a batch Aggregate with only
`replaceAlias` applied to the condition
(`PushDownLeftSemiAntiJoin.scala:63-78`, unchanged here and identical on
master).
Going by the code, with `t.x = [-0.0, -0.0]` and a small `u.s = ['-0.0']`,
`SELECT * FROM (SELECT DISTINCT x FROM t) a LEFT SEMI JOIN u ON cast(a.x AS
STRING) = u.s` should return no row, because the DISTINCT outputs `0.0`. The
condition has an equi-join key and a broadcastable right side, so
`canPlanAsBroadcastHashJoin` holds and the join moves below the Aggregate as
`cast(x AS STRING) = s` over the raw rows; both `-0.0` rows match and the query
returns `0.0`. `NormalizeFloatingNumbers` does not help, because these join
keys are strings. The LEFT ANTI form drops the row it should return, and over a
GROUP BY the moved join can split a group and change its count, as in the
description's HAVING example. Since `WHERE cast(x AS STRING) IN (SELECT s FROM
u)` is pushed here in normalized form before `RewritePredicateSubquery` runs,
the IN form and the join form of the same predicate now return different rows.
**Recommended change:** In PushDownLeftSemiAntiJoin's Aggregate case,
translate the join condition below a non-streaming Aggregate the way
pushBelowAggregate translates a filter: after alias expansion, rewrite each
pushed conjunct with normalizeGroupingExpressions over the Aggregate's
float/double grouping keys, and when the Aggregate has a grouped-agg pandas or
Arrow UDF (NormalizeFloatingNumbers.mayChangeKeyForm) treat a conjunct the
rewrite changes as not pushable, so that pushDownJoin keeps that conjunct above
the Aggregate. Factor the per-conjunct normalization out of pushBelowAggregate
so that both rules share it. Add left semi and anti join push-down optimizer
tests and DataFrame aggregate end-to-end tests.
**Why this works:** The Aggregate outputs its float/double keys normalized,
so a condition evaluated below it must read the normalized key wherever the raw
value could change its result; the shared rewrite produces that form and leaves
the exempt comparisons unwrapped, so the join below the Aggregate keeps exactly
the rows the join above it keeps. Treating changed conjuncts as not pushable
over an Aggregate whose key form is unsettled reuses pushDownJoin's existing
handling of conjuncts it cannot push: a semi join whose unpushed conjunct reads
a right-side column, and an anti join with any unpushed conjunct, stay above
the Aggregate, and a semi join's unpushed conjuncts that read only left-side
columns become a Filter above it.
**Scope:** Make the semi and anti join push-down rule rewrite the conditions
it moves below a batch Aggregate with the same float/double key normalization
the filter rule uses.
**Compatibility:** Semi and anti joins whose conditions read no float/double
grouping key, or read one only as a direct operand of the exempt comparisons,
are pushed exactly as before.
**Risks:** Semi and anti join conditions that read a float/double grouping
key through a non-exempt expression are moved in normalized form, so a source
that could have received their raw form no longer can, as for filters; there is
no flag, and reverting the change rolls it back. Over an Aggregate with a
grouped-agg pandas or Arrow UDF, a semi or anti join whose condition the
rewrite changes is no longer pushed below it, which gives up early filtering
for that join. Master has the same PushDownLeftSemiAntiJoin rule and the same
pushBelowAggregate logic, so making this change only on this branch leaves the
two branches returning different rows for these joins until master gets the
same change.
**Constraints:** Exempt streaming Aggregates exactly as the filter rule
does. Share the per-conjunct rewrite with pushBelowAggregate rather than
copying its exempt-predicate list, so the two rules cannot drift apart.
Describe the grouped-agg Python UDF case in any new comment as pandas or Arrow
UDFs (PythonUDAF), not as pandas UDFs alone.
**Exclusions:**
- Filter, semi join and anti join push-down below a Window on a float/double
partition column, a different, pre-existing failure in which a sign-revealing
condition splits a normalized partition; normalizing the pushed condition does
not fix it.
- Semi and anti joins over streaming Aggregates, which stay under the PR's
declared streaming deferral.
**Success:** SELECT * FROM (SELECT DISTINCT x FROM t) a LEFT SEMI JOIN u ON
cast(a.x AS STRING) = u.s returns no row for t.x = [-0.0, -0.0] and u.s =
['-0.0'], like the equivalent IN subquery, and the LEFT ANTI form returns 0.0.
A semi or anti join that compares a float/double grouping key only directly,
including the null-safe equalities INTERSECT and EXCEPT produce, is moved below
the Aggregate with its condition unchanged. Plans for semi and anti joins over
streaming Aggregates match the base branch.
**Verification:**
- **Regression:** LEFT SEMI and LEFT ANTI joins over DISTINCT and over GROUP
BY with count(*) on DOUBLE, FLOAT and struct keys holding -0.0 and 0.0, with a
sign-revealing equi-join condition against a broadcastable right side, return
the same rows as the equivalent IN and NOT IN subquery forms, and the GROUP BY
form keeps each group's count.
- **Behavior:** The optimized plan moves such a join below the Aggregate
with the key normalized in its condition, and moves a join that only compares
the key directly, including with a null-safe equality, with its condition
unchanged.
- **Compatibility:** Over an Aggregate with a grouped-agg pandas UDF a join
whose condition the rewrite changes stays above it, and over a streaming
Aggregate the plan matches the base branch.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2883,6 +2889,84 @@ object PushPredicateThroughNonJoin extends
Rule[LogicalPlan] with PredicateHelpe
case _ => false
}
+ // Splits `conds`, the conjuncts of a filter on top of `aggregate`, into the
ones to push below
+ // it, rewritten in terms of the aggregate's child, and the ones that stay
above it. A conjunct
+ // can be pushed if it is deterministic and, after alias expansion, only
reads the aggregate's
+ // child (that is, grouping keys and constants). Expressions above the
aggregate see its
+ // float/double grouping keys normalized (see NormalizeFloatingNumbers: -0.0
becomes 0.0 and every
+ // NaN becomes one canonical NaN), so a pushed conjunct reads them
normalized too, wherever the
+ // raw value could change its result. If the form of the keys the aggregate
outputs may still
+ // change (with grouped-agg pandas UDFs, see
NormalizeFloatingNumbers.mayChangeKeyForm), a
+ // conjunct that normalizing would change stays above it instead, where it
reads whatever the
+ // final plan outputs. Streaming aggregates keep the previous behavior, with
conjuncts pushed
+ // below them unnormalized: rules can still replace them with a Project of
the raw keys (see
+ // NormalizeFloatingNumbers.readsNormalizedKeys), and keeping a conjunct
above one could separate
+ // two aggregates that RemoveRedundantAggregates would merge, adding a
stateful operator. The CTE
+ // rule PushdownPredicatesAndPruneColumnsForCTEDef uses this too, to find
the filters it pushed.
+ private[optimizer] def pushBelowAggregate(
+ conds: Seq[Expression],
+ aggregate: Aggregate): (Seq[Expression], Seq[Expression]) = {
+ val aliasMap = getAliasMap(aggregate)
+ val keys = if (aggregate.isStreaming) {
+ Nil
+ } else {
+ aggregate.groupingExpressions
+ .filter(e => NormalizeFloatingNumbers.needNormalize(e.dataType))
+ .map(trimAliases)
+ }
+ val mayChangeKeyForm = NormalizeFloatingNumbers.mayChangeKeyForm(aggregate)
+ val rewritten = conds.map { cond =>
+ val replaced = replaceAlias(cond, aliasMap)
+ val pushable = cond.deterministic && cond.references.nonEmpty &&
+ replaced.references.subsetOf(aggregate.child.outputSet)
+ val normalized = if (pushable && keys.nonEmpty) {
+ normalizeGroupingExpressions(replaced, keys)
+ } else {
+ replaced
+ }
+ (cond, replaced, normalized, pushable &&
+ (!mayChangeKeyForm || normalized.fastEquals(replaced)))
+ }
+ val (pushDown, stayUp) = splitPushable(rewritten)(
+ canPush = _._4,
+ throwable = _._2.throwable)
+ (pushDown.map(_._3), stayUp.map(_._1))
+ }
+
+ // Rewrites `e` so that it gives the same result on the raw values of
`grouping` as `e` gives on
+ // their normalized values (see NormalizeFloatingNumbers). Each occurrence
of a grouping
+ // expression is wrapped in its normalized form, with one exception: a
float/double attribute
+ // that is a direct operand of one of the comparisons matched below is left
as is, and so is a
+ // float attribute widened to double (as when a FLOAT column is compared
with a DOUBLE or
+ // DECIMAL value), since widening keeps -0.0 and NaN. Those comparisons
already treat -0.0 and
+ // 0.0 as equal and all NaNs as equal (see SQLOrderingUtil.compareDoubles and
+ // CodegenContext.genEqual), and so does InSet, an IN list that OptimizeIn
converted. IsNull,
+ // IsNotNull and IsNaN cannot tell normalized values apart either, nor can
an IN subquery, which
+ // becomes a join on EqualTo conditions (whose keys NormalizeFloatingNumbers
normalizes on both
+ // sides when it is an equi-join). So wrapping would not change the result,
and leaving them as
+ // is keeps plain comparisons usable by data sources and partition pruning.
+ private[optimizer] def normalizeGroupingExpressions(
+ e: Expression,
+ grouping: Seq[Expression]): Expression = e match {
+ // A grouping key already normalized when the filter was pushed through an
Aggregate above on
+ // the same key. Any other normalized expression may be computed from a
grouping key (when the
+ // upper Aggregate groups by an expression of this one's key), so the key
inside it still has
+ // to be normalized. This also matches array and map keys: `normalize`
builds new lambda
+ // variables for them, but `semanticEquals` compares canonicalized trees,
which renumber them.
+ case _: KnownFloatingPointNormalized
+ if grouping.exists(g =>
NormalizeFloatingNumbers.normalize(g).semanticEquals(e)) => e
+ case _: EqualTo | _: EqualNullSafe | _: LessThan | _: LessThanOrEqual | _:
GreaterThan |
+ _: GreaterThanOrEqual | _: In | _: InSet | _: InSubquery | _: IsNull
| _: IsNotNull |
+ _: IsNaN =>
+ e.mapChildren {
+ case a: Attribute if a.dataType == FloatType || a.dataType ==
DoubleType => a
+ case c @ Cast(a: Attribute, DoubleType, _, _) if a.dataType ==
FloatType => c
+ case c => normalizeGroupingExpressions(c, grouping)
+ }
+ case _ if grouping.exists(_.semanticEquals(e)) =>
NormalizeFloatingNumbers.normalize(e)
Review Comment:
**Nit (P3):** The wrapper inserted here,
`KnownFloatingPointNormalized(NormalizeNaNAndZero(key))`, is not
null-intolerant: neither class overrides `nullIntolerant`, which defaults to
`false`, so `QueryPlanConstraints.scanNullIntolerantAttribute` stops at it.
Going by the rule order, `InferFiltersFromConstraints` runs after this push, so
for `SELECT * FROM (SELECT d, count(*) AS c FROM t GROUP BY d) WHERE d * 2.0 >
10.0` the pushed `(norm(d) * 2.0) > 10.0` no longer yields the `isnotnull(d)`
filter that the base branch's `(d * 2.0) > 10.0` did, and the scan no longer
receives `IsNotNull(d)`. Results stay the same, but row groups and files that
are entirely null in the key are no longer skipped. Both expressions return
null exactly when their input is null, so overriding `nullIntolerant` to `true`
in `NormalizeNaNAndZero` and `KnownFloatingPointNormalized` restores the
inference.
**Verification:**
- **Regression:** With full optimization, a conjunct pushed below a
DOUBLE-keyed Aggregate in normalized form, such as d * 2.0 > 10.0 or cast(d AS
STRING) = '1.0', yields an inferred isnotnull filter on d below the Aggregate.
- **Compatibility:** Normalizing a null input still yields null, and
filters, joins, windows and aggregates over null float/double keys return the
same rows as before.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala:
##########
@@ -239,13 +241,17 @@ object PushdownPredicatesAndPruneColumnsForCTEDef extends
Rule[LogicalPlan] with
}
if (removedAny) (u.withNewChildren(newChildren), true) else (u, false)
case agg: Aggregate =>
- // Mirror PushPredicateThroughNonJoin: translate the target through
the grouping
- // aliases with the same helper it uses to move grouping-key filters
below the
- // aggregate (filters referencing aggregate expressions stay up, so
they are always
- // found above this node).
- val translated = replaceAlias(target, getAliasMap(agg))
- val (newChild, removed) = remove(agg.child, translated)
- if (removed) (agg.withNewChildren(Seq(newChild)), true) else (agg,
false)
+ // Mirror PushPredicateThroughNonJoin: split and translate the target
with the same helper
+ // it uses to move filters below the aggregate. A filter it keeps
entirely above this node
+ // has been found above already, and one it splits is not entirely
below it.
+ val (pushDown, stayUp) =
+
PushPredicateThroughNonJoin.pushBelowAggregate(splitConjunctivePredicates(target),
agg)
+ if (pushDown.isEmpty || stayUp.nonEmpty) {
Review Comment:
**Nit (P3):** Nothing in `PushdownPredicatesForCTEDefStalenessSuite` reaches
this branch: the float/double test pushes the whole target below the Aggregate,
and the pandas UDF test finds the target at the top Filter before descending.
The branch is reached whenever the previous push-down is no longer the top
Filter, for example once `CombineFilters` merges a reference predicate on an
aggregate output (`cnt > 5 OR cnt > 7`) into the definition's `HAVING count(*)
> 1` filter. Without the `pushDown.isEmpty` check, `pushDown.reduce(And)` below
would then throw on an empty list, and without the `stayUp.nonEmpty` check a
split target would be removed only in part. A staleness test whose definition
is a HAVING filter over an Aggregate, with reference predicates on the
aggregate output, would pin this.
**Verification:**
- **Regression:** Rebuilding a CTE definition whose previous push-down
stayed above the Aggregate below another filter completes without an exception,
and a previous push-down that the Aggregate split into pushed and kept parts is
not removed only in part.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/NormalizeFloatingNumbers.scala:
##########
@@ -100,6 +103,68 @@ object NormalizeFloatingNumbers extends Rule[LogicalPlan] {
// Scaladoc just above.
}
+ /**
+ * Whether `aggregate` outputs its float/double grouping keys normalized.
The planner normalizes
+ * the grouping keys of every Aggregate (see `SparkStrategies.Aggregation`),
except one whose
+ * aggregate functions are all grouped-agg pandas UDFs, planned as
`ArrowAggregatePythonExec` on
Review Comment:
**Nit (P3):** The checks below test `isInstanceOf[PythonUDAF]`, which
`UserDefinedPythonFunction` also builds for grouped-agg Arrow UDFs
(`SQL_GROUPED_AGG_ARROW_UDF` and `SQL_GROUPED_AGG_ARROW_ITER_UDF`), and the
planner runs an Aggregate whose functions are all `PythonUDAF` as
`ArrowAggregatePythonExec` on the raw keys in both cases. This Scaladoc,
`mayChangeKeyForm`'s Scaladoc and the comment on `pushBelowAggregate` in
`Optimizer.scala` name only grouped-agg pandas UDFs, so a reader could conclude
that an Arrow UDF aggregate outputs normalized keys, or narrow the check to
pandas eval types. Saying "grouped-agg pandas or Arrow UDFs (`PythonUDAF`)", as
nearby planner comments do, fixes all three.
**Verification:**
- **Inspection:** No comment the PR adds about which Aggregates output raw
grouping keys describes the grouped-agg Python UDF case as pandas-only.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RemoveRedundantAggregates.scala:
##########
@@ -34,7 +34,8 @@ object RemoveRedundantAggregates extends Rule[LogicalPlan]
with AliasHelper {
val projectList =
lower.aggregateExpressions.filter(upper.references.contains(_))
upper.copy(child = Project(projectList, lower.child))
case agg @ Aggregate(groupingExps, _, child, _)
- if agg.groupOnly &&
child.distinctKeys.exists(_.subsetOf(ExpressionSet(groupingExps))) =>
+ if agg.groupOnly &&
child.distinctKeys.exists(_.subsetOf(ExpressionSet(groupingExps))) &&
+ !NormalizeFloatingNumbers.readsNormalizedKeys(agg,
agg.aggregateExpressions) =>
Review Comment:
**Nit (P3):** This keeps the Aggregate whenever its outputs read a
float/double key, even when the child already outputs that key normalized, for
example `df.groupBy("d").agg(max("x")).distinct()` or `(a INTERSECT b)
INTERSECT c` with a DOUBLE column, where the base branch removed the outer
Aggregate and keeping it adds a hash aggregation that changes no result. The
new test "Keep group only aggregate that normalizes a float key" says the rule
does not check this, but nothing here does, so a reader cannot tell the extra
aggregation is a known over-approximation rather than an oversight. A TODO here
naming the deferred check, whether the child already outputs the key
normalized, would record it.
**Verification:**
- **Inspection:** The guard that keeps a group-only Aggregate on a
float/double key is accompanied by a TODO naming the deferred check of whether
the child already outputs that key normalized.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RemoveRedundantAggregatesSuite.scala:
##########
@@ -119,13 +119,15 @@ class RemoveRedundantAggregatesSuite extends PlanTest {
}
test("Remove redundant aggregate with non-deterministic lower") {
+ // An integer key: the lower aggregate normalizes a float/double key, so
it would be kept.
Review Comment:
**Nit (P3):** By the rule's code, the original DOUBLE version of this test
still holds: the lower becomes `Aggregate([a, _nondeterministic], [a,
_nondeterministic AS c])` and the upper groups by `a` and `c` directly, so
`upperReadsNormalizedKeys` classifies `_nondeterministic AS c` as a key output,
the other output `a` reads no key, and the upper has no aggregate function or
computed grouping expression; the lower is still removed. So this comment says
the rule keeps an aggregate it removes, and with the integer key no test
outputs a float/double key through an alias the upper groups by directly, so a
regression in that alias handling would go unnoticed. Restoring `rand(0) as
"c"` and the original expected plan (`.select($"a", $"_nondeterministic" as
"c")`) fixes both. The comment on the other changed test is right: there the
upper is group-only and is kept for a DOUBLE `c`.
**Verification:**
- **Regression:** A redundant lower Aggregate whose DOUBLE grouping key is
pulled out of a non-deterministic expression and output through an alias, under
an upper Aggregate that groups by that alias directly, is removed.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/PythonUDFSuite.scala:
##########
@@ -126,6 +126,29 @@ class PythonUDFSuite extends SharedSparkSession {
assert(df.agg(pandasTestUDF(df("id"))).schema.fieldNames.exists(_.startsWith(udfName)))
}
+ test("SPARK-60150: filter on a float key above a grouped-agg pandas UDF
aggregate") {
+ assume(shouldTestPandasUDFs)
+ val pandasTestUDF = TestGroupedAggPandasUDF(name = "pandas_udf")
+ // The aggregate outputs the raw key -0.0, and the filter pushed below it
must read it raw.
Review Comment:
**Nit (P3):** With this PR nothing is pushed below this aggregate: it has a
`PythonUDAF`, so `mayChangeKeyForm` holds, and normalization changes `cast(x AS
STRING) = '-0.0'`, so `pushBelowAggregate` keeps the filter above it, where it
reads the raw `-0.0` that `ArrowAggregatePythonExec` outputs. The comment
describes a push-down the plan does not do and contradicts the next comment in
the same test.
```suggestion
// The aggregate outputs the raw key -0.0, and the filter, kept above
it, reads it raw.
```
**Verification:**
- **Inspection:** No comment in the grouped-agg pandas UDF filter test says
that the filter is pushed below the aggregate.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala:
##########
@@ -2659,4 +2659,235 @@ class FilterPushdownSuite extends PlanTest {
val optimizedC = Optimize.execute(queryC)
comparePlans(optimizedC, queryC, checkAnalysis = false)
}
+
+ test("SPARK-60150: push a filter on a float/double grouping key with the
normalized key") {
+ val x = $"x".double
+ val relation = LocalRelation(x)
+ val normX = NormalizeFloatingNumbers.normalize(x)
+
+ // SELECT * FROM (SELECT DISTINCT x FROM t) WHERE cast(x AS STRING) =
'-0.0'
+ // DISTINCT becomes Aggregate(x, x) in the optimizer, so build that shape
directly.
+ val originalQuery = relation.groupBy(x)(x).where(x.cast(StringType) ===
"-0.0")
+ val optimized = Optimize.execute(originalQuery.analyze)
+
+ // The Aggregate normalizes -0.0 to 0.0 (NormalizeFloatingNumbers), so the
pushed predicate
+ // must read the normalized key.
+ val correctAnswer = relation
+ .where(normX.cast(StringType) === "-0.0")
+ .groupBy(x)(x)
+ .analyze
+ comparePlans(optimized, correctAnswer)
+ }
+
+ test("SPARK-60150: normalize only the keys that can change a pushed filter's
result") {
+ val x = $"x".double
+ val y = $"y".float
+ val relation = LocalRelation(x, y)
+ val normX = NormalizeFloatingNumbers.normalize(x)
+
+ // Within an OR, the key is normalized under the Cast but not as a direct
comparison operand.
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x, y)(x, y).where(x > 5.0 || x.cast(StringType) ===
"-0.0").analyze),
+ relation.where(x > 5.0 || normX.cast(StringType) === "-0.0")
+ .groupBy(x, y)(x, y).analyze)
+
+ // Across conjuncts, only the one that reads the key through a Cast
changes.
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x, y)(x, y).where(y > 1.0f && x.cast(StringType) ===
"-0.0").analyze),
+ relation.where(y > 1.0f && normX.cast(StringType) === "-0.0")
+ .groupBy(x, y)(x, y).analyze)
+ }
+
+ test("SPARK-60150: normalize aliases computed from a float/double key after
alias expansion") {
+ val x = $"x".double
+ val relation = LocalRelation(x)
+ val normX = NormalizeFloatingNumbers.normalize(x)
+
+ // The alias is computed from the normalized key above the Aggregate, even
when the alias
+ // itself is not float/double or is compared directly.
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x)(x.cast(StringType).as("s")).where($"s" ===
"-0.0").analyze),
+ relation.where(normX.cast(StringType) === "-0.0")
+ .groupBy(x)(x.cast(StringType).as("s")).analyze)
+
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x)(Length(x.cast(StringType)).as("k")).where($"k" ===
4).analyze),
+ relation.where(Length(normX.cast(StringType)) === 4)
+ .groupBy(x)(Length(x.cast(StringType)).as("k")).analyze)
+
+ // A plain rename of the key compared directly is pushed down unchanged.
+ comparePlans(
+ Optimize.execute(relation.groupBy(x)(x.as("k")).where($"k" ===
0.0).analyze),
+ relation.where(x === 0.0).groupBy(x)(x.as("k")).analyze)
+ }
+
+ test("SPARK-60150: push down comparisons on a float/double grouping key
unchanged") {
+ val x = $"x".double
+ val y = $"y".float
+ val relation = LocalRelation(x, y, $"b".int)
+
+ // Comparisons treat -0.0/0.0 and all NaNs as equal, so they need no
normalization. That
+ // includes a FLOAT key widened to DOUBLE to be compared with a DOUBLE
value, and InSet.
+ val comparisons = x > 1.0 || (y === 0.0f && !IsNaN(x)) || x.in(2.0, 3.0)
|| x.isNull ||
+ y > 1.5 || y.in(1.5, 2.5) || InSet(x, Set(4.0, 5.0))
+ val originalQuery = relation
+ .groupBy(x, y)(x, y, count($"b").as("c"))
+ .where(comparisons)
+
+ val optimized = Optimize.execute(originalQuery.analyze)
+
+ val correctAnswer = relation
+ .where(comparisons)
+ .groupBy(x, y)(x, y, count($"b").as("c"))
+ .analyze
+ comparePlans(optimized, correctAnswer)
+ }
+
+ test("SPARK-60150: normalize grouping expressions and complex keys in pushed
filters") {
+ val x = $"x".double
+ val s = $"s".struct(StructType(Seq(StructField("d", DoubleType))))
+ val relation = LocalRelation(x, s)
+
+ // The grouping expression, not the column it reads, is what the Aggregate
normalizes.
+ val k = x * 2.0
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(k)(k.as("k")).where($"k".cast(StringType) ===
"-0.0").analyze),
+ relation.where(NormalizeFloatingNumbers.normalize(k).cast(StringType)
=== "-0.0")
+ .groupBy(k)(k.as("k")).analyze)
+
+ // A struct key is normalized field by field.
+ val field = GetStructField(s, 0)
+ comparePlans(
+ Optimize.execute(relation.groupBy(s)(s).where(field.cast(StringType) ===
"-0.0").analyze),
+ relation.where(GetStructField(NormalizeFloatingNumbers.normalize(s), 0)
+ .cast(StringType) === "-0.0").groupBy(s)(s).analyze)
+ }
+
+ test("SPARK-60150: don't normalize a pushed filter twice") {
+ val x = $"x".double
+ val relation = LocalRelation(x)
+ val normX = NormalizeFloatingNumbers.normalize(x)
+
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x)(x).groupBy(x)(x).where(x.cast(StringType) ===
"-0.0").analyze),
+ relation.where(normX.cast(StringType) ===
"-0.0").groupBy(x)(x).groupBy(x)(x).analyze)
+
+ // The upper key is computed from the lower key, so the lower key inside
the normalized upper
+ // key is normalized too.
+ val k = Pow(x, Literal(-1.0)).as("k")
+ val lower = relation.groupBy(x)(k)
+ val upperKey = k.toAttribute
+ comparePlans(
+ Optimize.execute(
+ lower.groupBy(upperKey)(upperKey).where(upperKey.cast(StringType) ===
"Infinity").analyze),
+ relation
+ .where(NormalizeFloatingNumbers.normalize(Pow(normX,
Literal(-1.0))).cast(StringType) ===
+ "Infinity")
+ .groupBy(x)(k)
+ .groupBy(upperKey)(upperKey)
+ .analyze)
+ }
+
+ test("SPARK-60150: keep a normalization-sensitive filter above a pandas UDF
aggregate") {
+ val x = $"x".double
+ val v = $"v".int
+ val relation = LocalRelation(x, v)
+ // Whether such an aggregate outputs normalized keys depends on which of
its aggregate
+ // functions column pruning keeps later, so a conjunct that normalizing
would change stays
+ // above it, while a plain comparison is still pushed below it.
+ val pandasAgg = PythonUDAF("pandasAgg", null, IntegerType, Seq(v),
udfDeterministic = true)
+ .toAggregateExpression().as("p")
+ val sensitive = x.cast(StringType) === "-0.0"
+ for (aggregates <- Seq(Seq(pandasAgg), Seq(pandasAgg, count(v).as("c")))) {
+ comparePlans(
+ Optimize.execute(
+ relation.groupBy(x)(x +: aggregates: _*).where(sensitive && x >
1.0).analyze),
+ relation.where(x > 1.0).groupBy(x)(x +: aggregates:
_*).where(sensitive).analyze)
+ }
+ }
+
+ test("SPARK-60150: push a filter below a streaming aggregate unnormalized,
as before") {
+ val x = $"x".double
+ val streaming = LocalRelation(Seq(x, $"v".int), isStreaming = true)
+ // A streaming aggregate can still be replaced with a Project of the raw
keys, and a filter kept
+ // above it could add a stateful operator.
+ val condition = x.cast(StringType) === "-0.0" && x > 1.0
+ comparePlans(
+ Optimize.execute(streaming.groupBy(x)(x,
count($"v").as("c")).where(condition).analyze),
+ streaming.where(condition).groupBy(x)(x, count($"v").as("c")).analyze)
+ }
+
+ test("SPARK-60150: normalizeGroupingExpressions") {
+ val x = $"x".double
+ val f = $"f".float
+ val y = $"y".int
+ val s = $"s".struct(StructType(Seq(StructField("d", DoubleType))))
+ val normX = NormalizeFloatingNumbers.normalize(x)
+ val normS = NormalizeFloatingNumbers.normalize(s)
+ val arr = $"arr".array(DoubleType)
+ def normalize(e: Expression): Expression =
+ PushPredicateThroughNonJoin.normalizeGroupingExpressions(e, Seq(x, f, s,
arr))
+ def unchanged(e: Expression): Unit = assert(normalize(e) == e)
+
+ // A grouping key on its own is normalized; other columns and literals are
not.
+ assert(normalize(x) == normX)
+ unchanged(y)
+ unchanged(Literal(0.0))
+
+ // A float/double key that is a direct operand of these comparisons is
left as is.
+ unchanged(x === 0.0)
+ unchanged(EqualNullSafe(x, Literal(0.0)))
+ unchanged(x < 1.0)
Review Comment:
**Nit (P3):** Every exempt predicate class except `LessThanOrEqual` is
asserted here or in the unchanged-comparisons test: `===`, `<=>`, `<`, `>=`,
`IN`, `InSet`, `InSubquery`, `IS NULL`, `IS NOT NULL` and `isnan` here, and `>`
there. Dropping `_: LessThanOrEqual` from the pattern in
`normalizeGroupingExpressions` would wrap the key in `x <= c` and in the upper
half of `BETWEEN`, losing data-source and partition-filter pushdown for them,
and no test would fail. A `<=` or `BETWEEN` conjunct in the
unchanged-comparisons test would pin the plan-level push-down too.
```suggestion
unchanged(x < 1.0)
unchanged(x <= 1.0)
```
**Verification:**
- **Regression:** A <= comparison, and the <= half of a BETWEEN, on a
float/double grouping key is pushed below the Aggregate with the key unwrapped.
--
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]