holdenk commented on code in PR #59979:
URL: https://github.com/apache/spark/pull/59979#discussion_r4584976396


##########
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:
   Checked by reading: no test in this PR has a correlated subquery over a 
float/double grouping key, and the rewrite in `normalizeGroupingExpressions` 
and the tests are the same on master (`4eecc14b1a6`, #59403). This backport 
stays the same change. It should be fixed on master first and then backported; 
leaving this thread unresolved for that.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
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:
   The stale comment above the LIMIT 1 cases is identical on master 
(`Optimizer.scala:1025` in `4eecc14b1a6`, still there at master tip), so this 
backport stays the same change. It should be fixed on master first and then 
backported; leaving this thread unresolved for that.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



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