forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCometExecSuite.scala
More file actions
2259 lines (2008 loc) · 82.6 KB
/
CometExecSuite.scala
File metadata and controls
2259 lines (2008 loc) · 82.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.comet.exec
import java.sql.Date
import java.time.{Duration, Period}
import scala.util.Random
import org.scalactic.source.Position
import org.scalatest.Tag
import org.apache.hadoop.fs.Path
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.{FunctionIdentifier, TableIdentifier}
import org.apache.spark.sql.catalyst.catalog.{BucketSpec, CatalogStatistics, CatalogTable}
import org.apache.spark.sql.catalyst.expressions.{Expression, ExpressionInfo, Hex}
import org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateMode, BloomFilterAggregate}
import org.apache.spark.sql.comet._
import org.apache.spark.sql.comet.execution.shuffle.{CometColumnarShuffle, CometShuffleExchangeExec}
import org.apache.spark.sql.execution.{CollectLimitExec, ProjectExec, SQLExecution, UnionExec}
import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanExec, BroadcastQueryStageExec}
import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
import org.apache.spark.sql.execution.exchange.{BroadcastExchangeExec, ReusedExchangeExec, ShuffleExchangeExec}
import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec, CartesianProductExec, SortMergeJoinExec}
import org.apache.spark.sql.execution.reuse.ReuseExchangeAndSubquery
import org.apache.spark.sql.execution.window.WindowExec
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.SESSION_LOCAL_TIMEZONE
import org.apache.spark.unsafe.types.UTF8String
import org.apache.comet.{CometConf, ExtendedExplainInfo}
import org.apache.comet.CometSparkSessionExtensions.{isSpark35Plus, isSpark40Plus}
import org.apache.comet.testing.{DataGenOptions, ParquetGenerator}
class CometExecSuite extends CometTestBase {
import testImplicits._
override protected def test(testName: String, testTags: Tag*)(testFun: => Any)(implicit
pos: Position): Unit = {
super.test(testName, testTags: _*) {
withSQLConf(
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_NATIVE_SCAN_IMPL.key -> CometConf.SCAN_AUTO) {
testFun
}
}
}
test("TopK operator should return correct results on dictionary column with nulls") {
withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> "") {
withTable("test_data") {
val data = (0 to 8000)
.flatMap(_ => Seq((1, null, "A"), (2, "BBB", "B"), (3, "BBB", "B"), (4, "BBB", "B")))
val tableDF = spark.sparkContext
.parallelize(data, 3)
.toDF("c1", "c2", "c3")
tableDF
.coalesce(1)
.sortWithinPartitions("c1")
.writeTo("test_data")
.using("parquet")
.create()
val df = sql("SELECT * FROM test_data ORDER BY c1 LIMIT 3")
checkSparkAnswerAndOperator(df)
}
}
}
test("DPP fallback") {
withTempDir { path =>
// create test data
val factPath = s"${path.getAbsolutePath}/fact.parquet"
val dimPath = s"${path.getAbsolutePath}/dim.parquet"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
val one_day = 24 * 60 * 60000
val fact = Range(0, 100)
.map(i => (i, new java.sql.Date(System.currentTimeMillis() + i * one_day), i.toString))
.toDF("fact_id", "fact_date", "fact_str")
fact.write.partitionBy("fact_date").parquet(factPath)
val dim = Range(0, 10)
.map(i => (i, new java.sql.Date(System.currentTimeMillis() + i * one_day), i.toString))
.toDF("dim_id", "dim_date", "dim_str")
dim.write.parquet(dimPath)
}
// note that this test does not trigger DPP with v2 data source
Seq("parquet").foreach { v1List =>
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> v1List,
CometConf.COMET_DPP_FALLBACK_ENABLED.key -> "true") {
spark.read.parquet(factPath).createOrReplaceTempView("dpp_fact")
spark.read.parquet(dimPath).createOrReplaceTempView("dpp_dim")
val df =
spark.sql(
"select * from dpp_fact join dpp_dim on fact_date = dim_date where dim_id > 7")
val (_, cometPlan) = checkSparkAnswer(df)
val infos = new ExtendedExplainInfo().generateExtendedInfo(cometPlan)
assert(infos.contains("Dynamic Partition Pruning is not supported"))
withSQLConf(CometConf.COMET_EXPLAIN_VERBOSE_ENABLED.key -> "true") {
val extendedExplain = new ExtendedExplainInfo().generateExtendedInfo(cometPlan)
assert(extendedExplain.contains("Comet accelerated 33% of eligible operators"))
}
}
}
}
}
test("ShuffleQueryStageExec could be direct child node of CometBroadcastExchangeExec") {
withSQLConf(CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
val table = "src"
withTable(table) {
withView("lv_noalias") {
sql(s"CREATE TABLE $table (key INT, value STRING) USING PARQUET")
sql(s"INSERT INTO $table VALUES(238, 'val_238')")
sql(
"CREATE VIEW lv_noalias AS SELECT myTab.* FROM src " +
"LATERAL VIEW explode(map('key1', 100, 'key2', 200)) myTab LIMIT 2")
val df = sql("SELECT * FROM lv_noalias a JOIN lv_noalias b ON a.key=b.key");
checkSparkAnswer(df)
}
}
}
}
// repro for https://github.com/apache/datafusion-comet/issues/1251
test("subquery/exists-subquery/exists-orderby-limit.sql") {
withSQLConf(CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
val table = "src"
withTable(table) {
sql(s"CREATE TABLE $table (key INT, value STRING) USING PARQUET")
sql(s"INSERT INTO $table VALUES(238, 'val_238')")
// the subquery returns the distinct group by values
checkSparkAnswerAndOperator(s"""SELECT * FROM $table
|WHERE EXISTS (SELECT MAX(key)
|FROM $table
|GROUP BY value
|LIMIT 1
|OFFSET 2)""".stripMargin)
checkSparkAnswerAndOperator(s"""SELECT * FROM $table
|WHERE NOT EXISTS (SELECT MAX(key)
|FROM $table
|GROUP BY value
|LIMIT 1
|OFFSET 2)""".stripMargin)
}
}
}
test("Sort on single struct should fallback to Spark") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false",
CometConf.COMET_EXEC_ENABLED.key -> "true",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
val data1 =
Seq(Tuple1(null), Tuple1((1, "a")), Tuple1((2, null)), Tuple1((3, "b")), Tuple1(null))
withParquetFile(data1) { file =>
readParquetFile(file) { df =>
val sort = df.sort("_1")
checkSparkAnswer(sort)
}
}
val data2 =
Seq(
Tuple2(null, 1),
Tuple2((1, "a"), 2),
Tuple2((2, null), 3),
Tuple2((3, "b"), 5),
Tuple2(null, 6))
withParquetFile(data2) { file =>
readParquetFile(file) { df =>
val sort = df.sort("_1")
checkSparkAnswer(sort)
}
}
}
}
test("Sort on array of boolean") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false",
CometConf.COMET_EXEC_ENABLED.key -> "true",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW test_list AS SELECT * FROM VALUES
| (array(true)),
| (array(false)),
| (array(false)),
| (array(false)) AS test(arr)
|""".stripMargin)
val df = sql("""
SELECT * FROM test_list ORDER BY arr
|""".stripMargin)
val sort = stripAQEPlan(df.queryExecution.executedPlan).collect { case s: CometSortExec =>
s
}.headOption
assert(sort.isDefined)
}
}
test("Sort on TimestampNTZType") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false",
CometConf.COMET_EXEC_ENABLED.key -> "true",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW test_list AS SELECT * FROM VALUES
| (TIMESTAMP_NTZ'2025-08-29 00:00:00'),
| (TIMESTAMP_NTZ'2023-07-07 00:00:00'),
| (convert_timezone('Asia/Kathmandu', 'UTC', TIMESTAMP_NTZ'2023-07-07 00:00:00')),
| (convert_timezone('America/Los_Angeles', 'UTC', TIMESTAMP_NTZ'2023-07-07 00:00:00')),
| (TIMESTAMP_NTZ'1969-12-31 00:00:00') AS test(ts_ntz)
|""".stripMargin)
val df = sql("""
SELECT * FROM test_list ORDER BY ts_ntz
|""".stripMargin)
checkSparkAnswer(df)
val sort = stripAQEPlan(df.queryExecution.executedPlan).collect { case s: CometSortExec =>
s
}.headOption
assert(sort.isDefined)
}
}
test("Sort on map w/ TimestampNTZType values") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false",
CometConf.COMET_EXEC_ENABLED.key -> "true",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW test_map AS SELECT * FROM VALUES
| (map('a', TIMESTAMP_NTZ'2025-08-29 00:00:00')),
| (map('b', TIMESTAMP_NTZ'2023-07-07 00:00:00')),
| (map('c', convert_timezone('Asia/Kathmandu', 'UTC', TIMESTAMP_NTZ'2023-07-07 00:00:00'))),
| (map('d', convert_timezone('America/Los_Angeles', 'UTC', TIMESTAMP_NTZ'2023-07-07 00:00:00'))) AS test(map)
|""".stripMargin)
val df = sql("""
SELECT * FROM test_map ORDER BY map_values(map) DESC
|""".stripMargin)
checkSparkAnswer(df)
val sort = stripAQEPlan(df.queryExecution.executedPlan).collect { case s: CometSortExec =>
s
}.headOption
assert(sort.isDefined)
}
}
test("Sort on map w/ boolean values") {
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
SQLConf.PARQUET_VECTORIZED_READER_ENABLED.key -> "false",
CometConf.COMET_EXEC_ENABLED.key -> "true",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_EXEC_SORT_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW test_map AS SELECT * FROM VALUES
| (map('a', true)),
| (map('b', true)),
| (map('c', false)),
| (map('d', true)) AS test(map)
|""".stripMargin)
val df = sql("""
SELECT * FROM test_map ORDER BY map_values(map) DESC
|""".stripMargin)
val sort = stripAQEPlan(df.queryExecution.executedPlan).collect { case s: CometSortExec =>
s
}.headOption
assert(sort.isDefined)
}
}
test(
"fall back to Spark when the partition spec and order spec are not the same for window function") {
withTempView("test") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW test_agg AS SELECT * FROM VALUES
| (1, true), (1, false),
|(2, true), (3, false), (4, true) AS test(k, v)
|""".stripMargin)
val df = sql("""
SELECT k, v, every(v) OVER (PARTITION BY k ORDER BY v) FROM test_agg
|""".stripMargin)
checkSparkAnswer(df)
}
}
test("Native window operator should be CometUnaryExec") {
withTempView("testData") {
sql("""
|CREATE OR REPLACE TEMPORARY VIEW testData AS SELECT * FROM VALUES
|(null, 1L, 1.0D, date("2017-08-01"), timestamp_seconds(1501545600), "a"),
|(1, 1L, 1.0D, date("2017-08-01"), timestamp_seconds(1501545600), "a"),
|(1, 2L, 2.5D, date("2017-08-02"), timestamp_seconds(1502000000), "a"),
|(2, 2147483650L, 100.001D, date("2020-12-31"), timestamp_seconds(1609372800), "a"),
|(1, null, 1.0D, date("2017-08-01"), timestamp_seconds(1501545600), "b"),
|(2, 3L, 3.3D, date("2017-08-03"), timestamp_seconds(1503000000), "b"),
|(3, 2147483650L, 100.001D, date("2020-12-31"), timestamp_seconds(1609372800), "b"),
|(null, null, null, null, null, null),
|(3, 1L, 1.0D, date("2017-08-01"), timestamp_seconds(1501545600), null)
|AS testData(val, val_long, val_double, val_date, val_timestamp, cate)
|""".stripMargin)
val df1 = sql("""
|SELECT val, cate, count(val) OVER(PARTITION BY cate ORDER BY val ROWS CURRENT ROW)
|FROM testData ORDER BY cate, val
|""".stripMargin)
checkSparkAnswer(df1)
}
}
test("subquery execution under CometTakeOrderedAndProjectExec should not fail") {
assume(isSpark35Plus, "SPARK-45584 is fixed in Spark 3.5+")
withTable("t1") {
sql("""
|CREATE TABLE t1 USING PARQUET
|AS SELECT * FROM VALUES
|(1, "a"),
|(2, "a"),
|(3, "a") t(id, value)
|""".stripMargin)
val df = sql("""
|WITH t2 AS (
| SELECT * FROM t1 ORDER BY id
|)
|SELECT *, (SELECT COUNT(*) FROM t2) FROM t2 LIMIT 10
|""".stripMargin)
checkSparkAnswerAndOperator(df)
}
}
test("Window range frame with long boundary should not fail") {
val df =
Seq((1L, "1"), (1L, "1"), (2147483650L, "1"), (3L, "2"), (2L, "1"), (2147483650L, "2"))
.toDF("key", "value")
checkSparkAnswer(
df.select(
$"key",
count("key").over(
Window.partitionBy($"value").orderBy($"key").rangeBetween(0, 2147483648L))))
checkSparkAnswer(
df.select(
$"key",
count("key").over(
Window.partitionBy($"value").orderBy($"key").rangeBetween(-2147483649L, 0))))
}
test("Unsupported window expression should fall back to Spark") {
checkAnswer(
spark.sql("select sum(a) over () from values 1.0, 2.0, 3.0 T(a)"),
Row(6.0) :: Row(6.0) :: Row(6.0) :: Nil)
checkAnswer(
spark.sql("select avg(a) over () from values 1.0, 2.0, 3.0 T(a)"),
Row(2.0) :: Row(2.0) :: Row(2.0) :: Nil)
}
test("fix CometNativeExec.doCanonicalize for ReusedExchangeExec") {
withSQLConf(
CometConf.COMET_EXEC_BROADCAST_FORCE_ENABLED.key -> "true",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
withTable("td") {
testData
.withColumn("bucket", $"key" % 3)
.write
.mode(SaveMode.Overwrite)
.bucketBy(2, "bucket")
.format("parquet")
.saveAsTable("td")
val df = sql("""
|SELECT t1.key, t2.key, t3.key
|FROM td AS t1
|JOIN td AS t2 ON t2.key = t1.key
|JOIN td AS t3 ON t3.key = t2.key
|WHERE t1.bucket = 1 AND t2.bucket = 1 AND t3.bucket = 1
|""".stripMargin)
val reusedPlan = ReuseExchangeAndSubquery.apply(df.queryExecution.executedPlan)
val reusedExchanges = collect(reusedPlan) { case r: ReusedExchangeExec =>
r
}
assert(reusedExchanges.size == 1)
assert(reusedExchanges.head.child.isInstanceOf[CometBroadcastExchangeExec])
}
}
}
test("ReusedExchangeExec should work on CometBroadcastExchangeExec") {
withSQLConf(
CometConf.COMET_EXEC_BROADCAST_FORCE_ENABLED.key -> "true",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.USE_V1_SOURCE_LIST.key -> "") {
withTempPath { path =>
spark
.range(5)
.withColumn("p", $"id" % 2)
.write
.mode("overwrite")
.partitionBy("p")
.parquet(path.toString)
withTempView("t") {
spark.read.parquet(path.toString).createOrReplaceTempView("t")
val df = sql("""
|SELECT t1.id, t2.id, t3.id
|FROM t AS t1
|JOIN t AS t2 ON t2.id = t1.id
|JOIN t AS t3 ON t3.id = t2.id
|WHERE t1.p = 1 AND t2.p = 1 AND t3.p = 1
|""".stripMargin)
val reusedPlan = ReuseExchangeAndSubquery.apply(df.queryExecution.executedPlan)
val reusedExchanges = collect(reusedPlan) { case r: ReusedExchangeExec =>
r
}
assert(reusedExchanges.size == 1)
assert(reusedExchanges.head.child.isInstanceOf[CometBroadcastExchangeExec])
}
}
}
}
test("CometShuffleExchangeExec logical link should be correct") {
withTempView("v") {
spark.sparkContext
.parallelize((1 to 4).map(i => TestData(i, i.toString)), 2)
.toDF("c1", "c2")
.createOrReplaceTempView("v")
Seq("native", "jvm").foreach { columnarShuffleMode =>
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
CometConf.COMET_SHUFFLE_MODE.key -> columnarShuffleMode) {
val df = sql("SELECT * FROM v where c1 = 1 order by c1, c2")
val shuffle = find(df.queryExecution.executedPlan) {
case _: CometShuffleExchangeExec if columnarShuffleMode.equalsIgnoreCase("jvm") =>
true
case _: ShuffleExchangeExec if !columnarShuffleMode.equalsIgnoreCase("jvm") => true
case _ => false
}.get
assert(shuffle.logicalLink.isEmpty)
}
}
}
}
test("Ensure that the correct outputPartitioning of CometSort") {
withTable("test_data") {
val tableDF = spark.sparkContext
.parallelize(
(1 to 10).map { i =>
(if (i > 4) 5 else i, i.toString, Date.valueOf(s"${2020 + i}-$i-$i"))
},
3)
.toDF("id", "data", "day")
tableDF.write.saveAsTable("test_data")
val df = sql("SELECT * FROM test_data")
.repartition($"data")
.sortWithinPartitions($"id", $"data", $"day")
df.collect()
val sort = stripAQEPlan(df.queryExecution.executedPlan).collect { case s: CometSortExec =>
s
}.head
assert(sort.outputPartitioning == sort.child.outputPartitioning)
}
}
test("Repeated shuffle exchange don't fail") {
Seq("true", "false").foreach { aqeEnabled =>
withSQLConf(
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled,
SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_DISTRIBUTION.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
val df =
Seq(("a", 1, 1), ("a", 2, 2), ("b", 1, 3), ("b", 1, 4)).toDF("key1", "key2", "value")
val windowSpec = Window.partitionBy("key1", "key2").orderBy("value")
val windowed = df
// repartition by subset of window partitionBy keys which satisfies ClusteredDistribution
.repartition($"key1")
.select(lead($"key1", 1).over(windowSpec), lead($"value", 1).over(windowSpec))
checkSparkAnswer(windowed)
}
}
}
test("try_sum should return null if overflow happens before merging") {
val longDf = Seq(Long.MaxValue, Long.MaxValue, 2).toDF("v")
val yearMonthDf = Seq(Int.MaxValue, Int.MaxValue, 2)
.map(Period.ofMonths)
.toDF("v")
val dayTimeDf = Seq(106751991L, 106751991L, 2L)
.map(Duration.ofDays)
.toDF("v")
Seq(longDf, yearMonthDf, dayTimeDf).foreach { df =>
checkSparkAnswer(df.repartitionByRange(2, col("v")).selectExpr("try_sum(v)"))
}
}
test("Fix corrupted AggregateMode when transforming plan parameters") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "table") {
val df = sql("SELECT * FROM table").groupBy($"_1").agg(sum("_2"))
val agg = stripAQEPlan(df.queryExecution.executedPlan).collectFirst {
case s: CometHashAggregateExec => s
}.get
assert(agg.mode.isDefined && agg.mode.get.isInstanceOf[AggregateMode])
val newAgg = agg.cleanBlock().asInstanceOf[CometHashAggregateExec]
assert(newAgg.mode.isDefined && newAgg.mode.get.isInstanceOf[AggregateMode])
}
}
test("CometBroadcastExchangeExec") {
withSQLConf(CometConf.COMET_EXEC_BROADCAST_FORCE_ENABLED.key -> "true") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl_a") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl_b") {
val df = sql(
"SELECT tbl_a._1, tbl_b._2 FROM tbl_a JOIN tbl_b " +
"WHERE tbl_a._1 > tbl_a._2 LIMIT 2")
val nativeBroadcast = find(df.queryExecution.executedPlan) {
case _: CometBroadcastExchangeExec => true
case _ => false
}.get.asInstanceOf[CometBroadcastExchangeExec]
val numParts = nativeBroadcast.executeColumnar().getNumPartitions
val rows = nativeBroadcast.executeCollect().toSeq.sortBy(row => row.getInt(0))
val rowContents = rows.map(row => row.getInt(0))
val expected = (0 until numParts).flatMap(_ => (0 until 5).map(i => i + 1)).sorted
assert(rowContents === expected)
}
}
}
}
test("CometBroadcastExchangeExec: empty broadcast") {
withSQLConf(CometConf.COMET_EXEC_BROADCAST_FORCE_ENABLED.key -> "true") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl_a") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl_b") {
val df = sql(
"SELECT /*+ BROADCAST(a) */ *" +
" FROM (SELECT * FROM tbl_a WHERE _1 < 0) a JOIN tbl_b b" +
" ON a._1 = b._1")
val nativeBroadcast = find(df.queryExecution.executedPlan) {
case _: CometBroadcastExchangeExec => true
case _ => false
}.get.asInstanceOf[CometBroadcastExchangeExec]
val rows = nativeBroadcast.executeCollect()
assert(rows.isEmpty)
}
}
}
}
test("scalar subquery") {
val dataTypes =
Seq(
"BOOLEAN",
"BYTE",
"SHORT",
"INT",
"BIGINT",
"FLOAT",
"DOUBLE",
// "DATE": TODO: needs to address issue #1364 first
// "TIMESTAMP", TODO: needs to address issue #1364 first
"STRING",
"BINARY",
"DECIMAL(38, 10)")
dataTypes.map { subqueryType =>
withSQLConf(
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm",
CometConf.COMET_EXPR_ALLOW_INCOMPATIBLE.key -> "true") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl") {
var column1 = s"CAST(max(_1) AS $subqueryType)"
if (subqueryType == "BINARY") {
// arrow-rs doesn't support casting integer to binary yet.
// We added it to upstream but it's not released yet.
column1 = "CAST(CAST(max(_1) AS STRING) AS BINARY)"
}
val df1 = sql(s"SELECT (SELECT $column1 FROM tbl) AS a, _1, _2 FROM tbl")
checkSparkAnswerAndOperator(df1)
var column2 = s"CAST(_1 AS $subqueryType)"
if (subqueryType == "BINARY") {
// arrow-rs doesn't support casting integer to binary yet.
// We added it to upstream but it's not released yet.
column2 = "CAST(CAST(_1 AS STRING) AS BINARY)"
}
val df2 = sql(s"SELECT _1, _2 FROM tbl WHERE $column2 > (SELECT $column1 FROM tbl)")
checkSparkAnswerAndOperator(df2)
// Non-correlated exists subquery will be rewritten to scalar subquery
val df3 = sql(
"SELECT * FROM tbl WHERE EXISTS " +
s"(SELECT $column2 FROM tbl WHERE _1 > 1)")
checkSparkAnswerAndOperator(df3)
// Null value
column1 = s"CAST(NULL AS $subqueryType)"
if (subqueryType == "BINARY") {
column1 = "CAST(CAST(NULL AS STRING) AS BINARY)"
}
val df4 = sql(s"SELECT (SELECT $column1 FROM tbl LIMIT 1) AS a, _1, _2 FROM tbl")
checkSparkAnswerAndOperator(df4)
}
}
}
}
test("Comet native metrics: scan") {
withSQLConf(
CometConf.COMET_EXEC_ENABLED.key -> "true",
// TODO: update this test to work with native_iceberg_compat/auto,
// scan is set to native_comet for now as a workaround
// https://github.com/apache/datafusion-comet/issues/1882
CometConf.COMET_NATIVE_SCAN_IMPL.key -> CometConf.SCAN_NATIVE_COMET) {
withTempDir { dir =>
val path = new Path(dir.toURI.toString, "native-scan.parquet")
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled = true, 10000)
withParquetTable(path.toString, "tbl") {
val df = sql("SELECT * FROM tbl WHERE _2 > _3")
df.collect()
find(df.queryExecution.executedPlan)(s =>
s.isInstanceOf[CometScanExec] || s.isInstanceOf[CometNativeScanExec])
.foreach(scan => {
val metrics = scan.metrics
scan match {
case _: CometScanExec => {
assert(metrics.contains("scanTime"))
assert(metrics.contains("cast_time"))
assert(metrics("scanTime").value > 0)
assert(metrics("cast_time").value > 0)
}
case _: CometNativeScanExec => {
assert(metrics.contains("time_elapsed_scanning_total"))
assert(metrics.contains("bytes_scanned"))
assert(metrics.contains("output_rows"))
assert(metrics.contains("time_elapsed_opening"))
assert(metrics.contains("time_elapsed_processing"))
assert(metrics.contains("time_elapsed_scanning_until_data"))
assert(metrics("time_elapsed_scanning_total").value > 0)
assert(metrics("bytes_scanned").value > 0)
assert(metrics("output_rows").value == 0)
assert(metrics("time_elapsed_opening").value > 0)
assert(metrics("time_elapsed_processing").value > 0)
assert(metrics("time_elapsed_scanning_until_data").value > 0)
}
}
})
}
}
}
}
test("Comet native metrics: project and filter") {
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "true") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl") {
val df = sql("SELECT _1 + 1, _2 + 2 FROM tbl WHERE _1 > 3")
df.collect()
var metrics = find(df.queryExecution.executedPlan) {
case _: CometProjectExec => true
case _ => false
}.map(_.metrics).get
assert(metrics.contains("output_rows"))
assert(metrics("output_rows").value == 1L)
metrics = find(df.queryExecution.executedPlan) {
case _: CometFilterExec => true
case _ => false
}.map(_.metrics).get
assert(metrics.contains("output_rows"))
assert(metrics("output_rows").value == 1L)
}
}
}
test("Comet native metrics: SortMergeJoin") {
withSQLConf(
CometConf.COMET_EXEC_ENABLED.key -> "true",
"spark.sql.adaptive.autoBroadcastJoinThreshold" -> "-1",
"spark.sql.autoBroadcastJoinThreshold" -> "-1",
"spark.sql.join.preferSortMergeJoin" -> "true") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl1") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "tbl2") {
val df = sql("SELECT * FROM tbl1 INNER JOIN tbl2 ON tbl1._1 = tbl2._1")
df.collect()
val metrics = find(df.queryExecution.executedPlan) {
case _: CometSortMergeJoinExec => true
case _ => false
}.map(_.metrics).get
assert(metrics.contains("input_batches"))
assert(metrics("input_batches").value == 2L)
assert(metrics.contains("input_rows"))
assert(metrics("input_rows").value == 10L)
assert(metrics.contains("output_batches"))
assert(metrics("output_batches").value == 1L)
assert(metrics.contains("output_rows"))
assert(metrics("output_rows").value == 5L)
assert(metrics.contains("peak_mem_used"))
assert(metrics("peak_mem_used").value > 1L)
assert(metrics.contains("join_time"))
assert(metrics("join_time").value > 1L)
assert(metrics.contains("spill_count"))
assert(metrics("spill_count").value == 0)
}
}
}
}
test("Comet native metrics: HashJoin") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "t1") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "t2") {
val df = sql("SELECT /*+ SHUFFLE_HASH(t1) */ * FROM t1 INNER JOIN t2 ON t1._1 = t2._1")
df.collect()
val metrics = find(df.queryExecution.executedPlan) {
case _: CometHashJoinExec => true
case _ => false
}.map(_.metrics).get
assert(metrics.contains("build_time"))
assert(metrics("build_time").value > 1L)
assert(metrics.contains("build_input_batches"))
assert(metrics("build_input_batches").value == 5L)
assert(metrics.contains("build_mem_used"))
assert(metrics("build_mem_used").value > 1L)
assert(metrics.contains("build_input_rows"))
assert(metrics("build_input_rows").value == 5L)
assert(metrics.contains("input_batches"))
assert(metrics("input_batches").value == 5L)
assert(metrics.contains("input_rows"))
assert(metrics("input_rows").value == 5L)
assert(metrics.contains("output_batches"))
assert(metrics("output_batches").value == 5L)
assert(metrics.contains("output_rows"))
assert(metrics("output_rows").value == 5L)
assert(metrics.contains("join_time"))
assert(metrics("join_time").value > 1L)
}
}
}
test("Comet native metrics: BroadcastHashJoin") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "t1") {
withParquetTable((0 until 5).map(i => (i, i + 1)), "t2") {
val df = sql("SELECT /*+ BROADCAST(t1) */ * FROM t1 INNER JOIN t2 ON t1._1 = t2._1")
df.collect()
val metrics = find(df.queryExecution.executedPlan) {
case _: CometBroadcastHashJoinExec => true
case _ => false
}.map(_.metrics).get
assert(metrics.contains("build_time"))
assert(metrics("build_time").value > 1L)
assert(metrics.contains("build_input_batches"))
assert(metrics("build_input_batches").value == 25L)
assert(metrics.contains("build_mem_used"))
assert(metrics("build_mem_used").value > 1L)
assert(metrics.contains("build_input_rows"))
assert(metrics("build_input_rows").value == 25L)
assert(metrics.contains("input_batches"))
assert(metrics("input_batches").value == 5L)
assert(metrics.contains("input_rows"))
assert(metrics("input_rows").value == 5L)
assert(metrics.contains("output_batches"))
assert(metrics("output_batches").value == 5L)
assert(metrics.contains("output_rows"))
assert(metrics("output_rows").value == 5L)
assert(metrics.contains("join_time"))
assert(metrics("join_time").value > 1L)
}
}
}
test(
"fix: ReusedExchangeExec + CometShuffleExchangeExec under QueryStageExec " +
"should be CometRoot") {
val tableName = "table1"
val dim = "dim"
withSQLConf(
SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true",
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "jvm") {
withTable(tableName, dim) {
sql(
s"CREATE TABLE $tableName (id BIGINT, price FLOAT, date DATE, ts TIMESTAMP) USING parquet " +
"PARTITIONED BY (id)")
sql(s"CREATE TABLE $dim (id BIGINT, date DATE) USING parquet")
spark
.range(1, 100)
.withColumn("date", date_add(expr("DATE '1970-01-01'"), expr("CAST(id % 4 AS INT)")))
.withColumn("ts", expr("TO_TIMESTAMP(date)"))
.withColumn("price", expr("CAST(id AS FLOAT)"))
.select("id", "price", "date", "ts")
.coalesce(1)
.write
.mode(SaveMode.Append)
.partitionBy("id")
.saveAsTable(tableName)
spark
.range(1, 10)
.withColumn("date", expr("DATE '1970-01-02'"))
.select("id", "date")
.coalesce(1)
.write
.mode(SaveMode.Append)
.saveAsTable(dim)
val query =
s"""
|SELECT $tableName.id, sum(price) as sum_price
|FROM $tableName, $dim
|WHERE $tableName.id = $dim.id AND $tableName.date = $dim.date
|GROUP BY $tableName.id HAVING sum(price) > (
| SELECT sum(price) * 0.0001 FROM $tableName, $dim WHERE $tableName.id = $dim.id AND $tableName.date = $dim.date
| )
|ORDER BY sum_price
|""".stripMargin
val df = sql(query)
checkSparkAnswerAndOperator(df)
val exchanges = stripAQEPlan(df.queryExecution.executedPlan).collect {
case s: CometShuffleExchangeExec if s.shuffleType == CometColumnarShuffle =>
s
}
assert(exchanges.length == 4)
}
}
}
test("Comet Shuffled Join should be optimized to CometBroadcastHashJoin by AQE") {
withSQLConf(
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10485760",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "native") {
withParquetTable((0 until 100).map(i => (i, i + 1)), "tbl_a") {
withParquetTable((0 until 100).map(i => (i, i + 2)), "tbl_b") {
withParquetTable((0 until 100).map(i => (i, i + 3)), "tbl_c") {
val df = sql("""SELECT /*+ BROADCAST(c) */ a1, sum_b2, c._2 FROM (
| SELECT a._1 a1, SUM(b._2) sum_b2 FROM tbl_a a
| JOIN tbl_b b ON a._1 = b._1
| GROUP BY a._1) t
|JOIN tbl_c c ON t.a1 = c._1
|""".stripMargin)
checkSparkAnswerAndOperator(df)
// Before AQE: 1 broadcast join
var broadcastHashJoinExec = stripAQEPlan(df.queryExecution.executedPlan).collect {
case s: CometBroadcastHashJoinExec => s
}
assert(broadcastHashJoinExec.length == 1)
// After AQE: shuffled join optimized to broadcast join
df.collect()
broadcastHashJoinExec = stripAQEPlan(df.queryExecution.executedPlan).collect {
case s: CometBroadcastHashJoinExec => s
}
assert(broadcastHashJoinExec.length == 2)
}
}
}
}
}
test("CometBroadcastExchange could be converted to rows using CometColumnarToRow") {
withSQLConf(
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "10485760",
CometConf.COMET_EXEC_SHUFFLE_ENABLED.key -> "true",
CometConf.COMET_SHUFFLE_MODE.key -> "auto") {
withParquetTable((0 until 100).map(i => (i, i + 1)), "tbl_a") {
withParquetTable((0 until 100).map(i => (i, i + 2)), "tbl_b") {
withParquetTable((0 until 100).map(i => (i, i + 3)), "tbl_c") {
val df = sql("""SELECT /*+ BROADCAST(c) */ a1, sum_b2, c._2 FROM (
| SELECT a._1 a1, SUM(b._2) sum_b2 FROM tbl_a a
| JOIN tbl_b b ON a._1 = b._1
| GROUP BY a._1) t
|JOIN tbl_c c ON t.a1 = c._1
|""".stripMargin)
checkSparkAnswerAndOperator(df)
// Before AQE: one CometBroadcastExchange, no CometColumnarToRow
var columnarToRowExec = stripAQEPlan(df.queryExecution.executedPlan).collect {
case s: CometColumnarToRowExec => s
}
assert(columnarToRowExec.isEmpty)
// Disable CometExecRule after the initial plan is generated. The CometSortMergeJoin and
// CometBroadcastHashJoin nodes in the initial plan will be converted to Spark BroadcastHashJoin
// during AQE. This will make CometBroadcastExchangeExec being converted to rows to be used by
// Spark BroadcastHashJoin.
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
df.collect()
}
// After AQE: CometBroadcastExchange has to be converted to rows to conform to Spark
// BroadcastHashJoin.
val plan = stripAQEPlan(df.queryExecution.executedPlan)
columnarToRowExec = plan.collect { case s: CometColumnarToRowExec =>
s
}
assert(columnarToRowExec.length == 1)
// This ColumnarToRowExec should be the immediate child of BroadcastHashJoinExec
val parent = plan.find(_.children.contains(columnarToRowExec.head))
assert(parent.get.isInstanceOf[BroadcastHashJoinExec])
// There should be a CometBroadcastExchangeExec under CometColumnarToRowExec
val broadcastQueryStage =
columnarToRowExec.head.find(_.isInstanceOf[BroadcastQueryStageExec])
assert(broadcastQueryStage.isDefined)
assert(
broadcastQueryStage.get
.asInstanceOf[BroadcastQueryStageExec]
.broadcast
.isInstanceOf[CometBroadcastExchangeExec])
}
}
}
}
}
test("expand operator") {
val data1 = (0 until 1000)
.map(_ % 5) // reduce value space to trigger dictionary encoding
.map(i => (i, i + 100, i + 10))
val data2 = (0 until 5).map(i => (i, i + 1, i * 1000))
Seq(data1, data2).foreach { tableData =>
withParquetTable(tableData, "tbl") {
val df = sql("SELECT _1, _2, SUM(_3) FROM tbl GROUP BY _1, _2 GROUPING SETS ((_1), (_2))")
checkSparkAnswerAndOperator(df)
}
}