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
2873 lines (2565 loc) · 105 KB
/
CometExecSuite.scala
File metadata and controls
2873 lines (2565 loc) · 105 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.{DynamicPruningExpression, 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._
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.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, CometExecIterator, ExtendedExplainInfo}
import org.apache.comet.CometSparkSessionExtensions.{isSpark35Plus, isSpark40Plus}
import org.apache.comet.serde.Config.ConfigMap
import org.apache.comet.testing.{DataGenOptions, ParquetGenerator, SchemaGenOptions}
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("SQLConf serde") {
def roundtrip = {
val protobuf = CometExecIterator.serializeCometSQLConfs()
ConfigMap.parseFrom(protobuf)
}
// test not setting the config
val deserialized: ConfigMap = roundtrip
assert(null == deserialized.getEntriesMap.get(CometConf.COMET_EXPLAIN_NATIVE_ENABLED.key))
// test explicitly setting the config
for (value <- Seq("true", "false")) {
withSQLConf(CometConf.COMET_EXPLAIN_NATIVE_ENABLED.key -> value) {
val deserialized: ConfigMap = roundtrip
assert(
value == deserialized.getEntriesMap.get(CometConf.COMET_EXPLAIN_NATIVE_ENABLED.key))
}
}
}
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) {
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("AQE Dynamic Partition Pruning is not supported"))
}
}
}
}
test("DPP fallback avoids inefficient Comet shuffle (#3874)") {
withTempDir { path =>
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)
}
// Force sort-merge join to get a shuffle exchange above the DPP scan
Seq("parquet").foreach { v1List =>
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> v1List,
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
spark.read.parquet(factPath).createOrReplaceTempView("dpp_fact2")
spark.read.parquet(dimPath).createOrReplaceTempView("dpp_dim2")
val df =
spark.sql(
"select * from dpp_fact2 join dpp_dim2 on fact_date = dim_date where dim_id > 7")
val (_, cometPlan) = checkSparkAnswer(df)
// Verify no CometShuffleExchangeExec wraps the DPP stage
assert(
!cometPlan.toString().contains("CometColumnarShuffle"),
"Should not use Comet columnar shuffle for stages with DPP scans")
}
}
}
}
test("non-AQE DPP with BHJ works with CometNativeScanExec") {
withTempDir { path =>
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 % 10) * one_day)))
.toDF("fact_id", "fact_date")
fact.write.partitionBy("fact_date").parquet(factPath)
val dim = Range(0, 10)
.map(i => (i, new java.sql.Date(System.currentTimeMillis() + i * one_day)))
.toDF("dim_id", "dim_date")
dim.write.parquet(dimPath)
}
// AQE off ensures PlanDynamicPruningFilters (non-AQE) creates the DPP filters
// with SubqueryBroadcastExec, not SubqueryAdaptiveBroadcastExec
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
spark.read.parquet(factPath).createOrReplaceTempView("dpp_fact_bhj")
spark.read.parquet(dimPath).createOrReplaceTempView("dpp_dim_bhj")
val df = spark.sql(
"select * from dpp_fact_bhj join dpp_dim_bhj on fact_date = dim_date where dim_id > 7")
// Exclude ReusedExchangeExec — it appears inside the DPP subquery after exchange reuse
val (_, cometPlan) = checkSparkAnswerAndOperator(df, classOf[ReusedExchangeExec])
val nativeScans = cometPlan.collect { case s: CometNativeScanExec => s }
assert(nativeScans.nonEmpty, "Expected CometNativeScanExec in plan")
val dppScans =
nativeScans.filter(_.partitionFilters.exists(_.isInstanceOf[DynamicPruningExpression]))
assert(
dppScans.nonEmpty,
"Expected at least one CometNativeScanExec with DynamicPruningExpression")
val infos = new ExtendedExplainInfo().generateExtendedInfo(cometPlan)
assert(
!infos.contains("AQE Dynamic Partition Pruning is not supported"),
s"Should not fall back for non-AQE DPP:\n$infos")
}
}
}
test("non-AQE DPP with SMJ works with CometNativeScanExec") {
withTempDir { path =>
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 % 10) * one_day)))
.toDF("fact_id", "fact_date")
fact.write.partitionBy("fact_date").parquet(factPath)
val dim = Range(0, 10)
.map(i => (i, new java.sql.Date(System.currentTimeMillis() + i * one_day)))
.toDF("dim_id", "dim_date")
dim.write.parquet(dimPath)
}
// AQE off + broadcast disabled -> SMJ is used. PlanDynamicPruningFilters can't reuse
// broadcast, so DPP uses SubqueryExec (aggregate) or Literal.TrueLiteral (if
// onlyInBroadcast). Either way, non-AQE DPP should work natively.
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
spark.read.parquet(factPath).createOrReplaceTempView("dpp_fact_smj")
spark.read.parquet(dimPath).createOrReplaceTempView("dpp_dim_smj")
val df = spark.sql(
"select * from dpp_fact_smj join dpp_dim_smj on fact_date = dim_date where dim_id > 7")
val (_, cometPlan) = checkSparkAnswerAndOperator(df)
val nativeScans = cometPlan.collect { case s: CometNativeScanExec => s }
assert(nativeScans.nonEmpty, "Expected CometNativeScanExec in plan")
val infos = new ExtendedExplainInfo().generateExtendedInfo(cometPlan)
assert(
!infos.contains("AQE Dynamic Partition Pruning is not supported"),
s"Should not fall back for non-AQE DPP:\n$infos")
}
}
}
test("non-AQE DPP with BHJ reuses broadcast exchange") {
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr(
"id % 10 as store_id",
"cast(id * 2 as int) as date_id",
"cast(id * 3 as int) as product_id",
"cast(id as int) as units_sold")
.write
.partitionBy("store_id")
.parquet(s"$path/fact")
spark
.range(10)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as country")
.write
.parquet(s"$path/dim")
}
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_reuse")
spark.read.parquet(s"$path/dim").createOrReplaceTempView("dim_reuse")
val df = spark.sql("""SELECT f.date_id, f.store_id
|FROM fact_reuse f JOIN dim_reuse d
|ON f.store_id = d.store_id
|WHERE d.country = 'DE'""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
// DPP subquery should use CometSubqueryBroadcastExec (not SubqueryBroadcastExec)
val cometSubqueries = collectWithSubqueries(cometPlan) {
case s: CometSubqueryBroadcastExec => s
}
assert(
cometSubqueries.nonEmpty,
"Expected CometSubqueryBroadcastExec in plan for exchange reuse")
// Broadcast exchange should be reused — only one CometBroadcastExchangeExec,
// the other replaced by ReusedExchangeExec
val reused = collectWithSubqueries(cometPlan) { case e: ReusedExchangeExec =>
e
}
assert(
reused.nonEmpty,
s"Expected ReusedExchangeExec for broadcast exchange reuse:\n${cometPlan.treeString}")
val broadcasts = collectWithSubqueries(cometPlan) { case e: CometBroadcastExchangeExec =>
e
}
assert(
broadcasts.size == 1,
s"Expected exactly 1 CometBroadcastExchangeExec (other reused):\n${cometPlan.treeString}")
// Verify canonical forms match — this is what ReuseExchangeAndSubquery uses to
// determine reuse eligibility
if (reused.nonEmpty && broadcasts.nonEmpty) {
val reusedChild = reused.head.child
assert(
reusedChild.canonicalized == broadcasts.head.canonicalized,
"ReusedExchangeExec child and CometBroadcastExchangeExec should have same " +
"canonical form for reuse")
}
}
}
}
test("non-AQE DPP with non-atomic type (struct/array) join key") {
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr(
"cast(id % 10 as int) as store_id",
"cast(id as int) as date_id",
"cast(id * 2 as int) as units_sold")
.write
.partitionBy("store_id")
.parquet(s"$path/fact")
spark
.range(10)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as country")
.write
.parquet(s"$path/dim")
}
Seq("struct", "array").foreach { dataType =>
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_nonatomic")
spark.read.parquet(s"$path/dim").createOrReplaceTempView("dim_nonatomic")
val df = spark.sql(s"""SELECT f.date_id, f.store_id FROM fact_nonatomic f
|JOIN dim_nonatomic d
|ON $dataType(f.store_id) = $dataType(d.store_id)
|WHERE d.country = 'DE'""".stripMargin)
checkSparkAnswer(df)
}
}
}
}
// Regression tests for DPP exchange/subquery reuse (from DynamicPartitionPruningSuite)
private def withDppTables(f: => Unit): Unit = {
val factData = Seq(
(1000, 1, 1, 10),
(1010, 2, 1, 10),
(1020, 2, 1, 10),
(1030, 3, 2, 10),
(1040, 3, 2, 50),
(1050, 3, 2, 50),
(1060, 3, 2, 50),
(1070, 4, 2, 10),
(1080, 4, 3, 20),
(1090, 4, 3, 10),
(1100, 4, 3, 10),
(1110, 5, 3, 10),
(1120, 6, 4, 10),
(1130, 7, 4, 50),
(1140, 8, 4, 50),
(1150, 9, 1, 20),
(1160, 10, 1, 20),
(1170, 11, 1, 30),
(1180, 12, 2, 20),
(1190, 13, 2, 20),
(1200, 14, 3, 40),
(1200, 15, 3, 70),
(1210, 16, 4, 10),
(1220, 17, 4, 20),
(1230, 18, 4, 20),
(1240, 19, 5, 40),
(1250, 20, 5, 40),
(1260, 21, 5, 40),
(1270, 22, 5, 50),
(1280, 23, 1, 50),
(1290, 24, 1, 50),
(1300, 25, 1, 50))
val storeData = Seq(
(1, "North-Holland", "NL"),
(2, "South-Holland", "NL"),
(3, "Bavaria", "DE"),
(4, "California", "US"),
(5, "Texas", "US"),
(6, "Texas", "US"))
val storeCode = Seq((1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60))
import testImplicits._
withTable("fact_np", "fact_sk", "fact_stats", "dim_stats", "dim_store", "code_stats") {
factData
.toDF("date_id", "store_id", "product_id", "units_sold")
.write
.format("parquet")
.saveAsTable("fact_np")
factData
.toDF("date_id", "store_id", "product_id", "units_sold")
.write
.partitionBy("store_id")
.format("parquet")
.saveAsTable("fact_sk")
factData
.toDF("date_id", "store_id", "product_id", "units_sold")
.write
.partitionBy("store_id")
.format("parquet")
.saveAsTable("fact_stats")
storeData
.toDF("store_id", "state_province", "country")
.write
.format("parquet")
.saveAsTable("dim_store")
storeData
.toDF("store_id", "state_province", "country")
.write
.format("parquet")
.saveAsTable("dim_stats")
storeCode
.toDF("store_id", "code")
.write
.partitionBy("store_id")
.format("parquet")
.saveAsTable("code_stats")
sql("ANALYZE TABLE fact_stats COMPUTE STATISTICS FOR COLUMNS store_id")
sql("ANALYZE TABLE dim_stats COMPUTE STATISTICS FOR COLUMNS store_id")
sql("ANALYZE TABLE dim_store COMPUTE STATISTICS FOR COLUMNS store_id")
sql("ANALYZE TABLE code_stats COMPUTE STATISTICS FOR COLUMNS store_id")
f
}
}
test("DPP broadcast exchange reuse") {
withDppTables {
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true") {
val df = sql("""SELECT /*+ BROADCAST(f)*/
|f.date_id, f.store_id, f.product_id, f.units_sold FROM fact_np f
|JOIN code_stats s
|ON f.store_id = s.store_id WHERE f.date_id <= 1030""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
val reusedExchanges = collectWithSubqueries(cometPlan) { case e: ReusedExchangeExec =>
e
}
assert(
reusedExchanges.nonEmpty,
s"Expected ReusedExchangeExec for broadcast exchange reuse:\n${cometPlan.treeString}")
}
}
}
test("DPP subquery reuse with uncorrelated scalar subquery") {
withDppTables {
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true") {
val df = sql("""SELECT d.store_id, SUM(f.units_sold),
| (SELECT SUM(f.units_sold)
| FROM fact_stats f JOIN dim_stats d ON d.store_id = f.store_id
| WHERE d.country = 'US') AS total_prod
|FROM fact_stats f JOIN dim_stats d ON d.store_id = f.store_id
|WHERE d.country = 'US'
|GROUP BY 1""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
val countSubqueryBroadcasts = collectWithSubqueries(cometPlan)({
case _: SubqueryBroadcastExec => 1
case _: CometSubqueryBroadcastExec => 1
}).sum
val countReusedSubqueryBroadcasts = collectWithSubqueries(cometPlan)({
case ReusedSubqueryExec(_: SubqueryBroadcastExec) => 1
case ReusedSubqueryExec(_: CometSubqueryBroadcastExec) => 1
}).sum
assert(
countSubqueryBroadcasts == 1,
s"Expected 1 subquery broadcast but got $countSubqueryBroadcasts:\n" +
cometPlan.treeString)
assert(
countReusedSubqueryBroadcasts == 1,
s"Expected 1 reused subquery broadcast but got $countReusedSubqueryBroadcasts:\n" +
cometPlan.treeString)
}
}
}
test("DPP with non-atomic type (struct/array) join key") {
withDppTables {
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "true") {
Seq("struct", "array").foreach { dataType =>
val df =
sql(s"""SELECT f.date_id, f.product_id, f.units_sold, f.store_id FROM fact_stats f
|JOIN dim_stats s
|ON $dataType(f.store_id) = $dataType(s.store_id) WHERE s.country = 'DE'
""".stripMargin)
checkSparkAnswer(df)
}
}
}
}
test("DPP non-atomic type uses CometSubqueryBroadcastExec") {
withDppTables {
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "true",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true") {
Seq("struct", "array").foreach { dataType =>
val df =
sql(s"""SELECT f.date_id, f.product_id, f.units_sold, f.store_id FROM fact_stats f
|JOIN dim_stats s
|ON $dataType(f.store_id) = $dataType(s.store_id) WHERE s.country = 'DE'
""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
val cometSubqueries = collectWithSubqueries(cometPlan) {
case s: CometSubqueryBroadcastExec => s
}
assert(
cometSubqueries.nonEmpty,
s"Expected DPP with CometSubqueryBroadcastExec for $dataType key:\n" +
cometPlan.treeString)
}
}
}
}
test("non-AQE DPP with two separate broadcast joins") {
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr(
"cast(id % 5 as int) as store_id",
"cast(id % 3 as int) as region_id",
"cast(id as int) as amount")
.write
.partitionBy("store_id", "region_id")
.parquet(s"$path/fact")
spark
.range(5)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as store_name")
.write
.parquet(s"$path/store_dim")
spark
.range(3)
.selectExpr("cast(id as int) as region_id", "cast(id as string) as region_name")
.write
.parquet(s"$path/region_dim")
}
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_two_joins")
spark.read.parquet(s"$path/store_dim").createOrReplaceTempView("store_dim")
spark.read.parquet(s"$path/region_dim").createOrReplaceTempView("region_dim")
val df = spark.sql("""SELECT f.amount, s.store_name, r.region_name
|FROM fact_two_joins f
|JOIN store_dim s ON f.store_id = s.store_id
|JOIN region_dim r ON f.region_id = r.region_id
|WHERE s.store_name = '1' AND r.region_name = '2'""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
val nativeScans = cometPlan.collect { case s: CometNativeScanExec => s }
assert(nativeScans.nonEmpty, "Expected CometNativeScanExec in plan")
val dppScans =
nativeScans.filter(_.partitionFilters.exists(_.isInstanceOf[DynamicPruningExpression]))
assert(
dppScans.nonEmpty,
"Expected at least one CometNativeScanExec with DynamicPruningExpression")
}
}
}
test("non-AQE DPP fallback when broadcast exchange is not Comet") {
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr("cast(id % 10 as int) as store_id", "cast(id as int) as amount")
.write
.partitionBy("store_id")
.parquet(s"$path/fact")
spark
.range(10)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as country")
.write
.parquet(s"$path/dim")
}
// Disable Comet broadcast exchange so SubqueryBroadcastExec wraps a Spark
// BroadcastExchangeExec. convertSubqueryBroadcasts should skip it (child isn't
// CometNativeExec). Query should still produce correct results via Spark's standard path.
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
CometConf.COMET_EXEC_BROADCAST_EXCHANGE_ENABLED.key -> "false",
CometConf.COMET_EXEC_BROADCAST_HASH_JOIN_ENABLED.key -> "false") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_fallback")
spark.read.parquet(s"$path/dim").createOrReplaceTempView("dim_fallback")
val df = spark.sql("""SELECT f.amount, f.store_id
|FROM fact_fallback f JOIN dim_fallback d
|ON f.store_id = d.store_id
|WHERE d.country = 'DE'""".stripMargin)
checkSparkAnswer(df)
}
}
}
test("non-AQE DPP with empty broadcast result") {
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr("cast(id % 10 as int) as store_id", "cast(id as int) as amount")
.write
.partitionBy("store_id")
.parquet(s"$path/fact")
spark
.range(10)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as country")
.write
.parquet(s"$path/dim")
}
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_empty")
spark.read.parquet(s"$path/dim").createOrReplaceTempView("dim_empty")
// Filter on dim that matches nothing -- DPP prunes all partitions
val df = spark.sql("""SELECT f.amount, f.store_id
|FROM fact_empty f JOIN dim_empty d
|ON f.store_id = d.store_id
|WHERE d.country = 'NONEXISTENT'""".stripMargin)
val result = df.collect()
assert(result.isEmpty, s"Expected empty result but got ${result.length} rows")
checkSparkAnswer(df)
}
}
}
test("non-AQE DPP resolves both outer and inner partition filters") {
// CometNativeScanExec.partitionFilters and CometScanExec.partitionFilters contain
// different InSubqueryExec instances. Both must be resolved for partition selection
// to work correctly. This test verifies correct results, which requires both sets
// of filters to be resolved.
withTempDir { dir =>
val path = s"${dir.getAbsolutePath}/data"
withSQLConf(CometConf.COMET_EXEC_ENABLED.key -> "false") {
spark
.range(100)
.selectExpr(
"cast(id % 10 as int) as store_id",
"cast(id as int) as date_id",
"cast(id as int) as amount")
.write
.partitionBy("store_id")
.parquet(s"$path/fact")
spark
.range(10)
.selectExpr("cast(id as int) as store_id", "cast(id as string) as country")
.write
.parquet(s"$path/dim")
}
withSQLConf(
SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true") {
spark.read.parquet(s"$path/fact").createOrReplaceTempView("fact_dual")
spark.read.parquet(s"$path/dim").createOrReplaceTempView("dim_dual")
val df = spark.sql("""SELECT f.date_id, f.store_id
|FROM fact_dual f JOIN dim_dual d
|ON f.store_id = d.store_id
|WHERE d.country = 'DE'""".stripMargin)
val (_, cometPlan) = checkSparkAnswer(df)
// Verify native scan is used
val nativeScans = cometPlan.collect { case s: CometNativeScanExec => s }
assert(nativeScans.nonEmpty, "Expected CometNativeScanExec in plan")
// Verify DPP is present
val dppScans =
nativeScans.filter(_.partitionFilters.exists(_.isInstanceOf[DynamicPruningExpression]))
assert(dppScans.nonEmpty, "Expected DPP filter on native scan")
}
}
}
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("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("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("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)
}