spark-test commented on code in PR #58195:
URL: https://github.com/apache/spark/pull/58195#discussion_r4608864460
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/UpdatingSessionsIterator.scala:
##########
@@ -51,13 +52,29 @@ class UpdatingSessionsIterator(
private[this] val groupingWithoutSessionProjection: UnsafeProjection =
UnsafeProjection.create(groupingWithoutSession, inputSchema)
- private val valuesExpressions: Seq[Attribute] =
inputSchema.diff(groupingExpressions)
+ // A non-binary-stable grouping key (e.g. a collated STRING) makes the
checker fall back
+ // to an ordering-based comparison, so differently spelled collation-equal
keys land in
+ // the same group; the bytes are checked first, so a key spelled like the
session's
+ // first row costs one byte comparison and only keys whose bytes differ pay
the ordering
+ // comparison. processedKeys below still hashes keys by bytes: once the
group boundaries
+ // compare under the collation, a collation group cannot recur in correctly
sorted
+ // input, so only a byte-identical key can hit the set.
+ private[this] val groupKeyEqualityCheck: (UnsafeRow, UnsafeRow) => Boolean =
+ UnsafeRowUtils.rowEqualityChecker(
+ groupingWithoutSession.map(_.dataType), checkBytesFirst = true)
+
+ // Every input column except the session column, in input order: each row of
a closed
+ // session keeps its own values for these columns, and only its session
column is
+ // replaced with the merged session. The rows of a session can spell a
collated grouping
+ // key differently, and the DISTINCT-aggregate and pandas grouped-aggregate
plans that
+ // consume this iterator read the grouping columns from the rows it emits.
+ private val nonSessionExpressions: Seq[Attribute] =
inputSchema.diff(Seq(sessionExpression))
Review Comment:
**Blocking (P1):** `Seq.diff` matches attributes with
`AttributeReference.equals`, which compares qualifier and metadata as well as
the expression ID. `sessionExpression` is the aggregate's grouping attribute
and `inputSchema` is the child's output, so the session column is removed only
when the two attributes match exactly, as they do when the session window is
grouped directly. When the session window is computed in a subquery or CTE, or
in a Dataset given an alias, and grouped outside, `SubqueryAlias.output` gives
the grouping attribute the alias qualifier while the child's `ProjectExec`
output for the same column has none. The diff then removes nothing,
`restoreProj` binds the session's expression ID to its first position, which is
the row's own session column, and the merged session in
`join2(rowWithoutSession, mergedSession)` is never read.
By this reading of the code, with rows ('foo', 10:00, 1), ('foo', 10:05, 2)
and ('foo', 10:08, 3) in `t`,
```sql
SELECT s, sw, count(DISTINCT v)
FROM (SELECT s, v, session_window(ts, '10 minutes') AS sw FROM t) sub
GROUP BY s, sw
```
returns three one-event sessions with a count of 1 each, where the base
branch returns one 10:00 to 10:18 session with a count of 3: its `restoreProj`
input put the merged session ahead of the row's own column, so the merged
session won. The same happens for a pandas grouped-aggregate UDF over that
shape, through `ArrowAggregatePythonExec`, and for any key type, binary-stable
keys included. Session windows grouped directly by `session_window(...)`, plain
aggregates and streaming queries do not run into it, which is why the new tests
pass. `UpdatingSessionsExec` already matches the session column with
`semanticEquals`; finding it here by expression ID instead of attribute
equality fixes it.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4599200689).
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:
Thanks, every row of a closed session now keeps its own grouping values.
This review raises two follow-ups on the new rewrite: the way it identifies the
session column can leave emitted rows with their own unmerged sessions, and its
intermediate per-row projection is not needed.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4599200689","thread_id":"inline:4599200689","verdict_sha256":"ef02e972631d278cbff1bc9bd3f395ff1da2f5cd83d7ddbae0e5c5066265bd36"}
-->
##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationSuite.scala:
##########
@@ -3330,4 +3331,299 @@ 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("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
Review Comment:
**Nit (P3):** Every row of this collated table, and of the struct-keyed
table in the next test, belongs to one UTF8_LCASE group, while the UTF8_BINARY
halves, which do hold two keys, take the byte branch. So the collation branch
of `groupKeyEqualityCheck` in `MergingSessionsIterator` and
`UpdatingSessionsIterator` only ever answers true in these tests: the path that
closes a session on a collated key change, records the key for the sortedness
guard and starts the next session never runs. A regression that treated keys
differing under the collation as equal, or built the checker over only some
fields of a multi-column key, would merge the sessions of distinct keys or hit
the sortedness error on real data while every assertion here still passes. A
second collated group whose sessions overlap the first in time, such as ('bar',
10:02) and ('BAR', 10:06), for the plain and the DISTINCT aggregate, directly
and in a struct, plus a two-column key whose rows differ only in its
non-collated
column, would catch it.
**Verification:**
- **Regression:** With two collated groups whose sessions overlap in time,
plain and one-DISTINCT session-window aggregation over a UTF8_LCASE key,
directly and in a struct, returns one merged session per collation group with
that group's count, and a two-column key keeps apart rows that differ only in
its non-collated column.
##########
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. It
pays off where
+ * most checks see keys spelled alike, such as rows compared against the
first row of
+ * the current group; where that trade-off has not been measured for a site,
pass
+ * `false` and compare collated keys with the ordering alone.
Review Comment:
**Nit (P3):** Read by its last clause, this tells every site that has not
measured the trade-off to pass `false`, but the window group limit, the pandas
window evaluator and both session iterators pass `true` without a measurement.
Read by its example, sort-based aggregation's `processCurrentSortedGroup` and
WindowExec's `fetchNextPartition` also compare each row with their group's
first key, yet pass `false`. What the six choices actually do is keep each
site's earlier per-check cost. Since both forms group keys the same way, the
Scaladoc could state the trade-off and leave each choice's reason to its call
site:
```suggestion
* 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.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4599200705).
**Verification:**
- **Inspection:** The rowEqualityChecker Scaladoc states the trade-off of
the byte pre-check and that both forms form the same groups, gives no rule for
choosing checkBytesFirst that the window group limit, the pandas window
evaluator, the two session iterators, sort-based aggregation or WindowExec's
evaluator contradicts, and claims no measurement the repository does not
contain.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/UpdatingSessionsIterator.scala:
##########
@@ -184,29 +201,26 @@ 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 nonSessionProj =
+ GenerateUnsafeProjection.generate(nonSessionExpressions, 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)
- }
+ nonSessionExpressions ++ Seq(sessionExpression.toAttribute))
private def closeCurrentSession(keyChanged: Boolean): Unit = {
returnRows = rowsForCurrentSession
rowsForCurrentSession = null
- val groupingKey = generateGroupingKey().copy()
+ // The merged session every row of this session is rewritten to.
Everything else in
+ // each row is projected from the row itself, so rows of a session that
mixes the
+ // spellings of a collated key keep their own spelling (see
nonSessionExpressions).
+ val mergedSession = new
SpecificInternalRow(Seq(sessionExpression.toAttribute).toStructType)
+ mergedSession.update(0, currentSession)
val currentRowsIter = returnRows.generateIterator().map { internalRow =>
- val valueRow = valueProj(internalRow)
- restoreProj(join2(groupingKey, valueRow)).copy()
+ val rowWithoutSession = nonSessionProj(internalRow)
Review Comment:
**Nit (P3):** `rowWithoutSession` is read only by `restoreProj` on the next
line, and every value `restoreProj` takes from it is also in `internalRow`. So
each emitted row is written twice: once with all of its non-session columns,
grouping strings included, and again with every column plus the merged session.
The base branch's intermediate row held only the value columns. One projection
over `join2(internalRow, mergedSession)` that keeps each non-session column at
its own ordinal and takes the session column, chosen by expression ID, from the
appended merged session gives the same rows with one write per row, on the
default binary-stable path as well.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58195#discussion_r4599200689).
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:
Thanks, the call-site comments now explain each choice by its trade-off.
This review raises one follow-up: the Scaladoc's rule for choosing
checkBytesFirst still does not match the choices the six callers make.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4599200705","thread_id":"inline:4599200705","verdict_sha256":"ef02e972631d278cbff1bc9bd3f395ff1da2f5cd83d7ddbae0e5c5066265bd36"}
-->
--
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]