spark-test commented on code in PR #60090:
URL: https://github.com/apache/spark/pull/60090#discussion_r4513646905
##########
sql/core/src/test/resources/sql-tests/inputs/window-resolution-edge-cases.sql:
##########
@@ -99,6 +99,148 @@ SELECT col1, MAX(ROW_NUMBER() OVER w) OVER () AS max_rn
FROM t1 WINDOW w AS (ORD
-- Nested windows over an aggregate, and in QUALIFY together with HAVING.
SELECT col1, MAX(RANK() OVER (ORDER BY SUM(col2))) OVER () AS m FROM t1 GROUP
BY col1;
+
+-- HAVING must be evaluated before every nested window layer.
+SELECT
+ k,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER () AS rank_sum
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY k
+HAVING k = 'keep'
+ORDER BY k;
+
+-- HAVING must also precede windows nested in the outer window specification.
+SELECT
+ k,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER (
+ PARTITION BY RANK() OVER (ORDER BY SUM(v) DESC)) AS partition_rank_sum,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER (
+ ORDER BY RANK() OVER (ORDER BY SUM(v) DESC)) AS ordered_rank_sum
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY k
+HAVING k = 'keep'
+ORDER BY k;
+
+-- Three nested window levels, mixed with single-level and two-level windows.
+SELECT
+ k,
+ COUNT(*) OVER () AS group_count,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER () AS rank_sum,
+ MAX(SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER ()) OVER () AS max_rank_sum
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY k
+HAVING k = 'keep'
+ORDER BY k;
+
+-- HAVING on an aggregate alias must precede every nested window layer.
+SELECT
+ k,
+ COUNT(*) AS row_count,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER () AS rank_sum
+FROM VALUES ('drop', 1), ('drop', 1), ('keep', 1) AS input(k, v)
+GROUP BY k
+HAVING row_count = 1
+ORDER BY k;
+
+-- A window alias is not valid in HAVING.
+SELECT
+ k,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER () AS rank_sum
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY k
+HAVING rank_sum = 1;
+
+-- Grouping analytics HAVING must be evaluated before every nested window
layer.
+SELECT
+ k,
+ SUM(RANK() OVER (ORDER BY SUM(v) DESC)) OVER () AS rank_sum
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY ROLLUP(k)
+HAVING k = 'keep'
+ORDER BY k;
+
+-- Grouping analytics HAVING must also precede a single window layer.
+SELECT
+ k,
+ COUNT(*) OVER () AS group_count
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY GROUPING SETS ((k), ())
+HAVING k = 'keep'
+ORDER BY k;
+
+-- Grouping analytics HAVING on a window alias keeps its existing analysis
behavior.
+SELECT
+ k,
+ COUNT(*) OVER () AS group_count
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY GROUPING SETS ((k), ())
+HAVING group_count = 3
Review Comment:
**Nit (P3):** `group_count = 3` compares a `bigint` with an `int` literal,
so it never reaches the new branch in `tryResolveHavingCondition`. Type
coercion skips an operator whose child is the still-unresolved `GROUPING SETS`
aggregate. The condition is therefore unresolved when
`tryResolveHavingCondition` checks it, the method returns early, and the
condition takes the older deferred route. That is why this case fails with the
same `MISSING_ATTRIBUTES` error under both flag values. `GROUPING_ID() = 1` and
`SUM(v) = 1` take the same route. The only grouping-analytics cases that reach
the branch are `k = 'keep'` and `k = (SELECT 'keep')`. No golden would fail if
the branch's `Filter` for a window-output reference, its `Project` that drops
HAVING-only aggregates, or its lateral-alias handling regressed.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60090#discussion_r4467450653),
[2](https://github.com/apache/spark/pull/60090#discussion_r4483274253).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -978,11 +978,23 @@ class Analyzer(
case a: AttributeReference => attrMap.getOrElse(a, a)
}
- if (extraAggExprs.isEmpty) {
+ val windowOutputSet = AttributeSet(
+ aggregate.aggregateExpressions.zip(newChild.output).collect {
+ case (expr, output) if expr.containsPattern(WINDOW_EXPRESSION) =>
output
+ })
+ val withHaving = if (
+ !conf.getConf(SQLConf.LEGACY_EVALUATE_HAVING_AFTER_INNER_WINDOW) &&
+ windowOutputSet.nonEmpty &&
newCond.references.intersect(windowOutputSet).isEmpty) {
+ UnresolvedHaving(newCond, newChild)
Review Comment:
**Non-blocking (P2):** This new `UnresolvedHaving` breaks grouping-analytics
queries that use a lateral column alias. `ResolveLateralColumnAliasReference`
deliberately leaves an `Aggregate` under `UnresolvedHaving` untouched, and a
`LateralColumnAliasReference` counts as resolved. Later in the same batch, the
HAVING case of `ExtractWindowExpressions` matches this aggregate and throws
`UNSUPPORTED_FEATURE.LATERAL_COLUMN_ALIAS_IN_AGGREGATE_WITH_WINDOW_AND_HAVING`.
On the base branch, the `Filter` parent let the lateral-alias rule lift the
aggregate into a `Project`, and the query analyzed. For example, this query
returns the `a` and `b` rows on the base branch and now fails by default:
```sql
SELECT k, SUM(v) AS s, s * 2 AS s2, SUM(SUM(v)) OVER (PARTITION BY k) AS ps
FROM VALUES ('a', 1), ('b', 2) AS t(k, v)
GROUP BY ROLLUP(k)
HAVING k IS NOT NULL
```
Its base-branch rows were already correct, because dropping the grand-total
group cannot change another partition. The migration note does not mention the
new error, and no golden uses a lateral alias on this route.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4935,19 +4963,48 @@ object ResolveUnresolvedHaving extends
Rule[LogicalPlan] {
*
* Returns None unless the condition can be evaluated below every Window in
the chain.
*/
- private def insertFilterBeforeWindow(filter: Filter): Option[LogicalPlan] =
filter.child match {
- case project: Project =>
- insertFilterBeforeWindow(filter.copy(child = project.child))
+ private def insertFilterBeforeWindow(filter: Filter): Option[LogicalPlan] = {
+ if
(SQLConf.get.getConf(SQLConf.LEGACY_EVALUATE_HAVING_AFTER_INNER_WINDOW)) {
+ insertFilterBeforeOuterWindow(filter)
+ } else {
+ insertFilterBeforeAllWindows(filter, foundWindow = false)
+ }
+ }
+
+ private def insertFilterBeforeAllWindows(
+ filter: Filter,
+ foundWindow: Boolean): Option[LogicalPlan] = filter.child match {
+ case project: Project if
filter.condition.references.subsetOf(project.child.outputSet) =>
+ insertFilterBeforeAllWindows(filter.copy(child = project.child),
foundWindow)
.map(child => project.withNewChildren(Seq(child)))
- case generate: Generate =>
- insertFilterBeforeWindow(filter.copy(child = generate.child))
+ case generate: Generate if
filter.condition.references.subsetOf(generate.child.outputSet) =>
+ insertFilterBeforeAllWindows(filter.copy(child = generate.child),
foundWindow)
.map(child => generate.withNewChildren(Seq(child)))
- case window: Window =>
- insertFilterBeforeWindowChain(filter, window)
+ case window: Window if
filter.condition.references.subsetOf(window.child.outputSet) =>
+ insertFilterBeforeAllWindows(filter.copy(child = window.child),
foundWindow = true)
+ .map(child => window.withNewChildren(Seq(child)))
+ case _ if foundWindow && !filter.child.containsPattern(WINDOW) &&
Review Comment:
**Blocking (P1):** In default mode this guard checks the stop node's whole
subtree, not just the SELECT-list window chain. Tree-pattern bits are unioned
over children, expressions, and subquery plans, so any `Window` below the
grouping `Aggregate` makes the walk return `None`. That includes a FROM-clause
derived table or view with a window function, a windowed join input, and a
WHERE subquery that uses one. `ResolveUnresolvedHaving` then keeps HAVING above
every SELECT-list window, and those windows count the groups that HAVING
removes. For example:
```sql
SELECT explode(array(k)) AS g, COUNT(*) OVER () AS c, k
FROM (SELECT k, v, ROW_NUMBER() OVER (ORDER BY v) AS rn
FROM VALUES ('drop', 2), ('keep', 1) AS t(k, v)) s
GROUP BY k
HAVING k = 'keep'
```
This returns `(keep, 2, keep)` by default. The base branch, and this PR with
`spark.sql.legacy.evaluateHavingAfterInnerWindow=true`, return `(keep, 1,
keep)`, as the Spark 4.3 migration note promises for generator queries. With
nested SELECT-list windows over such an input, every layer now sees the removed
groups. No generator golden reads from a windowed input.
Suggested fix: bound the check to the chain the walk descends through.
Accept the stop node unless a `Window` is reachable from it through `Project`,
`Generate`, and `Window` nodes. That still rejects a stop at or above a lower
window of the chain, and it no longer looks inside the aggregate's input.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60090#pullrequestreview-5770227938).
**Verification:**
- **Regression:** A generator query with COUNT(*) OVER () and a HAVING on
the grouping key evaluates HAVING before the window whenever the aggregate's
input contains a window function: when it reads from a derived table that uses
ROW_NUMBER(), and when its WHERE clause has a subquery that uses a window
function. For the ('drop', 2), ('keep', 1) input, with both rows kept by the
WHERE clause, the window counts 1, not 2.
- **Regression:** The same windowed-input shape with nested SELECT-list
windows places HAVING below every window layer and returns the corrected nested
result.
- **Behavior:** Generator queries whose HAVING reads a lower window's alias
keep HAVING above the whole window chain in both SELECT-list orders.
- **Compatibility:** With the legacy flag set to true, the windowed-input
generator queries keep their base-branch plans and results.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4935,19 +4963,48 @@ object ResolveUnresolvedHaving extends
Rule[LogicalPlan] {
*
* Returns None unless the condition can be evaluated below every Window in
the chain.
*/
- private def insertFilterBeforeWindow(filter: Filter): Option[LogicalPlan] =
filter.child match {
- case project: Project =>
- insertFilterBeforeWindow(filter.copy(child = project.child))
+ private def insertFilterBeforeWindow(filter: Filter): Option[LogicalPlan] = {
Review Comment:
**Nit (P3):** The Scaladoc above this method is unchanged from the base
branch. It still describes a single search through `Project` and `Generate`
nodes for "a Window chain". The method now dispatches on
`spark.sql.legacy.evaluateHavingAfterInnerWindow`. By default,
`insertFilterBeforeAllWindows` also descends through `Window` nodes and the
`Project`s between window layers, and either places HAVING below every
SELECT-list window or leaves it above all of them. With the flag set to true,
`insertFilterBeforeOuterWindow` places it only below the first contiguous run
of `Window` operators, which can put it between two layers. For a nested
generator chain, a reader cannot tell which of those two plans the method
produces. The Scaladoc could describe both branches, as the
`addWindowWithHaving` Scaladoc now does.
**Verification:**
- **Inspection:** The insertFilterBeforeWindow Scaladoc names the legacy
flag, describes the placement each value produces, and agrees with the stop
check being limited to the window chain.
--
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]