cloud-fan commented on code in PR #59460:
URL: https://github.com/apache/spark/pull/59460#discussion_r4551792798
##########
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.flatMap {
Review Comment:
**Non-blocking (P2):** With the sanity check now unwrapping `SortOrder`
first, a grouped constant-key group reaches the single-distinct path. But the
key that this strategy builds a few lines below (`distinctExpressions`, lines
664-670) still drops foldable children before it maps `SortOrder` to its child.
`SortOrder` is never foldable, so when the ordered `LISTAGG` is the first
distinct aggregate, its wrapped constant survives as the single-distinct key.
`AggUtils.planAggregateWithOneDistinct` then replaces every subexpression
canonically equal to a key with the key attribute. That includes a delimiter
literal equal to the constant, and `ListAgg.getDelimiterValue` evaluates the
delimiter without an input row.
Reading the code, for
```sql
SELECT k, listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY ','),
count(DISTINCT ',')
FROM VALUES (1), (1), (2) AS t(k) GROUP BY k
```
the rule leaves one unfiltered distinct group unrewritten and the sanity
check passes. The key is then `[',']`, the delimiter becomes the key attribute,
and the query fails at execution with an internal error. With `count(DISTINCT
',')` listed first, the key is empty and the query returns `(1, ',', 1)` and
`(2, ',', 1)`. The same failure happens next to an unordered `listagg(DISTINCT
',', ',')`, and when `','` comes from a projected literal column. A lone
grouped `listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER BY ',')` already fails
the same way on the base branch. No wrong rows are returned, and the base
branch also failed on the merged queries, with the `ClassCastException`. The
new tests use the constant `'a'` with the delimiter `','`, so they never hit
this case.
The previous review said `distinctExpressions` did not need to change. That
holds only when the delimiter differs from the constant.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59460#discussion_r4545535009).
**Recommended change:** In the planner's Aggregation strategy, build the
single-distinct key the way the sanity check above it now builds each distinct
aggregate's set: replace every SortOrder child with its children first, then
drop constants, keeping the first distinct aggregate's argument order. Compute
both from one local helper in the strategy so the two cannot drift apart again.
Add DataFrame aggregate tests in which a grouped ordered DISTINCT LISTAGG's
constant argument equals its delimiter and the LISTAGG is listed first, plus a
global variant of the same LISTAGG on empty and non-empty input.
**Why this works:** Every other distinct aggregate reaches the
single-distinct substitution with constant-free keys, because constants are
dropped before the key is built, and the substitution depends on that: a
constant key would also match equal literals elsewhere in the function, such as
the delimiter. Dropping constants after unwrapping SortOrder restores the
property for ordered LISTAGG. A constant-only ordered DISTINCT LISTAGG then
gets an empty key, which the planner already handles under GROUP BY, so no
literal is substituted and the delimiter keeps its value. Keys over
non-constant expressions come out exactly as before.
**Compatibility:** Single-distinct keys for aggregates without SortOrder
children, and for WITHIN GROUP keys over non-constant expressions, stay exactly
as they are. Global constant-only distinct aggregates keep going through the
Expand rewrite and keep returning NULL on empty input.
**Risks:** Grouped queries whose only distinct keys are constants inside
WITHIN GROUP ordering, such as a lone listagg(DISTINCT 'a', ',') WITHIN GROUP
(ORDER BY 'a') with GROUP BY k, get a different plan: the first aggregate no
longer groups by the constant. Results stay the same, and reverting the change
restores the old plan. An empty key is correct only under GROUP BY, because a
global aggregate with an empty key returns one row on empty input. The change
relies on the optimizer rule continuing to send global constant-only distinct
aggregates through the Expand rewrite.
**Constraints:** Keep the optimizer rule's SortOrder-unwrapped foldability
test in mustRewrite, and its comment, unchanged; they keep global constant-only
distinct aggregates away from an empty key. Keep the key's order and repeated
entries for non-constant arguments, such as [s, s] for listagg(DISTINCT s)
WITHIN GROUP (ORDER BY s) and [CAST(i AS STRING), i] for the cast form, because
the distinct attributes are matched to the key by position.
**Exclusions:**
- Removing repeated keys such as [s, s], which the single-distinct path
already produces for a lone ordered DISTINCT LISTAGG on the base branch.
- Changing the substitution in planAggregateWithOneDistinct itself, which is
not needed once the key holds no constants.
- Sharing one helper between the optimizer rule and the planner across
modules.
**Verification:**
- **Regression:** A grouped query with listagg(DISTINCT ',', ',') WITHIN
GROUP (ORDER BY ',') listed before count(DISTINCT ','), and one with it listed
before an unordered listagg(DISTINCT ',', ','), return ',' with a count of 1,
or ',' twice, for every group instead of an internal error.
- **Regression:** The same grouped query with the constant taken from a
projected literal column equal to the delimiter, and a grouped listagg(DISTINCT
',', ',') WITHIN GROUP (ORDER BY ',') on its own, return ',' for every group.
- **Compatibility:** A global listagg(DISTINCT ',', ',') WITHIN GROUP (ORDER
BY ','), alone and with sum(v), returns NULL and a NULL sum on empty input, and
',' with the sum on non-empty input.
- **Inspection:** The sanity check and the single-distinct key come from one
computation that replaces SortOrder children with their children before
dropping constants, and for aggregate functions without SortOrder children, or
with WITHIN GROUP keys over non-constant expressions, the key is the same
sequence as before.
--
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]