spark-test commented on code in PR #59979:
URL: https://github.com/apache/spark/pull/59979#discussion_r4582936809


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RemoveRedundantAggregates.scala:
##########
@@ -60,7 +61,29 @@ object RemoveRedundantAggregates extends Rule[LogicalPlan] 
with AliasHelper {
     // relation, while a global aggregation will return a single row.
     lazy val lowerIsGlobalAgg = lower.groupingExpressions.isEmpty
 
-    upperHasNoDuplicateSensitiveAgg && upperRefsOnlyDeterministicNonAgg && 
!lowerIsGlobalAgg
+    // The lower aggregation outputs its float/double grouping keys 
normalized, so it is not
+    // redundant if the upper aggregation would read them raw without it: 
through an output computed
+    // from a key, or inside an aggregate function or a computed grouping 
expression. A key the
+    // upper aggregation groups by directly is normalized by it. Streaming 
plans keep the previous
+    // behavior, see NormalizeFloatingNumbers.readsNormalizedKeys.
+    lazy val upperReadsNormalizedKeys = !lower.isStreaming && {

Review Comment:
   **Non-blocking (P2):** This check keeps a lower Aggregate whose float/double 
keys the upper one would read raw, but `CollapseGroupedSumOfCount`, which this 
backport leaves unchanged and which runs by default from 
`earlyScanPushDownRules` and `V2ScanRelationPushDown`, removes the same kind of 
lower Aggregate without it: it replaces a grouped lower Aggregate under an 
upper `SUM` of its `COUNT(1)` with a Project of the lower's outputs over the 
lower's child.
   
   Going by the code, with `t.x = [-0.0, 0.0]` (DOUBLE), `SELECT k, sum(c) FROM 
(SELECT cast(x AS STRING) AS k, count(1) AS c FROM t GROUP BY x) GROUP BY k` 
should return `('0.0', 2)`, but the collapsed plan groups `cast(x AS STRING)` 
over the raw rows and returns `('-0.0', 1)` and `('0.0', 1)`, as on the base 
branch. With `WHERE k = '0.0'` on top, the base branch pushed `cast(x AS 
STRING) = '0.0'` raw and returned `('0.0', 1)`; with this PR the pushed filter 
reads `cast(norm(x) AS STRING)`, keeps both rows, and the collapsed plan 
returns `('-0.0', 1)` and `('0.0', 1)`; the first fails the query's own 
predicate, which is the failure this PR sets out to remove. An upper `max(x)` 
or `min(x)` next to the collapsed `SUM` likewise returns `-0.0` where the lower 
Aggregate outputs `0.0`. This affects batch queries; master has the same rule.
   
   **Recommended change:** Move the check that RemoveRedundantAggregates makes 
as upperReadsNormalizedKeys, whether an upper Aggregate would read a lower 
Aggregate's float/double key raw through a lower output computed from it, 
inside an aggregate function or in a computed grouping expression, into 
NormalizeFloatingNumbers as a helper over the upper and lower Aggregates. Call 
it from RemoveRedundantAggregates.isLowerRedundant, and make 
CollapseGroupedSumOfCount.collapse return no rewrite when it holds. Add 
CollapseGroupedSumOfCount optimizer tests and DataFrame aggregate end-to-end 
tests. As with the rest of this backport, make the change on master first and 
then backport it here.
   
   **Why this works:** After the collapse, the upper Aggregate reads a lower 
float/double key raw only through a lower output computed from the key, an 
aggregate function such as MAX or MIN, or a computed grouping expression. 
Refusing the collapse in exactly those cases keeps the normalizing lower 
Aggregate, so the upper reads normalized keys and a filter pushed below it in 
normalized form agrees with the output. An upper Aggregate that groups by the 
key directly normalizes it itself, so it still collapses.
   
   **Scope:** Guard the sum-of-count collapse with the normalized-key check 
RemoveRedundantAggregates already uses, shared through NormalizeFloatingNumbers.
   
   **Compatibility:** Collapses whose upper Aggregate reads no lower 
float/double key, or groups by one directly, happen exactly as before.
   
   **Risks:** Rollups over a grouped COUNT(1) whose upper Aggregate reads a 
lower float/double key through a computed expression, a computed grouping or 
MAX and MIN keep their lower aggregation, so the collapse's saving is lost for 
them; there is no flag, and reverting the change rolls it back. Master has the 
same rule, so changing only this branch would leave the two branches returning 
different rows for these rollups until master gets the same change.
   
   **Constraints:** Share one check between RemoveRedundantAggregates and 
CollapseGroupedSumOfCount rather than copying it, so that if 
RemoveRedundantAggregates later normalizes the upper Aggregate's reads instead 
of keeping the lower one, the collapse follows the same choice. Keep the check 
false for streaming plans, as the PR's other guards are.
   
   **Success:** For t.x = [-0.0, 0.0], SELECT k, sum(c) FROM (SELECT cast(x AS 
STRING) AS k, count(1) AS c FROM t GROUP BY x) GROUP BY k returns ('0.0', 2), 
and with WHERE k = '0.0' on top it still returns only ('0.0', 2). For t.x = 
[-0.0], SELECT k, sum(c) FROM (SELECT pow(x, -1) AS k, count(1) AS c FROM t 
GROUP BY x) GROUP BY k returns Infinity, and an upper max(x) next to the SUM of 
the count returns 0.0. A rollup whose upper Aggregate groups by the lower 
float/double key directly, or reads no float/double key, still collapses to 
SUM(1).
   
   **Verification:**
   - **Regression:** Rollups that sum a grouped COUNT(1) over DOUBLE, FLOAT and 
struct keys holding -0.0 and 0.0, with an upper key computed from the lower 
key, an upper GROUP BY on a cast of it, or MAX and MIN of it, return the rows 
the uncollapsed plan returns, with and without a sign-revealing filter on top, 
and no returned row fails the filter.
   - **Behavior:** The optimized plan keeps the lower Aggregate in those cases 
and still collapses to SUM(1) when the upper Aggregate groups by the 
float/double key directly or reads none.
   - **Compatibility:** RemoveRedundantAggregates keeps and removes the same 
lower Aggregates as before the check moved, and streaming plans are optimized 
as on 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)
+    case _ => e.mapChildren(normalizeGroupingExpressions(_, grouping))

Review Comment:
   **Nit (P3):** This generic case also rewrites subqueries: 
`SubqueryExpression.children` are `outerAttrs ++ joinCond`, and by the time the 
filter is pushed `PullupCorrelatedPredicates` has moved the correlation into 
`joinCond`, so a correlation like `cast(u.y AS STRING) = cast(x AS STRING)` is 
pushed as `cast(u.y AS STRING) = cast(norm(x) AS STRING)` while `u.y = x` stays 
raw. Every subquery the new tests use is uncorrelated (`InSubquery` over a 
`ListQuery(LocalRelation(...))` in FilterPushdownSuite, and `x IN (SELECT y 
FROM u)` and the struct IN/NOT IN queries in DataFrameAggregateSuite). Going by 
the code, with `t.x = [-0.0, 0.0]` and `u.y = [0.0]`, `SELECT x, c FROM (SELECT 
x, count(*) AS c FROM t GROUP BY x) WHERE EXISTS (SELECT 1 FROM u WHERE 
cast(u.y AS STRING) = cast(x AS STRING))` returns `(0.0, 2)` with this PR; if 
the rewrite stopped descending into subquery expressions it would return the 
base branch's `(0.0, 1)` and no test would fail.
   
   **Verification:**
   - **Regression:** A correlated EXISTS or IN subquery whose correlation reads 
a float/double grouping key through a sign-revealing expression returns the 
rows it returns above the Aggregate, for example (0.0, 2) for t.x = [-0.0, 0.0] 
and u.y = [0.0], and the pushed plan reads the normalized key in that 
correlation while a direct equality on the key stays unwrapped.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1007,11 +1024,9 @@ object LimitPushDown extends Rule[LogicalPlan] {
       LocalLimit(exp, project.copy(child = pushLocalLimitThroughJoin(exp, 
join)))
     // Push down limit 1 through Aggregate and turn Aggregate into Project if 
it is group only.
     case Limit(le @ IntegerLiteral(1), a: Aggregate) if a.groupOnly =>
-      val newAgg = EliminateSorts(a.copy(child = LocalLimit(le, 
a.child))).asInstanceOf[Aggregate]
-      Limit(le, Project(newAgg.aggregateExpressions, newAgg.child))
+      Limit(le, pushLimitOneThroughGroupOnlyAggregate(le, a))

Review Comment:
   **Nit (P3):** Both cases under this comment now call 
`pushLimitOneThroughGroupOnlyAggregate`, which keeps the Aggregate when its 
outputs read a float/double key it normalizes, as the new LimitPushdownSuite 
test expects for `groupBy(d)(d).limit(1)`, but the comment above them still 
says the Aggregate is turned into a Project.
   
   ```suggestion
       // Push down limit 1 through a group-only Aggregate, see 
pushLimitOneThroughGroupOnlyAggregate.
       case Limit(le @ IntegerLiteral(1), a: Aggregate) if a.groupOnly =>
         Limit(le, pushLimitOneThroughGroupOnlyAggregate(le, a))
   ```
   
   **Verification:**
   - **Inspection:** The comment above LimitPushDown's LIMIT 1 cases states the 
exception for group-only Aggregates whose outputs read float/double keys they 
normalize, or defers to pushLimitOneThroughGroupOnlyAggregate.



-- 
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]

Reply via email to