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


##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,130 @@ 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

Review Comment:
   **Nit (P3):** `InferWindowGroupLimit` rewrites when `limit <= 
conf.windowGroupLimitThreshold`, and the threshold defaults to 1000, which 
nothing in this suite overrides, so by that condition `WHERE r <= 1` already 
qualifies for `WindowGroupLimitExec` at the default; setting the threshold to 1 
only pins the value. Either say so or drop the setting:
   
   ```suggestion
       // Pins the threshold at 1; the default of 1000 already yields 
WindowGroupLimitExec for r <= 1
   ```
   
   **Verification:**
   - **Inspection:** The comment describes the threshold setting as pinning an 
upper bound that the default already satisfies for r <= 1, not as forcing 
InferWindowGroupLimit to insert the operator.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -243,7 +251,7 @@ class GroupedLimitIterator(
     // Before we start to fetch new input rows, make a copy of nextGroup.
     var currentGroup = nextGroup.copy()
 
-    def hasNext: Boolean = nextRowAvailable && nextGroup == currentGroup
+    def hasNext: Boolean = nextRowAvailable && groupEqualityCheck(nextGroup, 
currentGroup)

Review Comment:
   **Non-blocking (P2):** The byte-first check added since the last review 
keeps byte-identical keys cheap, but a row whose key bytes differ from its 
group's first key, such as 'foo' in a UTF8_LCASE group that starts with 'FOO', 
still pays a failed byte compare plus an `InterpretedOrdering` comparison every 
time this check runs. Reading the unchanged iterator chain, it runs about six 
times for the same pair of rows before `fetchNextRow` advances: 
`GroupedLimitIterator.hasNext` calls `limitIterator.hasNext` twice, `next()` 
repeats both through `hasNext`, and then `BaseLimitIterator.next` and 
`GroupIterator.next` each check once more. A group that ends under the limit 
fails the check in `hasNext` and again in `skipRemainingRows`. This happens in 
both the Partial and the Final node, and for ICU collations every comparison 
also converts both keys to Java strings. Query results are unchanged. In 
mixed-spelling groups that already fit within the limit, which the base branch 
forwarded the s
 ame way, the repeats are pure CPU cost; in larger groups they eat into the 
pruning gain. The end-to-end cost has not been measured.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4578723317).
   
   **Recommended change:** Make GroupIterator remember the result of the 
group-equality check for the current fetched row, and clear it whenever 
fetchNextRow advances the input or skipRemainingRows replaces currentGroup. Add 
a collation window group limit test whose groups end both under and over the 
limit.
   
   **Why this works:** The repeated hasNext calls from GroupedLimitIterator and 
the limit iterators then reuse one comparison per fetched row, so a row whose 
key bytes differ from its group's first key pays one collation comparison per 
node instead of about six, and a group that ends under the limit pays one at 
its boundary instead of two.
   
   **Scope:** Evaluate the window group limit's boundary check once per fetched 
row.
   
   **Compatibility:** Which rows each window group limit node forwards stays 
the same.
   
   **Risks:** A remembered answer that outlives a change of nextGroup or 
currentGroup would merge the next group into the previous one, and the limit 
could then drop rows WindowExec needs, returning a wrong result; every point 
that changes either value must clear it.
   
   **Constraints:** Track whether the remembered answer is current with an 
explicit flag cleared at each change, not by comparing row identity, because 
the input iterator and the grouping projection reuse their row objects.
   
   **Success:** GroupIterator evaluates the group-equality check at most once 
per fetched row, plus once after each change of currentGroup. The rows each 
limit node forwards and the query results are unchanged for collated and 
binary-stable specs.
   
   **Verification:**
   - **Regression:** For a collated PARTITION BY spec with mixed spellings, 
including groups that end under the limit followed by groups that exceed it, 
and for ROW_NUMBER, RANK and DENSE_RANK, the Final node forwards exactly the 
rows collation-aware grouping selects and the query answers stay correct.
   - **Inspection:** Each fetched row's group membership is decided by one 
evaluation of the equality check, and the remembered answer is cleared wherever 
the input advances or the current group changes.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -237,4 +237,22 @@ object UnsafeRowUtils {
       !st.supportsBinaryEquality
     case _ => false
   }
+
+  /**
+   * Returns an equality checker for grouping keys (UnsafeRows) of the given 
data types.
+   * If every type is binary-stable, equality is a plain binary comparison. 
Otherwise (e.g.
+   * a STRING with a non-binary collation), values that are semantically equal 
can have
+   * different binary representations, so the checker falls back to an 
ordering-based
+   * comparison that applies to all fields. Byte-identical rows compare equal 
under every
+   * collation and SQL ordering, so the fallback checks the bytes first to 
keep the common
+   * same-spelling case cheap.
+   */
+  def rowEqualityChecker(dataTypes: Seq[DataType]): (UnsafeRow, UnsafeRow) => 
Boolean = {
+    if (dataTypes.forall(isBinaryStable)) {
+      (key1, key2) => key1.equals(key2)
+    } else {
+      val ordering = InterpretedOrdering.forSchema(dataTypes)

Review Comment:
   **Non-blocking (P2):** `InterpretedOrdering.forSchema` keeps the collection 
type of the sequence it is given, and `InterpretedOrdering.compare` reads 
`ordering.size` and then four sequences by index for every field it visits. 
GROUP BY and PARTITION BY lists from SQL (`asScala.map(...).toSeq` in 
`AstBuilder`), Spark Connect (`asScala.toSeq.map` in `SparkConnectPlanner`) and 
PySpark's classic API (`PythonUtils.toSeq`) are Scala `List`s, so each 
comparison that misses the byte fast path walks the list, at a cost that grows 
with the square of the last key position it reaches. The base branch's 
`SortBasedAggregationIterator` built this ordering from 
`groupingAttributes.map(_.dataType).toIndexedSeq`, so sort-based aggregation 
over collated keys now does more work per comparison than before, and the new 
window group limit comparison pays the same walk. One to three keys cost only a 
few extra steps; wide specs with a collated key pay more. This comes from 
reading the parser, planner and e
 xecutor code, not from running a query. Converting here restores indexed 
lookups for every caller:
   
   ```suggestion
         val ordering = InterpretedOrdering.forSchema(dataTypes.toIndexedSeq)
   ```
   
   **Verification:**
   - **Inspection:** The fallback ordering the helper builds is backed by an 
indexed sequence for every caller, so the per-field lookups in each comparison 
no longer walk a linked list, and callers that already pass an indexed sequence 
get the same ordering as before.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,130 @@ 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") {
+    // A mixed spec with one DOUBLE and one collated STRING key takes the 
InterpretedOrdering
+    // path, which must compare every field: with byte grouping 'foo'/'FOO' 
split each d value
+    // into separate groups so the Final node forwards all 5 rows, while a 
comparator over s
+    // alone would collapse the d = 1.0 and d = 2.0 groups into one and 
forward a single row
+    // (dropping the d = 2.0 survivor). Only collation-aware grouping over all 
fields forwards
+    // exactly one survivor per (d, collated s) group. We assert on the Final 
node's
+    // numOutputRows (deterministic with one shuffle partition, see the test 
above) because
+    // the final query answer alone cannot distinguish these cases.

Review Comment:
   **Nit (P3):** The claim that the final answer cannot distinguish these cases 
holds for byte grouping, whose answer `WindowExec` recomputes correctly, but 
not for the comparator over `s` alone: following the iterator logic, that 
comparator makes the Final node forward only `(1.0, 'foo', 1)`, so the answer 
loses `Row(2.0, "foo", 4)` and `checkAnswer` fails too. A reader could conclude 
that only the forwarded-row assertion guards the comparison over all key 
fields. Suggested wording:
   
   ```suggestion
       // exactly one survivor per (d, collated s) group. checkAnswer catches 
the s-only case,
       // but not byte grouping, whose answer WindowExec recomputes correctly, 
so we also assert
       // on the Final node's numOutputRows (deterministic with one shuffle 
partition).
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4578723335).
   
   **Verification:**
   - **Inspection:** The comment says the final answer cannot distinguish byte 
grouping from collation-aware grouping, and that a comparator over the collated 
key alone changes the answer as well as the forwarded-row count.



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