cloud-fan commented on code in PR #59460:
URL: https://github.com/apache/spark/pull/59460#discussion_r4545535009


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala:
##########
@@ -625,7 +625,10 @@ abstract class SparkStrategies extends 
QueryPlanner[SparkPlan] {
         val (functionsWithDistinct, functionsWithoutDistinct) =
           aggExpressions.partition(_.isDistinct)
         val distinctAggChildSets = functionsWithDistinct.map { ae =>
-          ExpressionSet(ae.aggregateFunction.children.filterNot(_.foldable))
+          
ExpressionSet(ae.aggregateFunction.children.filterNot(_.foldable).map {
+            case s: SortOrder => s.child
+            case e => e
+          })

Review Comment:
   **Non-blocking (P2):** This drops foldable children before unwrapping 
`SortOrder`, but `RewriteDistinctAggregates.groupDistinctAggs` unwraps first 
(`evalChildren(...).filter(!_.foldable)`, falling back to the first argument 
when nothing is left). `SortOrder` is `Unevaluable`, so it is never foldable: a 
`SortOrder` over a literal survives `filterNot` here and contributes the 
literal, while the rule drops it.
   
   So for constant keys under `GROUP BY` the two views still disagree. Reading 
the code, for
   
   ```sql
   SELECT k, count(DISTINCT 'a'), listagg(DISTINCT 'a', ',') WITHIN GROUP 
(ORDER BY 'a')
   FROM t GROUP BY k
   ```
   
   the rule keys both aggregates on `{'a'}`, sees one distinct group with no 
`FILTER`, and leaves the `Aggregate` unrewritten. This check then computes `{}` 
for `count` and `{'a'}` for `listagg` and throws the internal "query analyzer 
bug" error. An unordered `listagg(DISTINCT 'a', ',')` in place of `count` hits 
the same error, and so, plausibly, does a constant column that 
`FoldablePropagation` turns into such a key. The base branch also failed on 
this query (with the `ClassCastException`), so this is the part of the earlier 
merged-group finding that the fix still misses, not a regression: the alignment 
covers non-constant `WITHIN GROUP` keys only.
   
   Unwrapping before filtering makes the check compute the set the rule groups 
by, and a short comment saying so would keep them in step:
   
   ```suggestion
             ExpressionSet(ae.aggregateFunction.children.flatMap {
               case s: SortOrder => s.children
               case e => Seq(e)
             }.filterNot(_.foldable))
   ```
   
   `distinctExpressions` below does not need to change for this.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59460#issuecomment-6802347289), 
[2](https://github.com/apache/spark/pull/59460#discussion_r4281025876), 
[3](https://github.com/apache/spark/pull/59460#pullrequestreview-5530591938).
   
   **Verification:**
   - **Regression:** A grouped query with listagg(DISTINCT 'a', ',') WITHIN 
GROUP (ORDER BY 'a') next to count(DISTINCT 'a'), without FILTER, returns 1 and 
'a' for every group instead of the internal 'query analyzer bug' error. The 
same holds next to an unordered listagg(DISTINCT 'a', ','), and when the 
constant comes from a subquery column projected as a literal.
   - **Behavior:** The same grouped constant-key queries return the same 
results with the ordered LISTAGG listed before and after the other distinct 
aggregate, so that either one supplies the planner's single-distinct key.
   - **Inspection:** For an aggregate function without SortOrder children the 
sanity check computes the same set as before. For SortOrder children it unwraps 
them before dropping foldable expressions, the order the rule's distinct 
grouping key uses.



##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameAggregateSuite.scala:
##########
@@ -5761,7 +5761,97 @@ class DataFrameAggregateSuite extends SharedSparkSession
     assert(outType.precision == 24 && outType.scale == 6,
       s"expected DecimalType(24, 6) from un-rewritten AVG, got $outType")
   }
+
+  test("SPARK-60124: listagg(DISTINCT ...) with FILTER") {
+    val df = Seq(
+      ("b", 1), ("a", 1), ("a", 1), (null.asInstanceOf[String], 1), ("c", 0)
+    ).toDF("s", "keep")
+
+    checkAnswer(
+      df.selectExpr("listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s) FILTER 
(WHERE keep = 1)"),
+      Seq(Row("a|b"))
+    )
+    checkAnswer(
+      df.selectExpr(
+        "count(DISTINCT keep)",
+        "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s) FILTER (WHERE keep 
= 1)"
+      ),
+      Seq(Row(2, "a|b"))
+    )
+    // Regular listagg alongside two distinct groups forces 
RewriteDistinctAggregates to execute
+    checkAnswer(
+      df.selectExpr(
+        "count(DISTINCT keep)",
+        "count(DISTINCT s)",
+        "listagg(s, '|') WITHIN GROUP (ORDER BY s)"
+      ),
+      Seq(Row(2, 3, "a|a|b|c"))
+    )
+  }
+
+  test("SPARK-60124: listagg(DISTINCT ...) merged single-distinct path without 
FILTER") {
+    val df = Seq(
+      ("b", 1), ("a", 1), ("a", 1), (null.asInstanceOf[String], 1), ("c", 0)
+    ).toDF("s", "keep")
+
+    // count(DISTINCT s) with listagg(DISTINCT s) without FILTER
+    checkAnswer(
+      df.selectExpr(
+        "count(DISTINCT s)",
+        "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s)"
+      ),
+      Seq(Row(3, "a|b|c"))
+    )
+
+    // listagg(DISTINCT s) ASC alongside listagg(DISTINCT s) DESC without 
FILTER
+    checkAnswer(
+      df.selectExpr(
+        "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s ASC)",
+        "listagg(DISTINCT s, '|') WITHIN GROUP (ORDER BY s DESC)"
+      ),
+      Seq(Row("a|b|c", "c|b|a"))
+    )
+  }
+
+  test("SPARK-60124: listagg with ORDER BY expression differing from 
aggregated column") {
+    // 1. Regular listagg with ORDER BY separate column alongside two distinct 
groups
+    // Note: 'b' has ord=1 and 'a' has ord=2 so ord order ("b" then "a") is 
opposite
+    // alphabetical order ("a" then "b"). This verifies ord is used, not s.
+    val df1 = Seq(
+      ("b", 1, 1), ("a", 1, 2), ("a", 1, 2), (null.asInstanceOf[String], 1, 
3), ("c", 0, 4)
+    ).toDF("s", "keep", "ord")
+
+    checkAnswer(
+      df1.selectExpr(
+        "count(DISTINCT keep)",
+        "count(DISTINCT s)",
+        "listagg(s, '|') WITHIN GROUP (ORDER BY ord ASC)"
+      ),
+      Seq(Row(2, 3, "b|a|a|c"))
+    )
+
+    checkAnswer(
+      df1.selectExpr(
+        "count(DISTINCT keep)",
+        "count(DISTINCT s)",
+        "listagg(s, '|') WITHIN GROUP (ORDER BY ord DESC)"
+      ),
+      Seq(Row(2, 3, "c|a|a|b"))
+    )
+
+    // 2. Distinct listagg with ORDER BY separate integer column ensuring 
numeric ordering

Review Comment:
   **Nit (P3):** The query below orders by `i`, the column `listagg` 
aggregates, not by a separate column. What differs is the expression: `listagg` 
aggregates the implicit `CAST(i AS STRING)` while ordering by the integer `i`, 
which is why `9` sorts before `10`.
   
   ```suggestion
       // 2. Distinct listagg ordered by i itself; it aggregates CAST(i AS 
STRING), so order is numeric
   ```
   
   **Verification:**
   - **Inspection:** The comment for the cast-form case no longer calls the 
order key a separate column, and it names ordering by i with the aggregated 
value as i's implicit string cast.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala:
##########
@@ -213,7 +220,7 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
     // non-grouping aggregation queries with distinct aggregate expressions 
will be incorrectly
     // handled by the aggregation strategy, causing wrong results when working 
with empty tables.
     distinctAggs.exists(_.filter.isDefined) || (groupingExpressions.isEmpty &&
-      distinctAggs.exists(_.aggregateFunction.children.forall(_.foldable)))
+      distinctAggs.exists(e => 
evalChildren(e.aggregateFunction.children).forall(_.foldable)))

Review Comment:
   **Non-blocking (P2):** Because `evalChildren` unwraps `SortOrder` here, a 
global `listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY 'x')` now counts as 
all-constant, so a query like
   
   ```sql
   SELECT listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY 'x'), sum(v) FROM t
   ```
   
   is rewritten into an `Expand` plus two `Aggregate`s. On the base branch 
`SortOrder('x')` was not foldable, so this query went to the planner's 
single-distinct path. That path keys it on the literal, because 
`distinctExpressions` keeps the `SortOrder` and maps it to `'x'`, and it 
already returned the right answer, including `NULL` on an empty table. Reading 
the plan, the results stay the same, but every input row now goes through the 
`Expand`, and with a regular aggregate such as `sum(v)` the first aggregate 
reads two rows per input row. The `ClassCastException` fix does not need this: 
a single unfiltered distinct group never reaches 
`patchAggregateFunctionChildren`, and the PR does not say why this shape should 
change plans.
   
   **Recommended change:** Keep the SortOrder-unwrapped foldability test in 
mustRewrite and add a comment at that clause. The comment says that an ordered 
distinct aggregate whose arguments and WITHIN GROUP keys are all constants 
counts as all-foldable, so a global aggregate with it is rewritten like 
COUNT(DISTINCT 1). It also says the rule must not rely on the planner keeping a 
SortOrder-wrapped constant as the single-distinct key, and that the extra 
Expand for such a query is accepted. Add an aggregate end-to-end test for the 
global constant-only ordered LISTAGG on empty and non-empty input.
   
   **Why this works:** Keeping the rewrite means the single-distinct path never 
receives a global aggregate whose distinct arguments are all constants, 
whatever order the planner uses to unwrap SortOrder and drop constants. The 
planner's sanity check, once repaired, deliberately drops such constants, so 
this keeps empty-table results independent of the one planner computation that 
still keeps them. The comment records why the cost stays, so a later cleanup 
does not restore the base branch's routing without the planner change it needs.
   
   **Scope:** Document in mustRewrite why constant-only WITHIN GROUP ordering 
counts as all-foldable and why the rewrite's cost is accepted, and test the 
global constant-only ordered LISTAGG's results.
   
   **Compatibility:** A global aggregate whose distinct arguments are all 
constants, including constants inside WITHIN GROUP ordering, keeps going 
through the Expand rewrite and returns NULL for LISTAGG on an empty table.
   
   **Risks:** A global aggregate whose distinct arguments are constants only 
inside WITHIN GROUP ordering keeps one Expand projection per input row, two 
with a regular aggregate, compared with the base branch. Results are unchanged. 
Restoring the base plan later means changing this clause and the planner's 
single-distinct key together.
   
   **Constraints:** The comment must stay true together with the sanity-check 
repair: after it, the sanity check drops SortOrder-wrapped constants, and only 
the single-distinct key computation still keeps them.
   
   **Exclusions:**
   - Restoring the base branch's single-distinct plan for a global 
constant-only ordered LISTAGG, because that would make its empty-table result 
depend on how the planner unwraps SortOrder.
   
   **Success:** A comment at mustRewrite's foldability clause explains three 
things: an ordered distinct aggregate with only constant arguments and WITHIN 
GROUP keys counts as all-foldable; the rule must not rely on the planner 
keeping a SortOrder-wrapped constant as the single-distinct key; and the extra 
Expand for such a query is accepted. A global listagg(DISTINCT 'x', ',') WITHIN 
GROUP (ORDER BY 'x'), alone or with a regular aggregate, returns NULL on empty 
input and 'x' on non-empty input. This repair changes no plan or result for any 
query.
   
   **Verification:**
   - **Behavior:** A global listagg(DISTINCT 'x', ',') WITHIN GROUP (ORDER BY 
'x'), alone and with sum(v), returns NULL (and a NULL sum) on an empty input 
and 'x' on a non-empty input.
   - **Inspection:** The comment at mustRewrite's foldability clause names the 
case of constants inside WITHIN GROUP ordering, the empty-table reason for 
rewriting it, and the accepted Expand cost.



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