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


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimitSuite.scala:
##########
@@ -351,6 +352,199 @@ class InferWindowGroupLimitSuite extends PlanTest {
     }
   }
 
+  test("Eliminate the Window/Filter once WindowGroupLimit already truncates to 
one row") {
+    for (cond <- Seq($"rn" === 1, $"rn" <= 1, $"rn" < 2,
+        Literal(1) === $"rn", Literal(1) >= $"rn", Literal(2) > $"rn");
+      order <- Seq(c.desc, c.asc)) {
+      val originalQuery =
+        testRelation
+          .select(a, b, c,
+            windowExpr(RowNumber(),
+              windowSpec(a :: Nil, order :: Nil, windowFrame)).as("rn"))
+          .where(cond)
+
+      val correctAnswer =
+        testRelation
+          .windowGroupLimit(a :: Nil, order :: Nil, RowNumber(), 1)
+          .select(a, b, c, Literal(1).as("rn"))
+
+      comparePlans(
+        Optimize.execute(originalQuery.analyze),
+        WithoutOptimize.execute(correctAnswer.analyze))
+    }
+  }
+
+  test("Eliminate the Window/Filter with a multi-column partition/order spec") 
{
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(Seq(a, b), Seq(c.desc, b.asc), windowFrame)).as("rn"))
+        .where($"rn" === 1)
+
+    val correctAnswer =
+      testRelation
+        .windowGroupLimit(Seq(a, b), Seq(c.desc, b.asc), RowNumber(), 1)
+        .select(a, b, c, Literal(1).as("rn"))
+
+    comparePlans(
+      Optimize.execute(originalQuery.analyze),
+      WithoutOptimize.execute(correctAnswer.analyze))
+  }
+
+  test("Eliminate the Window/Filter also fires with an empty partitionSpec 
when the " +
+      "top-k sort fallback is disabled") {
+    // With the default config, limit == 1 and an empty partitionSpec take the 
Limit+Sort
+    // fallback path instead (see "Insert limit node for top-k computation" 
above) and never
+    // reach this rule's WindowGroupLimit-based elimination. Disabling the 
fallback here forces
+    // the WindowGroupLimit path so the elimination branch is exercised with 
no PARTITION BY.
+    withSQLConf(SQLConf.TOP_K_SORT_FALLBACK_THRESHOLD.key -> "0") {
+      val originalQuery =
+        testRelation
+          .select(a, b, c,
+            windowExpr(RowNumber(),
+              windowSpec(Nil, c.desc :: Nil, windowFrame)).as("rn"))
+          .where($"rn" === 1)
+
+      val correctAnswer =
+        testRelation
+          .windowGroupLimit(Nil, c.desc :: Nil, RowNumber(), 1)
+          .select(a, b, c, Literal(1).as("rn"))
+
+      comparePlans(
+        Optimize.execute(originalQuery.analyze),
+        WithoutOptimize.execute(correctAnswer.analyze))
+    }
+  }
+
+  test("Eliminate the Window/Filter keeps rn's exprId for downstream 
references") {
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"))
+        .where($"rn" === 1)
+        .select(a, b, c, $"rn")
+
+    val result = Optimize.execute(originalQuery.analyze)
+    assert(result.output.map(_.exprId) == 
originalQuery.analyze.output.map(_.exprId))
+    assert(!result.exists(_.isInstanceOf[Window]) && 
!result.exists(_.isInstanceOf[Filter]))
+  }
+
+  test("Eliminate the Window/Filter preserves rn's qualifier and metadata") {
+    val metadata = new MetadataBuilder().putString("tag", "pii").build()
+    val rnAlias = Alias(
+      windowExpr(RowNumber(), windowSpec(a :: Nil, c.desc :: Nil, 
windowFrame)), "rn")(
+      qualifier = Seq("t"), explicitMetadata = Some(metadata))
+
+    val originalQuery =
+      testRelation
+        .select(a, b, c, rnAlias)
+        .where($"rn" === 1)
+        .analyze
+
+    val rnAttr = Optimize.execute(originalQuery).output.last

Review Comment:
   **Nit (P3):** Both assertions read only `output.last`. If the elimination 
stopped firing for an alias that carries a qualifier and explicit metadata, 
`Optimize` would return the `Filter` over the `Window`, whose last output is 
the alias's own attribute with qualifier `Seq("t")` and the same metadata, so 
the test would still pass. Checking that no `Window` or `Filter` remains, as 
the exprId test above does, makes it depend on the rewrite having run:
   
   ```suggestion
       val optimized = Optimize.execute(originalQuery)
       assert(!optimized.exists(_.isInstanceOf[Window]) && 
!optimized.exists(_.isInstanceOf[Filter]))
       val rnAttr = optimized.output.last
   ```
   
   **Verification:**
   - **Regression:** The qualifier and metadata test asserts that no Window or 
Filter remains in the optimized plan, alongside rn's qualifier and metadata. It 
therefore fails if the elimination does not fire for an alias that carries a 
qualifier and explicit metadata.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimit.scala:
##########
@@ -112,20 +152,33 @@ object InferWindowGroupLimit extends Rule[LogicalPlan] 
with PredicateHelper {
           }
           // Pick a rank-like function with the smallest limit
           selectedLimits.minBy(_._1) match {
-            case (limit, rankLikeFunction) if limit <= 
conf.windowGroupLimitThreshold &&
+            case (limit, rankLikeFunction, alias) if limit <= 
conf.windowGroupLimitThreshold &&
               child.maxRows.forall(_ > limit) =>
               if (limit > 0) {
-                val newFilterChild = if 
(rankLikeFunction.isInstanceOf[RowNumber] &&
+                if (rankLikeFunction.isInstanceOf[RowNumber] &&
                   partitionSpec.isEmpty && limit < 
conf.topKSortFallbackThreshold) {
                   // Top n (Limit + Sort) have better performance than 
WindowGroupLimit if the
                   // window function is RowNumber and Window partitionSpec is 
empty.
-                  Limit(Literal(limit), window)
+                  filter.withNewChildren(Seq(Limit(Literal(limit), window)))
                 } else {
                   val windowGroupLimit =
                     WindowGroupLimit(partitionSpec, orderSpec, 
rankLikeFunction, limit, child)
-                  window.withNewChildren(Seq(windowGroupLimit))
+                  if (limit == 1 && windowExpressions.length == 1 && 
window.hint.isEmpty &&
+                    rankLikeFunction.isInstanceOf[RowNumber] &&
+                    isTop1(condition, alias.toAttribute)) {

Review Comment:
   **Blocking (P1):** This branch drops the `Window` and `Filter`, so 
`WindowGroupLimitExec` alone now decides which rows come back, and it does not 
form groups the way `WindowExec` does. `GroupedLimitIterator` starts a new 
group whenever the projected key `UnsafeRow` changes byte for byte 
(`WindowGroupLimitExec.scala:246`), while `WindowExec` compares keys that are 
not binary-stable with an `InterpretedOrdering` 
(`WindowEvaluatorFactory.scala:67-74`). The shuffle hashes collated keys by 
collation and the sort orders them with `semanticCompare`, so collation-equal 
keys arrive together, but the limit still keeps one row each time the key bytes 
change.
   
   Reading the code, for `k STRING COLLATE UTF8_LCASE` with rows `('a', 1), 
('A', 2)`, `SELECT * FROM (SELECT k, ts, row_number() OVER (PARTITION BY k 
ORDER BY ts) AS rn FROM t) WHERE rn = 1` returns only `('a', 1, 1)` on the base 
branch, but both `('a', 1, 1)` and `('A', 2, 1)` with this change. Keys that 
alternate in `ORDER BY` order, such as `('a', 1), ('A', 2), ('a', 3)`, can all 
come back. This affects every accepted top-1 query whose `PARTITION BY` has a 
string with any collation other than `UTF8_BINARY` (for example `UTF8_LCASE`, 
`UNICODE_CI` or an `_RTRIM` collation), at the top level or inside a struct or 
array, with default settings. A typical case is latest-row-per-key 
deduplication over case-insensitive keys, which silently returns duplicates. 
The new tests use only `IntegerType` keys, so none of them fails.
   
   Adding `partitionSpec.forall(e => 
UnsafeRowUtils.isBinaryStable(e.dataType))` to this guard, the same check 
`WindowExec` uses to decide whether byte equality defines its groups, keeps the 
base-branch plan for those keys. The class doc and the inline comment below 
should then say that the `Window` and `Filter` are redundant only when every 
partition key is binary-stable.
   
   **Verification:**
   - **Regression:** Top-1 ROW_NUMBER queries over partition keys that are not 
binary-stable return exactly one row per collation-equal group, the same rows 
as with the optimization turned off. Check this for rows that differ only in 
case under a case-insensitive collation, such as ('a', 1) and ('A', 2), for 
mixed-case data like the existing collation window test's, and for an ICU 
collation and a trailing-space-insensitive collation.
   - **Behavior:** Optimizer plan coverage shows that the top-1 elimination is 
skipped, leaving the WindowGroupLimit under the unchanged Window and Filter, 
when a partition key is a collated string or a struct or array containing one. 
The same coverage shows the elimination still applies when every partition key 
is binary-stable.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimitSuite.scala:
##########
@@ -351,6 +352,199 @@ class InferWindowGroupLimitSuite extends PlanTest {
     }
   }
 
+  test("Eliminate the Window/Filter once WindowGroupLimit already truncates to 
one row") {
+    for (cond <- Seq($"rn" === 1, $"rn" <= 1, $"rn" < 2,
+        Literal(1) === $"rn", Literal(1) >= $"rn", Literal(2) > $"rn");
+      order <- Seq(c.desc, c.asc)) {
+      val originalQuery =
+        testRelation
+          .select(a, b, c,
+            windowExpr(RowNumber(),
+              windowSpec(a :: Nil, order :: Nil, windowFrame)).as("rn"))
+          .where(cond)
+
+      val correctAnswer =
+        testRelation
+          .windowGroupLimit(a :: Nil, order :: Nil, RowNumber(), 1)
+          .select(a, b, c, Literal(1).as("rn"))
+
+      comparePlans(
+        Optimize.execute(originalQuery.analyze),
+        WithoutOptimize.execute(correctAnswer.analyze))
+    }
+  }
+
+  test("Eliminate the Window/Filter with a multi-column partition/order spec") 
{
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(Seq(a, b), Seq(c.desc, b.asc), windowFrame)).as("rn"))
+        .where($"rn" === 1)
+
+    val correctAnswer =
+      testRelation
+        .windowGroupLimit(Seq(a, b), Seq(c.desc, b.asc), RowNumber(), 1)
+        .select(a, b, c, Literal(1).as("rn"))
+
+    comparePlans(
+      Optimize.execute(originalQuery.analyze),
+      WithoutOptimize.execute(correctAnswer.analyze))
+  }
+
+  test("Eliminate the Window/Filter also fires with an empty partitionSpec 
when the " +
+      "top-k sort fallback is disabled") {
+    // With the default config, limit == 1 and an empty partitionSpec take the 
Limit+Sort
+    // fallback path instead (see "Insert limit node for top-k computation" 
above) and never
+    // reach this rule's WindowGroupLimit-based elimination. Disabling the 
fallback here forces
+    // the WindowGroupLimit path so the elimination branch is exercised with 
no PARTITION BY.
+    withSQLConf(SQLConf.TOP_K_SORT_FALLBACK_THRESHOLD.key -> "0") {
+      val originalQuery =
+        testRelation
+          .select(a, b, c,
+            windowExpr(RowNumber(),
+              windowSpec(Nil, c.desc :: Nil, windowFrame)).as("rn"))
+          .where($"rn" === 1)
+
+      val correctAnswer =
+        testRelation
+          .windowGroupLimit(Nil, c.desc :: Nil, RowNumber(), 1)
+          .select(a, b, c, Literal(1).as("rn"))
+
+      comparePlans(
+        Optimize.execute(originalQuery.analyze),
+        WithoutOptimize.execute(correctAnswer.analyze))
+    }
+  }
+
+  test("Eliminate the Window/Filter keeps rn's exprId for downstream 
references") {
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"))
+        .where($"rn" === 1)
+        .select(a, b, c, $"rn")
+
+    val result = Optimize.execute(originalQuery.analyze)
+    assert(result.output.map(_.exprId) == 
originalQuery.analyze.output.map(_.exprId))
+    assert(!result.exists(_.isInstanceOf[Window]) && 
!result.exists(_.isInstanceOf[Filter]))
+  }
+
+  test("Eliminate the Window/Filter preserves rn's qualifier and metadata") {
+    val metadata = new MetadataBuilder().putString("tag", "pii").build()
+    val rnAlias = Alias(
+      windowExpr(RowNumber(), windowSpec(a :: Nil, c.desc :: Nil, 
windowFrame)), "rn")(
+      qualifier = Seq("t"), explicitMetadata = Some(metadata))
+
+    val originalQuery =
+      testRelation
+        .select(a, b, c, rnAlias)
+        .where($"rn" === 1)
+        .analyze
+
+    val rnAttr = Optimize.execute(originalQuery).output.last
+    assert(rnAttr.qualifier == Seq("t"))
+    assert(rnAttr.metadata == metadata)
+  }
+
+  test("Not eliminated when the Window carries a hint that the Project rewrite 
can't preserve") {
+    case object TestWindowHint extends WindowHint
+
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"))
+        .where($"rn" === 1)
+        .analyze
+        .transform { case w: Window => w.copy(hint = Some(TestWindowHint)) }
+
+    val correctAnswer =
+      testRelation
+        .windowGroupLimit(a :: Nil, c.desc :: Nil, RowNumber(), 1)
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"))
+        .where($"rn" === 1)
+        .analyze
+        .transform { case w: Window => w.copy(hint = Some(TestWindowHint)) }
+
+    comparePlans(
+      Optimize.execute(originalQuery),
+      WithoutOptimize.execute(correctAnswer))
+  }
+
+  test("Not eliminated when the Window computes more than the top-1 
RowNumber") {
+    val originalQuery =
+      testRelation
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"),
+          windowExpr(Rank(c :: Nil),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rank"))
+        .where($"rn" === 1)
+
+    val correctAnswer =
+      testRelation
+        .windowGroupLimit(a :: Nil, c.desc :: Nil, RowNumber(), 1)
+        .select(a, b, c,
+          windowExpr(RowNumber(),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rn"),
+          windowExpr(Rank(c :: Nil),
+            windowSpec(a :: Nil, c.desc :: Nil, windowFrame)).as("rank"))
+        .where($"rn" === 1)
+
+    comparePlans(
+      Optimize.execute(originalQuery.analyze),
+      WithoutOptimize.execute(correctAnswer.analyze))
+  }
+
+  test("Not eliminated for Rank/DenseRank even when the limit is 1 (ties could 
leave more " +
+      "than one row per group)") {

Review Comment:
   **Nit (P3):** Ties are not what makes this exclusion necessary: tied top 
rows all have rank 1, so `1 AS rn` would be correct for them. 
`RankLimitIterator` and `DenseRankLimitIterator` raise `rank` only after 
reading the first row of the next rank, and `BaseLimitIterator` emits every row 
it reads, so with limit 1 and order keys `10, 9` both rows get through even 
without ties, and only the retained `Window` and `Filter` remove the `9`. A 
follow-up that trusted this name could extend the elimination to `RANK` when 
the `ORDER BY` keys are unique and label the rank-2 row 1. Naming the real 
mechanism avoids that:
   
   ```suggestion
     test("Not eliminated for Rank/DenseRank even when the limit is 1 (their 
limit iterators " +
         "can keep a row ranked past the limit)") {
   ```
   
   **Verification:**
   - **Inspection:** The Rank/DenseRank exclusion test is named for the 
rank-based group limit's ability to keep a row ranked past the limit, and no 
test name or comment in the change still attributes the exclusion to ties.



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