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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -205,6 +206,19 @@ class GroupedLimitIterator(
 
   val grouping = UnsafeProjection.create(partitionSpec, output)
 
+  private val groupEqualityCheck: (UnsafeRow, UnsafeRow) => Boolean =
+    if (partitionSpec.forall(e => UnsafeRowUtils.isBinaryStable(e.dataType))) {
+      (key1, key2) => key1.equals(key2)
+    } else {
+      // InterpretedOrdering is applied to all fields when any field is 
non-binary-stable
+      // (e.g. a collated STRING). As a side effect, any DOUBLE/FLOAT fields 
in the same
+      // spec use SQLOrderingUtil.compareDoubles, so -0.0 and +0.0 compare as 
equal --
+      // consistent with the sort order, but different from a pure-Double spec 
(binary path).
+      val types = partitionSpec.map(_.dataType)
+      val ordering = InterpretedOrdering.forSchema(types)
+      (key1, key2) => ordering.compare(key1, key2) == 0

Review Comment:
   **Non-blocking (P2):** For a spec with a collated key, this lambda runs 
`InterpretedOrdering.compare` on every boundary check, including checks where 
both key rows are byte-identical. That is every check inside a group whose key 
is consistently spelled, and every check on a row that shares its group's first 
spelling. Reading the unchanged iterator chain, the check runs about six times 
per forwarded row and once per skipped row, in both the Partial and the Final 
node. `GroupedLimitIterator.hasNext` reaches it at lines 243 and 248, `next()` 
repeats that, and lines 116 and 263 check again; `skipRemainingRows` checks 
once per skipped row. Each call allocates fresh `UTF8String`s for both keys. 
UTF8_LCASE then rescans both for ASCII before lower-casing them, and ICU 
collations decode both to Java strings before `Collator.compare`. On the base 
branch, each of these checks was a single `UnsafeRow.equals`.
   
   So for collated keys whose equal values already have identical bytes, such 
as UNICODE keys in ordinary text or consistently cased UTF8_LCASE data, this 
default-on optimization forwards exactly the same rows as before but pays this 
extra CPU on every row. CollationBenchmark puts the raw UTF8_LCASE and UNICODE 
comparators at 1.7x and 7.4x of UTF8_BINARY, before the interpretive overhead; 
the end-to-end cost has not been measured. Byte-identical rows of one schema 
compare equal under every collation and SQL ordering, so testing the bytes 
first keeps the groups exactly as they are:
   
   ```suggestion
         (key1, key2) => key1.equals(key2) || ordering.compare(key1, key2) == 0
   ```
   
   **Verification:**
   - **Inspection:** The collated-key predicate returns true for byte-equal key 
rows before reaching the interpreted ordering and otherwise returns the 
ordering's equality result over all key fields; because byte-equal rows of one 
schema compare as equal under every collation and SQL ordering, it forms 
exactly the groups the ordering alone forms.
   - **Inspection:** The choice between the two predicates, made from whether 
every partition key is binary-stable, and the bare byte comparison used when 
they all are, are unchanged.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -205,6 +206,19 @@ class GroupedLimitIterator(
 
   val grouping = UnsafeProjection.create(partitionSpec, output)
 
+  private val groupEqualityCheck: (UnsafeRow, UnsafeRow) => Boolean =
+    if (partitionSpec.forall(e => UnsafeRowUtils.isBinaryStable(e.dataType))) {
+      (key1, key2) => key1.equals(key2)
+    } else {
+      // InterpretedOrdering is applied to all fields when any field is 
non-binary-stable
+      // (e.g. a collated STRING). As a side effect, any DOUBLE/FLOAT fields 
in the same
+      // spec use SQLOrderingUtil.compareDoubles, so -0.0 and +0.0 compare as 
equal --
+      // consistent with the sort order, but different from a pure-Double spec 
(binary path).

Review Comment:
   **Nit (P3):** This says that pure-Double specs on the binary path treat -0.0 
and +0.0 differently, and that FLOAT fields use `compareDoubles`. Neither 
matches what this operator sees. `NormalizeFloatingNumbers` rewrites float and 
double Window partition keys, including struct and array members and map 
values, to `knownfloatingpointnormalized(normalizenanandzero(...))`. It runs in 
the catalyst optimizer's Finish Analysis and NormalizeFloatingNumbers batches, 
before `SparkOptimizer`'s "Infer window group limit" batch copies the Window's 
partition spec into `WindowGroupLimit`. So `grouping` already yields 0.0 for 
-0.0 and one canonical NaN, and the binary path groups those values exactly as 
this path and `WindowExec` do. Separately, `InterpretedOrdering` compares FLOAT 
fields with `SQLOrderingUtil.compareFloats`. As written, the comment invites a 
redundant normalization or a "fix" to the binary branch. Suggested wording:
   
   ```suggestion
         // InterpretedOrdering is applied to all fields when any field is 
non-binary-stable
         // (e.g. a collated STRING). Float and double keys arrive already 
normalized by
         // NormalizeFloatingNumbers (-0.0 becomes 0.0, NaNs are canonical), so 
this path and
         // the binary path group them the same way WindowExec does.
   ```
   
   **Verification:**
   - **Inspection:** The comment in the collated-key branch claims no 
signed-zero or NaN difference between the byte path and the ordering path, 
names no DOUBLE-only comparator for FLOAT fields, and agrees with 
floating-point window keys being normalized before the limit is inserted.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3328,4 +3329,110 @@ class CollationSuite extends DatasourceV2SQLBase with 
AdaptiveSparkPlanHelper {
         Map("p" -> "hello")),
       Row(false, true))
   }
+
+  test("RANK/DENSE_RANK/ROW_NUMBER with collated PARTITION BY via 
WindowGroupLimitExec") {
+    // threshold=1 forces InferWindowGroupLimit -> WindowGroupLimitExec for 
WHERE r <= 1
+    withSQLConf(SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "1") {
+      withTable("t") {
+        sql("CREATE TABLE t (s STRING COLLATE UTF8_LCASE, i INT) USING 
PARQUET")
+        sql("INSERT INTO t VALUES ('foo', 1), ('FOO', 2), ('bar', 3), ('BAR', 
4)")
+
+        // 'foo'/'FOO' and 'bar'/'BAR' collapse to one partition each under 
UTF8_LCASE.
+        val rankDf = sql("""SELECT s, i, r FROM (
+                           |  SELECT s, i, RANK() OVER (PARTITION BY s ORDER 
BY i) AS r
+                           |  FROM t) WHERE r <= 1""".stripMargin)
+        assert(collectFirst(rankDf.queryExecution.executedPlan) {
+          case _: WindowGroupLimitExec => ()
+        }.isDefined, "expected WindowGroupLimitExec in plan")
+        checkAnswer(rankDf, Row("foo", 1, 1) :: Row("bar", 3, 1) :: Nil)
+
+        val denseDf = sql("""SELECT s, i, r FROM (
+                            |  SELECT s, i, DENSE_RANK() OVER (PARTITION BY s 
ORDER BY i) AS r
+                            |  FROM t) WHERE r <= 1""".stripMargin)
+        assert(collectFirst(denseDf.queryExecution.executedPlan) {
+          case _: WindowGroupLimitExec => ()
+        }.isDefined, "expected WindowGroupLimitExec in plan for DENSE_RANK")
+        checkAnswer(denseDf, Row("foo", 1, 1) :: Row("bar", 3, 1) :: Nil)
+
+        val rnDf = sql("""SELECT s, i, r FROM (
+                         |  SELECT s, i, ROW_NUMBER() OVER (PARTITION BY s 
ORDER BY i) AS r
+                         |  FROM t) WHERE r <= 1""".stripMargin)
+        assert(collectFirst(rnDf.queryExecution.executedPlan) {
+          case _: WindowGroupLimitExec => ()
+        }.isDefined, "expected WindowGroupLimitExec in plan for ROW_NUMBER")
+        checkAnswer(rnDf, Row("foo", 1, 1) :: Row("bar", 3, 1) :: Nil)
+      }
+
+      // UTF8_BINARY: 'foo' and 'FOO' are distinct partitions, so all four 
rows get rank 1.
+      withTable("t2") {
+        sql("CREATE TABLE t2 (s STRING, i INT) USING PARQUET")
+        sql("INSERT INTO t2 VALUES ('foo', 1), ('FOO', 2), ('bar', 3), ('BAR', 
4)")
+
+        checkAnswer(
+          sql("""SELECT s, i, r FROM (
+                |  SELECT s, i, RANK() OVER (PARTITION BY s ORDER BY i) AS r
+                |  FROM t2) WHERE r <= 1""".stripMargin),
+          Row("FOO", 2, 1) :: Row("BAR", 4, 1) :: Row("bar", 3, 1) :: 
Row("foo", 1, 1) :: Nil)
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collapses collated partitions (forwarded-row 
regression)") {
+    // The final query result is identical with or without collation-aware 
grouping -- the
+    // downstream WindowExec + Filter always recompute it -- so checkAnswer 
alone cannot
+    // catch a regression to binary grouping. The only observable that 
distinguishes the
+    // fix is how many rows WindowGroupLimitExec forwards: binary grouping 
fails to collapse
+    // 'a'/'A' and forwards every row, while collation-aware grouping 
collapses each
+    // UTF8_LCASE partition to its top-k.
+    //
+    // We assert on the Final node's numOutputRows only. With a single shuffle 
partition
+    // every window partition lands in one reduce task, so that count is 
deterministic
+    // across environments (2 = one survivor per collated partition). The 
Partial node's
+    // count depends on scan parallelism, so it is intentionally excluded. AQE 
is disabled
+    // to keep executedPlan stable and avoid shuffle-partition coalescing.
+    withSQLConf(
+        SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "1",
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      withTable("t") {
+        sql("CREATE TABLE t (s STRING COLLATE UTF8_LCASE, i INT) USING 
PARQUET")
+        // Alternating spellings within each UTF8_LCASE partition maximize the 
gap: under
+        // binary grouping every adjacent row starts a new group. Distinct 
ORDER BY values
+        // (i) keep which row survives WHERE r <= 1 deterministic (no ties).
+        sql("""INSERT INTO t VALUES
+              |  ('a', 1), ('A', 2), ('a', 3), ('A', 4), ('a', 5), ('A', 6),
+              |  ('b', 7), ('B', 8), ('b', 9), ('B', 10)""".stripMargin)
+        val df = sql("""SELECT s, i, r FROM (
+                       |  SELECT s, i, ROW_NUMBER() OVER (PARTITION BY s ORDER 
BY i) AS r
+                       |  FROM t) WHERE r <= 1""".stripMargin)
+        // Collation-correct answer, unaffected by the fix.
+        checkAnswer(df, Row("a", 1, 1) :: Row("b", 7, 1) :: Nil)
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix collapses each collated partition to its single survivor 
(2 rows).
+        // Pre-fix binary grouping forwards all 10 rows.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with Double in mixed partition 
spec") {
+    withSQLConf(SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "1") {
+      withTable("t_dbl") {
+        sql("CREATE TABLE t_dbl (d DOUBLE, s STRING COLLATE UTF8_LCASE, i INT) 
USING PARQUET")
+        sql("INSERT INTO t_dbl VALUES (-0.0, 'foo', 1), (0.0, 'foo', 2)")
+        // UTF8_LCASE on s is non-binary-stable, so InterpretedOrdering is 
used for all
+        // fields including d. SQLOrderingUtil.compareDoubles treats -0.0 == 
+0.0, so both
+        // rows land in one partition group and only the rank-1 row survives 
the filter.
+        val df = sql(
+          """SELECT d, s, i FROM (
+            |  SELECT d, s, i, RANK() OVER (PARTITION BY d, s ORDER BY i) AS r
+            |  FROM t_dbl) WHERE r <= 1""".stripMargin)
+        assert(df.count() == 1, "-0.0 and +0.0 should be treated as equal 
partition keys")

Review Comment:
   **Non-blocking (P2):** Reading the code, this assertion passes whether or 
not `WindowGroupLimitExec` groups these keys correctly, for three reasons:
   
   - `-0.0` without a `D` suffix is a DECIMAL literal, and `BigDecimal` has no 
negative zero, so both rows store `d = 0.0`.
   - Even a real `-0.0D` would reach the limit already normalized, because 
`NormalizeFloatingNumbers` rewrites the Window's partition keys before 
`InferWindowGroupLimit` copies them.
   - Which rows survive `r <= 1` is decided by the `WindowExec` and filter 
above the limit, which already group correctly.
   
   Both projected keys are byte-identical, so `count()` is 1 with byte equality 
(the code before this fix), with the `forall` dispatch weakened to `exists`, or 
with an ordering over `s` alone. On other data, that last change would merge 
window partitions that differ on `d` and drop rows. The test also never asserts 
that a `WindowGroupLimitExec` was planned. So the mixed collated-plus-DOUBLE 
dispatch has no test that can fail, and the message claims a signed-zero check 
the test cannot observe.
   
   To make it observable, give the test rows whose groups differ under byte and 
collation equality and also differ on `d`, run it under the same configs as the 
forwarded-row test, and assert the Final node's `numOutputRows` alongside 
`checkAnswer`. For example:
   
   ```scala
   withSQLConf(
       SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "1",
       SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
       SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
     withTable("t_dbl") {
       sql("CREATE TABLE t_dbl (d DOUBLE, s STRING COLLATE UTF8_LCASE, i INT) 
USING PARQUET")
       sql("""INSERT INTO t_dbl VALUES
             |  (1.0D, 'foo', 1), (1.0D, 'FOO', 2), (1.0D, 'foo', 3),
             |  (2.0D, 'foo', 4), (2.0D, 'FOO', 5)""".stripMargin)
       val df = sql("""SELECT d, s, i FROM (
                      |  SELECT d, s, i, ROW_NUMBER() OVER (PARTITION BY d, s 
ORDER BY i) AS r
                      |  FROM t_dbl) WHERE r <= 1""".stripMargin)
       checkAnswer(df, Row(1.0, "foo", 1) :: Row(2.0, "foo", 4) :: Nil)
       val finalForwarded = collect(df.queryExecution.executedPlan) {
         case w: WindowGroupLimitExec if w.mode == Final => 
w.metrics("numOutputRows").value
       }.sum
       assert(finalForwarded == 2,
         s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
     }
   }
   ```
   
   By the iterator's logic, byte grouping would make the Final node forward 
every row, and a comparison that ignored `d` would forward a single row and 
lose the `d = 2.0` survivor. Either drop the signed-zero claims from the 
comment and message, or keep a `-0.0D` row with a comment that credits its 
grouping to the optimizer's float normalization.
   
   **Verification:**
   - **Regression:** With the boundary check reverted to byte equality, with 
the predicate choice switched to byte equality whenever any key is 
binary-stable, or with a comparison over the collated key alone, the reworked 
mixed-spec case fails on its forwarded-row count or its answer, and it passes 
with collation-aware grouping over all key fields.
   - **Inspection:** No comment or assertion message in the case credits 
signed-zero grouping to the limit's own comparison, and any negative-zero value 
it inserts is written as a DOUBLE literal rather than an unsuffixed decimal.



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