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


##########
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:
   **Blocking (P1):** For a key that is not binary-stable, this ordering 
compares every key field, binary-stable ones included, and 
`InterpretedOrdering.compare` asks each non-null field's physical type for its 
ordering (`ordering.scala:69`). `PhysicalCalendarIntervalType.ordering` throws 
`DATATYPE_CANNOT_ORDER` (`PhysicalDataType.scala:160-163`), yet GROUP BY 
accepts CALENDAR INTERVAL keys (`ExprUtils.scala:247-256`), hash aggregation 
admits them next to a collated string, and the sort in front of the session 
iterators orders them in generated code. `MergingSessionsIterator` and 
`UpdatingSessionsIterator`, which compared these keys by bytes on the base 
branch, now reach this ordering.
   
   By this reading of the code, `SELECT n, iv, count(*) FROM (SELECT name 
COLLATE UTF8_LCASE AS n, make_interval(0, 0, 0, d) AS iv, ts FROM VALUES ('a', 
1, TIMESTAMP'2026-01-01 10:00:00'), ('a', 2, TIMESTAMP'2026-01-01 10:01:00') AS 
t(name, d, ts)) GROUP BY n, iv, session_window(ts, '5 minutes')` returns two 
rows on the base branch. At the head, once both keys land in one partition, as 
AQE's coalescing of this small shuffle gives, `MergingSessionsIterator` checks 
('a', 1 day) against ('a', 2 days), the strings compare equal and the interval 
field throws `[DATATYPE_CANNOT_ORDER] Type PhysicalCalendarIntervalType does 
not support ordered operations.` A one-DISTINCT aggregate fails the same way in 
`UpdatingSessionsIterator`. This affects every batch session-window aggregation 
whose key without the session column holds both a non-binary collated string 
and a non-null interval, directly or nested in a struct or array, whenever two 
keys with equal fields before the interval meet in a parti
 tion; with the interval as the first grouping column, any two distinct keys 
do. The window operators cannot receive such a key, because partition keys must 
be orderable, and sort-based aggregation already throws for it on the base 
branch.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4595214448).
   
   **Recommended change:** In UnsafeRowUtils.rowEqualityChecker, when any key 
type contains a CALENDAR INTERVAL, build the fallback comparison with 
RowOrdering.createNaturalAscendingOrdering over the key types instead of 
InterpretedOrdering.forSchema, keep the byte pre-check exactly as 
checkBytesFirst selects it, and keep InterpretedOrdering for every other key; 
say in the helper's Scaladoc that keys holding a CALENDAR INTERVAL use the 
generated comparator because the interpreted ordering cannot compare intervals. 
Add collation session-window aggregation tests that group by a UTF8_LCASE 
string and a CALENDAR INTERVAL, and a helper unit test for such a key in both 
checkBytesFirst forms.
   
   **Why this works:** The generated comparator is the one the planner's sort 
already uses on these keys. It compares a CALENDAR INTERVAL with 
CalendarInterval.compareTo, which returns zero exactly when months, days and 
microseconds match, so the checker separates keys whose intervals differ as the 
byte comparison did before this PR and as hash aggregation does, while collated 
strings still compare under their collation. Switching only keys that hold an 
interval leaves the comparison of every other key as the PR chose it.
   
   **Compatibility:** Binary-stable keys keep plain byte equality at every 
site, the helper keeps the interpreted ordering and the PR's checkBytesFirst 
choices for collated keys without an interval, and the groups every session 
iterator forms for such keys stay as they are.
   
   **Risks:** Sort-based aggregation over a non-binary collated string and a 
CALENDAR INTERVAL, which fails on the base branch, starts returning results; 
reverting the branch in the helper restores that failure. With code generation 
turned off for testing, keys holding an interval still fall back to the 
interpreted ordering and fail, as the planner's sort over them already does in 
that mode.
   
   **Constraints:** Keep InterpretedOrdering in the helper for every key that 
holds no CALENDAR INTERVAL, so WindowExec, the pandas window evaluator, the 
session iterators and sort-based aggregation keep their current comparison for 
such keys and the open decision about its cost at the correction sites stays 
with the author. Keep the meaning of checkBytesFirst: the byte comparison runs 
before the generated comparison exactly when the caller asks for it.
   
   **Exclusions:**
   - Choosing a cheaper comparison for collated keys without an interval, which 
the window group limit's own repair and the open decision about the cost at the 
correction sites settle.
   
   **Verification:**
   - **Regression:** A batch session-window aggregation over a UTF8_LCASE 
string and a make_interval value, with rows ('a', 1 day) and ('a', 2 days) in 
one shuffle partition, returns two rows with a count of 1 each for a plain 
aggregate and for a one-DISTINCT aggregate instead of failing with 
DATATYPE_CANNOT_ORDER, also when the interval is the first grouping column and 
when it sits in a struct beside the collated string.
   - **Behavior:** In the same aggregation, rows ('foo', 1 day) and ('FOO', 1 
day) within the session gap merge into one session while ('foo', 1 day) and 
('foo', 2 days) stay in separate groups, through both the plain and the 
one-DISTINCT plan.
   - **Behavior:** For a key of a UTF8_LCASE string and a CALENDAR INTERVAL, 
the helper's checker in both checkBytesFirst forms reports byte-identical keys 
and keys that differ only in the string's case as equal and keys whose 
intervals differ as unequal.
   - **Inspection:** For keys without a CALENDAR INTERVAL the shared checker 
still compares with InterpretedOrdering, so WindowExec, the pandas window 
evaluator, the session iterators and sort-based aggregation keep their 
comparison for those keys.



##########
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:
   **Non-blocking (P2):** On the base branch each limit node checked group 
membership with `UnsafeRow.equals` alone. Through this checker, every check 
whose key bytes differ, which is every group boundary and, for mostly distinct 
keys, about every row in both the Partial and the Final node, runs 
`InterpretedOrdering.compare` after the failed byte comparison 
(`UnsafeRowUtils.scala:263-265`). That evaluates each field through a 
`BoundReference`, boxing primitive values such as a DOUBLE next to the collated 
string, and for a struct key reads `PhysicalStructType.ordering`, which builds 
a new nested ordering on every comparison (`PhysicalDataType.scala:420-423`). 
The forwarded rows and answers stay the same, so this is extra CPU on queries 
the base branch already pruned correctly, such as `row_number() OVER (PARTITION 
BY k ORDER BY ts) = 1` over mostly distinct struct keys holding a UTF8_LCASE 
string.
   
   The PR description accepts this cost and names a generated ordering as the 
alternative; this review asks for `UnsafeRowKeyOperations.areEqual` instead, 
which forms the same groups on these orderable, float-normalized partition keys 
without that work. The collation comparison itself remains, so flat keys under 
ICU collations gain little; the saving is mostly for struct and mixed keys, and 
it has not been measured.
   
   **Recommended change:** In GroupedLimitIterator, when some partition-key 
type is not binary-stable and UnsafeRowKeyOperations.supportsDataType admits 
every key type, build one UnsafeRowKeyOperations over a StructType of the key 
types and decide group membership with nextGroup.equals(currentGroup) || 
keyOperations.areEqual(nextGroup, currentGroup), the shape ObjectAggregationMap 
uses; keep the shared checker, a single byte comparison, for binary-stable keys 
and for any key type the key operations do not admit. Keep the remembered 
answer and every point that clears it, and update the comment above the check 
to say that this operator compares collated keys with the key equality to avoid 
the interpreted ordering's work at each group boundary. Add a forwarded-row 
test whose PARTITION BY key is a struct holding a UTF8_LCASE string with mixed 
spellings.
   
   **Why this works:** UnsafeRowKeyOperations.areEqual walks per-field 
operations built once: binary-stable fields compare by bytes and collated 
strings with the collation's equality, which for UTF8_LCASE and ICU collations 
is the comparator returning zero, the test the interpreted ordering applies. A 
check that fails the byte comparison therefore pays one collation comparison 
per collated field without evaluating bound references, boxing primitive values 
or building a nested ordering for a struct key. Partition keys reaching the 
limit are orderable and have their floats normalized, so byte equality of their 
binary-stable fields matches the ordering, the groups are the ones WindowExec 
forms, and each limit node forwards the same rows.
   
   **Compatibility:** Query results, the rows each limit node forwards, the 
remembered answer and the binary-stable path are unchanged.
   
   **Risks:** The window group limit and the WindowExec above it now decide 
partition membership with different implementations, which give the same groups 
only while the key equality matches the ordering's equality on normalized, 
orderable keys; if a later change made the key equality treat as equal two keys 
the ordering separates, the limit would drop rows WindowExec needs. Reverting 
to the shared checker removes that risk and brings back the work this repair 
removes. For flat collated keys most of the added boundary cost stays, because 
every collation-aware implementation pays the collation comparison at each 
boundary and ICU collations dominate it; the saving is mostly for struct and 
mixed keys, and its size has not been measured.
   
   **Constraints:** Binary-stable partition keys keep the shared checker's 
single byte comparison. Keep the remembered group-equality answer and every 
point that clears it. Do not change the shared checker or its other callers for 
this repair; the interval keys that the shared checker's own repair handles 
never reach the window group limit.
   
   **Exclusions:**
   - Removing the collation comparison at each group boundary, which collapsing 
mixed-spelling partitions needs.
   - Changing the comparison at WindowExec, sort-based aggregation, the pandas 
window evaluator or the session-window iterators, whose cost the author decides 
separately.
   
   **Verification:**
   - **Regression:** For PARTITION BY keys holding a UTF8_LCASE string 
directly, in a struct, in an array, and next to a DOUBLE, with mixed spellings 
and groups that end under, at and over the limit, the Final node forwards one 
row per collation group up to the limit, matching WindowExec's partitions, and 
the answers equal those with the window group limit disabled.
   - **Behavior:** A new forwarded-row case whose PARTITION BY key is a struct 
holding a UTF8_LCASE string with alternating spellings sees the Final node 
forward one row per collation group for ROW_NUMBER with r <= 1.
   - **Inspection:** With a binary-stable partition spec the limit's check is a 
single UnsafeRow.equals, with a collated spec the key operations admit it never 
calls the interpreted ordering, and the remembered answer is still cleared when 
the input advances and when the current group changes.



##########
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:
   **Nit (P3):** This reason also describes 
`WindowEvaluatorFactory.fetchNextPartition` 
(`WindowEvaluatorFactory.scala:105-116`), which copies the partition's first 
key and checks every following row against it exactly as this loop does (lines 
319-330 of this file), yet passes `checkBytesFirst = false` because the 
trade-off has not been measured there (`WindowEvaluatorFactory.scala:67-72`). 
Since the `rowEqualityChecker` Scaladoc now leaves each choice's reason to its 
call site, a reader is given a reason that would make WindowExec's choice look 
wrong. The pre-check pays off only when most rows are spelled like their 
group's first row; what sets this site apart is that its loop compared key 
bytes alone before this change, and checking bytes first keeps that single byte 
comparison for such keys:
   
   ```suggestion
         // 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,
         // which keeps the single byte comparison this loop made before it 
used the collation.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4608864469).
   
   **Verification:**
   - **Inspection:** The comment above the pandas window evaluator's group-key 
checker gives a reason for checking bytes first that does not also describe 
WindowExec's partition loop, and it uses no pull-request wording such as 'base 
branch'.



##########
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:
   **Nit (P3):** Every other test in this mixin that registers a view or 
function wraps it in `self.temp_view(...)` and `self.temp_func(...)` (for 
example lines 589-591 of this file), and `ReusedSQLTestCase.tearDown` drops 
neither. After this test the view `t` and the function `spellings` stay 
registered for the tests that run after it, in this class and in the Spark 
Connect parity class, so those tests depend on test order, and `t` is the name 
most likely to collide. Registering both, running the query and asserting 
inside `with self.temp_view("t"), self.temp_func("spellings"):` drops them even 
when the assertion fails.
   
   **Verification:**
   - **Inspection:** The subquery test registers its view and function inside 
the suite's temp_view and temp_func context managers, so both are dropped even 
when its assertion fails.



##########
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:
   **Nit (P3):** Besides the two plans named here, 
`PythonIncrementalAggregateExec.plan` wraps its child in 
`AggUtils.mayAppendUpdatingSessionExec` 
(`PythonIncrementalAggregateExec.scala:394-398`), and its partial stage sends 
the emitted rows' grouping columns, session column included, to the Python 
worker (`PythonIncrementalAggregateExec.scala:233-241`). A batch session-window 
aggregation with a Python UDAF therefore depends on both the merged-session 
binding and each row's own grouping values, but a maintainer weighing a change 
to this rewrite reads that only two plans depend on it:
   
   ```suggestion
     // subquery or CTE and grouped outside, and the DISTINCT-aggregate, pandas
     // grouped-aggregate and Python UDAF aggregation plans that consume this 
iterator read
     // the grouping columns from the rows it emits.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58195#discussion_r4608864460).
   
   **Verification:**
   - **Inspection:** The comment above UpdatingSessionsIterator's 
session-column rewrite names the Python UDAF aggregation plan together with the 
one-DISTINCT aggregate and pandas grouped-aggregate plans, or no longer reads 
as a complete list of the iterator's consumers.



##########
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 = {

Review Comment:
   Thanks, both session-window iterators now compare grouping keys with the 
shared checker, and the new tests cover direct and struct keys, distinct 
collation groups and a two-column key. This review raises one follow-up: a 
session-window aggregation whose grouping key also holds a CALENDAR INTERVAL 
value now fails at these checks.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4595214448","thread_id":"inline:4595214448","verdict_sha256":"cb46a826d260b518058cdeb485f83e6d3df5d63529a71bcaf216521e10daf3c5"}
 -->



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