n-young commented on code in PR #60090:
URL: https://github.com/apache/spark/pull/60090#discussion_r4525917647


##########
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:
   Fixed in b970dec8938b. ResolveDeferredHaving now runs immediately after 
ExtractWindowExpressions and before ResolveQualify, so QUALIFY sees the placed 
Filter and window chain. Added regressions both without lateral aliases and 
with lateral aliases plus a grouping column outside the SELECT list.



##########
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:
   Fixed in b970dec8938b. The HAVING-only aggregate case now uses `HAVING 
COUNT(*) = 1L` with data that distinguishes the surviving groups, so it reaches 
the deferred branch and exercises the projection that drops the extra 
aggregate. Default and legacy goldens differ as expected.



##########
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:
   Fixed in b970dec8938b. Restored the existing QUALIFY-with-HAVING query 
directly under its section header, moved the new HAVING cases after that 
section, and regenerated the execution and analyzer goldens.



##########
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:
   Fixed in b970dec8938b. The deferred marker is converted to a Filter in the 
main resolution batch before PullOutNondeterministic runs, so the seeded RAND 
predicate remains below the SELECT-list window chain. Added default and legacy 
golden coverage.



##########
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:
   Fixed in b970dec8938b. Added a third lateral-alias level (`s3`) to exercise 
fixed-point lifting and a separate `HAVING s = 1L` case to exercise placement 
on the lifted-alias Project. Both default and legacy plans/results are covered.



##########
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:
   Fixed in b970dec8938b. DeferredHaving now remains unresolved and is placed 
immediately after ExtractWindowExpressions in the main resolution batch, before 
HandleSpecialCommand can freeze the query. Added v2 CTAS/RTAS coverage, 
including a lateral-alias CTAS, plus CREATE/ALTER VIEW and CACHE TABLE cases 
with HAVING subqueries.



##########
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:
   Fixed in b970dec8938b. Window-output classification now uses expression-only 
traversal (`expr.exists(_.isInstanceOf[WindowExpression])`), which does not 
descend into subquery plans. Added both requested regressions: a subquery-only 
window with ORDER BY SUM(v), and a subquery alias alongside a real window with 
default/legacy results.



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