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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4364,8 +4364,17 @@ class Analyzer(
         (newCond, newAgg)
 
       case p: Project =>
-        // First resolve against this Project's children output.
-        val resolved = resolveExpressionByPlanChildren(cond, p)
+        // First resolve against this Project's children output, leaving out 
the attributes of the
+        // window functions that ExtractWindowExpressions moved below it. They 
are SELECT aliases,
+        // and an input column with the same name takes precedence over them. 
A name that only
+        // matches such an alias is resolved against the SELECT list 
afterwards.
+        val windowAttrs = windowOutputs(p.child)
+        val resolved = if (windowAttrs.isEmpty) {
+          resolveExpressionByPlanChildren(cond, p)
+        } else {
+          val inputs = Project(p.child.output.filterNot(windowAttrs.contains), 
p.child)

Review Comment:
   **Blocking (P1):** `inputs` removes only the attributes that Window nodes 
define, so any other SELECT alias in `p.child.output` stays in it and is 
treated like an input column: a non-window item computed in the Project below 
the windows, an aggregate alias, or an alias of an expression built on a window 
function, which addWindow's Project defines. When such an alias has the same 
name as a bare window alias and no input column does, the lookup on line 4376 
now finds one candidate where the base branch found two. `SELECT score AS rn, 
ROW_NUMBER() OVER (ORDER BY score DESC) AS rn FROM VALUES (1, 1), (2, 20), (3, 
10) AS t(id, score) QUALIFY rn = 1` fails with AMBIGUOUS_REFERENCE on the base 
branch; by my reading of the code it now binds `score AS rn` and returns (1, 3) 
with no error, while a filter on the window value would return (20, 1). The 
aggregate form `SELECT a, SUM(b) AS rn, ROW_NUMBER() OVER (ORDER BY a) AS rn 
FROM testData2 GROUP BY a QUALIFY rn = 1` likewise binds `SUM(b)` 
 now. The QUALIFY docs rank input columns ahead of SELECT aliases, not one 
SELECT alias ahead of another, so this reference should stay ambiguous, and 
when an input column does have the name, the other alias should not win over it 
either.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4394,6 +4403,17 @@ class Analyzer(
         (resolved, other)
     }
 
+    /**
+     * The attributes defined by the Window nodes of this query block below 
`plan`, which
+     * `ExtractWindowExpressions` creates for the window functions of the 
SELECT list. They are
+     * above the Aggregate of the block, if any, and below the Projects of the 
SELECT list.
+     */
+    private def windowOutputs(plan: LogicalPlan): AttributeSet = plan match {
+      case w: Window => w.windowOutputSet ++ windowOutputs(w.child)
+      case p: Project => windowOutputs(p.child)

Review Comment:
   **Non-blocking (P2):** This case walks through the Projects without 
collecting the aliases they compute, and ExtractWindowExpressions makes a 
SELECT alias a Window output only when the item is a bare aliased window 
function (Analyzer.scala:3776-3779). An item that wraps a window function, such 
as `ROW_NUMBER() OVER (ORDER BY score DESC) + 0 AS rn` or `CAST(ROW_NUMBER() 
OVER (...) AS BIGINT) AS rn`, is computed in addWindow's Project from an 
internal `_weN` column, and a non-window item of a SELECT list with a window 
function is computed in the Project below the windows, so neither is left out 
and both still win over a same-named input column. Over t(id, score, rn) 
holding (1, 30, 0), (2, 20, 0), (3, 10, 1), by my reading of the code the bare 
form with `QUALIFY rn = 1` now returns (3, 3), the `+ 0` form still returns (1, 
1), and `SELECT id, score * 10 AS rn, ROW_NUMBER() OVER (ORDER BY id) AS w FROM 
t QUALIFY rn = 1` still filters on `score * 10`. The QUALIFY docs give an input 
col
 umn precedence over any same-named SELECT alias, and the PR description scopes 
out only aggregate aliases.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4364,8 +4364,17 @@ class Analyzer(
         (newCond, newAgg)
 
       case p: Project =>
-        // First resolve against this Project's children output.
-        val resolved = resolveExpressionByPlanChildren(cond, p)
+        // First resolve against this Project's children output, leaving out 
the attributes of the
+        // window functions that ExtractWindowExpressions moved below it. They 
are SELECT aliases,
+        // and an input column with the same name takes precedence over them. 
A name that only
+        // matches such an alias is resolved against the SELECT list 
afterwards.
+        val windowAttrs = windowOutputs(p.child)
+        val resolved = if (windowAttrs.isEmpty) {
+          resolveExpressionByPlanChildren(cond, p)
+        } else {
+          val inputs = Project(p.child.output.filterNot(windowAttrs.contains), 
p.child)
+          resolveExpressionByPlanChildren(cond, p.copy(child = inputs))

Review Comment:
   **Blocking (P1):** When no column matches, `resolveExpression` falls back to 
`LiteralFunctionResolution` (ColumnResolutionHelper.scala:158-165), which maps 
current_user, user, session_user, current_date, current_timestamp, 
current_time, localtime, and grouping__id to built-in functions. With the 
window outputs removed from this lookup, a window alias with one of those names 
finds no column, so it binds the function, the condition counts as resolved, 
and the SELECT-output fallback in `apply` never sees the alias. With the 
default `spark.sql.ansi.enforceReservedKeywords=false`, `SELECT id, 
FIRST_VALUE(name) OVER (ORDER BY id) AS user FROM VALUES (1, 'alice'), (2, 
'bob') AS t(id, name) QUALIFY user = 'alice'` filters on the window value on 
the base branch; by my reading of the code it now compares `current_user()` 
with 'alice' and returns both rows or none depending on the session user, and a 
filter such as `QUALIFY user IS NOT NULL` keeps every row. A backquoted name 
takes the same 
 path. HAVING and ORDER BY bind such a name to the SELECT alias, and the PR 
description says a name that only matches a window alias still resolves to that 
alias as before.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4394,6 +4403,17 @@ class Analyzer(
         (resolved, other)
     }
 
+    /**
+     * The attributes defined by the Window nodes of this query block below 
`plan`, which
+     * `ExtractWindowExpressions` creates for the window functions of the 
SELECT list. They are
+     * above the Aggregate of the block, if any, and below the Projects of the 
SELECT list.
+     */
+    private def windowOutputs(plan: LogicalPlan): AttributeSet = plan match {
+      case w: Window => w.windowOutputSet ++ windowOutputs(w.child)

Review Comment:
   **Nit (P3):** The recursion into `w.child` is what leaves out the aliases of 
inner Window nodes; ExtractWindowExpressions stacks one Window per distinct 
partition spec, order spec, and function type, with the first spec in 
SELECT-list order innermost. Every new qualify.sql query has one window 
specification per query block, and no other QUALIFY test has a window alias 
that collides with an input column, so changing this case to `case w: Window => 
w.windowOutputSet` would keep every test green. A query such as `SELECT id, 
ROW_NUMBER() OVER (ORDER BY score DESC) AS rn, SUM(score) OVER () AS total FROM 
VALUES (1, 30, 0), (2, 20, 0), (3, 10, 1) AS t(id, score, rn) QUALIFY rn = 1` 
would pin it: by my reading of the code it returns (3, 3, 60) with the 
recursion and (1, 1, 60) without it.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/resources/sql-tests/inputs/qualify.sql:
##########
@@ -54,3 +54,28 @@ QUALIFY a = 1;
 SELECT a, RANK() OVER (ORDER BY b) AS rank
 FROM testData2
 QUALIFY COUNT(1) > 1;
+
+-- An input column takes precedence over a SELECT alias with the same name

Review Comment:
   **Nit (P3):** The third query under this heading, `SELECT a, SUM(b) AS b, 
... GROUP BY a QUALIFY b > 2`, checks the opposite: its golden plan filters on 
`b#xL`, the alias of `sum(b#x)` (analyzer-results/qualify.sql.out:238 and 242), 
so the aggregate alias wins over the input column `b`. The change gives input 
columns precedence only over bare window function aliases. Narrowing the 
heading, and giving the aggregate query its own comment that says an aggregate 
alias still applies when the same-named input column is not grouped, would keep 
the comments true to what the queries check:
   
   ```suggestion
   -- An input column takes precedence over a same-named window function alias
   ```
   
   See **Shared repair plan 2** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4364,8 +4364,17 @@ class Analyzer(
         (newCond, newAgg)
 
       case p: Project =>
-        // First resolve against this Project's children output.
-        val resolved = resolveExpressionByPlanChildren(cond, p)
+        // First resolve against this Project's children output, leaving out 
the attributes of the
+        // window functions that ExtractWindowExpressions moved below it. They 
are SELECT aliases,
+        // and an input column with the same name takes precedence over them. 
A name that only

Review Comment:
   **Nit (P3):** The PR description and the reply in the Aggregate thread say 
that aggregate aliases are left out on purpose, but this comment speaks only of 
the window-function attributes, so a reader cannot tell that an aggregate alias 
still takes precedence over a same-named grouping column, which HAVING would 
use instead. In `SELECT a AS k, SUM(b) AS a, ROW_NUMBER() OVER (ORDER BY 
SUM(b)) AS rn FROM testData2 GROUP BY a QUALIFY a > 2`, `a` binds to `SUM(b)`, 
so by my reading of the code all three groups pass instead of only a = 3. The 
reason given, that ungrouped input columns cannot be referenced after GROUP BY, 
does not cover a grouping column. A TODO here that names aggregate aliases 
sharing a name with a grouping column would mark the exemption as deliberate.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60749#discussion_r4641884244).
   
   See **Shared repair plan 2** in the review body.



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