You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "dbatomic (via GitHub)" <gi...@apache.org> on 2024/02/27 16:56:20 UTC

[PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

dbatomic opened a new pull request, #45290:
URL: https://github.com/apache/spark/pull/45290

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   This PR is part of collation effort. For details please refer to umbrella JIRA ticket with linked designed document.
   
   This PR adds support for Aggregates and GROUP BY against strings with collation.
   This PR adds following:
   1) `SortAggregate` support for columns with collation.
   2) Rule that will force SortAggs in case of non-binary collations.
   3) Tests.
   4) Golden file for collations (which includes basic filters and aggs).
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   Please refer to document in JIRA for overall collation effort.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   With this PR users will have proper support for aggregates against strings that are collated with non-binary collations (e.g. UTF8_BINARY_LCASE).
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   Tests in `CollationSuite` plus golden file tests.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   Yes.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1505922202


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala:
##########
@@ -405,11 +405,21 @@ abstract class HashExpression[E] extends Expression {
     s"$result = $hasherClassName.hashInt($input.months, $microsecondsHash);"
   }
 
-  protected def genHashString(input: String, result: String): String = {
-    val baseObject = s"$input.getBaseObject()"
-    val baseOffset = s"$input.getBaseOffset()"
-    val numBytes = s"$input.numBytes()"
-    s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+  protected def genHashString(
+     ctx: CodegenContext, input: String, result: String, stringType: StringType): String = {
+    if (stringType.isDefaultCollation) {
+      val baseObject = s"$input.getBaseObject()"
+      val baseOffset = s"$input.getBaseOffset()"
+      val numBytes = s"$input.numBytes()"
+      s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+    } else {
+      val stringHash = ctx.freshName("stringHash")
+      s"""
+        long $stringHash = CollationFactory.fetchCollation(${stringType.collationId})

Review Comment:
   Right. I will leave this change for another PR.
   
   We need this to make reshuffle working properly btw, but I will make that change in a separate PR.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1508938251


##########
sql/api/src/main/scala/org/apache/spark/sql/types/StringType.scala:
##########
@@ -33,6 +33,14 @@ class StringType private(val collationId: Int) extends AtomicType with Serializa
    */
   def isDefaultCollation: Boolean = collationId == StringType.DEFAULT_COLLATION_ID
 
+  /**
+   * Binary collation implies that strings are considered equal only if they are
+   * byte for byte equal. E.g. all accent or case-insensitive collations are considered non-binary.
+   * If this field is true, byte level operations can be used against this datatype (e.g. for
+   * equality and hashing).
+   */
+  def isBinaryCollation: Boolean = CollationFactory.fetchCollation(collationId).isBinaryCollation

Review Comment:
   when shall we treat default collation and binary collation differently?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1504687213


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala:
##########
@@ -405,11 +405,21 @@ abstract class HashExpression[E] extends Expression {
     s"$result = $hasherClassName.hashInt($input.months, $microsecondsHash);"
   }
 
-  protected def genHashString(input: String, result: String): String = {
-    val baseObject = s"$input.getBaseObject()"
-    val baseOffset = s"$input.getBaseOffset()"
-    val numBytes = s"$input.numBytes()"
-    s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+  protected def genHashString(
+     ctx: CodegenContext, input: String, result: String, stringType: StringType): String = {
+    if (stringType.isDefaultCollation) {
+      val baseObject = s"$input.getBaseObject()"
+      val baseOffset = s"$input.getBaseOffset()"
+      val numBytes = s"$input.numBytes()"
+      s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+    } else {
+      val stringHash = ctx.freshName("stringHash")
+      s"""
+        long $stringHash = CollationFactory.fetchCollation(${stringType.collationId})

Review Comment:
   why is this needed if we're going to force sort aggregate anyways?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517243024


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   This test case failed in the daily test of Maven + Java 21, both on Linux and MacOS. @dbatomic Do you have time to investigate the cause of this failure?
   
   - linux: https://github.com/apache/spark/actions/runs/8189363924/job/22416511124
   
   ![image](https://github.com/apache/spark/assets/1475305/2b39b2d2-a4b2-45ec-8bd9-42c36f22a0b9)
   
   
   - macos-14: https://github.com/apache/spark/actions/runs/8194082205/job/22416483724
   
   ![image](https://github.com/apache/spark/assets/1475305/280c413b-71d6-4715-80a6-1f5ae27a5097)
   
   also cc @HyukjinKwon because I noticed that you are paying attention to the tests of maven + Java 21 on macos-14



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1518057279


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   https://github.com/apache/spark/pull/45436



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517357872


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   Looking into this. Thanks.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #45290: [SPARK-46834][SQL][Collations] Support for aggregates
URL: https://github.com/apache/spark/pull/45290


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517243024


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   This test case failed in the daily test of Maven + Java 21, both on Linux and MacOS. @dbatomic Do you have time to investigate the cause of this failure?
   
   - linux: https://github.com/apache/spark/actions/runs/8189363924/job/22416511124
   
   ```
   - aggregates count respects collation *** FAILED ***
     Exception thrown while executing query:
     == Parsed Logical Plan ==
     CTE [t]
     :  +- 'SubqueryAlias t
     :     +- 'Project ['collate('col1, unicode_CI) AS c#427560]
     :        +- 'UnresolvedInlineTable [col1], [[AAA], [aaa]]
     +- 'Aggregate ['c], [unresolvedalias('COUNT(1)), 'c]
        +- 'UnresolvedRelation [t], [], false
     
     == Analyzed Logical Plan ==
     count(1): bigint, c: string COLLATE 'UNICODE_CI'
     WithCTE
     :- CTERelationDef 106, false
     :  +- SubqueryAlias t
     :     +- Project [collate(col1#427562, unicode_CI) AS c#427560]
     :        +- LocalRelation [col1#427562]
     +- Aggregate [c#427560], [count(1) AS count(1)#427563L, c#427560]
        +- SubqueryAlias t
           +- CTERelationRef 106, true, [c#427560], false
     
     == Optimized Logical Plan ==
     Aggregate [c#427560], [count(1) AS count(1)#427563L, c#427560]
     +- LocalRelation [c#427560]
     
     == Physical Plan ==
     AdaptiveSparkPlan isFinalPlan=false
     +- == Current Plan ==
        SortAggregate(key=[c#427560], functions=[count(1)], output=[count(1)#427563L, c#427560])
        +- Sort [c#427560 ASC NULLS FIRST], false, 0
           +- ShuffleQueryStage 0
              +- Exchange hashpartitioning(c#427560, 5), ENSURE_REQUIREMENTS, [plan_id=435997]
                 +- SortAggregate(key=[c#427560], functions=[partial_count(1)], output=[c#427560, count#427567L])
                    +- *(1) Sort [c#427560 ASC NULLS FIRST], false, 0
                       +- *(1) LocalTableScan [c#427560]
     +- == Initial Plan ==
        SortAggregate(key=[c#427560], functions=[count(1)], output=[count(1)#427563L, c#427560])
        +- Sort [c#427560 ASC NULLS FIRST], false, 0
           +- Exchange hashpartitioning(c#427560, 5), ENSURE_REQUIREMENTS, [plan_id=435931]
              +- SortAggregate(key=[c#427560], functions=[partial_count(1)], output=[c#427560, count#427567L])
                 +- Sort [c#427560 ASC NULLS FIRST], false, 0
                    +- LocalTableScan [c#427560]
     
     == Exception ==
     org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 393.0 failed 1 times, most recent failure: Lost task 1.0 in stage 393.0 (TID 394) (localhost executor driver): java.lang.StringIndexOutOfBoundsException: Index 3 out of bounds for length 3
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
     	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
     	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
     	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
     	at java.base/java.lang.String.checkIndex(String.java:4832)
     	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
     	at java.base/java.lang.String.charAt(String.java:1555)
     	at com.ibm.icu.impl.coll.UTF16CollationIterator.handleNextCE32(UTF16CollationIterator.java:107)
     	at com.ibm.icu.impl.coll.CollationIterator.nextCE(CollationIterator.java:247)
     	at com.ibm.icu.impl.coll.CollationKeys.writeSortKeyUpToQuaternary(CollationKeys.java:374)
     	at com.ibm.icu.text.RuleBasedCollator.writeSortKey(RuleBasedCollator.java:1159)
     	at com.ibm.icu.text.RuleBasedCollator.getRawCollationKey(RuleBasedCollator.java:1146)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1071)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1064)
     	at org.apache.spark.sql.catalyst.util.CollationFactory$Collation.lambda$new$2(CollationFactory.java:104)
     	at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.apply(Unknown Source)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8$adapted(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$18(ShuffleExchangeExec.scala:401)
     	at scala.collection.Iterator$$anon$9.next(Iterator.scala:584)
     	at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:169)
     	at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:56)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:111)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:54)
     	at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:171)
     	at org.apache.spark.scheduler.Task.run(Task.scala:146)
     	at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$5(Executor.scala:632)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally(SparkErrorUtils.scala:64)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally$(SparkErrorUtils.scala:61)
     	at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:97)
     	at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:635)
     	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
     	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
     	at java.base/java.lang.Thread.run(Thread.java:1583)
   ```
   
   - macos-14: https://github.com/apache/spark/actions/runs/8194082205/job/22416483724
   
   ```
   - aggregates count respects collation *** FAILED ***
     Exception thrown while executing query:
     == Parsed Logical Plan ==
     CTE [t]
     :  +- 'SubqueryAlias t
     :     +- 'Project ['collate('col1, unicode_CI) AS c#427467]
     :        +- 'UnresolvedInlineTable [col1], [[aaa], [aaa]]
     +- 'Aggregate ['c], [unresolvedalias('COUNT(1)), 'c]
        +- 'UnresolvedRelation [t], [], false
     
     == Analyzed Logical Plan ==
     count(1): bigint, c: string COLLATE 'UNICODE_CI'
     WithCTE
     :- CTERelationDef 103, false
     :  +- SubqueryAlias t
     :     +- Project [collate(col1#427469, unicode_CI) AS c#427467]
     :        +- LocalRelation [col1#427469]
     +- Aggregate [c#427467], [count(1) AS count(1)#427470L, c#427467]
        +- SubqueryAlias t
           +- CTERelationRef 103, true, [c#427467], false
     
     == Optimized Logical Plan ==
     Aggregate [c#427467], [count(1) AS count(1)#427470L, c#427467]
     +- LocalRelation [c#427467]
     
     == Physical Plan ==
     AdaptiveSparkPlan isFinalPlan=false
     +- == Current Plan ==
        SortAggregate(key=[c#427467], functions=[count(1)], output=[count(1)#427470L, c#427467])
        +- Sort [c#427467 ASC NULLS FIRST], false, 0
           +- ShuffleQueryStage 0
              +- Exchange hashpartitioning(c#427467, 5), ENSURE_REQUIREMENTS, [plan_id=435580]
                 +- SortAggregate(key=[c#427467], functions=[partial_count(1)], output=[c#427467, count#427474L])
                    +- *(1) Sort [c#427467 ASC NULLS FIRST], false, 0
                       +- *(1) LocalTableScan [c#427467]
     +- == Initial Plan ==
        SortAggregate(key=[c#427467], functions=[count(1)], output=[count(1)#427470L, c#427467])
        +- Sort [c#427467 ASC NULLS FIRST], false, 0
           +- Exchange hashpartitioning(c#427467, 5), ENSURE_REQUIREMENTS, [plan_id=435514]
              +- SortAggregate(key=[c#427467], functions=[partial_count(1)], output=[c#427467, count#427474L])
                 +- Sort [c#427467 ASC NULLS FIRST], false, 0
                    +- LocalTableScan [c#427467]
     
     == Exception ==
     org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 387.0 failed 1 times, most recent failure: Lost task 0.0 in stage 387.0 (TID 387) (localhost executor driver): java.lang.StringIndexOutOfBoundsException: Index 4 out of bounds for length 3
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
     	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
     	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
     	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
     	at java.base/java.lang.String.checkIndex(String.java:4832)
     	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
     	at java.base/java.lang.String.charAt(String.java:1555)
     	at com.ibm.icu.impl.coll.UTF16CollationIterator.handleNextCE32(UTF16CollationIterator.java:107)
     	at com.ibm.icu.impl.coll.CollationIterator.nextCE(CollationIterator.java:247)
     	at com.ibm.icu.impl.coll.CollationKeys.writeSortKeyUpToQuaternary(CollationKeys.java:374)
     	at com.ibm.icu.text.RuleBasedCollator.writeSortKey(RuleBasedCollator.java:1159)
     	at com.ibm.icu.text.RuleBasedCollator.getRawCollationKey(RuleBasedCollator.java:1146)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1071)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1064)
     	at org.apache.spark.sql.catalyst.util.CollationFactory$Collation.lambda$new$2(CollationFactory.java:104)
     	at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.apply(Unknown Source)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8$adapted(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$18(ShuffleExchangeExec.scala:401)
     	at scala.collection.Iterator$$anon$9.next(Iterator.scala:584)
     	at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:169)
     	at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:56)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:111)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:54)
     	at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:171)
     	at org.apache.spark.scheduler.Task.run(Task.scala:146)
     	at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$5(Executor.scala:632)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally(SparkErrorUtils.scala:64)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally$(SparkErrorUtils.scala:61)
     	at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:97)
     	at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:635)
     	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
     	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
     	at java.base/java.lang.Thread.run(Thread.java:1583)
   ```
   
   also cc @HyukjinKwon because I noticed that you are paying attention to the tests of maven + Java 21 on macos-14



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1504680132


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +186,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {

Review Comment:
   maybe we should also test struct columns with collations inside



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507924464


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashMapGenerator.scala:
##########
@@ -173,7 +173,10 @@ abstract class HashMapGenerator(
             ${hashBytes(bytes)}
           """
         }
-      case _: StringType => hashBytes(s"$input.getBytes()")
+      case StringType => hashBytes(s"$input.getBytes()")
+      case st: StringType =>
+        hashLong(s"CollationFactory.fetchCollation(${st.collationId})" +

Review Comment:
   I see. I feel the code can be more readable if we do
   ```
   case st: StringType =>
     if (st.isDefaultCollation) {
   
     } else {
   
     }
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1505326604


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala:
##########
@@ -405,11 +405,21 @@ abstract class HashExpression[E] extends Expression {
     s"$result = $hasherClassName.hashInt($input.months, $microsecondsHash);"
   }
 
-  protected def genHashString(input: String, result: String): String = {
-    val baseObject = s"$input.getBaseObject()"
-    val baseOffset = s"$input.getBaseOffset()"
-    val numBytes = s"$input.numBytes()"
-    s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+  protected def genHashString(
+     ctx: CodegenContext, input: String, result: String, stringType: StringType): String = {
+    if (stringType.isDefaultCollation) {
+      val baseObject = s"$input.getBaseObject()"
+      val baseOffset = s"$input.getBaseOffset()"
+      val numBytes = s"$input.numBytes()"
+      s"$result = $hasherClassName.hashUnsafeBytes($baseObject, $baseOffset, $numBytes, $result);"
+    } else {
+      val stringHash = ctx.freshName("stringHash")
+      s"""
+        long $stringHash = CollationFactory.fetchCollation(${stringType.collationId})

Review Comment:
   same question here.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507732131


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashMapGenerator.scala:
##########
@@ -173,7 +173,10 @@ abstract class HashMapGenerator(
             ${hashBytes(bytes)}
           """
         }
-      case _: StringType => hashBytes(s"$input.getBytes()")
+      case StringType => hashBytes(s"$input.getBytes()")
+      case st: StringType =>
+        hashLong(s"CollationFactory.fetchCollation(${st.collationId})" +

Review Comment:
   It is. The thing is that we are still going to use HashAgg for binary collations (e.g. UNICODE_CI which is also covered by tests). We need to do proper hashing in this case.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506214267


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala:
##########
@@ -353,9 +353,20 @@ object MergeScalarSubqueries extends Rule[LogicalPlan] {
         case a: AggregateExpression => a
       })
     }
+    val groupByExpressionSeq = Seq(newPlan, cachedPlan).map { plan =>
+      plan.groupingExpressions.flatMap(_.collect {

Review Comment:
   Ups, my bad. Good catch! Let me see if I can add a test that verifies this logic.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506221249


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashMapGenerator.scala:
##########
@@ -173,7 +173,10 @@ abstract class HashMapGenerator(
             ${hashBytes(bytes)}
           """
         }
-      case _: StringType => hashBytes(s"$input.getBytes()")
+      case StringType => hashBytes(s"$input.getBytes()")
+      case st: StringType =>
+        hashLong(s"CollationFactory.fetchCollation(${st.collationId})" +

Review Comment:
   is this needed by this PR?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507736504


##########
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/UnsafeRow.java:
##########
@@ -95,6 +96,20 @@ public static boolean isMutable(DataType dt) {
       pdt instanceof PhysicalCalendarIntervalType;
   }
 
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  public static boolean isBinaryStable(DataType dt) {
+    if (dt instanceof StringType st) {

Review Comment:
   done. I also moved method to `UnsafeRowUtils`. It feels a bit more natural to do this kind of checks in scala.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517309692


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   cc @dongjoon-hyun too



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506259546


##########
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/UnsafeRow.java:
##########
@@ -95,6 +96,20 @@ public static boolean isMutable(DataType dt) {
       pdt instanceof PhysicalCalendarIntervalType;
   }
 
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  public static boolean isBinaryStable(DataType dt) {
+    if (dt instanceof StringType st) {

Review Comment:
   oh, I see. Yes, we need that as well.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1509062803


##########
sql/api/src/main/scala/org/apache/spark/sql/types/StringType.scala:
##########
@@ -33,6 +33,14 @@ class StringType private(val collationId: Int) extends AtomicType with Serializa
    */
   def isDefaultCollation: Boolean = collationId == StringType.DEFAULT_COLLATION_ID
 
+  /**
+   * Binary collation implies that strings are considered equal only if they are
+   * byte for byte equal. E.g. all accent or case-insensitive collations are considered non-binary.
+   * If this field is true, byte level operations can be used against this datatype (e.g. for
+   * equality and hashing).
+   */
+  def isBinaryCollation: Boolean = CollationFactory.fetchCollation(collationId).isBinaryCollation

Review Comment:
   Binary collation means that you can do hash and equal (and contains) on binary representation.
   Default collation means that you can do hash, equal and *sort* on binary representation.
   
   Example of binary collation is UNICODE at identical ICU level. You need to consult ICU tables to do ordering but hashing/eq should work on byte level.
   
   I dislike naming `default collation` and I think that we should switch to something more descriptive for UCS_BASIC. After joins, my next PR will be to:
   1) Rename `UCS_BASIC` -> `UTF8_BINARY` and `UCS_BASIC_LCASE` to `UTF_BINARY_LCASE`.
   2) Figure out default collation story. E.g. it should probably be something like "isBinarySortable" or something like that.
   
   But this PR is about aggregates so let's leave this for the next PR :)



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517982724


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   @stefankandic picked up fixing the issue. This is a race condition in ICU library (problem on spark side where we don't properly setup the library).



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507920309


##########
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/UnsafeRow.java:
##########
@@ -30,6 +30,7 @@
 import org.apache.spark.SparkUnsupportedOperationException;
 import org.apache.spark.sql.catalyst.InternalRow;
 import org.apache.spark.sql.catalyst.types.*;
+import org.apache.spark.sql.catalyst.util.CollationFactory;

Review Comment:
   unnecessary change



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506202232


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +186,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {

Review Comment:
   Added test case to golden file. Please take a look.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506223036


##########
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/UnsafeRow.java:
##########
@@ -95,6 +96,20 @@ public static boolean isMutable(DataType dt) {
       pdt instanceof PhysicalCalendarIntervalType;
   }
 
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  public static boolean isBinaryStable(DataType dt) {
+    if (dt instanceof StringType st) {

Review Comment:
   shall we check nested field/array elements recursively?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1505328033


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala:
##########
@@ -353,9 +353,20 @@ object MergeScalarSubqueries extends Rule[LogicalPlan] {
         case a: AggregateExpression => a
       })
     }
+    val groupByExpressionSeq = Seq(newPlan, cachedPlan).map { plan =>
+      plan.groupingExpressions.flatMap(_.collect {

Review Comment:
   I think it should be just `plan.groupingExpressions`, e.g. `GROUO BY func(a)` can be supported by hash aggregate if `func(a)` returns normal string, no matter if `a` is string with collation or not.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507922548


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -197,4 +197,21 @@ object UnsafeRowUtils {
       s"rowSizeInBytes: ${row.getSizeInBytes}\nfieldStatus:\n" +
       fieldStatusArr.mkString("\n")
   }
+
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  def isBinaryStable(dataType: DataType): Boolean = dataType match {
+    case st: StringType => CollationFactory.fetchCollation(st.collationId).isBinaryCollation
+    case _: AtomicType => true
+    case _: ArrayType => isBinaryStable(dataType.asInstanceOf[ArrayType].elementType)
+    case _: MapType => isBinaryStable(dataType.asInstanceOf[MapType].keyType) &&
+      isBinaryStable(dataType.asInstanceOf[MapType].valueType)
+    case _: StructType =>

Review Comment:
   ditto, `case StructType(fields) => ...`



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "LuciferYang (via GitHub)" <gi...@apache.org>.
LuciferYang commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1517243024


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   This test case failed in the daily test of Maven + Java 21, both on Linux and MacOS. @dbatomic Do you have time to investigate the cause of this failure?
   
   - linux: https://github.com/apache/spark/actions/runs/8189363924/job/22416511124
   
   ![image](https://github.com/apache/spark/assets/1475305/2b39b2d2-a4b2-45ec-8bd9-42c36f22a0b9)
   
   
   - macos-14: https://github.com/apache/spark/actions/runs/8194082205/job/22416483724
   
   ```
   - aggregates count respects collation *** FAILED ***
     Exception thrown while executing query:
     == Parsed Logical Plan ==
     CTE [t]
     :  +- 'SubqueryAlias t
     :     +- 'Project ['collate('col1, unicode_CI) AS c#427467]
     :        +- 'UnresolvedInlineTable [col1], [[aaa], [aaa]]
     +- 'Aggregate ['c], [unresolvedalias('COUNT(1)), 'c]
        +- 'UnresolvedRelation [t], [], false
     
     == Analyzed Logical Plan ==
     count(1): bigint, c: string COLLATE 'UNICODE_CI'
     WithCTE
     :- CTERelationDef 103, false
     :  +- SubqueryAlias t
     :     +- Project [collate(col1#427469, unicode_CI) AS c#427467]
     :        +- LocalRelation [col1#427469]
     +- Aggregate [c#427467], [count(1) AS count(1)#427470L, c#427467]
        +- SubqueryAlias t
           +- CTERelationRef 103, true, [c#427467], false
     
     == Optimized Logical Plan ==
     Aggregate [c#427467], [count(1) AS count(1)#427470L, c#427467]
     +- LocalRelation [c#427467]
     
     == Physical Plan ==
     AdaptiveSparkPlan isFinalPlan=false
     +- == Current Plan ==
        SortAggregate(key=[c#427467], functions=[count(1)], output=[count(1)#427470L, c#427467])
        +- Sort [c#427467 ASC NULLS FIRST], false, 0
           +- ShuffleQueryStage 0
              +- Exchange hashpartitioning(c#427467, 5), ENSURE_REQUIREMENTS, [plan_id=435580]
                 +- SortAggregate(key=[c#427467], functions=[partial_count(1)], output=[c#427467, count#427474L])
                    +- *(1) Sort [c#427467 ASC NULLS FIRST], false, 0
                       +- *(1) LocalTableScan [c#427467]
     +- == Initial Plan ==
        SortAggregate(key=[c#427467], functions=[count(1)], output=[count(1)#427470L, c#427467])
        +- Sort [c#427467 ASC NULLS FIRST], false, 0
           +- Exchange hashpartitioning(c#427467, 5), ENSURE_REQUIREMENTS, [plan_id=435514]
              +- SortAggregate(key=[c#427467], functions=[partial_count(1)], output=[c#427467, count#427474L])
                 +- Sort [c#427467 ASC NULLS FIRST], false, 0
                    +- LocalTableScan [c#427467]
     
     == Exception ==
     org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 387.0 failed 1 times, most recent failure: Lost task 0.0 in stage 387.0 (TID 387) (localhost executor driver): java.lang.StringIndexOutOfBoundsException: Index 4 out of bounds for length 3
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
     	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
     	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
     	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
     	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
     	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
     	at java.base/java.lang.String.checkIndex(String.java:4832)
     	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
     	at java.base/java.lang.String.charAt(String.java:1555)
     	at com.ibm.icu.impl.coll.UTF16CollationIterator.handleNextCE32(UTF16CollationIterator.java:107)
     	at com.ibm.icu.impl.coll.CollationIterator.nextCE(CollationIterator.java:247)
     	at com.ibm.icu.impl.coll.CollationKeys.writeSortKeyUpToQuaternary(CollationKeys.java:374)
     	at com.ibm.icu.text.RuleBasedCollator.writeSortKey(RuleBasedCollator.java:1159)
     	at com.ibm.icu.text.RuleBasedCollator.getRawCollationKey(RuleBasedCollator.java:1146)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1071)
     	at com.ibm.icu.text.RuleBasedCollator.getCollationKey(RuleBasedCollator.java:1064)
     	at org.apache.spark.sql.catalyst.util.CollationFactory$Collation.lambda$new$2(CollationFactory.java:104)
     	at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.apply(Unknown Source)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$8$adapted(ShuffleExchangeExec.scala:330)
     	at org.apache.spark.sql.execution.exchange.ShuffleExchangeExec$.$anonfun$prepareShuffleDependency$18(ShuffleExchangeExec.scala:401)
     	at scala.collection.Iterator$$anon$9.next(Iterator.scala:584)
     	at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:169)
     	at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:56)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:111)
     	at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:54)
     	at org.apache.spark.TaskContext.runTaskWithListeners(TaskContext.scala:171)
     	at org.apache.spark.scheduler.Task.run(Task.scala:146)
     	at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$5(Executor.scala:632)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally(SparkErrorUtils.scala:64)
     	at org.apache.spark.util.SparkErrorUtils.tryWithSafeFinally$(SparkErrorUtils.scala:61)
     	at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:97)
     	at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:635)
     	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
     	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
     	at java.base/java.lang.Thread.run(Thread.java:1583)
   ```
   
   also cc @HyukjinKwon because I noticed that you are paying attention to the tests of maven + Java 21 on macos-14



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1518057279


##########
sql/core/src/test/scala/org/apache/spark/sql/CollationSuite.scala:
##########
@@ -183,6 +185,57 @@ class CollationSuite extends DatasourceV2SQLBase {
     }
   }
 
+  test("aggregates count respects collation") {
+    Seq(
+      ("ucs_basic", Seq("AAA", "aaa"), Seq(Row(1, "AAA"), Row(1, "aaa"))),

Review Comment:
   https://github.com/apache/spark/pull/45436 should fix the issue



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1508848081


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashMapGenerator.scala:
##########
@@ -173,7 +173,10 @@ abstract class HashMapGenerator(
             ${hashBytes(bytes)}
           """
         }
-      case _: StringType => hashBytes(s"$input.getBytes()")
+      case StringType => hashBytes(s"$input.getBytes()")
+      case st: StringType =>
+        hashLong(s"CollationFactory.fetchCollation(${st.collationId})" +

Review Comment:
   I did some refactoring here. Please take a look. I kept pattern matching but I think it looks a bit nicer now.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #45290:
URL: https://github.com/apache/spark/pull/45290#issuecomment-1975551130

   thanks, merging to master!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1506258459


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/MergeScalarSubqueries.scala:
##########
@@ -353,9 +353,20 @@ object MergeScalarSubqueries extends Rule[LogicalPlan] {
         case a: AggregateExpression => a
       })
     }
+    val groupByExpressionSeq = Seq(newPlan, cachedPlan).map { plan =>
+      plan.groupingExpressions.flatMap(_.collect {

Review Comment:
   Added test please take a look.
   
   I also added string with collation to `dsl/package` since that was a natural way to enable the optimizer tests and i guess that we need this anyhow, although this is not strictly related to aggs.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-46834][SQL][Collations] Support for aggregates [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45290:
URL: https://github.com/apache/spark/pull/45290#discussion_r1507922150


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -197,4 +197,21 @@ object UnsafeRowUtils {
       s"rowSizeInBytes: ${row.getSizeInBytes}\nfieldStatus:\n" +
       fieldStatusArr.mkString("\n")
   }
+
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  def isBinaryStable(dataType: DataType): Boolean = dataType match {
+    case st: StringType => CollationFactory.fetchCollation(st.collationId).isBinaryCollation
+    case _: AtomicType => true
+    case _: ArrayType => isBinaryStable(dataType.asInstanceOf[ArrayType].elementType)

Review Comment:
   nit: `case ArrayType(et) => isBinaryStable(et)`



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/UnsafeRowUtils.scala:
##########
@@ -197,4 +197,21 @@ object UnsafeRowUtils {
       s"rowSizeInBytes: ${row.getSizeInBytes}\nfieldStatus:\n" +
       fieldStatusArr.mkString("\n")
   }
+
+  /**
+   * True if comparisons, equality and hashing can be done purely on binary representation of
+   * Unsafe row. i.e. binary(e1) = binary(e2) <=> e1 = e2.
+   * e.g. this is not true for non-binary collations (any case/accent insensitive collation
+   * can lead to rows being semantically equal even though their binary representations differ).
+   */
+  def isBinaryStable(dataType: DataType): Boolean = dataType match {
+    case st: StringType => CollationFactory.fetchCollation(st.collationId).isBinaryCollation
+    case _: AtomicType => true
+    case _: ArrayType => isBinaryStable(dataType.asInstanceOf[ArrayType].elementType)
+    case _: MapType => isBinaryStable(dataType.asInstanceOf[MapType].keyType) &&

Review Comment:
   ditto



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org