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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimit.scala:
##########
@@ -50,25 +53,72 @@ import 
org.apache.spark.sql.catalyst.trees.TreePattern.{FILTER, WINDOW}
  *      SELECT *, ROW_NUMBER() OVER(PARTITION BY k ORDER BY a) AS rn FROM Tab1
  *   ) WHERE 5 >= rn;
  * }}}
+ *
+ * As a special case, once the `WindowGroupLimit` has truncated every 
partition group to at
+ * most one row (`limit = 1`), a `row_number()` recomputed over that same 
partition/order spec
+ * can only ever produce the literal `1` for the surviving row, making the 
`Window` and its
+ * top-1 `Filter` provably dead computation. When the `Window` computes 
nothing else and carries
+ * no hint, this rule replaces both with a `Project` that aliases the literal 
`1` onto the
+ * original `rn` output, instead of inserting the `WindowGroupLimit` below an 
otherwise-unchanged
+ * `Window`/`Filter`:
+ * {{{
+ *   Filter(rn = 1 / rn <= 1 / rn < 2)
+ *     Window(row_number() AS rn, partitionSpec, orderSpec)
+ *       Tab1
+ * }}}
+ * becomes
+ * {{{
+ *   Project(..., 1 AS rn)
+ *     WindowGroupLimit(partitionSpec, orderSpec, row_number(), limit = 1)
+ *       Tab1
+ * }}}
+ * A deterministic extra conjunct alongside the top-1 predicate (e.g. `rn = 1 
AND v > 6`) is kept
+ * as a `Filter` over the new `Project` rather than dropped, since it is 
evaluated on the same
+ * single surviving row either way. A nondeterministic one is left in place 
instead (keeping the
+ * `Window`/`Filter` unchanged), since relocating it would change which rows 
it is evaluated on.

Review Comment:
   **Nit (P3):** Reading the code, the reason given here does not hold. With 
limit 1, `ROW_NUMBER` and binary-stable keys, every row the final 
`WindowGroupLimitExec` emits gets `rn = 1`. The `WindowExec` above it neither 
reorders nor repartitions those rows, because its required distribution and 
ordering match the group limit's. So for `rn = 1 AND rand(0) > 0.5`, the kept 
`Filter` evaluates `rand(0)` on exactly the rows, in the same order and 
partition, that a `Filter(rand(0) > 0.5)` over the new `Project` would. If 
relocating did change which rows a conjunct sees, the deterministic case in the 
sentence before would be wrong too.
   
   The guard itself is a reasonable conservative choice. Describing it as one 
keeps a later maintainer from keeping or removing it for the wrong reason:
   
   ```suggestion
    * `Window`/`Filter` unchanged), as a conservative choice not to move it to 
another operator.
   ```
   
   **Verification:**
   - **Inspection:** The InferWindowGroupLimit class documentation gives a 
reason for keeping the original plan when an extra conjunct is nondeterministic 
that does not contradict its statement that a deterministic conjunct is 
evaluated on the same single row either way.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimit.scala:
##########
@@ -112,20 +162,41 @@ 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))
+                  lazy val (top1Conjuncts, remainingConjuncts) =
+                    splitTop1Conjuncts(condition, alias.toAttribute)
+                  if (limit == 1 && windowExpressions.length == 1 && 
window.hint.isEmpty &&
+                    rankLikeFunction.isInstanceOf[RowNumber] &&
+                    partitionSpec.forall(e => 
UnsafeRowUtils.isBinaryStable(e.dataType)) &&

Review Comment:
   **Nit (P3):** This guard admits `FLOAT` and `DOUBLE` keys, nested or not, 
because `isBinaryStable` rejects only strings without binary equality. 
`WindowGroupLimitExec`, however, groups rows by raw key bytes, in which `0.0`, 
`-0.0` and different `NaN` bit patterns differ. Those keys are byte-stable here 
only because the `NormalizeFloatingNumbers` batch has already rewritten the 
`Window`'s `partitionSpec` before this rule copies it into the 
`WindowGroupLimit` (line 175). Reading the code, if this rule ever ran before 
that batch, deduplicating `Seq((0.0, 1), (-0.0, 2))` by its first column would 
return two rows instead of one.
   
   A kept conjunct such as `v > 6` has a similar dependency. When the dedup 
sits inside a subquery that is later rewritten into a join, such as an `IN` 
subquery, predicate pushdown runs again after this rewrite and moves the 
conjunct through the new `Project` onto the group limit. It stops there only 
because `PushPredicateThroughNonJoin.canPushThrough` leaves `WindowGroupLimit` 
out. On the base branch neither dependency mattered, because the `Window` and 
`Filter` re-checked the group limit's output.
   
   No test fails if either premise breaks. The new tests are plan comparisons 
in an executor without `NormalizeFloatingNumbers`, using `INT` keys, and the 
extra-conjunct test normalizes its expected plan with the same 
`PushDownPredicates`. The existing end-to-end top-1 cases in 
`DataFrameWindowFunctionsSuite` ("SPARK-37099") use a `STRING` key and no extra 
conjunct. These two shapes are the ones the still-open request for an 
end-to-end test would most need to cover.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60517#issuecomment-6905664271), 
[2](https://github.com/apache/spark/pull/60517#issuecomment-6912580169).
   
   **Verification:**
   - **Regression:** Top-1 ROW_NUMBER deduplication over FLOAT and DOUBLE 
partition keys that hold 0.0, -0.0 and NaN values with different bit patterns, 
both as top-level keys and inside a struct or array, returns one row per 
SQL-equal key, matches the result with the window group limit disabled, and has 
no Window left in its optimized plan.
   - **Regression:** Top-1 ROW_NUMBER deduplication with a deterministic extra 
conjunct on a non-partition column, where one group's first-ranked row fails 
the conjunct and its second-ranked row passes it, gives no result for that 
group both as a top-level query and inside an IN subquery, where predicate 
pushdown runs again after the rewrite; each query matches its result with the 
window group limit disabled and has no Window left in its optimized plan.
   - **Regression:** The optimizer plan check for a kept extra conjunct fails 
when predicate pushdown places the conjunct's Filter below the WindowGroupLimit 
instead of above it.
   - **Inspection:** The InferWindowGroupLimit class documentation says that 
float and double partition keys are safe only because NormalizeFloatingNumbers 
has already normalized the partition spec before the rule copies it into the 
WindowGroupLimit.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InferWindowGroupLimit.scala:
##########
@@ -112,20 +162,41 @@ 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))
+                  lazy val (top1Conjuncts, remainingConjuncts) =
+                    splitTop1Conjuncts(condition, alias.toAttribute)
+                  if (limit == 1 && windowExpressions.length == 1 && 
window.hint.isEmpty &&
+                    rankLikeFunction.isInstanceOf[RowNumber] &&
+                    partitionSpec.forall(e => 
UnsafeRowUtils.isBinaryStable(e.dataType)) &&
+                    top1Conjuncts.nonEmpty && 
remainingConjuncts.forall(_.deterministic)) {
+                    // The surviving row's row_number() can only be 1, so the 
top-1 conjunct(s)
+                    // are always true and that part of the Filter is dead 
computation. Keep the
+                    // alias's qualifier/metadata so the output schema is 
unaffected. See the
+                    // class doc for the binary-stable and determinism 
requirements above.
+                    val newAlias = Alias(Literal(1), alias.name)(
+                      exprId = alias.exprId,
+                      qualifier = alias.qualifier,
+                      explicitMetadata = Some(alias.metadata))
+                    val project = Project(child.output :+ newAlias, 
windowGroupLimit)

Review Comment:
   **Nit (P3):** With this `Project` placed directly on the group limit, the 
final `WindowGroupLimitExec` becomes the last operator that limits each group 
for an eliminated top-1 query: no `WindowExec` or `FilterExec` re-checks its 
rows. Its scaladoc, which this PR leaves unchanged 
(`WindowGroupLimitExec.scala:34-38`), still says the operator "is designed to 
filter out unnecessary rows before WindowExec" and that its specs "Should be 
the same as" `WindowExec`'s, and the logical `WindowGroupLimit` has no doc at 
all.
   
   The operator already keeps extra rows for the rank-based functions: 
`RankLimitIterator` emits the first row of the next rank, which is safe only 
while a `Window` and `Filter` follow. Nothing tells a maintainer, or a plugin 
that replaces the operator, that for `RowNumber` the final node must now emit 
exactly the first `limit` rows of each group of byte-equal partition keys. If 
that ever loosened, top-1 deduplication would silently return more than one `rn 
= 1` row per key, and the catalyst plan tests could not catch it. Stating that 
guarantee in the `WindowGroupLimitExec` scaladoc, together with the fact that 
this rewrite relies on it, puts it where someone changing the operator will 
look.
   
   **Verification:**
   - **Inspection:** The WindowGroupLimitExec documentation states the 
exact-output guarantee for RowNumber that the top-1 elimination relies on, says 
that the elimination relies on it, and no longer describes the operator only as 
a pre-filter before WindowExec.



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