spark-test commented on code in PR #58195:
URL: https://github.com/apache/spark/pull/58195#discussion_r4599200727
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/SortBasedAggregationIterator.scala:
##########
@@ -107,14 +107,12 @@ class SortBasedAggregationIterator(
sortedInputHasNewGroup = false
}
+ // The base branch compared collated keys with the interpreted ordering
alone, so the
+ // checker skips the byte pre-check: this iterator mostly compares a
group's first row
+ // against rows of other groups, and with mostly unique keys every check
would run a
+ // failed byte comparison before the same ordering comparison.
Review Comment:
**Nit (P3):** `processCurrentSortedGroup` (lines 132-146) compares the
group's first key with every following row until the first mismatch. So an
n-row group makes n-1 same-group checks and one check against the next group,
and 'mostly compares a group's first row against rows of other groups' holds
only when groups are mostly single rows. The comment at
WindowEvaluatorFactory.scala:67-69, which cites mostly mismatched keys, has the
same problem. `fetchNextPartition` copies the key into `currentGroup` (line
107), so its first check of every partition compares a key with its own copy
and is always byte-identical, as is the check of every row spelled like the
partition's first. Checks whose bytes differ dominate there only in partitions
spelled mostly unlike their first row. For the same reason, the
`rowEqualityChecker` Scaladoc's 'strictly extra work for inputs whose checks
mostly mismatch' never holds at WindowExec. The reason these two sites skip the
pre-check is that its trade-o
ff there has not been measured, and the comments could say that. Here, for
example:
```suggestion
// The checker skips the byte pre-check, whose trade-off here has not
been measured:
// the pre-check would answer each check of a row spelled like its
group's first row,
// but add a failed byte comparison to every other check, including the
check that ends
// each group, so inputs with mostly single-row groups would pay more
per check.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4595214453).
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:
+ // the base branch compared keys by bytes alone, so the pre-check keeps
same-spelling
+ // keys as cheap as they were before the collation-aware grouping.
Review Comment:
**Nit (P3):** 'The base branch' is pull-request vocabulary: once this is
merged it names nothing. Here it also follows 'both branches', which means the
checker's byte and ordering paths, so it reads as one of them. The same wording
appears at ArrowWindowPythonEvaluatorFactory.scala:261,
SortBasedAggregationIterator.scala:110 and WindowEvaluatorFactory.scala:67. The
`rowEqualityChecker` Scaladoc tells callers to pass `true` at 'sites whose
previous comparison was byte equality', a rule a new caller cannot apply.
Stating the trade-off itself would keep each choice explained. The pre-check
answers identically spelled keys with one byte comparison but adds a failed
byte comparison to every check whose bytes differ. So it pays off where most
checks see identically spelled keys, and the sites that pass `false` can
compare collated keys with the ordering alone until that trade-off is measured
for them. For this site, for example:
```suggestion
// 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.
```
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/UpdatingSessionsIterator.scala:
##########
@@ -109,7 +120,7 @@ class UpdatingSessionsIterator(
if (currentKeys == null) {
startNewSession(row, keys, sessionStruct)
- } else if (keys != currentKeys) {
+ } else if (!groupKeyEqualityCheck(keys, currentKeys)) {
Review Comment:
**Blocking (P1):** This check now lets one session hold keys that are equal
under the collation but differ in bytes, such as 'foo' and 'FOO' under
UTF8_LCASE. `closeCurrentSession` is unchanged, though. It rebuilds every
buffered row as `restoreProj(join2(groupingKey, valueProj(row)))`, where
`groupingKey` is `currentKeys`, a copy of the session's first key (line 162),
and `valuesExpressions = inputSchema.diff(groupingExpressions)` (line 65)
leaves out the grouping columns. So every row of a mixed-spelling session
leaves this iterator carrying the first row's grouping values. On the base
branch the byte check ended a session at every byte change, so this rebuild
changed nothing but the session column. The previous review recommended this
check without accounting for the rebuild.
Two plans consume those rows:
- A batch session-window aggregation with one DISTINCT argument set and no
FILTER. `RewriteDistinctAggregates` leaves it alone, and
`planAggregateWithOneDistinct` puts `UpdatingSessionsExec` directly under the
partial aggregate. That aggregate evaluates the non-distinct aggregates and the
distinct expressions over these rows.
- A pandas grouped-aggregate UDF over a session window.
`ArrowAggregatePythonExec` runs this iterator before `GroupedIterator` and the
UDF input projection.
Take `s STRING COLLATE UTF8_LCASE` and the rows ('foo', 10:00), ('FOO',
10:05), ('foo', 10:08). By this reading of the code, `SELECT collect_list(s),
count(DISTINCT s COLLATE UTF8_BINARY) FROM t GROUP BY s, session_window(ts, '10
minutes')` returns three copies of 'foo' and a distinct count of 1 instead of
2. Under UTF8_BINARY_RTRIM, `sum(length(s))` over 'a' and 'a ' in a query with
a DISTINCT aggregate gives 2 instead of 4. In a query without a DISTINCT
aggregate, `collect_list(s)` goes through `MergingSessionsExec`, whose partial
buffers come from the original rows, and returns each row's own spelling. So
the answer now depends on the plan. On the base branch the three-row input
failed with 'The iterator must be sorted by key and session start!', so the
change turns an explicit failure into a silent wrong value. It affects any such
query whose grouping key contains a non-binary collated string, directly or
nested, once a session mixes spellings. The new DISTINCT tests assert o
nly the session length and `count(DISTINCT v)`, neither of which the rewrite
changes.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4595214448).
**Recommended change:** Make UpdatingSessionsIterator.closeCurrentSession
keep each buffered row's own grouping-column values and replace only its
session column with the merged session. Today every row of a closed session is
rebuilt from the session's first key. That was harmless while a session held
only byte-identical keys, but it now overwrites the other spellings of a
collated key, so aggregates that read the grouping column on the DISTINCT and
pandas grouped-aggregate paths see only the first spelling. Add collation
session-window tests that read the grouping column inside the aggregation: a
query whose only DISTINCT aggregate is count(DISTINCT s COLLATE UTF8_BINARY),
next to collect_list(s), so that it is planned with UpdatingSessionsExec, with
the collated string both directly in the key and nested in a struct; and a
pandas grouped-aggregate UDF over a session window that receives s.
**Why this works:** Rebuild each buffered row from its own non-session
columns plus the merged session, instead of taking the grouping columns from
currentKeys. One way is to project every input column except the session column
from the row itself, join that with a one-field row holding the merged session,
and bind the output schema to that layout. currentKeys keeps its other uses,
the group-boundary check and the processedKeys sortedness guard. For
binary-stable keys every row in a session already has currentKeys' bytes, so
the rebuilt rows are byte-identical to today's.
**Scope:** Keep each row's own grouping values when UpdatingSessionsIterator
rewrites the session column, and cover the DISTINCT and pandas
grouped-aggregate session-window paths with tests that read the grouping column.
**Compatibility:** Session boundaries, the merged session values, the
processedKeys sortedness guard and the output for binary-stable keys stay as
they are. Only the grouping-column values of rows in sessions that mix
byte-different, collation-equal keys change, back to each row's own value.
**Risks:** On the DISTINCT path, the key reported for a collated group is
today always the session's first spelling, because every row carries it. Once
rows keep their own spellings, the aggregate above reports the spelling it sees
first, which can vary with task and arrival order. The reported key is still
one of the group's spellings, and the existing DISTINCT tests already avoid
asserting it. Reverting this change restores the current behavior.
**Constraints:** Leave the group-boundary check, the processedKeys guard and
the session merge logic unchanged; only the values written into each emitted
row change. Rows for binary-stable keys must stay byte-identical to today's
output, because every existing plan that runs this iterator consumes them.
**Success:** Every row UpdatingSessionsIterator emits carries its own input
value in every column except the session column, which holds the merged
session. A session-window aggregation over a UTF8_LCASE key s, whose only
DISTINCT aggregate is count(DISTINCT s COLLATE UTF8_BINARY), over rows 'foo',
'FOO' and 'foo' in one session, returns 2 from that aggregate and the three
original spellings from collect_list(s), as collect_list(s) already returns in
the same query without a DISTINCT aggregate. A pandas grouped-aggregate UDF
over a session window receives each row's own spelling of the grouping column.
Sessions still merge under the collation: the DISTINCT query still returns one
10:00 to 10:18 session instead of an internal error.
**Verification:**
- **Regression:** A batch session-window aggregation over rows ('foo',
10:00), ('FOO', 10:05) and ('foo', 10:08) with a 10-minute gap, grouped by a
key that holds the UTF8_LCASE string directly or nested in a struct, returns
one 10:00 to 10:18 session in which collect_list of the string gives the three
original spellings and the query's only DISTINCT aggregate, a count of the
string's distinct UTF8_BINARY values, gives 2; with that single DISTINCT
argument set the query is planned with UpdatingSessionsExec.
- **Regression:** A pandas grouped-aggregate UDF over a session window,
whose argument is the UTF8_LCASE grouping column, receives the original
spelling of every row in the merged session.
- **Compatibility:** Session-window queries over a UTF8_BINARY key, and over
keys with no collated string, return the same rows and values as before, and
UpdatingSessionsIterator emits byte-identical rows for them.
##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,268 @@ 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. Every group's rows mix spellings, so each boundary check
-- including
+ // the check of the skipped row, which is spelled unlike the group's first
row -- runs
+ // the collation comparison instead of hitting the byte-equality fast
path. The default
+ // window group limit threshold (1000) already admits r <= 2.
Review Comment:
**Nit (P3):** Group 'a' is the single row ('a', 1), so not every group mixes
spellings. Not every boundary check runs the collation comparison either. Each
group's first row is checked against its own copy, at construction and after
every switch in `skipRemainingRows`, and the byte comparison answers that
check. Only ('B', 4), the skipped ('B', 5) and ('C', 7) reach the collation
comparison because of their spelling. The checks of ('b', 3) and ('c', 6)
against the previous group reach it only because those keys differ.
```suggestion
// 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.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4595214482).
**Verification:**
- **Inspection:** The comment on the under-and-over-limit window group limit
test no longer says that every group mixes spellings or that every boundary
check runs the collation comparison, and what it says about which checks reach
the collation comparison matches the rows ('a', 1), ('b', 3), ('B', 4), ('B',
5), ('c', 6) and ('C', 7).
##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,268 @@ 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. Every group's rows mix spellings, so each boundary check
-- including
+ // the check of the skipped row, which is spelled unlike the group's first
row -- runs
+ // the collation comparison instead of hitting 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("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 session gap is asserted as end - start
in seconds
Review Comment:
**Nit (P3):** In session windows the gap is the inactivity duration passed
as `session_window(ts, '10 minutes')`, here 600 seconds. `end - start` is the
merged session's length: the expected 1080 is 10:00 to 10:18. A reader who
checks 1080 under the name `gap` against the 10-minute gap expects 600. Calling
the value the session length or duration removes the mismatch. That means this
comment, the one at lines 3530-3531, and the `AS gap` aliases at lines 3521,
3534, 3570 and 3577.
**Verification:**
- **Inspection:** The collated session-window tests no longer alias end -
start as gap or call it the session gap, and their expected values are
unchanged.
--
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]