forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCometTestBase.scala
More file actions
1158 lines (1052 loc) · 39.6 KB
/
CometTestBase.scala
File metadata and controls
1158 lines (1052 loc) · 39.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.spark.sql
import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.duration._
import scala.reflect.ClassTag
import scala.reflect.runtime.universe.TypeTag
import scala.util.Try
import org.scalatest.BeforeAndAfterEach
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.fs.Path
import org.apache.parquet.column.ParquetProperties
import org.apache.parquet.example.data.Group
import org.apache.parquet.example.data.simple.{SimpleGroup, SimpleGroupFactory}
import org.apache.parquet.hadoop.ParquetWriter
import org.apache.parquet.hadoop.example.{ExampleParquetWriter, GroupWriteSupport}
import org.apache.parquet.schema.{MessageType, MessageTypeParser}
import org.apache.spark._
import org.apache.spark.internal.config.{MEMORY_OFFHEAP_ENABLED, MEMORY_OFFHEAP_SIZE, SHUFFLE_MANAGER}
import org.apache.spark.sql.comet._
import org.apache.spark.sql.comet.execution.shuffle.{CometColumnarShuffle, CometNativeShuffle, CometShuffleExchangeExec}
import org.apache.spark.sql.execution._
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.internal._
import org.apache.spark.sql.test._
import org.apache.spark.sql.types.{DecimalType, StructType}
import org.apache.comet._
import org.apache.comet.shims.ShimCometSparkSessionExtensions
/**
* Base class for testing. This exists in `org.apache.spark.sql` since [[SQLTestUtils]] is
* package-private.
*/
abstract class CometTestBase
extends QueryTest
with SQLTestUtils
with BeforeAndAfterEach
with AdaptiveSparkPlanHelper
with ShimCometSparkSessionExtensions
with ShimCometTestBase {
import testImplicits._
protected val shuffleManager: String =
"org.apache.spark.sql.comet.execution.shuffle.CometShuffleManager"
protected def sparkConf: SparkConf = {
val conf = new SparkConf()
conf.set("spark.hadoop.fs.file.impl", classOf[DebugFilesystem].getName)
conf.set("spark.ui.enabled", "false")
conf.set(SQLConf.SHUFFLE_PARTITIONS, 10) // reduce parallelism in tests
conf.set(SQLConf.ANSI_ENABLED.key, "false")
conf.set(SHUFFLE_MANAGER, shuffleManager)
conf.set(MEMORY_OFFHEAP_ENABLED.key, "true")
conf.set(MEMORY_OFFHEAP_SIZE.key, "2g")
conf.set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key, "1g")
conf.set(SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key, "1g")
conf.set(CometConf.COMET_ENABLED.key, "true")
conf.set(CometConf.COMET_ONHEAP_ENABLED.key, "true")
conf.set(CometConf.COMET_EXEC_ENABLED.key, "true")
conf.set(CometConf.COMET_EXEC_SHUFFLE_ENABLED.key, "true")
conf.set(CometConf.COMET_RESPECT_PARQUET_FILTER_PUSHDOWN.key, "true")
conf.set(CometConf.COMET_SPARK_TO_ARROW_ENABLED.key, "true")
conf.set(CometConf.COMET_NATIVE_SCAN_ENABLED.key, "true")
conf.set(CometConf.COMET_SCAN_ALLOW_INCOMPATIBLE.key, "true")
conf.set(CometConf.COMET_ONHEAP_MEMORY_OVERHEAD.key, "2g")
conf.set(CometConf.COMET_EXEC_SORT_MERGE_JOIN_WITH_JOIN_FILTER_ENABLED.key, "true")
conf
}
protected def isFeatureEnabled(feature: String): Boolean = {
try {
NativeBase.isFeatureEnabled(feature)
} catch {
case _: Throwable =>
false
}
}
/**
* A helper function for comparing Comet DataFrame with Spark result using absolute tolerance.
*/
protected def checkAnswerWithTol(
dataFrame: DataFrame,
expectedAnswer: Seq[Row],
absTol: Double): Unit = {
val actualAnswer = dataFrame.collect()
require(
actualAnswer.length == expectedAnswer.length,
s"actual num rows ${actualAnswer.length} != expected num of rows ${expectedAnswer.length}")
actualAnswer.zip(expectedAnswer).foreach { case (actualRow, expectedRow) =>
checkAnswerWithTol(actualRow, expectedRow, absTol)
}
}
/**
* Compares two answers and makes sure the answer is within absTol of the expected result.
*/
protected def checkAnswerWithTol(
actualAnswer: Row,
expectedAnswer: Row,
absTol: Double): Unit = {
require(
actualAnswer.length == expectedAnswer.length,
s"actual answer length ${actualAnswer.length} != " +
s"expected answer length ${expectedAnswer.length}")
require(absTol > 0 && absTol <= 1e-6, s"absTol $absTol is out of range (0, 1e-6]")
actualAnswer.toSeq.zip(expectedAnswer.toSeq).foreach {
case (actual: Double, expected: Double) =>
if (actual.isInfinity || expected.isInfinity) {
assert(actual.isInfinity == expected.isInfinity, s"actual answer $actual != $expected")
} else if (!actual.isNaN && !expected.isNaN) {
assert(
math.abs(actual - expected) < absTol,
s"actual answer $actual not within $absTol of correct answer $expected")
}
case (actual, expected) =>
assert(actual == expected, s"$actualAnswer did not equal $expectedAnswer")
}
}
protected def checkSparkAnswer(query: String): (SparkPlan, SparkPlan) = {
checkSparkAnswer(sql(query))
}
/**
* Check the answer of a Comet SQL query with Spark result.
* @param df
* The DataFrame of the query.
* @return
* A tuple of the SparkPlan of the query and the SparkPlan of the Comet query.
*/
protected def checkSparkAnswer(df: => DataFrame): (SparkPlan, SparkPlan) = {
var expected: Array[Row] = Array.empty
var sparkPlan = null.asInstanceOf[SparkPlan]
withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
val dfSpark = datasetOfRows(spark, df.logicalPlan)
expected = dfSpark.collect()
sparkPlan = dfSpark.queryExecution.executedPlan
}
val dfComet = datasetOfRows(spark, df.logicalPlan)
checkAnswer(dfComet, expected)
(sparkPlan, dfComet.queryExecution.executedPlan)
}
/** Check for the correct results as well as the expected fallback reason */
def checkSparkAnswerAndFallbackReason(sql: String, fallbackReason: String): Unit = {
val (_, cometPlan) = checkSparkAnswer(sql)
val explain = new ExtendedExplainInfo().generateVerboseExtendedInfo(cometPlan)
assert(explain.contains(fallbackReason))
}
protected def checkSparkAnswerAndOperator(query: String, excludedClasses: Class[_]*): Unit = {
checkSparkAnswerAndOperator(sql(query), excludedClasses: _*)
}
protected def checkSparkAnswerAndOperator(
df: => DataFrame,
excludedClasses: Class[_]*): Unit = {
checkSparkAnswerAndOperator(df, Seq.empty, excludedClasses: _*)
}
protected def checkSparkAnswerAndOperator(
df: => DataFrame,
includeClasses: Seq[Class[_]],
excludedClasses: Class[_]*): Unit = {
checkCometOperators(stripAQEPlan(df.queryExecution.executedPlan), excludedClasses: _*)
checkPlanContains(stripAQEPlan(df.queryExecution.executedPlan), includeClasses: _*)
checkSparkAnswer(df)
}
protected def checkSparkAnswerAndOperatorWithTol(df: => DataFrame, tol: Double = 1e-6): Unit = {
checkSparkAnswerAndOperatorWithTol(df, tol, Seq.empty)
}
protected def checkSparkAnswerAndOperatorWithTol(
df: => DataFrame,
tol: Double,
includeClasses: Seq[Class[_]],
excludedClasses: Class[_]*): Unit = {
checkCometOperators(stripAQEPlan(df.queryExecution.executedPlan), excludedClasses: _*)
checkPlanContains(stripAQEPlan(df.queryExecution.executedPlan), includeClasses: _*)
checkSparkAnswerWithTol(df, tol)
}
protected def checkCometOperators(plan: SparkPlan, excludedClasses: Class[_]*): Unit = {
val wrapped = wrapCometSparkToColumnar(plan)
wrapped.foreach {
case _: CometNativeScanExec | _: CometScanExec | _: CometBatchScanExec =>
case _: CometSinkPlaceHolder | _: CometScanWrapper =>
case _: CometColumnarToRowExec =>
case _: CometSparkToColumnarExec =>
case _: CometExec | _: CometShuffleExchangeExec =>
case _: CometBroadcastExchangeExec =>
case _: WholeStageCodegenExec | _: ColumnarToRowExec | _: InputAdapter =>
case op =>
if (!excludedClasses.exists(c => c.isAssignableFrom(op.getClass))) {
assert(
false,
s"Expected only Comet native operators, but found ${op.nodeName}.\n" +
s"plan: ${new ExtendedExplainInfo().generateVerboseExtendedInfo(plan)}")
}
}
}
protected def checkPlanContains(plan: SparkPlan, includePlans: Class[_]*): Unit = {
includePlans.foreach { case planClass =>
if (plan.find(op => planClass.isAssignableFrom(op.getClass)).isEmpty) {
assert(
false,
s"Expected plan to contain ${planClass.getSimpleName}, but not.\n" +
s"plan: $plan")
}
}
}
/** Wraps the CometRowToColumn as ScanWrapper, so the child operators will not be checked */
private def wrapCometSparkToColumnar(plan: SparkPlan): SparkPlan = {
plan.transformDown {
// don't care the native operators
case p: CometSparkToColumnarExec => CometScanWrapper(null, p)
}
}
/**
* Check the answer of a Comet SQL query with Spark result using absolute tolerance.
*/
protected def checkSparkAnswerWithTol(query: String, absTol: Double = 1e-6): DataFrame = {
checkSparkAnswerWithTol(sql(query), absTol)
}
/**
* Check the answer of a Comet DataFrame with Spark result using absolute tolerance.
*/
protected def checkSparkAnswerWithTol(df: => DataFrame, absTol: Double): DataFrame = {
var expected: Array[Row] = Array.empty
withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
val dfSpark = datasetOfRows(spark, df.logicalPlan)
expected = dfSpark.collect()
}
val dfComet = datasetOfRows(spark, df.logicalPlan)
checkAnswerWithTol(dfComet, expected, absTol: Double)
dfComet
}
protected def checkSparkMaybeThrows(
df: => DataFrame): (Option[Throwable], Option[Throwable]) = {
var expected: Option[Throwable] = None
withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
expected = Try(datasetOfRows(spark, df.logicalPlan).collect()).failed.toOption
}
val actual = Try(datasetOfRows(spark, df.logicalPlan).collect()).failed.toOption
(expected, actual)
}
protected def checkSparkAnswerAndCompareExplainPlan(
df: DataFrame,
expectedInfo: Set[String],
checkExplainString: Boolean = true): Unit = {
var expected: Array[Row] = Array.empty
var dfSpark: Dataset[Row] = null
withSQLConf(CometConf.COMET_ENABLED.key -> "false", EXTENDED_EXPLAIN_PROVIDERS_KEY -> "") {
dfSpark = datasetOfRows(spark, df.logicalPlan)
expected = dfSpark.collect()
}
val dfComet = datasetOfRows(spark, df.logicalPlan)
checkAnswer(dfComet, expected)
if (checkExplainString) {
val diff = StringUtils.difference(
dfSpark.queryExecution.explainString(ExtendedMode),
dfComet.queryExecution.explainString(ExtendedMode))
if (supportsExtendedExplainInfo(dfSpark.queryExecution)) {
for (info <- expectedInfo) {
if (!diff.contains(info)) {
fail(s"Extended explain diff did not contain [$info]. Diff: $diff.")
}
}
}
}
val extendedInfo =
new ExtendedExplainInfo().generateExtendedInfo(dfComet.queryExecution.executedPlan)
val expectedStr = expectedInfo.toSeq.sorted.mkString("\n")
if (!extendedInfo.equalsIgnoreCase(expectedStr)) {
fail(s"$extendedInfo != $expectedStr (case-insensitive comparison)")
}
}
private var _spark: SparkSessionType = _
override protected implicit def spark: SparkSessionType = _spark
protected implicit def sqlContext: SQLContext = _spark.sqlContext
override protected def sparkContext: SparkContext = {
SparkContext.clearActiveContext()
val conf = sparkConf
if (!conf.contains("spark.master")) {
conf.setMaster("local[5]")
}
if (!conf.contains("spark.app.name")) {
conf.setAppName(java.util.UUID.randomUUID().toString)
}
SparkContext.getOrCreate(conf)
}
protected def createSparkSession: SparkSessionType = {
SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()
SparkSession
.builder()
.config(
sparkContext.getConf
) // Don't use `sparkConf` as we can have overridden it in plugin
.withExtensions(new CometSparkSessionExtensions)
.getOrCreate()
}
protected def initializeSession(): Unit = {
if (_spark == null) _spark = createSparkSession
}
protected override def beforeAll(): Unit = {
initializeSession()
super.beforeAll()
}
protected override def afterAll(): Unit = {
try {
super.afterAll()
} finally {
if (_spark != null) {
try {
_spark.stop()
} finally {
_spark = null
SparkSession.clearActiveSession()
SparkSession.clearDefaultSession()
}
}
}
}
protected override def beforeEach(): Unit = {
super.beforeEach()
DebugFilesystem.clearOpenStreams()
}
protected override def afterEach(): Unit = {
super.afterEach()
spark.sharedState.cacheManager.clearCache()
eventually(timeout(10.seconds), interval(2.seconds)) {
DebugFilesystem.assertNoOpenStreams()
}
}
protected def readResourceParquetFile(name: String): DataFrame = {
spark.read.parquet(getResourceParquetFilePath(name))
}
protected def getResourceParquetFilePath(name: String): String = {
Thread.currentThread().getContextClassLoader.getResource(name).toString
}
protected def withParquetDataFrame[T <: Product: ClassTag: TypeTag](
data: Seq[T],
withDictionary: Boolean = true,
schema: Option[StructType] = None)(f: DataFrame => Unit): Unit = {
withParquetFile(data, withDictionary)(path => readParquetFile(path, schema)(f))
}
protected def withParquetTable[T <: Product: ClassTag: TypeTag](
data: Seq[T],
tableName: String,
withDictionary: Boolean = true)(f: => Unit): Unit = {
withParquetDataFrame(data, withDictionary) { df =>
df.createOrReplaceTempView(tableName)
withTempView(tableName)(f)
}
}
protected def withParquetTable(df: DataFrame, tableName: String)(f: => Unit): Unit = {
df.createOrReplaceTempView(tableName)
withTempView(tableName)(f)
}
protected def withParquetTable(path: String, tableName: String)(f: => Unit): Unit = {
val df = spark.read.format("parquet").load(path)
withParquetTable(df, tableName)(f)
}
protected def withParquetFile[T <: Product: ClassTag: TypeTag](
data: Seq[T],
withDictionary: Boolean = true)(f: String => Unit): Unit = {
withTempPath { file =>
spark
.createDataFrame(data)
.write
.option("parquet.enable.dictionary", withDictionary.toString)
.parquet(file.getCanonicalPath)
f(file.getCanonicalPath)
}
}
protected def readParquetFile(path: String, schema: Option[StructType] = None)(
f: DataFrame => Unit): Unit = schema match {
case Some(s) => f(spark.read.format("parquet").schema(s).load(path))
case None => f(spark.read.format("parquet").load(path))
}
protected def createParquetWriter(
schema: MessageType,
path: Path,
dictionaryEnabled: Boolean = false,
pageSize: Int = 1024,
dictionaryPageSize: Int = 1024,
pageRowCountLimit: Int = ParquetProperties.DEFAULT_PAGE_ROW_COUNT_LIMIT,
rowGroupSize: Long = 1024 * 1024L): ParquetWriter[Group] = {
val hadoopConf = spark.sessionState.newHadoopConf()
ExampleParquetWriter
.builder(path)
.withDictionaryEncoding(dictionaryEnabled)
.withType(schema)
// TODO we need to shim this and use withRowGroupSize(Long) with later parquet-hadoop versions to remove
// the deprecated warning here
.withRowGroupSize(rowGroupSize.toInt)
.withPageSize(pageSize)
.withDictionaryPageSize(dictionaryPageSize)
.withPageRowCountLimit(pageRowCountLimit)
.withConf(hadoopConf)
.build()
}
// Maps `i` to both positive and negative to test timestamp after and before the Unix epoch
protected def getValue(i: Long, div: Long): Long = {
val value = if (i % 2 == 0) i else -i
value % div
}
def makeParquetFileAllPrimitiveTypes(path: Path, dictionaryEnabled: Boolean, n: Int): Unit = {
makeParquetFileAllPrimitiveTypes(path, dictionaryEnabled, 0, n)
}
def getPrimitiveTypesParquetSchema: String = {
if (usingDataSourceExecWithIncompatTypes(conf)) {
// Comet complex type reader has different behavior for uint_8, uint_16 types.
// The issue stems from undefined behavior in the parquet spec and is tracked
// here: https://github.com/apache/parquet-java/issues/3142
// here: https://github.com/apache/arrow-rs/issues/7040
// and here: https://github.com/apache/datafusion-comet/issues/1348
"""
|message root {
| optional boolean _1;
| optional int32 _2(INT_8);
| optional int32 _3(INT_16);
| optional int32 _4;
| optional int64 _5;
| optional float _6;
| optional double _7;
| optional binary _8(UTF8);
| optional int32 _9(UINT_32);
| optional int32 _10(UINT_32);
| optional int32 _11(UINT_32);
| optional int64 _12(UINT_64);
| optional binary _13(ENUM);
| optional FIXED_LEN_BYTE_ARRAY(3) _14;
| optional int32 _15(DECIMAL(5, 2));
| optional int64 _16(DECIMAL(18, 10));
| optional FIXED_LEN_BYTE_ARRAY(16) _17(DECIMAL(38, 37));
| optional INT64 _18(TIMESTAMP(MILLIS,true));
| optional INT64 _19(TIMESTAMP(MICROS,true));
| optional INT32 _20(DATE);
| optional binary _21;
| optional INT32 _id;
|}
""".stripMargin
} else {
"""
|message root {
| optional boolean _1;
| optional int32 _2(INT_8);
| optional int32 _3(INT_16);
| optional int32 _4;
| optional int64 _5;
| optional float _6;
| optional double _7;
| optional binary _8(UTF8);
| optional int32 _9(UINT_8);
| optional int32 _10(UINT_16);
| optional int32 _11(UINT_32);
| optional int64 _12(UINT_64);
| optional binary _13(ENUM);
| optional FIXED_LEN_BYTE_ARRAY(3) _14;
| optional int32 _15(DECIMAL(5, 2));
| optional int64 _16(DECIMAL(18, 10));
| optional FIXED_LEN_BYTE_ARRAY(16) _17(DECIMAL(38, 37));
| optional INT64 _18(TIMESTAMP(MILLIS,true));
| optional INT64 _19(TIMESTAMP(MICROS,true));
| optional INT32 _20(DATE);
| optional binary _21;
| optional INT32 _id;
|}
""".stripMargin
}
}
def makeParquetFileAllPrimitiveTypes(
path: Path,
dictionaryEnabled: Boolean,
begin: Int,
end: Int,
nullEnabled: Boolean = true,
pageSize: Int = 128,
randomSize: Int = 0): Unit = {
// alwaysIncludeUnsignedIntTypes means we include unsignedIntTypes in the test even if the
// reader does not support them
val schemaStr = getPrimitiveTypesParquetSchema
val schema = MessageTypeParser.parseMessageType(schemaStr)
val writer = createParquetWriter(
schema,
path,
dictionaryEnabled = dictionaryEnabled,
pageSize = pageSize,
dictionaryPageSize = pageSize)
val idGenerator = new AtomicInteger(0)
val rand = scala.util.Random
val data = (begin until end).map { i =>
if (nullEnabled && rand.nextBoolean()) {
None
} else {
if (dictionaryEnabled) Some(i % 4) else Some(i)
}
}
data.foreach { opt =>
val record = new SimpleGroup(schema)
opt match {
case Some(i) =>
record.add(0, i % 2 == 0)
record.add(1, i.toByte)
record.add(2, i.toShort)
record.add(3, i)
record.add(4, i.toLong)
record.add(5, i.toFloat)
record.add(6, i.toDouble)
record.add(7, i.toString * 48)
record.add(8, (-i).toByte)
record.add(9, (-i).toShort)
record.add(10, -i)
record.add(11, (-i).toLong)
record.add(12, i.toString)
record.add(13, ((i % 10).toString * 3).take(3))
record.add(14, i)
record.add(15, i.toLong)
record.add(16, ((i % 10).toString * 16).take(16))
record.add(17, i.toLong)
record.add(18, i.toLong)
record.add(19, i)
record.add(20, i.toString)
record.add(21, idGenerator.getAndIncrement())
case _ =>
}
writer.write(record)
}
(0 until randomSize).foreach { _ =>
val i = rand.nextLong()
val record = new SimpleGroup(schema)
record.add(0, i % 2 == 0)
record.add(1, i.toByte)
record.add(2, i.toShort)
record.add(3, i.toInt)
record.add(4, i)
record.add(5, java.lang.Float.intBitsToFloat(i.toInt))
record.add(6, java.lang.Double.longBitsToDouble(i))
record.add(7, i.toString * 24)
record.add(8, (-i).toByte)
record.add(9, (-i).toShort)
record.add(10, (-i).toInt)
record.add(11, -i)
record.add(12, i.toString)
record.add(13, i.toString.take(3).padTo(3, '0'))
record.add(14, i.toInt % 100000)
record.add(15, i % 1000000000000000000L)
record.add(16, i.toString.take(16).padTo(16, '0'))
record.add(17, i)
record.add(18, i)
record.add(19, i.toInt)
record.add(20, i.toString)
record.add(21, idGenerator.getAndIncrement())
writer.write(record)
}
writer.close()
}
protected def makeRawTimeParquetFileColumns(
path: Path,
dictionaryEnabled: Boolean,
n: Int,
rowGroupSize: Long = 1024 * 1024L): Seq[Option[Long]] = {
val schemaStr =
"""
|message root {
| optional int64 _0(INT_64);
| optional int64 _1(INT_64);
| optional int64 _2(INT_64);
| optional int64 _3(INT_64);
| optional int64 _4(INT_64);
| optional int64 _5(INT_64);
|}
""".stripMargin
val schema = MessageTypeParser.parseMessageType(schemaStr)
val writer = createParquetWriter(
schema,
path,
dictionaryEnabled = dictionaryEnabled,
rowGroupSize = rowGroupSize)
val div = if (dictionaryEnabled) 10 else n // maps value to a small range for dict to kick in
val rand = scala.util.Random
val expected = (0 until n).map { i =>
if (rand.nextBoolean()) {
None
} else {
Some(getValue(i, div))
}
}
expected.foreach { opt =>
val record = new SimpleGroup(schema)
opt match {
case Some(i) =>
record.add(0, i)
record.add(1, i * 1000) // convert millis to micros, same below
record.add(2, i)
record.add(3, i)
record.add(4, i * 1000)
record.add(5, i * 1000)
case _ =>
}
writer.write(record)
}
writer.close()
expected
}
// Creates Parquet file of timestamp values
protected def makeRawTimeParquetFile(
path: Path,
dictionaryEnabled: Boolean,
n: Int,
rowGroupSize: Long = 1024 * 1024L): Seq[Option[Long]] = {
val schemaStr =
"""
|message root {
| optional int64 _0(TIMESTAMP_MILLIS);
| optional int64 _1(TIMESTAMP_MICROS);
| optional int64 _2(TIMESTAMP(MILLIS,true));
| optional int64 _3(TIMESTAMP(MILLIS,false));
| optional int64 _4(TIMESTAMP(MICROS,true));
| optional int64 _5(TIMESTAMP(MICROS,false));
| optional int64 _6(INT_64);
|}
""".stripMargin
val schema = MessageTypeParser.parseMessageType(schemaStr)
val writer = createParquetWriter(
schema,
path,
dictionaryEnabled = dictionaryEnabled,
rowGroupSize = rowGroupSize)
val div = if (dictionaryEnabled) 10 else n // maps value to a small range for dict to kick in
val rand = scala.util.Random
val expected = (0 until n).map { i =>
if (rand.nextBoolean()) {
None
} else {
Some(getValue(i, div))
}
}
expected.foreach { opt =>
val record = new SimpleGroup(schema)
opt match {
case Some(i) =>
record.add(0, i)
record.add(1, i * 1000) // convert millis to micros, same below
record.add(2, i)
record.add(3, i)
record.add(4, i * 1000)
record.add(5, i * 1000)
record.add(6, i * 1000)
case _ =>
}
writer.write(record)
}
writer.close()
expected
}
// Generate a file based on a complex schema. Schema derived from https://arrow.apache.org/blog/2022/10/17/arrow-parquet-encoding-part-3/
def makeParquetFileComplexTypes(
path: Path,
dictionaryEnabled: Boolean,
numRows: Integer = 10000): Unit = {
val schemaString =
"""
message ComplexDataSchema {
optional group optional_array (LIST) {
repeated group list {
optional int32 element;
}
}
required group array_of_struct (LIST) {
repeated group list {
optional group struct_element {
required int32 field1;
optional group optional_nested_array (LIST) {
repeated group list {
required int32 element;
}
}
}
}
}
optional group optional_map (MAP) {
repeated group key_value {
required int32 key;
optional int32 value;
}
}
required group complex_map (MAP) {
repeated group key_value {
required group map_key {
required int32 key_field1;
optional int32 key_field2;
}
required group map_value {
required int32 value_field1;
repeated int32 value_field2;
}
}
}
}
"""
val schema: MessageType = MessageTypeParser.parseMessageType(schemaString)
GroupWriteSupport.setSchema(schema, spark.sparkContext.hadoopConfiguration)
val writer = createParquetWriter(schema, path, dictionaryEnabled)
val groupFactory = new SimpleGroupFactory(schema)
for (i <- 0 until numRows) {
val record = groupFactory.newGroup()
// Optional array of optional integers
if (i % 2 == 0) { // optional_array for every other row
val optionalArray = record.addGroup("optional_array")
for (j <- 0 until (i % 5)) {
val elementGroup = optionalArray.addGroup("list")
if (j % 2 == 0) { // some elements are optional
elementGroup.append("element", j)
}
}
}
// Required array of structs
val arrayOfStruct = record.addGroup("array_of_struct")
for (j <- 0 until (i % 3) + 1) { // Add one to three elements
val structElementGroup = arrayOfStruct.addGroup("list").addGroup("struct_element")
structElementGroup.append("field1", i * 10 + j)
// Optional nested array
if (j % 2 != 0) { // optional nested array for every other struct
val nestedArray = structElementGroup.addGroup("optional_nested_array")
for (k <- 0 until (i % 4)) { // Add zero to three elements.
val nestedElementGroup = nestedArray.addGroup("list")
nestedElementGroup.append("element", i + j + k)
}
}
}
// Optional map
if (i % 3 == 0) { // optional_map every third row
val optionalMap = record.addGroup("optional_map")
optionalMap
.addGroup("key_value")
.append("key", i)
.append("value", i)
if (i % 5 == 0) { // another optional entry
optionalMap
.addGroup("key_value")
.append("key", i)
// Value is optional
if (i % 10 == 0) {
optionalMap
.addGroup("key_value")
.append("key", i)
.append("value", i)
}
}
}
// Required map with complex key and value types
val complexMap = record.addGroup("complex_map")
val complexMapKeyVal = complexMap.addGroup("key_value")
complexMapKeyVal
.addGroup("map_key")
.append("key_field1", i)
complexMapKeyVal
.addGroup("map_value")
.append("value_field1", i)
.append("value_field2", i * 100)
.append("value_field2", i * 101)
.append("value_field2", i * 102)
writer.write(record)
}
writer.close()
}
protected def makeDateTimeWithFormatTable(
path: Path,
dictionaryEnabled: Boolean,
n: Int,
rowGroupSize: Long = 1024 * 1024L): Seq[Option[Long]] = {
val schemaStr =
"""
|message root {
| optional int64 _0(TIMESTAMP_MILLIS);
| optional int64 _1(TIMESTAMP_MICROS);
| optional int64 _2(TIMESTAMP(MILLIS,true));
| optional int64 _3(TIMESTAMP(MILLIS,false));
| optional int64 _4(TIMESTAMP(MICROS,true));
| optional int64 _5(TIMESTAMP(MICROS,false));
| optional int64 _6(INT_64);
| optional int32 _7(DATE);
| optional binary format(UTF8);
| optional binary dateFormat(UTF8);
| }
""".stripMargin
val schema = MessageTypeParser.parseMessageType(schemaStr)
val writer = createParquetWriter(
schema,
path,
dictionaryEnabled = dictionaryEnabled,
rowGroupSize = rowGroupSize)
val div = if (dictionaryEnabled) 10 else n // maps value to a small range for dict to kick in
val expected = (0 until n).map { i =>
Some(getValue(i, div))
}
expected.foreach { opt =>
val timestampFormats = List(
"YEAR",
"YYYY",
"YY",
"MON",
"MONTH",
"MM",
"QUARTER",
"WEEK",
"DAY",
"DD",
"HOUR",
"MINUTE",
"SECOND",
"MILLISECOND",
"MICROSECOND")
val dateFormats = List("YEAR", "YYYY", "YY", "MON", "MONTH", "MM", "QUARTER", "WEEK")
val formats = timestampFormats.zipAll(dateFormats, "NONE", "YEAR")
formats.foreach { format =>
val record = new SimpleGroup(schema)
opt match {
case Some(i) =>
record.add(0, i)
record.add(1, i * 1000) // convert millis to micros, same below
record.add(2, i)
record.add(3, i)
record.add(4, i * 1000)
record.add(5, i * 1000)
record.add(6, i * 1000)
record.add(7, i.toInt)
record.add(8, format._1)
record.add(9, format._2)
case _ =>
}
writer.write(record)
}
}
writer.close()
expected
}
def makeDecimalRDD(num: Int, decimal: DecimalType, useDictionary: Boolean): DataFrame = {
val div = if (useDictionary) 5 else num // narrow the space to make it dictionary encoded
spark
.range(num)
.map(_ % div)
// Parquet doesn't allow column names with spaces, have to add an alias here.
// Minus 500 here so that negative decimals are also tested.
.select((($"value" - 500) / 100.0) cast decimal as Symbol("dec"))
.coalesce(1)
}
def stripRandomPlanParts(plan: String): String = {
plan.replaceFirst("file:.*,", "").replaceAll(raw"#\d+", "")
}
protected def checkCometExchange(
df: DataFrame,
cometExchangeNum: Int,
native: Boolean): Seq[CometShuffleExchangeExec] = {
if (CometConf.COMET_EXEC_SHUFFLE_ENABLED.get()) {
val sparkPlan = stripAQEPlan(df.queryExecution.executedPlan)
val cometShuffleExecs = sparkPlan.collect { case b: CometShuffleExchangeExec => b }
assert(
cometShuffleExecs.length == cometExchangeNum,
s"$sparkPlan has ${cometShuffleExecs.length} " +
s" CometShuffleExchangeExec node which doesn't match the expected: $cometExchangeNum")
if (native) {
cometShuffleExecs.foreach { b =>
assert(b.shuffleType == CometNativeShuffle)
}
} else {
cometShuffleExecs.foreach { b =>
assert(b.shuffleType == CometColumnarShuffle)
}
}
cometShuffleExecs
} else {
Seq.empty
}
}
/**
* The test encapsulates integration Comet test and does following:
* - prepares data using SELECT query and saves it to the Parquet file in temp folder
* - creates a temporary table with name `tableName` on top of temporary parquet file
* - runs the query `testQuery` reading data from `tableName`
*
* Asserts the `testQuery` data with Comet is the same is with Apache Spark and also asserts
* only Comet operator are in the physical plan
*
* Example:
*
* {{{
* test("native reader - read simple ARRAY fields with SHORT field") {
* testSingleLineQuery(
* """
* |select array(cast(1 as short)) arr
* |""".stripMargin,
* "select arr from tbl",
* sqlConf = Seq(
* CometConf.COMET_SCAN_ALLOW_INCOMPATIBLE.key -> "false",
* "spark.comet.explainFallback.enabled" -> "false"
* ),
* debugCometDF = df => {
* df.printSchema()
* df.explain("extended")
* df.show()