spark-test commented on code in PR #60090:
URL: https://github.com/apache/spark/pull/60090#discussion_r4520661153


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -3860,6 +3860,25 @@ class Analyzer(
       Project(windowOps.output ++ newExpressionsWithWindowFunctions, windowOps)
     } // end of addWindow
 
+    /**
+     * Extracts all nested window expressions and places the HAVING filter 
below every Window.
+     */
+    private def addWindowWithHaving(

Review Comment:
   Thanks, the deferral fixes the main cases: by default these conditions now 
sit directly above the constructed aggregate, below every window layer, and the 
legacy goldens keep the old plans. This review raises two related gaps: a 
HAVING condition with a nondeterministic expression still runs after the 
windows, and the check for window outputs also counts window functions inside 
SELECT-list subqueries.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4483274253","thread_id":"inline:4483274253","verdict_sha256":"9a44e4eb39e25daa1ff19c07eba62246851e79f49216e1120af7e116395299ab"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4971,12 +5040,19 @@ object ResolveUnresolvedHaving extends 
Rule[LogicalPlan] {
         if havingCondition.resolved && child.resolved =>
         val filter = Filter(condition = havingCondition, child = child)
         insertFilterBeforeWindow(filter).getOrElse(filter)
+      case d @ DeferredHaving(condition, child) if d.resolved =>

Review Comment:
   **Blocking (P1):** This case runs in the last analyzer batch, after 
`HandleSpecialCommand`. That rule calls `checkAnalysis` on every resolved 
analysis-only command and marks its query analyzed, which turns the query into 
an inner child. `ResolveUnresolvedHaving` reaches neither inner children nor 
analyzed subtrees, so a `DeferredHaving` inside a command's query is never 
converted, and no optimizer rule or planner strategy handles it.
   
   By the review's reading of the code, with default settings and a v2 catalog 
`testcat`:
   
   ```sql
   CREATE TABLE testcat.ns.t AS
   SELECT k, COUNT(*) OVER () AS c
   FROM VALUES ('drop', 2), ('keep', 1) AS t(k, v)
   GROUP BY ROLLUP(k)
   HAVING k = 'keep'
   ```
   
   `CreateTableAsSelectExec` creates the table, then `writeToTable` runs the 
frozen query through a new `QueryExecution` whose analysis skips it again, so 
planning fails with `No plan for DeferredHaving`, reported as an internal 
error, and the table is dropped. REPLACE TABLE AS SELECT takes the same path. 
On the base branch the HAVING is already a `Filter` when the command is 
checked, and the statement writes its row.
   
   The same early check also validates the marker as a subquery host: `CREATE 
VIEW`, `ALTER VIEW ... AS` and `CACHE TABLE ... AS SELECT` of such a query 
whose HAVING has an `IN`, `EXISTS` or correlated scalar subquery fail at 
creation with `UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY`, although the bare 
SELECT runs. With `spark.sql.legacy.storeAnalyzedPlanForView=true`, temporary 
views and `CACHE TABLE ... AS SELECT` store the unconverted plan, which fails 
when read. v1 data source and Hive CTAS are not affected, because they 
re-analyze their query when they write. No test runs a command over a deferred 
HAVING.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1030,11 +1042,37 @@ class Analyzer(
         case a: AttributeReference => attrMap.getOrElse(a, a)
       }
 
+      val windowOutputSet = AttributeSet(
+        aggregate.aggregateExpressions.zip(newChild.output).collect {
+          case (expr, output) if expr.containsPattern(WINDOW_EXPRESSION) => 
output

Review Comment:
   **Blocking (P1):** `containsPattern(WINDOW_EXPRESSION)` reads tree-pattern 
bits, and a subquery expression's bits include its plan's, so a SELECT-list 
subquery that uses a window function counts as a window output here. Window 
extraction and `Aggregate.resolved` walk only the expression tree and treat 
that item as an ordinary expression. By the review's reading of the code, two 
effects follow.
   
   When such a subquery is the only window-bearing item, HAVING is deferred 
over an aggregate that no window extraction touches, so `DeferredHaving` sits 
directly on the resolved `Aggregate` until the last batch. 
`ResolveReferencesInSort` and `ResolveAggregateFunctions` resolve ORDER BY 
aggregates only under an `Aggregate` or a `Filter` over one, so this query, 
which analyzed on the base branch, now fails with an unresolved column:
   
   ```sql
   SELECT k,
     (SELECT MAX(rn) FROM (SELECT ROW_NUMBER() OVER (ORDER BY x) AS rn
                           FROM VALUES (1) AS q(x))) AS sq
   FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
   GROUP BY ROLLUP(k)
   HAVING k = 'keep'
   ORDER BY SUM(v)
   ```
   
   Such queries also lose the `UpdateOuterReferences` rewrite of outer 
aggregate references in HAVING subqueries, and they reach the command failure 
this review raises separately.
   
   When the HAVING reads such an alias, for example `HAVING sq = 1 AND k = 
'keep'` next to `COUNT(*) OVER () AS group_count`, the condition counts as 
reading a window output and stays above every real window, so `group_count` 
would still be 3 instead of the 1 that `GROUP BY k` gives, although the 
migration note and the config doc say such conditions now run first.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60090#discussion_r4483274253).
   
   **Verification:**
   - **Regression:** By default, the ROLLUP query whose only window is inside a 
SELECT-list subquery, with HAVING k = 'keep' and ORDER BY SUM(v), analyzes and 
returns the keep row with the filter directly over the aggregate.
   - **Regression:** By default, the ROLLUP query with COUNT(*) OVER () AS 
group_count and HAVING sq = 1 AND k = 'keep', where sq is a windowed subquery 
alias, returns group_count 1, as GROUP BY k does, and with the legacy flag it 
returns the base-branch value 3.
   - **Compatibility:** A grouping-analytics HAVING that reads a real 
SELECT-list window alias keeps the filter above every window under both flag 
values.



##########
sql/core/src/test/resources/sql-tests/inputs/window-resolution-edge-cases.sql:
##########
@@ -99,6 +99,227 @@ 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;
+
+-- Lateral aliases must be resolved before grouping analytics HAVING is 
deferred.
+SELECT
+  k,
+  SUM(v) AS s,
+  s * 2 AS s2,
+  SUM(SUM(v)) OVER (PARTITION BY k) AS partition_sum
+FROM VALUES ('a', 1), ('b', 2) AS input(k, v)
+GROUP BY ROLLUP(k)
+HAVING k IS NOT NULL
+ORDER BY k;
+
+-- Lateral aliases do not prevent HAVING from preceding the window.
+SELECT
+  k,
+  SUM(v) AS s,
+  s * 2 AS s2,
+  COUNT(*) OVER () AS group_count
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY ROLLUP(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 = 3L
+ORDER BY k;
+
+-- Grouping functions keep their existing placement and must still be 
rewritten.
+SELECT
+  k,
+  COUNT(*) OVER () AS group_count
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY GROUPING SETS ((k), ())
+HAVING GROUPING_ID() = 1L
+ORDER BY k;
+
+-- Aggregates used only by HAVING must remain available until the filter is 
evaluated.
+SELECT
+  k,
+  COUNT(*) OVER () AS group_count
+FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
+GROUP BY ROLLUP(k)
+HAVING SUM(v) = 1L

Review Comment:
   **Nit (P3):** With `1L` this golden still has the same analyzed plan by 
default and with the legacy flag: `Window` over `Project [k]` over `Filter 
(sum(v) = 1)` over the `Aggregate`, which is the older route. When 
`tryResolveHavingCondition` first sees this condition, `v` only becomes a 
`TempResolvedColumn` inside that method and `sum` is resolved later in the same 
pass, so the condition is unresolved and the method returns early; by then the 
ROLLUP aggregate has been built, and the HAVING goes through 
`ExtractWindowExpressions` and `ResolveAggregateFunctions` instead. No other 
golden adds a HAVING-only aggregate on this route, so the `Project` that drops 
HAVING-only aggregates above `DeferredHaving` never runs in a test, and a 
regression there would go unnoticed. A HAVING-only aggregate whose arguments 
are literals, such as `HAVING COUNT(*) = 1L`, is already resolved at that point 
and would reach it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60090#discussion_r4513646905).
   
   **Verification:**
   - **Regression:** A grouping-analytics query whose HAVING reads only an 
aggregate that is absent from the SELECT list and already resolved before the 
aggregate is built has different default and legacy plans and results: by 
default the window counts only the surviving groups and the output omits the 
HAVING-only aggregate.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1030,11 +1042,37 @@ class Analyzer(
         case a: AttributeReference => attrMap.getOrElse(a, a)
       }
 
+      val windowOutputSet = AttributeSet(
+        aggregate.aggregateExpressions.zip(newChild.output).collect {
+          case (expr, output) if expr.containsPattern(WINDOW_EXPRESSION) => 
output
+        })
+      val filter = Filter(newCond, newChild)
+      val canDeferHaving =
+        !conf.getConf(SQLConf.LEGACY_EVALUATE_HAVING_AFTER_INNER_WINDOW) &&
+          windowOutputSet.nonEmpty && 
newCond.references.intersect(windowOutputSet).isEmpty
+      val withHaving = if (!canDeferHaving) {
+        filter
+      } else if (hasGroupingFunction(newCond)) {
+        // TODO: Defer grouping functions after they can be rewritten outside 
the main batch.
+        filter
+      } else {
+        val liftedChild = resolveLateralColumnAliases(newChild)
+        if (!liftedChild.containsPattern(LATERAL_COLUMN_ALIAS_REFERENCE)) {
+          val liftedAttrMap = 
AttributeMap(newChild.output.zip(liftedChild.output))
+          val remappedCondition = newCond.transform {
+            case a: AttributeReference => liftedAttrMap.getOrElse(a, a)
+          }
+          DeferredHaving(remappedCondition, liftedChild)

Review Comment:
   **Blocking (P1):** The parser puts QUALIFY directly over HAVING, and 
`ResolveQualify` runs in the main batch right after window extraction, while 
the `DeferredHaving` created here stays until the last batch. Once window 
extraction resolves the marker's child, `ResolveQualify` fires: 
`resolveQualifyCondition` treats the marker as a leaf, and `hasWindowInPlan` 
recognizes only `Window`, `Project` and `Filter`, so it does not see the 
windows below. A QUALIFY condition without its own window function then throws 
`QUALIFY_REQUIRES_WINDOW_FUNCTION`, whose message wrongly says the query has no 
window function.
   
   By the review's reading of the code, with default settings this query fails 
analysis:
   
   ```sql
   SELECT k, RANK() OVER (PARTITION BY k ORDER BY SUM(v)) AS rnk
   FROM VALUES ('a', 1), ('b', 2) AS input(k, v)
   GROUP BY ROLLUP(k)
   HAVING k IS NOT NULL
   QUALIFY rnk = 1
   ```
   
   On the base branch the child is a `Filter` over the window chain, so it 
would return `(a, 1)` and `(b, 1)`, which is also the correct result because 
each partition holds one group. Queries this PR sets out to fix fail the same 
way, such as one with `COUNT(*) OVER () AS group_count`, `HAVING k = 'keep'` 
and `QUALIFY group_count > 0`. Because the leaf case also stops at the marker, 
a QUALIFY that reads a grouping column outside the SELECT list, which the base 
branch adds to the aggregate, now stays unresolved. This holds with or without 
lateral column aliases, and no golden combines grouping analytics, a deferrable 
HAVING, a window and QUALIFY.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4960,9 +5014,24 @@ object RemoveTempResolvedColumn extends 
Rule[LogicalPlan] {
 }
 
 /**
- * Rule that's used to handle `UnresolvedHaving` nodes with resolved 
`condition` and `child`.
- * It's placed outside the main batch to avoid conflicts with other rules that 
resolve
- * `UnresolvedHaving` in the main batch.
+ * Holds a resolved HAVING condition until window extraction finishes while 
preserving its child's
+ * output for parent resolution.
+ */
+private[analysis] case class DeferredHaving(
+    condition: Expression,
+    child: LogicalPlan) extends OrderPreservingUnaryNode {

Review Comment:
   **Non-blocking (P2):** Because this marker is a resolved unary node whose 
output is its child's, `PullOutNondeterministic`, which runs before the last 
batch, rewrites it as it rewrites any such node: it moves the nondeterministic 
expression into a new `Project` below the marker and makes the condition read 
the new `_nondeterministic` attribute. `insertFilterBeforeAllWindows` then 
cannot descend past that `Project`, because the attribute is not in its child's 
output, and keeps the `Filter` above every window. By the review's reading of 
the code, this query would still return `group_count = 3`, as on the base 
branch:
   
   ```sql
   SELECT k, COUNT(*) OVER () AS group_count
   FROM VALUES ('drop', 2), ('keep', 1) AS input(k, v)
   GROUP BY ROLLUP(k)
   HAVING k = 'keep' AND rand() < 2D
   ```
   
   Without `rand()`, or with `GROUP BY k`, it would return 1. The migration 
note and the config doc say such conditions now run before the windows, and the 
PR defers only grouping functions. Plain GROUP BY and generator queries are not 
affected, because `PullOutNondeterministic` leaves a `Filter` and an unresolved 
node alone. No test covers a nondeterministic HAVING on this route.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60090#discussion_r4483274253).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/resources/sql-tests/inputs/window-resolution-edge-cases.sql:
##########
@@ -99,6 +99,227 @@ 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;
+
+-- Lateral aliases must be resolved before grouping analytics HAVING is 
deferred.

Review Comment:
   **Nit (P3):** These cases use one alias level (`SUM(v) AS s, s * 2 AS s2`) 
and a HAVING on `k`. `resolveLateralColumnAliases` converges for them after two 
applications of `ResolveLateralColumnAliasReference`, while a chained alias 
such as `s2 + 1 AS s3` needs a third, because the first unwrap leaves the 
reference to `s2` for a later round. And because the condition reads `k`, the 
placement walk always ends at the `Aggregate`, so its terminal case on a 
lifted-alias `Project`, and the `Project` and `Generate` branches of 
`hasWindowInWindowChain`, never run. By the review's reading of the code, a 
lift capped at two rounds, or a terminal accepted only on an `Aggregate`, would 
leave every new golden unchanged, yet a query that adds `s2 + 1 AS s3` with 
`HAVING k = 'keep'`, or one with `HAVING s = 1L`, would fall back to HAVING 
above the window and count the removed groups (`group_count` 3 instead of 1). 
The literal must be `1L`: with an int literal the condition needs a cast and 
takes t
 he older route.
   
   **Verification:**
   - **Regression:** A grouping-analytics query whose lateral aliases chain 
through three levels evaluates a grouping-key HAVING below the window by 
default and counts only the surviving groups.
   - **Regression:** A grouping-analytics query with lateral aliases whose 
HAVING reads a lifted aggregate alias places the filter directly above the 
Project that defines the alias, below the window, by default, and keeps it 
above the window with the legacy flag.



##########
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:
   Thanks, the type-matched literals helped: the window-output case now 
analyzes, the grouping-function filter stays above the window, and the 
lateral-alias plans change with the flag, so those cases reach the new branch. 
The HAVING-only aggregate case still does not: `HAVING SUM(v) = 1L` has the 
same plan by default and with the legacy flag, so no golden reaches the 
projection that drops HAVING-only aggregates above the deferred HAVING. This 
review raises that remaining gap, with its cause and a case that does reach the 
branch.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4513646905","thread_id":"inline:4513646905","verdict_sha256":"9a44e4eb39e25daa1ff19c07eba62246851e79f49216e1120af7e116395299ab"}
 -->



##########
sql/core/src/test/resources/sql-tests/inputs/window-resolution-edge-cases.sql:
##########
@@ -99,6 +99,227 @@ 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.

Review Comment:
   **Nit (P3):** This block starts between the two queries of the existing 
section headed `-- Nested windows over an aggregate, and in QUALIFY together 
with HAVING.` at line 100. The QUALIFY-with-HAVING query that comment 
describes, which directly followed the section's first query on the base 
branch, now sits after `RESET spark.sql.legacy.evaluateHavingAfterInnerWindow` 
at line 323 with no comment of its own, and the regenerated analyzer and result 
goldens carry the same order. Moving the new tests after that query, in their 
own section, and regenerating the goldens restores it.
   
   **Verification:**
   - **Inspection:** The section comment about nested windows and QUALIFY with 
HAVING is followed by both of its queries, and the regenerated golden files 
differ from the current ones only in order.



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