spark-test commented on code in PR #58195:
URL: https://github.com/apache/spark/pull/58195#discussion_r4595214448
##########
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:
**Non-blocking (P2):** This helper now decides group boundaries for every
window operator and for sort-based aggregation, but the two session-window
grouping iterators still compare grouping keys by bytes.
`MergingSessionsIterator` starts a new group unless `currentGroupingKey ==
groupingKey` (MergingSessionsIterator.scala:167), and
`UpdatingSessionsIterator` closes a session when `keys != currentKeys`
(UpdatingSessionsIterator.scala:112). Batch planning feeds both a stream
partitioned with `CollationAwareMurmur3Hash` and sorted under the collation,
and nothing rejects collated session-window keys in batch; streaming rejects
them in the state store.
By this reading of the code, `SELECT k, session_window.start, count(*) FROM
t GROUP BY k, session_window(ts, '10 minutes')` with `k STRING COLLATE
UTF8_LCASE` and the rows ('foo', 10:00), ('FOO', 10:05), ('foo', 10:08) returns
three sessions with count 1 instead of one session from 10:00 to 10:18 with
count 3. With a DISTINCT aggregate (`UpdatingSessionsExec`) or a pandas
grouped-aggregate UDF over the session window, the second 'foo' is found in the
byte-keyed `processedKeys` set. The query then fails with the internal error
'The iterator must be sorted by key and session start!'. This happens whenever
the grouping key without the session column contains a non-binary collated
string, directly or nested in a struct or array.
The previous review left session windows out of the pandas window fix as a
separate grouping family. This review raises them because this helper is
documented for grouping keys and already serves sort-based aggregation, whose
session-window counterparts these iterators are, and nothing in the PR defers
them.
**Recommended change:** In `MergingSessionsIterator` and
`UpdatingSessionsIterator`, build `UnsafeRowUtils.rowEqualityChecker` once from
the types of the grouping expressions without the session column. Use it in
place of `currentGroupingKey == groupingKey` and `keys != currentKeys`. Add
session-window aggregation tests over a collated grouping key for a plain and a
DISTINCT aggregate, with the collated string both directly in the key and
nested in a struct. The byte-keyed `processedKeys` set can stay as it is: once
boundaries compare under the collation, a collation group cannot recur in
correctly sorted input. If session windows are left for a follow-up instead, a
TODO at those two checks would record that.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#pullrequestreview-5916692634).
**Verification:**
- **Regression:** For batch session-window aggregation whose grouping key
without the session column contains a non-binary collated string, directly as a
UTF8_LCASE key or nested in a struct that holds one, a count over ('foo',
10:00), ('FOO', 10:05) and ('foo', 10:08) with a 10-minute gap returns one
session from 10:00 to 10:18 with count 3, and the same query with a DISTINCT
aggregate, which runs the session iterator that pandas grouped aggregation over
session windows also uses, returns that session instead of failing with an
internal error.
- **Compatibility:** The same session-window queries over a UTF8_BINARY key
keep 'foo' and 'FOO' in separate sessions.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortBasedAggregationIterator.scala:
##########
@@ -108,13 +108,7 @@ class SortBasedAggregationIterator(
}
groupKeyEqualityCheck =
- if (groupingExpressions.forall(e =>
UnsafeRowUtils.isBinaryStable(e.dataType))) {
- (key1: UnsafeRow, key2: UnsafeRow) => key1.equals(key2)
- } else {
- val types = groupingAttributes.map(_.dataType).toIndexedSeq
- val ordering = InterpretedOrdering.forSchema(types)
- (key1: UnsafeRow, key2: UnsafeRow) => ordering.compare(key1, key2) == 0
- }
+ UnsafeRowUtils.rowEqualityChecker(groupingAttributes.map(_.dataType))
Review Comment:
**Non-blocking (P2):** On the base branch, this iterator and `WindowExec`'s
evaluator compared collated keys with the interpreted ordering alone. Through
the helper, every check now runs `key1.equals(key2)` first
(UnsafeRowUtils.scala:255). That makes same-spelling checks cheaper. But these
two sites already grouped collated keys correctly, and every check whose key
bytes differ now runs a failed byte comparison before the same interpreted
comparison.
This iterator never compares a group's first row with itself, so mostly
single-row groups get no byte hit to offset that. Take `SELECT k, max(v) FROM t
GROUP BY k` with `k STRING COLLATE UTF8_LCASE`, `v STRING` and mostly unique
`k`. The STRING buffer of `max` rules out hash and object-hash aggregation, so
both aggregation sides run this iterator, and by this reading of the code each
of their rows does strictly more work than before. `WindowExec` is affected
only for long partitions spelled mostly unlike their first row: its first-row
self-check becomes a byte hit, and a multi-key partition spec that arrives as a
list also gets cheaper indexed lookups there.
Groups and results are unchanged. Each extra comparison is a size check or a
few word reads, small next to the interpreted collation comparison, and no
benchmark measures either side. The earlier review suggested the pre-check for
the window group limit, whose base-branch comparison was byte equality. That
site and the pandas window evaluator are where it pays off, because it bounds
what their correction costs.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4578723317).
**Recommended change:** Add a parameter to UnsafeRowUtils.rowEqualityChecker
that controls whether its collated branch compares key bytes before the
interpreted ordering, keep the byte-first form for the window group limit and
the pandas window evaluator, and have SortBasedAggregationIterator and
WindowExec's evaluator skip it so they compare collated keys with the
interpreted ordering alone, as on the base branch; describe the choice in the
helper's Scaladoc and extend the helper's unit tests to the new form. Commit
3cf27aad326 applied the byte-first form at these two sites so that
same-spelling keys cost a single byte comparison at every site; there that gain
comes with a failed byte comparison on every mismatched check, so their
base-branch ordering-only comparison is the starting point.
**Why this works:** The byte pre-check pays off where the base branch
compared bytes, because it keeps same-spelling checks as cheap as before the
correction; at sites that already used the interpreted ordering it trades
cheaper same-spelling checks for a failed byte comparison on every mismatched
check, which regresses inputs whose checks mostly mismatch. Skipping it at
those two sites removes the failed byte comparison and leaves no more work per
check than on the base branch, while the binary-stable branch and the indexed
ordering stay shared, so no caller's groups change.
**Scope:** Let the shared equality helper skip its byte pre-check, and have
WindowExec and sort-based aggregation skip it so they keep the base branch's
comparison for collated keys.
**Compatibility:** Group membership at every caller stays exactly that of
the interpreted ordering for collated keys and of byte equality for
binary-stable keys.
**Risks:** WindowExec and sort-based aggregation give up the byte shortcut
this PR added for same-spelling collated keys and go back to one interpreted
comparison per check, as on the base branch; passing the byte-first option at
those two call sites rolls it back.
**Constraints:** The window group limit and the pandas window evaluator keep
the byte pre-check, and the session-window iterators use it once they adopt the
helper, because their base-branch comparison was byte equality and the
pre-check bounds the cost of their correction. The option changes only whether
bytes are compared first; every caller's groups stay those of the interpreted
ordering for collated keys and of byte equality for binary-stable keys.
**Exclusions:**
- Enabling the byte shortcut at WindowExec and sort-based aggregation, which
a separate change can do with measurements of both same-spelling and mismatched
workloads.
**Success:** SortBasedAggregationIterator and WindowExec's evaluator compare
keys that contain a non-binary collated string with the interpreted ordering
alone, as on the base branch, and form the same groups. The window group limit
and the pandas window evaluator still compare key bytes before the interpreted
ordering. Binary-stable keys use plain byte equality at every caller.
**Verification:**
- **Behavior:** For a key with a UTF8_LCASE string and an integer, the
helper's form without the byte pre-check treats byte-identical keys and
differently spelled collation-equal keys as equal and keys that differ in
either field as unequal, matching the byte-first form.
- **Inspection:** The collated checker that sort-based aggregation and
WindowExec build runs no byte comparison before the interpreted ordering, while
the checker of the window group limit and the pandas window evaluator compares
bytes first.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/window/WindowGroupLimitExec.scala:
##########
@@ -205,12 +206,31 @@ 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.
+ private val groupEqualityCheck: (UnsafeRow, UnsafeRow) => Boolean =
+ UnsafeRowUtils.rowEqualityChecker(partitionSpec.map(_.dataType))
+
// Manage the stream and the grouping.
var nextRow: UnsafeRow = null
var nextGroup: UnsafeRow = null
var nextRowAvailable: Boolean = false
+
+ // Result of the group-equality check for the row currently held in
nextRow/nextGroup,
+ // remembered so that the limit iterators' repeated hasNext calls evaluate
the check at
+ // most once per fetched row; for collated keys each evaluation pays a
comparison over
+ // all key fields. Whether the remembered answer is current is tracked with
an explicit
Review Comment:
**Nit (P3):** A row that starts a new group is checked twice.
`GroupIterator.hasNext` checks it against the previous group, and the false
answer ends that group. Then `skipRemainingRows` copies its key into
`currentGroup` and clears the flag, so the next `hasNext` checks it again
against that copy. A byte comparison always answers that second check, so the
cache still avoids the repeated collation comparisons; only the stated bound is
off. Suggested wording:
```suggestion
// remembered so that the limit iterators' repeated hasNext calls evaluate
the check at
// most once per fetched row and current group (a row that starts a new
group is checked
// again after the switch); for collated keys each evaluation pays a
comparison over all
// key fields. Whether the remembered answer is current is tracked with an
explicit
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4584838004).
**Verification:**
- **Inspection:** The comment says that a row starting a new group is
checked again after the group switch, or bounds the check per fetched row and
current group, and no sentence claims a single evaluation per fetched row.
##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,167 @@ 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. Mixed spellings keep the boundary checks on the collation
comparison
+ // 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),
Review Comment:
**Nit (P3):** The only row the over-limit group skips, ('b', 5), is spelled
like the group's first row ('b', 3), whose key `currentGroup` copies. So
`key1.equals(key2)` answers its skip check, and the check never reaches the
collation comparison that the test's comment says the mixed spellings exercise.
If `skipRemainingRows` compared bytes, as the base branch's `nextGroup ==
currentGroup` did, it would still skip this row, the Final node would still
forward 5 rows, and the test would pass. Spelling the skipped row differently
keeps the expected answer and the 5 forwarded rows, while that regression would
forward 6:
```suggestion
| ('b', 3), ('B', 4), ('B', 5),
```
The comment at lines 3490-3491 then needs updating too, because ('B', 4) and
('B', 5) form one byte-group of two rows. For example:
```scala
// rows. Pre-fix byte grouping: each spelling forms its own
byte-group, and every
// byte-group fits within the limit, so all 6 rows are forwarded.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4584838004).
**Verification:**
- **Regression:** With a skip loop that compares key bytes instead of the
cached collation-aware check, the under/over-limit case forwards 6 rows from
the Final node and fails, while the current iterator forwards 5 and passes.
- **Inspection:** The comment that explains why byte grouping forwards all 6
rows describes the new rows, in which the 'B' rows form one byte-group that
fits within the limit, instead of saying that every row is its own byte-group.
--
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]