vinodkc commented on code in PR #58195:
URL: https://github.com/apache/spark/pull/58195#discussion_r4595449935
##########
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:
Done (f1dda77be99). Both `MergingSessionsIterator` and
`UpdatingSessionsIterator` now build
`UnsafeRowUtils.rowEqualityChecker(groupingWithoutSession.map(_.dataType),
checkBytesFirst = true)` for their group-boundary checks, and the byte-keyed
`processedKeys` set stays as you suggested. Added the requested tests in
`CollationSuite`: session-window aggregation over a UTF8_LCASE grouping key for
a plain and a DISTINCT aggregate, with the collated string directly in the key
and nested in a struct, plus UTF8_BINARY compatibility halves. I also verified
the regression empirically before fixing: pre-fix, the plain aggregate returns
exactly the three unmerged one-row sessions you predicted (gap 600s each)
instead of one 10:00-10:18 session with count 3; post-fix both tests pass. The
session gap is asserted as `end - start` in seconds so the expectations do not
depend on the session time zone.
##########
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:
Done (f1dda77be99). `rowEqualityChecker` now takes a required
`checkBytesFirst` parameter, and its Scaladoc describes when to pass which: the
window group limit, the pandas window evaluator, and the session-window
iterators keep the byte-first form (their base-branch comparison was byte
equality), while `SortBasedAggregationIterator` and `WindowExec`'s evaluator
pass `false` so collated keys go straight to the interpreted ordering, as on
the base branch. The helper's unit tests now cover both forms.
##########
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:
Done (f1dda77be99) -- the comment uses your wording now.
##########
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:
Done (f1dda77be99) -- the rows are now `('b', 3), ('B', 4), ('B', 5)`, with
the surrounding comments updated: the two `'B'` rows form one byte-group that
fits within the limit, so pre-fix byte grouping still forwards all 6 rows while
the fixed iterator forwards 5.
--
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]