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


##########
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:
   Checked by reading: `Expression.nullIntolerant` defaults to `false` and 
neither `NormalizeNaNAndZero` nor `KnownFloatingPointNormalized` overrides it, 
so `scanNullIntolerantAttribute` stops at the wrapper. The wrapper and this use 
of it are the same on master (`4eecc14b1a6`, #59403), 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 
-->



##########
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:
   Agreed that `PythonUDAF` also covers grouped-agg Arrow UDFs (see the comment 
at `PythonUDF.scala:275`). The same pandas-only wording is on master in 
`NormalizeFloatingNumbers.scala` (the `outputsNormalizedKeys` and 
`mayChangeKeyForm` Scaladocs) and in the `pushBelowAggregate` comment, 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 
-->



##########
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:
   The comment is identical on master (`PythonUDFSuite.scala:132`), 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 
-->



##########
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:
   Checked by reading `isLowerRedundant`, not by running the test: with the 
DOUBLE `rand(0) as "c"` the upper groups by the key output directly, so 
`upperReadsNormalizedKeys` is false and the lower is removed, which matches 
your description. The integer-key rewrite and its comment are the same on 
master (`RemoveRedundantAggregatesSuite.scala:122`), 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 
-->



##########
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:
   Confirmed that `normalizeGroupingExpressions` is not tested with `<=` in 
that test, and the same test is on master (`FilterPushdownSuite.scala:2846`), 
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 
-->



##########
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:
   The rebuild branch and the staleness suite are identical on master 
(`PushdownPredicatesAndPruneColumnsForCTEDef.scala:249`), 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 
-->



##########
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:
   The guard has no TODO on master either (`RemoveRedundantAggregates.scala`, 
same lines), 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