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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -237,4 +237,35 @@ 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.
+   *
+   * `checkBytesFirst` controls whether that fallback compares the key bytes 
before the
+   * ordering, and is only observable for non-binary-stable keys: 
byte-identical rows
+   * compare equal under every collation and SQL ordering, so a byte-first 
check answers
+   * same-spelling keys with one byte comparison, while every check whose 
bytes differ
+   * pays a failed byte comparison before the same ordering comparison. Both 
forms group
+   * keys the same way, so the choice only moves cost between checks of 
identically
+   * spelled keys and all other checks; each call site's comment says why it 
passes the
+   * value it does.
+   */
+  def rowEqualityChecker(
+      dataTypes: Seq[DataType],
+      checkBytesFirst: Boolean): (UnsafeRow, UnsafeRow) => Boolean = {
+    if (dataTypes.forall(isBinaryStable)) {
+      (key1, key2) => key1.equals(key2)
+    } else {
+      val ordering = InterpretedOrdering.forSchema(dataTypes.toIndexedSeq)

Review Comment:
   Thanks, keys holding a CALENDAR INTERVAL now use the generated comparator in 
`rowEqualityChecker`, and the new session-window and helper unit tests cover 
the plain, one-DISTINCT and struct cases. This review raises a related 
follow-up for grouping and partition keys that hold a user-defined type inside 
an array or map.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4623032774","thread_id":"inline:4623032774","verdict_sha256":"d2ea5bf57c096f27932887bb70e4f0f0db90008f8fefd224754adb3825c62e9d"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -237,4 +237,49 @@ 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.
+   *
+   * Keys holding a CALENDAR INTERVAL use the generated comparator, because the
+   * interpreted ordering cannot compare intervals (their physical ordering is
+   * unsupported); the generated comparator is the one the planner's sort 
applies to
+   * such keys.
+   *
+   * `checkBytesFirst` controls whether that fallback compares the key bytes 
before the
+   * ordering, and is only observable for non-binary-stable keys: 
byte-identical rows
+   * compare equal under every collation and SQL ordering, so a byte-first 
check answers
+   * same-spelling keys with one byte comparison, while every check whose 
bytes differ
+   * pays a failed byte comparison before the same ordering comparison. Both 
forms group
+   * keys the same way, so the choice only moves cost between checks of 
identically
+   * spelled keys and all other checks; each call site's comment says why it 
passes the
+   * value it does.
+   */
+  def rowEqualityChecker(
+      dataTypes: Seq[DataType],
+      checkBytesFirst: Boolean): (UnsafeRow, UnsafeRow) => Boolean = {
+    if (dataTypes.forall(isBinaryStable)) {
+      (key1, key2) => key1.equals(key2)
+    } else {
+      val ordering = if (dataTypes.exists(containsCalendarInterval)) {

Review Comment:
   **Blocking (P1):** For a key that is not binary-stable and holds no CALENDAR 
INTERVAL, this selects `InterpretedOrdering`, which unwraps a user-defined type 
only when the key field itself is one (`ordering.scala:43-49`). For an array 
field it asks `PhysicalArrayType` for its ordering, whose element ordering 
comes from `PhysicalDataType(elementType)` (`PhysicalDataType.scala:380-382`). 
`PhysicalDataType` has no case for a UDT and returns 
`UninitializedPhysicalType` (`PhysicalDataType.scala:37-70`), whose ordering 
throws `DATATYPE_CANNOT_ORDER` (`PhysicalDataType.scala:445-449`); 
`PhysicalMapType` builds its key and value orderings the same way 
(`PhysicalDataType.scala:281-284`). `MergingSessionsIterator`, 
`UpdatingSessionsIterator` and 
`ArrowWindowPythonEvaluatorFactory.fetchNextPartition` compared these keys by 
bytes on the base branch and now reach this ordering. The planner's sort and 
`GroupedIterator` order the same keys with the generated comparator, which 
unwraps a UDT at any
  depth (`CodeGenerator.scala:1176`, `2815`), and hash aggregation compares an 
array of a UDT by bytes.
   
   By this reading of the code, `SELECT s, count(*) FROM t GROUP BY s, arr, 
session_window(ts, '10 minutes')` with `s STRING COLLATE UTF8_LCASE` and `arr 
ARRAY<VectorUDT>` (for example `collect_list` of an ML features column), over 
('a', [v1], 10:00) and ('a', [v2], 10:01), returns two rows with a count of 1 
on the base branch. At the head, once both rows land in one shuffle partition, 
as AQE's coalescing of this small shuffle makes them, `MergingSessionsIterator` 
sees two keys whose bytes differ, the strings compare equal, and the array 
field throws `[DATATYPE_CANNOT_ORDER] Type UninitializedPhysicalType does not 
support ordered operations.`, an error that names an internal type rather than 
the column. A one-DISTINCT aggregate fails the same way in 
`UpdatingSessionsIterator`, and a pandas window UDF over 
`Window.partitionBy('s', 'arr')` fails in `fetchNextPartition`.
   
   This affects every batch session-window aggregation, and every window UDF 
that `ArrowWindowPythonExec` evaluates, whose key holds a non-binary collated 
string next to an array whose element type is a UDT, or, for session windows, a 
map whose key or value type is one. It fails whenever two adjacent keys in a 
partition differ in bytes while the fields before the array compare equal, 
including keys that differ only in the string's case. Streaming session windows 
never see such keys, because stateful operators reject key schemas that are not 
binary-stable, and WindowExec and sort-based aggregation already failed on such 
keys on the base branch, because they used the same interpreted ordering.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4623032774).
   
   **Recommended change:** In UnsafeRowUtils.rowEqualityChecker, build the 
generated comparator (RowOrdering.createNaturalAscendingOrdering) when a key 
type holds a user-defined type as well as when it holds a CALENDAR INTERVAL, 
detecting the user-defined type the way the existing interval check detects an 
interval, and say in the Scaladoc that the interpreted ordering cannot compare 
a user-defined type nested in an array or map. Keep 
InterpretedOrdering.forSchema for every other key that is not binary-stable, 
and keep the byte pre-check exactly as checkBytesFirst selects it. Add 
collation tests for batch session-window aggregation, with a plain and a 
one-DISTINCT aggregate, whose key holds a UTF8_LCASE string next to an array of 
a user-defined type and, in a second case, next to a map whose value type is a 
user-defined type; a pandas window UDF test partitioned by such a string and an 
array of a user-defined type; and a helper unit test for such a key in both 
checkBytesFirst forms. 
 This extends the interval branch that commit 107ca58cd4c added for the same 
reason.
   
   **Why this works:** The generated comparator unwraps a user-defined type at 
every depth, in both its comparison code and its value access, and compares 
collated strings with the same collation comparator the interpreted ordering 
uses, so for these keys it decides group membership exactly as the planner's 
sort ordered them. Selecting it whenever a key type holds a user-defined type 
removes the only path by which the shared checker reaches the physical ordering 
that throws, at every operator that calls the checker.
   
   **Compatibility:** Keys that hold neither a user-defined type nor a CALENDAR 
INTERVAL keep their current comparator at every caller, binary-stable keys keep 
byte equality, and checkBytesFirst keeps its meaning, so groups, results and 
per-check cost stay the same for every other input.
   
   **Risks:** WindowExec's evaluator and sort-based aggregation call the same 
checker, so for keys holding a user-defined type they also switch to the 
generated comparator: keys with one inside an array or map, which failed there 
on the base branch as well, start returning results, and keys with one at the 
top level or inside a struct, which already worked, form the same groups 
through a comparator generated once per task; reverting the new condition 
restores the current behavior.
   
   **Constraints:** Keep InterpretedOrdering for keys that hold neither a 
user-defined type nor a CALENDAR INTERVAL, so the open decision about the 
interpreted ordering's cost at the pandas window evaluator and the 
session-window iterators stays with the author. Keep the byte comparison before 
the generated comparison exactly when the caller passes checkBytesFirst = true.
   
   **Exclusions:**
   - Teaching the array and map physical orderings to unwrap a user-defined 
type, which would also change interpreted sorts and every other user of those 
orderings outside the operators this PR changes.
   - Running with code generation disabled, where the comparator falls back to 
the interpreted ordering and keys holding a user-defined type inside an array 
still fail, as the planner's sort over them already does in that mode.
   
   **Verification:**
   - **Regression:** A batch session-window aggregation grouped by a UTF8_LCASE 
string and an array of a user-defined type, over rows that share the string but 
differ in the array and rows whose strings differ only in case, returns the 
expected per-group counts for a plain aggregate and for a one-DISTINCT 
aggregate, also with the array as the first grouping column, instead of failing 
with DATATYPE_CANNOT_ORDER; the same holds when the key holds a map whose value 
type is a user-defined type in place of the array.
   - **Regression:** A pandas window UDF over a partition spec of a UTF8_LCASE 
string and an array of a user-defined type returns each partition's aggregate 
instead of failing.
   - **Behavior:** For a key of a UTF8_LCASE string and an array of a 
user-defined type, the checker in both checkBytesFirst forms treats 
byte-identical keys and keys differing only in the string's case as equal and 
keys whose arrays differ as unequal.
   - **Inspection:** The checker still builds the interpreted ordering for key 
types that hold neither a user-defined type nor a CALENDAR INTERVAL, and still 
compares key bytes before the ordering exactly when checkBytesFirst is true.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3332,587 @@ class CollationSuite extends DatasourceV2SQLBase with 
AdaptiveSparkPlanHelper {
         Map("p" -> "hello")),
       Row(false, true))
   }
+
+  test("RANK/DENSE_RANK/ROW_NUMBER with collated PARTITION BY via 
WindowGroupLimitExec") {
+    // Pins the threshold at 1; the default of 1000 already yields 
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

Review Comment:
   **Nit (P3):** Since the window group limit switched to the key equality, a 
spec with one DOUBLE and one UTF8_LCASE key is not binary-stable and 
`UnsafeRowKeyOperations` admits every key type, so `GroupedLimitIterator` 
compares it with `key1.equals(key2) || keyOperations.areEqual(key1, key2)` 
(`WindowGroupLimitExec.scala:218-226`), and no orderable partition spec reaches 
the interpreted ordering there anymore. A maintainer reading this comment would 
look to this test for coverage of a path the operator no longer takes:
   
   ```suggestion
       // A mixed spec with one DOUBLE and one collated STRING key takes the 
UnsafeRowKeyOperations
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4623032788).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3332,587 @@ class CollationSuite extends DatasourceV2SQLBase with 
AdaptiveSparkPlanHelper {
         Map("p" -> "hello")),
       Row(false, true))
   }
+
+  test("RANK/DENSE_RANK/ROW_NUMBER with collated PARTITION BY via 
WindowGroupLimitExec") {
+    // Pins the threshold at 1; the default of 1000 already yields 
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. 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, see the
+    // test above).
+    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")
+        // Alternating spellings within each (d, s) partition maximize the gap 
between byte
+        // and collation grouping. Distinct ORDER BY values (i) keep which row 
survives
+        // WHERE r <= 1 deterministic (no ties).
+        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
+        // Post-fix: one survivor per (d, collated s) group = 2 rows. Pre-fix 
byte grouping
+        // forwards all 5 rows; a comparator over s alone would forward only 1.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with groups under and over the 
limit") {
+    // Exercises the cached group-equality check at every kind of group 
boundary: group 'a'
+    // ends under the limit (r <= 2 but only one row, so the limit is never 
reached), group
+    // 'b' exceeds it (one row is skipped via skipRemainingRows), and group 
'c' ends exactly
+    // at the limit. Groups 'b' and 'c' mix spellings, so the checks of their 
later rows --
+    // including the skipped row ('B', 5), spelled unlike the group's first 
row -- run the
+    // collation comparison instead of the byte-equality fast path. The 
default window
+    // group limit threshold (1000) already admits r <= 2.
+    withSQLConf(
+        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")
+        sql("""INSERT INTO t VALUES
+              |  ('a', 1),
+              |  ('b', 3), ('B', 4), ('B', 5),
+              |  ('c', 6), ('C', 7)""".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 <= 2""".stripMargin)
+        checkAnswer(df,
+          Row("a", 1, 1) ::
+          Row("b", 3, 1) :: Row("B", 4, 2) ::
+          Row("c", 6, 1) :: Row("C", 7, 2) :: Nil)
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: 1 row from 'a', 2 from 'b' (its third row is skipped), 2 
from 'c' = 5
+        // rows. Pre-fix byte grouping: each spelling forms its own byte-group 
('b' alone,
+        // then the two 'B' rows together), and every byte-group fits within 
the limit, so
+        // all 6 rows are forwarded.
+        assert(finalForwarded == 5,
+          s"WindowGroupLimitExec(Final) should forward 5 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with struct and array 
partition keys") {
+    // A struct or array key holding a mixed-spelling UTF8_LCASE string must 
compare over
+    // every nested field: byte grouping splits each spelling into its own 
group and
+    // forwards every row, while a comparison over the collated string alone 
would also
+    // merge keys whose other fields differ. checkAnswer alone cannot catch 
either (the
+    // WindowExec above the limit recomputes the answer), so the Final node's
+    // numOutputRows is asserted as in the tests above, and the answers are 
compared
+    // against the same query with the window group limit disabled.

Review Comment:
   **Nit (P3):** Only byte grouping escapes the answer check. A comparison over 
the collated string alone would put ('a', 1) and ('a', 2) in one group and, 
with `r <= 1`, drop the ('a', 2) survivor before the WindowExec above the 
limit, so the answer would no longer equal the query with the limit disabled. 
This test's own comment at lines 3526-3528 says so, as does the mixed-spec 
test's comment at lines 3432-3434:
   
   ```suggestion
       // merge keys whose other fields differ. The answer check catches a 
comparison over the
       // string alone, which drops a survivor, but not byte grouping, whose 
answer the WindowExec
       // above the limit recomputes, so the Final node's numOutputRows is 
asserted as in the tests
       // above, and the answers are compared against the same query with the 
limit disabled.
   ```
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3332,587 @@ class CollationSuite extends DatasourceV2SQLBase with 
AdaptiveSparkPlanHelper {
         Map("p" -> "hello")),
       Row(false, true))
   }
+
+  test("RANK/DENSE_RANK/ROW_NUMBER with collated PARTITION BY via 
WindowGroupLimitExec") {
+    // Pins the threshold at 1; the default of 1000 already yields 
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. 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, see the
+    // test above).
+    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")
+        // Alternating spellings within each (d, s) partition maximize the gap 
between byte
+        // and collation grouping. Distinct ORDER BY values (i) keep which row 
survives
+        // WHERE r <= 1 deterministic (no ties).
+        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
+        // Post-fix: one survivor per (d, collated s) group = 2 rows. Pre-fix 
byte grouping
+        // forwards all 5 rows; a comparator over s alone would forward only 1.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with groups under and over the 
limit") {
+    // Exercises the cached group-equality check at every kind of group 
boundary: group 'a'
+    // ends under the limit (r <= 2 but only one row, so the limit is never 
reached), group
+    // 'b' exceeds it (one row is skipped via skipRemainingRows), and group 
'c' ends exactly
+    // at the limit. Groups 'b' and 'c' mix spellings, so the checks of their 
later rows --
+    // including the skipped row ('B', 5), spelled unlike the group's first 
row -- run the
+    // collation comparison instead of the byte-equality fast path. The 
default window
+    // group limit threshold (1000) already admits r <= 2.
+    withSQLConf(
+        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")
+        sql("""INSERT INTO t VALUES
+              |  ('a', 1),
+              |  ('b', 3), ('B', 4), ('B', 5),
+              |  ('c', 6), ('C', 7)""".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 <= 2""".stripMargin)
+        checkAnswer(df,
+          Row("a", 1, 1) ::
+          Row("b", 3, 1) :: Row("B", 4, 2) ::
+          Row("c", 6, 1) :: Row("C", 7, 2) :: Nil)
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: 1 row from 'a', 2 from 'b' (its third row is skipped), 2 
from 'c' = 5
+        // rows. Pre-fix byte grouping: each spelling forms its own byte-group 
('b' alone,
+        // then the two 'B' rows together), and every byte-group fits within 
the limit, so
+        // all 6 rows are forwarded.
+        assert(finalForwarded == 5,
+          s"WindowGroupLimitExec(Final) should forward 5 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with struct and array 
partition keys") {
+    // A struct or array key holding a mixed-spelling UTF8_LCASE string must 
compare over
+    // every nested field: byte grouping splits each spelling into its own 
group and
+    // forwards every row, while a comparison over the collated string alone 
would also
+    // merge keys whose other fields differ. checkAnswer alone cannot catch 
either (the
+    // WindowExec above the limit recomputes the answer), so the Final node's
+    // numOutputRows is asserted as in the tests above, and the answers are 
compared
+    // against the same query with the window group limit disabled.
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      // Struct key: ('a', 1) / ('A', 1) / ('a', 1) alternate spellings of one 
collation
+      // group, ('a', 2) is a second group that differs only in its 
non-collated field.
+      withTable("t_st") {
+        sql("""CREATE TABLE t_st (st STRUCT<s: STRING COLLATE UTF8_LCASE, i 
INT>, ts TIMESTAMP)
+              |  USING PARQUET""".stripMargin)
+        sql("""INSERT INTO t_st VALUES
+              |  (named_struct('s', 'a', 'i', 1), timestamp'2026-01-01 
10:00:00'),
+              |  (named_struct('s', 'A', 'i', 1), timestamp'2026-01-01 
10:05:00'),
+              |  (named_struct('s', 'a', 'i', 1), timestamp'2026-01-01 
10:08:00'),
+              |  (named_struct('s', 'a', 'i', 2), timestamp'2026-01-01 
10:02:00')""".stripMargin)
+        val df = sql("""SELECT st, ts, r FROM (
+                       |  SELECT st, ts, ROW_NUMBER() OVER (PARTITION BY st 
ORDER BY ts) AS r
+                       |  FROM t_st) WHERE r <= 1""".stripMargin)
+        // The answer must equal the same query with the window group limit 
disabled:
+        // a check that wrongly merged two collation groups would drop rows the
+        // WindowExec above the limit needs.
+        val limitedAnswer = df.collect()
+        withSQLConf(SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "-1") {
+          val unlimitedAnswer = sql("""SELECT st, ts, r FROM (
+                                      |  SELECT st, ts,
+                                      |    ROW_NUMBER() OVER (PARTITION BY st 
ORDER BY ts) AS r
+                                      |  FROM t_st) WHERE r <= 
1""".stripMargin).collect()
+          assert(limitedAnswer.toSet == unlimitedAnswer.toSet)
+        }
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: one survivor per collation group ('a'/'A' with i = 1, and 
i = 2) =
+        // 2 rows. Pre-fix byte grouping forwards one row per byte group = 3; a

Review Comment:
   **Nit (P3):** The Final node sorts its input by (st, ts) under the 
collation, so it sees ('a', 1)@10:00, ('A', 1)@10:05, ('a', 1)@10:08 and ('a', 
2)@10:02. The two ('a', 1) rows are not adjacent, so byte grouping finds four 
runs of byte-equal keys and forwards all 4 rows, as the test's header says. The 
3 in the comment would mislead a maintainer checking that the assertion of 2 
separates the fix from byte grouping:
   
   ```suggestion
           // 2 rows. Pre-fix byte grouping forwards one row per run of 
byte-equal keys = 4; a
   ```
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/tests/pandas/test_pandas_udf_grouped_agg.py:
##########
@@ -1148,6 +1148,78 @@ def avg_age_iter(it: Iterator[pd.Series]) -> float:
         expected = [Row(id=1, avg_age=27.5), Row(id=2, avg_age=37.5)]
         self.assertEqual(actual, expected)
 
+    def test_collation_session_window_grouped_agg(self):
+        # SPARK-58928: for a session window, ArrowAggregatePythonExec runs
+        # UpdatingSessionsIterator before the grouped iterator and the UDF 
input
+        # projection, and that iterator must rewrite only the session column 
of each
+        # buffered row. If it also rewrote the grouping columns to the 
session's first
+        # key, a pandas grouped-aggregate UDF whose argument reads the 
collated grouping
+        # column would see only the first spelling of the group.
+        from datetime import datetime
+
+        df = self.spark.createDataFrame(
+            [
+                ("foo", datetime(2026, 1, 1, 10, 0, 0), 1.0),
+                ("FOO", datetime(2026, 1, 1, 10, 5, 0), 2.0),
+                ("foo", datetime(2026, 1, 1, 10, 8, 0), 3.0),
+            ],
+            "s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v DOUBLE",
+        )
+
+        @pandas_udf("string")
+        def spellings(s: pd.Series) -> str:
+            return ",".join(sorted(s))
+
+        result = (
+            df.groupby("s", sf.session_window("ts", "10 minutes"))
+            .agg(spellings(df["s"]).alias("sp"))
+            .select("sp")
+        )
+
+        # The three rows merge into one session under the collation, and the 
UDF receives
+        # each row's own spelling of the grouping column.
+        assertDataFrameEqual(result, [Row(sp="FOO,foo,foo")])
+
+    def test_collation_session_window_grouped_agg_subquery(self):
+        # SPARK-58928: through a subquery, the session attribute in the 
grouping list
+        # carries the subquery's qualifier while the same column of the input 
schema
+        # does not. UpdatingSessionsIterator must find the session column by 
expression
+        # ID when it binds the merged session into each buffered row; matching 
by
+        # attribute equality leaves every row with its own per-event session.
+        from datetime import datetime
+
+        df = self.spark.createDataFrame(
+            [
+                ("foo", datetime(2026, 1, 1, 10, 0, 0), 1.0),
+                ("FOO", datetime(2026, 1, 1, 10, 5, 0), 2.0),
+                ("foo", datetime(2026, 1, 1, 10, 8, 0), 3.0),
+            ],
+            "s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v DOUBLE",
+        )
+        df.createOrReplaceTempView("t")

Review Comment:
   **Nit (P3):** This registration runs before `with self.temp_view("t"), 
self.temp_func("spellings"):`, and line 1210 registers the same view again 
inside that block, so the comment at lines 1205-1208, which says both objects 
are registered through the context managers, does not hold for this call. If 
defining the `spellings` UDF failed, `t` would stay registered for the mixin's 
later tests and its Spark Connect parity class. Removing this call leaves the 
only registration inside the managed block.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4623032844).
   
   **Verification:**
   - **Inspection:** The pandas session-window subquery test registers its view 
and its function only inside the temp_view and temp_func managers, matching the 
comment that explains the cleanup.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3332,587 @@ class CollationSuite extends DatasourceV2SQLBase with 
AdaptiveSparkPlanHelper {
         Map("p" -> "hello")),
       Row(false, true))
   }
+
+  test("RANK/DENSE_RANK/ROW_NUMBER with collated PARTITION BY via 
WindowGroupLimitExec") {
+    // Pins the threshold at 1; the default of 1000 already yields 
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. 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, see the
+    // test above).
+    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")
+        // Alternating spellings within each (d, s) partition maximize the gap 
between byte
+        // and collation grouping. Distinct ORDER BY values (i) keep which row 
survives
+        // WHERE r <= 1 deterministic (no ties).
+        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
+        // Post-fix: one survivor per (d, collated s) group = 2 rows. Pre-fix 
byte grouping
+        // forwards all 5 rows; a comparator over s alone would forward only 1.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with groups under and over the 
limit") {
+    // Exercises the cached group-equality check at every kind of group 
boundary: group 'a'
+    // ends under the limit (r <= 2 but only one row, so the limit is never 
reached), group
+    // 'b' exceeds it (one row is skipped via skipRemainingRows), and group 
'c' ends exactly
+    // at the limit. Groups 'b' and 'c' mix spellings, so the checks of their 
later rows --
+    // including the skipped row ('B', 5), spelled unlike the group's first 
row -- run the
+    // collation comparison instead of the byte-equality fast path. The 
default window
+    // group limit threshold (1000) already admits r <= 2.
+    withSQLConf(
+        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")
+        sql("""INSERT INTO t VALUES
+              |  ('a', 1),
+              |  ('b', 3), ('B', 4), ('B', 5),
+              |  ('c', 6), ('C', 7)""".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 <= 2""".stripMargin)
+        checkAnswer(df,
+          Row("a", 1, 1) ::
+          Row("b", 3, 1) :: Row("B", 4, 2) ::
+          Row("c", 6, 1) :: Row("C", 7, 2) :: Nil)
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: 1 row from 'a', 2 from 'b' (its third row is skipped), 2 
from 'c' = 5
+        // rows. Pre-fix byte grouping: each spelling forms its own byte-group 
('b' alone,
+        // then the two 'B' rows together), and every byte-group fits within 
the limit, so
+        // all 6 rows are forwarded.
+        assert(finalForwarded == 5,
+          s"WindowGroupLimitExec(Final) should forward 5 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("WindowGroupLimitExec collation grouping with struct and array 
partition keys") {
+    // A struct or array key holding a mixed-spelling UTF8_LCASE string must 
compare over
+    // every nested field: byte grouping splits each spelling into its own 
group and
+    // forwards every row, while a comparison over the collated string alone 
would also
+    // merge keys whose other fields differ. checkAnswer alone cannot catch 
either (the
+    // WindowExec above the limit recomputes the answer), so the Final node's
+    // numOutputRows is asserted as in the tests above, and the answers are 
compared
+    // against the same query with the window group limit disabled.
+    withSQLConf(
+        SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      // Struct key: ('a', 1) / ('A', 1) / ('a', 1) alternate spellings of one 
collation
+      // group, ('a', 2) is a second group that differs only in its 
non-collated field.
+      withTable("t_st") {
+        sql("""CREATE TABLE t_st (st STRUCT<s: STRING COLLATE UTF8_LCASE, i 
INT>, ts TIMESTAMP)
+              |  USING PARQUET""".stripMargin)
+        sql("""INSERT INTO t_st VALUES
+              |  (named_struct('s', 'a', 'i', 1), timestamp'2026-01-01 
10:00:00'),
+              |  (named_struct('s', 'A', 'i', 1), timestamp'2026-01-01 
10:05:00'),
+              |  (named_struct('s', 'a', 'i', 1), timestamp'2026-01-01 
10:08:00'),
+              |  (named_struct('s', 'a', 'i', 2), timestamp'2026-01-01 
10:02:00')""".stripMargin)
+        val df = sql("""SELECT st, ts, r FROM (
+                       |  SELECT st, ts, ROW_NUMBER() OVER (PARTITION BY st 
ORDER BY ts) AS r
+                       |  FROM t_st) WHERE r <= 1""".stripMargin)
+        // The answer must equal the same query with the window group limit 
disabled:
+        // a check that wrongly merged two collation groups would drop rows the
+        // WindowExec above the limit needs.
+        val limitedAnswer = df.collect()
+        withSQLConf(SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "-1") {
+          val unlimitedAnswer = sql("""SELECT st, ts, r FROM (
+                                      |  SELECT st, ts,
+                                      |    ROW_NUMBER() OVER (PARTITION BY st 
ORDER BY ts) AS r
+                                      |  FROM t_st) WHERE r <= 
1""".stripMargin).collect()
+          assert(limitedAnswer.toSet == unlimitedAnswer.toSet)
+        }
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: one survivor per collation group ('a'/'A' with i = 1, and 
i = 2) =
+        // 2 rows. Pre-fix byte grouping forwards one row per byte group = 3; a
+        // comparator over the string field alone would forward 1.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+
+      // Array key: ['a', 'b'] / ['A', 'B'] alternate spellings of one 
collation group,
+      // ['a', 'c'] is a second group that differs in its second element.
+      withTable("t_arr") {
+        sql("CREATE TABLE t_arr (arr ARRAY<STRING COLLATE UTF8_LCASE>, i INT) 
USING PARQUET")
+        sql("""INSERT INTO t_arr VALUES
+              |  (array('a', 'b'), 1), (array('A', 'B'), 2), (array('a', 'c'), 
3)""".stripMargin)
+        val df = sql("""SELECT arr, r FROM (
+                       |  SELECT arr, ROW_NUMBER() OVER (PARTITION BY arr 
ORDER BY i) AS r
+                       |  FROM t_arr) WHERE r <= 1""".stripMargin)
+        val limitedAnswer = df.collect()
+        withSQLConf(SQLConf.WINDOW_GROUP_LIMIT_THRESHOLD.key -> "-1") {
+          val unlimitedAnswer = sql("""SELECT arr, r FROM (
+                                      |  SELECT arr,
+                                      |    ROW_NUMBER() OVER (PARTITION BY arr 
ORDER BY i) AS r
+                                      |  FROM t_arr) WHERE r <= 
1""".stripMargin).collect()
+          assert(limitedAnswer.toSet == unlimitedAnswer.toSet)
+        }
+        val finalForwarded = collect(df.queryExecution.executedPlan) {
+          case w: WindowGroupLimitExec if w.mode == Final =>
+            w.metrics("numOutputRows").value
+        }.sum
+        // Post-fix: one survivor per collation group = 2 rows. Pre-fix byte 
grouping
+        // forwards one row per byte group = 3.
+        assert(finalForwarded == 2,
+          s"WindowGroupLimitExec(Final) should forward 2 rows, got 
$finalForwarded")
+      }
+    }
+  }
+
+  test("session window aggregation groups collated keys (plain and distinct 
aggregates)") {
+    // The two session-window grouping iterators compare the grouping key 
without the
+    // session column: MergingSessionsIterator for plain aggregates, and
+    // UpdatingSessionsIterator for DISTINCT aggregates (also used by pandas 
grouped
+    // aggregation over session windows). Before collation-aware grouping they 
compared
+    // that key by bytes, so a UTF8_LCASE key whose rows mix spellings split 
into one
+    // session per spelling ('foo' 10:00, 'FOO' 10:05, 'foo' 10:08 gave three 
one-row
+    // sessions), and the DISTINCT path hit its sortedness guard ("The 
iterator must be
+    // sorted by key and session start!") as soon as a spelling recurred after 
the first
+    // session of its byte-group. The merged session length is asserted as end 
- start in
+    // seconds so the expectation does not depend on the session time zone.
+    withTable("t") {
+      sql("CREATE TABLE t (s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v INT) 
USING PARQUET")
+      sql("""INSERT INTO t VALUES
+            |  ('foo', timestamp'2026-01-01 10:00:00', 1),
+            |  ('FOO', timestamp'2026-01-01 10:05:00', 2),
+            |  ('foo', timestamp'2026-01-01 10:08:00', 3)""".stripMargin)
+
+      checkAnswer(
+        sql("""SELECT s,
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(*) FROM t
+              |  GROUP BY s, session_window(ts, '10 minutes')""".stripMargin),
+        // One merged session from 10:00 to 10:18; the grouping key reported 
is the first
+        // spelling of the collated group, which the sort on session start 
makes
+        // deterministic.
+        Row("foo", 1080L, 3L) :: Nil)
+
+      // count(DISTINCT v) plans UpdatingSessionsExec before the aggregation. 
The
+      // spelling of the reported key depends on shuffle arrival order, so 
only the
+      // session length and the count are asserted.
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(DISTINCT v) FROM t
+              |  GROUP BY s, session_window(ts, '10 minutes')""".stripMargin),
+        Row(1080L, 3L) :: Nil)
+
+      // A query whose only DISTINCT aggregate reads the grouping column: the 
partial
+      // aggregate under the one-distinct plan evaluates its expressions over 
the rows
+      // UpdatingSessionsIterator emits, so those rows must keep each row's 
own spelling
+      // of s. If the iterator rewrote the grouping columns to the session's 
first key,
+      // count(DISTINCT s COLLATE UTF8_BINARY) would see one value instead of 
two and
+      // collect_list three copies of 'foo'.
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(DISTINCT s COLLATE UTF8_BINARY),
+              |  sort_array(collect_list(s COLLATE UTF8_BINARY)) FROM t
+              |  GROUP BY s, session_window(ts, '10 minutes')""".stripMargin),
+        Row(1080L, 2L, Seq("FOO", "foo", "foo")) :: Nil)
+    }
+
+    // UTF8_BINARY keeps 'foo' and 'FOO' in separate sessions; the two 'foo' 
rows still
+    // merge with each other (10:00 to 10:18 spans both).
+    withTable("t2") {
+      sql("CREATE TABLE t2 (s STRING, ts TIMESTAMP, v INT) USING PARQUET")
+      sql("""INSERT INTO t2 VALUES
+            |  ('foo', timestamp'2026-01-01 10:00:00', 1),
+            |  ('FOO', timestamp'2026-01-01 10:05:00', 2),
+            |  ('foo', timestamp'2026-01-01 10:08:00', 3)""".stripMargin)
+
+      checkAnswer(
+        sql("""SELECT s, count(*) FROM t2
+              |  GROUP BY s, session_window(ts, '10 minutes')""".stripMargin),
+        Row("foo", 2L) :: Row("FOO", 1L) :: Nil)
+    }
+  }
+
+  test("session window aggregation groups collated keys nested in a struct") {
+    // Same as the direct-key test, but the collated string sits inside the 
struct
+    // grouping key, so the binary-stability check must recurse into the 
struct to
+    // select the ordering-based comparison.
+    withTable("t") {
+      sql("""CREATE TABLE t (st STRUCT<s: STRING COLLATE UTF8_LCASE>, ts 
TIMESTAMP, v INT)
+            |  USING PARQUET""".stripMargin)
+      sql("""INSERT INTO t VALUES
+            |  (named_struct('s', 'foo'), timestamp'2026-01-01 10:00:00', 1),
+            |  (named_struct('s', 'FOO'), timestamp'2026-01-01 10:05:00', 2),
+            |  (named_struct('s', 'foo'), timestamp'2026-01-01 10:08:00', 
3)""".stripMargin)
+
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(*) FROM t
+              |  GROUP BY st, session_window(ts, '10 minutes')""".stripMargin),
+        Row(1080L, 3L) :: Nil)
+
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(DISTINCT v) FROM t
+              |  GROUP BY st, session_window(ts, '10 minutes')""".stripMargin),
+        Row(1080L, 3L) :: Nil)
+
+      // As in the direct-key test, the one-distinct plan's aggregates read 
the grouping
+      // column from the rows UpdatingSessionsIterator emits, so the nested 
collated
+      // field must keep each row's own spelling.
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(session_window.end AS LONG) - CAST(session_window.start 
AS LONG)
+              |    AS session_length,
+              |  count(DISTINCT st.s COLLATE UTF8_BINARY),
+              |  sort_array(collect_list(st.s COLLATE UTF8_BINARY)) FROM t
+              |  GROUP BY st, session_window(ts, '10 minutes')""".stripMargin),
+        Row(1080L, 2L, Seq("FOO", "foo", "foo")) :: Nil)
+    }
+
+    // Without the collation the struct keys are compared by bytes and the 
spellings
+    // stay in separate sessions.
+    withTable("t2") {
+      sql("CREATE TABLE t2 (st STRUCT<s: STRING>, ts TIMESTAMP, v INT) USING 
PARQUET")
+      sql("""INSERT INTO t2 VALUES
+            |  (named_struct('s', 'foo'), timestamp'2026-01-01 10:00:00', 1),
+            |  (named_struct('s', 'FOO'), timestamp'2026-01-01 10:05:00', 2),
+            |  (named_struct('s', 'foo'), timestamp'2026-01-01 10:08:00', 
3)""".stripMargin)
+
+      checkAnswer(
+        sql("""SELECT count(*) FROM t2
+              |  GROUP BY st, session_window(ts, '10 minutes')""".stripMargin),
+        Row(2L) :: Row(1L) :: Nil)
+    }
+  }
+
+  test("session window aggregation merges sessions computed in a subquery") {
+    // UpdatingSessionsIterator binds the merged session into each buffered 
row through a
+    // projection that must find the session column by expression ID: through 
a subquery,
+    // the session attribute in the grouping list carries the subquery's 
qualifier while
+    // the same column of the input schema does not, and matching by attribute 
equality
+    // leaves the merged session unbound, so every emitted row keeps its own 
per-event
+    // session instead of the merged one.
+    withTable("t") {
+      sql("CREATE TABLE t (s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v INT) 
USING PARQUET")
+      sql("""INSERT INTO t VALUES
+            |  ('foo', timestamp'2026-01-01 10:00:00', 1),
+            |  ('FOO', timestamp'2026-01-01 10:05:00', 2),
+            |  ('foo', timestamp'2026-01-01 10:08:00', 3)""".stripMargin)
+
+      // The one-distinct plan runs UpdatingSessionsExec over the subquery's 
output.
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(sw.end AS LONG) - CAST(sw.start AS LONG) AS 
session_length,
+              |  count(DISTINCT v)
+              |  FROM (SELECT s, v, session_window(ts, '10 minutes') AS sw 
FROM t) sub
+              |  GROUP BY s, sw""".stripMargin),
+        Row(1080L, 3L) :: Nil)
+
+      // The aggregates read the grouping column from the rows the iterator 
emits, so
+      // this also checks that each row keeps its own spelling through the 
subquery.
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(sw.end AS LONG) - CAST(sw.start AS LONG) AS 
session_length,
+              |  count(DISTINCT s COLLATE UTF8_BINARY),
+              |  sort_array(collect_list(s COLLATE UTF8_BINARY))
+              |  FROM (SELECT s, v, session_window(ts, '10 minutes') AS sw 
FROM t) sub
+              |  GROUP BY s, sw""".stripMargin),
+        Row(1080L, 2L, Seq("FOO", "foo", "foo")) :: Nil)
+    }
+
+    // Binary-stable keys take the same path and must keep merging through a 
subquery.
+    withTable("t2") {
+      sql("CREATE TABLE t2 (s STRING, ts TIMESTAMP, v INT) USING PARQUET")
+      sql("""INSERT INTO t2 VALUES
+            |  ('foo', timestamp'2026-01-01 10:00:00', 1),
+            |  ('foo', timestamp'2026-01-01 10:05:00', 2),
+            |  ('foo', timestamp'2026-01-01 10:08:00', 3)""".stripMargin)
+
+      checkAnswer(
+        sql("""SELECT
+              |  CAST(sw.end AS LONG) - CAST(sw.start AS LONG) AS 
session_length,
+              |  count(DISTINCT v)
+              |  FROM (SELECT s, v, session_window(ts, '10 minutes') AS sw 
FROM t2) sub
+              |  GROUP BY s, sw""".stripMargin),
+        Row(1080L, 3L) :: Nil)
+    }
+  }
+
+  test("session window aggregation keeps distinct collated keys in separate 
sessions") {
+    // The other session tests hold a single collation group, so the collation 
branch of
+    // the iterators' group-equality check only ever answers true there. Here 
a second

Review Comment:
   **Nit (P3):** The later test 'session window aggregation groups collated 
keys holding a calendar interval' (line 3844) keeps ('foo'/'FOO', 1 day) apart 
from ('foo', 2 days), so the checker for keys that are not binary-stable 
already answers false at that boundary in both session iterators. What this 
test adds is collated strings that differ under the collation, which no other 
session test has:
   
   ```suggestion
       // No other session test holds collated strings that differ under the 
collation (the
       // interval test's groups differ only in the interval). Here a second
   ```
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -205,12 +206,34 @@ class GroupedLimitIterator(
 
   val grouping = UnsafeProjection.create(partitionSpec, output)
 
+  // A non-binary-stable key (e.g. a collated STRING) makes the checker fall 
back to an
+  // ordering-based comparison over all fields. Float and double keys arrive 
already
+  // normalized by NormalizeFloatingNumbers (-0.0 becomes 0.0, NaNs are 
canonical), so
+  // both branches group them the same way WindowExec does. The bytes are 
checked first,
+  // so a key spelled like its group's first row costs one byte comparison and 
only keys
+  // whose bytes differ pay the ordering comparison.
+  private val groupKeyEqualityCheck: (UnsafeRow, UnsafeRow) => Boolean =
+    UnsafeRowUtils.rowEqualityChecker(partitionSpec.map(_.dataType), 
checkBytesFirst = true)

Review Comment:
   Thanks, for collated keys the window group limit now checks bytes first and 
then calls `UnsafeRowKeyOperations.areEqual`, keeps the shared checker for 
binary-stable keys, and the new struct and array cases assert the forwarded-row 
counts and compare their answers with the limit disabled. This review raises 
one related nit about a test comment that still names the interpreted ordering.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4623032788","thread_id":"inline:4623032788","verdict_sha256":"d2ea5bf57c096f27932887bb70e4f0f0db90008f8fefd224754adb3825c62e9d"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowWindowPythonEvaluatorFactory.scala:
##########
@@ -257,6 +258,11 @@ class ArrowWindowPythonEvaluatorFactory(
         }
       )
       val grouping = UnsafeProjection.create(partitionSpec, childOutput)
+      // The bytes are checked first, so a key spelled like its group's first 
row costs
+      // one byte comparison and only keys whose bytes differ pay the ordering 
comparison;
+      // most checks here compare a row against the first row of the group it 
belongs to.

Review Comment:
   Thanks, the comment now explains the byte pre-check by the single byte 
comparison this loop made before it used the collation, which no longer reads 
as a reason WindowExec's partition loop should check bytes first too.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4623032798","thread_id":"inline:4623032798","verdict_sha256":"d2ea5bf57c096f27932887bb70e4f0f0db90008f8fefd224754adb3825c62e9d"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/UpdatingSessionsIterator.scala:
##########
@@ -184,29 +194,39 @@ class UpdatingSessionsIterator(
     throw SparkException.internalError("The iterator must be sorted by key and 
session start!")
   }
 
-  private val join = new JoinedRow
   private val join2 = new JoinedRow
 
-  private val valueProj = GenerateUnsafeProjection.generate(valuesExpressions, 
inputSchema)
-  private val restoreProj = GenerateUnsafeProjection.generate(inputSchema,
-    groupingWithoutSession.map(_.toAttribute) ++ 
Seq(sessionExpression.toAttribute) ++
-      valuesExpressions.map(_.toAttribute))
-
-  private def generateGroupingKey(): InternalRow = {
-    val newRow = new 
SpecificInternalRow(Seq(sessionExpression.toAttribute).toStructType)
-    newRow.update(0, currentSession)
-    join(currentKeys, newRow)
-  }
+  // The merged session is read from the field appended after the row's own 
columns
+  // (field 0 of the right side of join2 below), an ordinal no input column 
occupies, so
+  // the rewrite projection cannot resolve it to a buffered row's session 
column.
+  private[this] val mergedSessionReference = BoundReference(
+    inputSchema.length, sessionExpression.dataType, sessionExpression.nullable)
+
+  // One projection rewrites each buffered row: every non-session column keeps 
its own
+  // ordinal, so each row of a session keeps its own values, including its own 
spelling
+  // of a collated grouping key, and only the session column takes the merged 
session
+  // from the appended field. The session column is matched by expression ID 
rather than
+  // by attribute equality: the session attribute in the grouping list can 
carry a
+  // qualifier that the input column lacks, as when the session window is 
computed in a
+  // subquery or CTE and grouped outside, and the DISTINCT-aggregate and pandas
+  // grouped-aggregate plans that consume this iterator read the grouping 
columns from
+  // the rows it emits.

Review Comment:
   Thanks, the comment above the session-column rewrite now names the Python 
UDAF aggregation plan alongside the one-DISTINCT and pandas grouped-aggregate 
plans.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4623032829","thread_id":"inline:4623032829","verdict_sha256":"d2ea5bf57c096f27932887bb70e4f0f0db90008f8fefd224754adb3825c62e9d"}
 -->



##########
python/pyspark/sql/tests/pandas/test_pandas_udf_grouped_agg.py:
##########
@@ -1148,6 +1148,72 @@ def avg_age_iter(it: Iterator[pd.Series]) -> float:
         expected = [Row(id=1, avg_age=27.5), Row(id=2, avg_age=37.5)]
         self.assertEqual(actual, expected)
 
+    def test_collation_session_window_grouped_agg(self):
+        # SPARK-58928: for a session window, ArrowAggregatePythonExec runs
+        # UpdatingSessionsIterator before the grouped iterator and the UDF 
input
+        # projection, and that iterator must rewrite only the session column 
of each
+        # buffered row. If it also rewrote the grouping columns to the 
session's first
+        # key, a pandas grouped-aggregate UDF whose argument reads the 
collated grouping
+        # column would see only the first spelling of the group.
+        from datetime import datetime
+
+        df = self.spark.createDataFrame(
+            [
+                ("foo", datetime(2026, 1, 1, 10, 0, 0), 1.0),
+                ("FOO", datetime(2026, 1, 1, 10, 5, 0), 2.0),
+                ("foo", datetime(2026, 1, 1, 10, 8, 0), 3.0),
+            ],
+            "s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v DOUBLE",
+        )
+
+        @pandas_udf("string")
+        def spellings(s: pd.Series) -> str:
+            return ",".join(sorted(s))
+
+        result = (
+            df.groupby("s", sf.session_window("ts", "10 minutes"))
+            .agg(spellings(df["s"]).alias("sp"))
+            .select("sp")
+        )
+
+        # The three rows merge into one session under the collation, and the 
UDF receives
+        # each row's own spelling of the grouping column.
+        assertDataFrameEqual(result, [Row(sp="FOO,foo,foo")])
+
+    def test_collation_session_window_grouped_agg_subquery(self):
+        # SPARK-58928: through a subquery, the session attribute in the 
grouping list
+        # carries the subquery's qualifier while the same column of the input 
schema
+        # does not. UpdatingSessionsIterator must find the session column by 
expression
+        # ID when it binds the merged session into each buffered row; matching 
by
+        # attribute equality leaves every row with its own per-event session.
+        from datetime import datetime
+
+        df = self.spark.createDataFrame(
+            [
+                ("foo", datetime(2026, 1, 1, 10, 0, 0), 1.0),
+                ("FOO", datetime(2026, 1, 1, 10, 5, 0), 2.0),
+                ("foo", datetime(2026, 1, 1, 10, 8, 0), 3.0),
+            ],
+            "s STRING COLLATE UTF8_LCASE, ts TIMESTAMP, v DOUBLE",
+        )
+        df.createOrReplaceTempView("t")

Review Comment:
   Thanks, the view and function are now registered, and the query and 
assertion run, inside the temp_view and temp_func managers, so both objects are 
dropped even when the assertion fails. This review raises one leftover: an 
earlier registration of the view still runs before the managed block.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4623032844","thread_id":"inline:4623032844","verdict_sha256":"d2ea5bf57c096f27932887bb70e4f0f0db90008f8fefd224754adb3825c62e9d"}
 -->



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