-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathstatistics_test.cc
More file actions
1808 lines (1553 loc) · 71 KB
/
statistics_test.cc
File metadata and controls
1808 lines (1553 loc) · 71 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.
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <vector>
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/memory_pool.h"
#include "arrow/testing/builder.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_ops.h"
#include "arrow/util/config.h"
#include "arrow/util/float16.h"
#include "arrow/util/logging_internal.h"
#include "arrow/util/ubsan.h"
#include "parquet/column_reader.h"
#include "parquet/column_writer.h"
#include "parquet/file_reader.h"
#include "parquet/file_writer.h"
#include "parquet/platform.h"
#include "parquet/schema.h"
#include "parquet/statistics.h"
#include "parquet/test_util.h"
#include "parquet/thrift_internal.h"
#include "parquet/types.h"
using arrow::default_memory_pool;
using arrow::MemoryPool;
using arrow::util::Float16;
using arrow::util::SafeCopy;
namespace bit_util = arrow::bit_util;
namespace parquet {
using schema::GroupNode;
using schema::NodePtr;
using schema::PrimitiveNode;
namespace test {
// ----------------------------------------------------------------------
// Test comparators
static ByteArray ByteArrayFromString(const std::string& s) {
auto ptr = reinterpret_cast<const uint8_t*>(s.data());
return ByteArray(static_cast<uint32_t>(s.size()), ptr);
}
static FLBA FLBAFromString(const std::string& s) {
auto ptr = reinterpret_cast<const uint8_t*>(s.data());
return FLBA(ptr);
}
TEST(Comparison, SignedByteArray) {
// Signed byte array comparison is only used for Decimal comparison. When
// decimals are encoded as byte arrays they use twos complement big-endian
// encoded values. Comparisons of byte arrays of unequal types need to handle
// sign extension.
auto comparator = MakeComparator<ByteArrayType>(Type::BYTE_ARRAY, SortOrder::SIGNED);
struct Case {
std::vector<uint8_t> bytes;
int order;
ByteArray ToByteArray() const {
return ByteArray(static_cast<int>(bytes.size()), bytes.data());
}
};
// Test a mix of big-endian comparison values that are both equal and
// unequal after sign extension.
std::vector<Case> cases = {
{{0x80, 0x80, 0, 0}, 0}, {{/*0xFF,*/ 0x80, 0, 0}, 1},
{{0xFF, 0x80, 0, 0}, 1}, {{/*0xFF,*/ 0xFF, 0x01, 0}, 2},
{{/*0xFF, 0xFF,*/ 0x80, 0}, 3}, {{/*0xFF,*/ 0xFF, 0x80, 0}, 3},
{{0xFF, 0xFF, 0x80, 0}, 3}, {{/*0xFF,0xFF,0xFF,*/ 0x80}, 4},
{{/*0xFF, 0xFF, 0xFF,*/ 0xFF}, 5}, {{/*0, 0,*/ 0x01, 0x01}, 6},
{{/*0,*/ 0, 0x01, 0x01}, 6}, {{0, 0, 0x01, 0x01}, 6},
{{/*0,*/ 0x01, 0x01, 0}, 7}, {{0x01, 0x01, 0, 0}, 8}};
for (size_t x = 0; x < cases.size(); x++) {
const auto& case1 = cases[x];
// Empty array is always the smallest values
EXPECT_TRUE(comparator->Compare(ByteArray(), case1.ToByteArray())) << x;
EXPECT_FALSE(comparator->Compare(case1.ToByteArray(), ByteArray())) << x;
// Equals is always false.
EXPECT_FALSE(comparator->Compare(case1.ToByteArray(), case1.ToByteArray())) << x;
for (size_t y = 0; y < cases.size(); y++) {
const auto& case2 = cases[y];
if (case1.order < case2.order) {
EXPECT_TRUE(comparator->Compare(case1.ToByteArray(), case2.ToByteArray()))
<< x << " (order: " << case1.order << ") " << y << " (order: " << case2.order
<< ")";
} else {
EXPECT_FALSE(comparator->Compare(case1.ToByteArray(), case2.ToByteArray()))
<< x << " (order: " << case1.order << ") " << y << " (order: " << case2.order
<< ")";
}
}
}
}
TEST(Comparison, UnsignedByteArray) {
// Check if UTF-8 is compared using unsigned correctly
auto comparator = MakeComparator<ByteArrayType>(Type::BYTE_ARRAY, SortOrder::UNSIGNED);
std::string s1 = "arrange";
std::string s2 = "arrangement";
ByteArray s1ba = ByteArrayFromString(s1);
ByteArray s2ba = ByteArrayFromString(s2);
ASSERT_TRUE(comparator->Compare(s1ba, s2ba));
// Multi-byte UTF-8 characters
s1 = "braten";
s2 = "bügeln";
s1ba = ByteArrayFromString(s1);
s2ba = ByteArrayFromString(s2);
ASSERT_TRUE(comparator->Compare(s1ba, s2ba));
s1 = "ünk123456"; // ü = 252
s2 = "ănk123456"; // ă = 259
s1ba = ByteArrayFromString(s1);
s2ba = ByteArrayFromString(s2);
ASSERT_TRUE(comparator->Compare(s1ba, s2ba));
}
TEST(Comparison, SignedFLBA) {
int size = 4;
auto comparator =
MakeComparator<FLBAType>(Type::FIXED_LEN_BYTE_ARRAY, SortOrder::SIGNED, size);
std::vector<uint8_t> byte_values[] = {
{0x80, 0, 0, 0}, {0xFF, 0xFF, 0x01, 0}, {0xFF, 0xFF, 0x80, 0},
{0xFF, 0xFF, 0xFF, 0x80}, {0xFF, 0xFF, 0xFF, 0xFF}, {0, 0, 0x01, 0x01},
{0, 0x01, 0x01, 0}, {0x01, 0x01, 0, 0}};
std::vector<FLBA> values_to_compare;
for (auto& bytes : byte_values) {
values_to_compare.emplace_back(FLBA(bytes.data()));
}
for (size_t x = 0; x < values_to_compare.size(); x++) {
EXPECT_FALSE(comparator->Compare(values_to_compare[x], values_to_compare[x])) << x;
for (size_t y = x + 1; y < values_to_compare.size(); y++) {
EXPECT_TRUE(comparator->Compare(values_to_compare[x], values_to_compare[y]))
<< x << " " << y;
EXPECT_FALSE(comparator->Compare(values_to_compare[y], values_to_compare[x]))
<< y << " " << x;
}
}
}
TEST(Comparison, UnsignedFLBA) {
int size = 10;
auto comparator =
MakeComparator<FLBAType>(Type::FIXED_LEN_BYTE_ARRAY, SortOrder::UNSIGNED, size);
std::string s1 = "Anti123456";
std::string s2 = "Bunkd123456";
FLBA s1flba = FLBAFromString(s1);
FLBA s2flba = FLBAFromString(s2);
ASSERT_TRUE(comparator->Compare(s1flba, s2flba));
s1 = "Bunk123456";
s2 = "Bünk123456";
s1flba = FLBAFromString(s1);
s2flba = FLBAFromString(s2);
ASSERT_TRUE(comparator->Compare(s1flba, s2flba));
}
TEST(Comparison, SignedInt96) {
parquet::Int96 a{{1, 41, 14}}, b{{1, 41, 42}};
parquet::Int96 aa{{1, 41, 14}}, bb{{1, 41, 14}};
parquet::Int96 aaa{{1, 41, static_cast<uint32_t>(-14)}}, bbb{{1, 41, 42}};
auto comparator = MakeComparator<Int96Type>(Type::INT96, SortOrder::SIGNED);
ASSERT_TRUE(comparator->Compare(a, b));
ASSERT_TRUE(!comparator->Compare(aa, bb) && !comparator->Compare(bb, aa));
ASSERT_TRUE(comparator->Compare(aaa, bbb));
}
TEST(Comparison, UnsignedInt96) {
parquet::Int96 a{{1, 41, 14}}, b{{1, static_cast<uint32_t>(-41), 42}};
parquet::Int96 aa{{1, 41, 14}}, bb{{1, 41, static_cast<uint32_t>(-14)}};
parquet::Int96 aaa, bbb;
auto comparator = MakeComparator<Int96Type>(Type::INT96, SortOrder::UNSIGNED);
ASSERT_TRUE(comparator->Compare(a, b));
ASSERT_TRUE(comparator->Compare(aa, bb));
// INT96 Timestamp
aaa.value[2] = 2451545; // 2000-01-01
bbb.value[2] = 2451546; // 2000-01-02
// 12 hours + 34 minutes + 56 seconds.
Int96SetNanoSeconds(aaa, 45296000000000);
// 12 hours + 34 minutes + 50 seconds.
Int96SetNanoSeconds(bbb, 45290000000000);
ASSERT_TRUE(comparator->Compare(aaa, bbb));
aaa.value[2] = 2451545; // 2000-01-01
bbb.value[2] = 2451545; // 2000-01-01
// 11 hours + 34 minutes + 56 seconds.
Int96SetNanoSeconds(aaa, 41696000000000);
// 12 hours + 34 minutes + 50 seconds.
Int96SetNanoSeconds(bbb, 45290000000000);
ASSERT_TRUE(comparator->Compare(aaa, bbb));
aaa.value[2] = 2451545; // 2000-01-01
bbb.value[2] = 2451545; // 2000-01-01
// 12 hours + 34 minutes + 55 seconds.
Int96SetNanoSeconds(aaa, 45295000000000);
// 12 hours + 34 minutes + 56 seconds.
Int96SetNanoSeconds(bbb, 45296000000000);
ASSERT_TRUE(comparator->Compare(aaa, bbb));
}
TEST(Comparison, SignedInt64) {
int64_t a = 1, b = 4;
int64_t aa = 1, bb = 1;
int64_t aaa = -1, bbb = 1;
NodePtr node = PrimitiveNode::Make("SignedInt64", Repetition::REQUIRED, Type::INT64);
ColumnDescriptor descr(node, 0, 0);
auto comparator = MakeComparator<Int64Type>(&descr);
ASSERT_TRUE(comparator->Compare(a, b));
ASSERT_TRUE(!comparator->Compare(aa, bb) && !comparator->Compare(bb, aa));
ASSERT_TRUE(comparator->Compare(aaa, bbb));
}
TEST(Comparison, UnsignedInt64) {
uint64_t a = 1, b = 4;
uint64_t aa = 1, bb = 1;
uint64_t aaa = 1, bbb = -1;
NodePtr node = PrimitiveNode::Make("UnsignedInt64", Repetition::REQUIRED, Type::INT64,
ConvertedType::UINT_64);
ColumnDescriptor descr(node, 0, 0);
ASSERT_EQ(SortOrder::UNSIGNED, descr.sort_order());
auto comparator = MakeComparator<Int64Type>(&descr);
ASSERT_TRUE(comparator->Compare(a, b));
ASSERT_TRUE(!comparator->Compare(aa, bb) && !comparator->Compare(bb, aa));
ASSERT_TRUE(comparator->Compare(aaa, bbb));
}
TEST(Comparison, UnsignedInt32) {
uint32_t a = 1, b = 4;
uint32_t aa = 1, bb = 1;
uint32_t aaa = 1, bbb = -1;
NodePtr node = PrimitiveNode::Make("UnsignedInt32", Repetition::REQUIRED, Type::INT32,
ConvertedType::UINT_32);
ColumnDescriptor descr(node, 0, 0);
ASSERT_EQ(SortOrder::UNSIGNED, descr.sort_order());
auto comparator = MakeComparator<Int32Type>(&descr);
ASSERT_TRUE(comparator->Compare(a, b));
ASSERT_TRUE(!comparator->Compare(aa, bb) && !comparator->Compare(bb, aa));
ASSERT_TRUE(comparator->Compare(aaa, bbb));
}
TEST(Comparison, UnknownSortOrder) {
NodePtr node =
PrimitiveNode::Make("Unknown", Repetition::REQUIRED, Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::INTERVAL, 12);
ColumnDescriptor descr(node, 0, 0);
ASSERT_THROW(Comparator::Make(&descr), ParquetException);
}
// ----------------------------------------------------------------------
template <typename TestType>
class TestStatistics : public PrimitiveTypedTest<TestType> {
public:
using c_type = typename TestType::c_type;
std::vector<c_type> GetDeepCopy(
const std::vector<c_type>&); // allocates new memory for FLBA/ByteArray
c_type* GetValuesPointer(std::vector<c_type>&);
void DeepFree(std::vector<c_type>&);
void TestMinMaxEncode() {
this->GenerateData(1000);
auto statistics1 = MakeStatistics<TestType>(this->schema_.Column(0));
statistics1->Update(this->values_ptr_, this->values_.size(), 0);
std::string encoded_min = statistics1->EncodeMin();
std::string encoded_max = statistics1->EncodeMax();
auto statistics2 = MakeStatistics<TestType>(
this->schema_.Column(0), encoded_min, encoded_max, this->values_.size(),
/*null_count=*/0, /*distinct_count=*/0,
/*has_min_max=*/true, /*has_null_count=*/true, /*has_distinct_count=*/true,
/*is_min_value_exact=*/true, /*is_max_value_exact=*/true);
auto statistics3 = MakeStatistics<TestType>(this->schema_.Column(0));
std::vector<uint8_t> valid_bits(
bit_util::BytesForBits(static_cast<uint32_t>(this->values_.size())) + 1, 255);
statistics3->UpdateSpaced(this->values_ptr_, valid_bits.data(), 0,
this->values_.size(), this->values_.size(), 0);
std::string encoded_min_spaced = statistics3->EncodeMin();
std::string encoded_max_spaced = statistics3->EncodeMax();
// Use old API without is_{min/max}_value_exact
auto statistics4 = MakeStatistics<TestType>(
this->schema_.Column(0), encoded_min, encoded_max, this->values_.size(),
/*null_count=*/0, /*distinct_count=*/0,
/*has_min_max=*/true, /*has_null_count=*/true, /*has_distinct_count=*/true);
ASSERT_EQ(encoded_min, statistics2->EncodeMin());
ASSERT_EQ(encoded_max, statistics2->EncodeMax());
ASSERT_EQ(statistics1->min(), statistics2->min());
ASSERT_EQ(statistics1->max(), statistics2->max());
ASSERT_EQ(statistics1->is_min_value_exact(), std::make_optional(true));
ASSERT_EQ(statistics1->is_max_value_exact(), std::make_optional(true));
ASSERT_EQ(statistics2->is_min_value_exact(), std::make_optional(true));
ASSERT_EQ(statistics2->is_max_value_exact(), std::make_optional(true));
ASSERT_EQ(encoded_min_spaced, statistics2->EncodeMin());
ASSERT_EQ(encoded_max_spaced, statistics2->EncodeMax());
ASSERT_EQ(statistics3->min(), statistics2->min());
ASSERT_EQ(statistics3->max(), statistics2->max());
ASSERT_EQ(statistics3->is_min_value_exact(), std::make_optional(true));
ASSERT_EQ(statistics3->is_max_value_exact(), std::make_optional(true));
ASSERT_EQ(statistics4->min(), statistics2->min());
ASSERT_EQ(statistics4->max(), statistics2->max());
ASSERT_EQ(statistics4->is_min_value_exact(), std::nullopt);
ASSERT_EQ(statistics4->is_max_value_exact(), std::nullopt);
}
void TestReset() {
this->GenerateData(1000);
auto statistics = MakeStatistics<TestType>(this->schema_.Column(0));
statistics->Update(this->values_ptr_, this->values_.size(), 0);
ASSERT_EQ(this->values_.size(), statistics->num_values());
statistics->Reset();
ASSERT_TRUE(statistics->HasNullCount());
ASSERT_FALSE(statistics->HasMinMax());
ASSERT_FALSE(statistics->HasDistinctCount());
ASSERT_EQ(0, statistics->null_count());
ASSERT_EQ(0, statistics->num_values());
ASSERT_EQ(0, statistics->distinct_count());
ASSERT_EQ("", statistics->EncodeMin());
ASSERT_EQ("", statistics->EncodeMax());
}
void TestMerge() {
int num_null[2];
random_numbers(2, 42, 0, 100, num_null);
auto statistics1 = MakeStatistics<TestType>(this->schema_.Column(0));
this->GenerateData(1000);
statistics1->Update(this->values_ptr_, this->values_.size() - num_null[0],
num_null[0]);
auto statistics2 = MakeStatistics<TestType>(this->schema_.Column(0));
this->GenerateData(1000);
statistics2->Update(this->values_ptr_, this->values_.size() - num_null[1],
num_null[1]);
auto total = MakeStatistics<TestType>(this->schema_.Column(0));
total->Merge(*statistics1);
total->Merge(*statistics2);
ASSERT_EQ(num_null[0] + num_null[1], total->null_count());
ASSERT_EQ(this->values_.size() * 2 - num_null[0] - num_null[1], total->num_values());
ASSERT_EQ(total->min(), std::min(statistics1->min(), statistics2->min()));
ASSERT_EQ(total->max(), std::max(statistics1->max(), statistics2->max()));
}
void TestEquals() {
const auto n_values = 1;
auto statistics_have_minmax1 = MakeStatistics<TestType>(this->schema_.Column(0));
const auto seed1 = 1;
this->GenerateData(n_values, seed1);
statistics_have_minmax1->Update(this->values_ptr_, this->values_.size(), 0);
auto statistics_have_minmax2 = MakeStatistics<TestType>(this->schema_.Column(0));
const auto seed2 = 9999;
this->GenerateData(n_values, seed2);
statistics_have_minmax2->Update(this->values_ptr_, this->values_.size(), 0);
auto statistics_no_minmax = MakeStatistics<TestType>(this->schema_.Column(0));
ASSERT_EQ(true, statistics_have_minmax1->Equals(*statistics_have_minmax1));
ASSERT_EQ(true, statistics_no_minmax->Equals(*statistics_no_minmax));
ASSERT_EQ(false, statistics_have_minmax1->Equals(*statistics_have_minmax2));
ASSERT_EQ(false, statistics_have_minmax1->Equals(*statistics_no_minmax));
}
void TestFullRoundtrip(int64_t num_values, int64_t null_count) {
this->GenerateData(num_values);
// compute statistics for the whole batch
auto expected_stats = MakeStatistics<TestType>(this->schema_.Column(0));
expected_stats->Update(this->values_ptr_, num_values - null_count, null_count);
auto sink = CreateOutputStream();
auto gnode = std::static_pointer_cast<GroupNode>(this->node_);
std::shared_ptr<WriterProperties> writer_properties =
WriterProperties::Builder().enable_statistics("column")->build();
auto file_writer = ParquetFileWriter::Open(sink, gnode, writer_properties);
auto row_group_writer = file_writer->AppendRowGroup();
auto column_writer =
static_cast<TypedColumnWriter<TestType>*>(row_group_writer->NextColumn());
// simulate the case when data comes from multiple buffers,
// in which case special care is necessary for FLBA/ByteArray types
for (int i = 0; i < 2; i++) {
int64_t batch_num_values = i ? num_values - num_values / 2 : num_values / 2;
int64_t batch_null_count = i ? null_count : 0;
DCHECK(null_count <= num_values); // avoid too much headache
std::vector<int16_t> definition_levels(batch_null_count, 0);
definition_levels.insert(definition_levels.end(),
batch_num_values - batch_null_count, 1);
auto beg = this->values_.begin() + i * num_values / 2;
auto end = beg + batch_num_values;
std::vector<c_type> batch = GetDeepCopy(std::vector<c_type>(beg, end));
c_type* batch_values_ptr = GetValuesPointer(batch);
column_writer->WriteBatch(batch_num_values, definition_levels.data(), nullptr,
batch_values_ptr);
DeepFree(batch);
}
column_writer->Close();
row_group_writer->Close();
file_writer->Close();
ASSERT_OK_AND_ASSIGN(auto buffer, sink->Finish());
auto source = std::make_shared<::arrow::io::BufferReader>(buffer);
auto file_reader = ParquetFileReader::Open(source);
auto rg_reader = file_reader->RowGroup(0);
auto column_chunk = rg_reader->metadata()->ColumnChunk(0);
if (!column_chunk->is_stats_set()) return;
std::shared_ptr<Statistics> stats = column_chunk->statistics();
// check values after serialization + deserialization
EXPECT_EQ(null_count, stats->null_count());
EXPECT_EQ(num_values - null_count, stats->num_values());
EXPECT_TRUE(expected_stats->HasMinMax());
EXPECT_EQ(expected_stats->EncodeMin(), stats->EncodeMin());
EXPECT_EQ(expected_stats->EncodeMax(), stats->EncodeMax());
std::shared_ptr<EncodedStatistics> enc_stats = column_chunk->encoded_statistics();
EXPECT_EQ(null_count, enc_stats->null_count);
EXPECT_TRUE(enc_stats->has_min);
EXPECT_TRUE(enc_stats->has_max);
EXPECT_EQ(expected_stats->EncodeMin(), enc_stats->min());
EXPECT_EQ(expected_stats->EncodeMax(), enc_stats->max());
EXPECT_EQ(enc_stats->is_min_value_exact, std::make_optional(true));
EXPECT_EQ(enc_stats->is_max_value_exact, std::make_optional(true));
}
};
template <typename TestType>
typename TestType::c_type* TestStatistics<TestType>::GetValuesPointer(
std::vector<typename TestType::c_type>& values) {
return values.data();
}
template <>
bool* TestStatistics<BooleanType>::GetValuesPointer(std::vector<bool>& values) {
static std::vector<uint8_t> bool_buffer;
bool_buffer.clear();
bool_buffer.resize(values.size());
std::copy(values.begin(), values.end(), bool_buffer.begin());
return reinterpret_cast<bool*>(bool_buffer.data());
}
template <typename TestType>
typename std::vector<typename TestType::c_type> TestStatistics<TestType>::GetDeepCopy(
const std::vector<typename TestType::c_type>& values) {
return values;
}
template <>
std::vector<FLBA> TestStatistics<FLBAType>::GetDeepCopy(const std::vector<FLBA>& values) {
std::vector<FLBA> copy;
MemoryPool* pool = ::arrow::default_memory_pool();
for (const FLBA& flba : values) {
uint8_t* ptr;
PARQUET_THROW_NOT_OK(pool->Allocate(FLBA_LENGTH, &ptr));
memcpy(ptr, flba.ptr, FLBA_LENGTH);
copy.emplace_back(ptr);
}
return copy;
}
template <>
std::vector<ByteArray> TestStatistics<ByteArrayType>::GetDeepCopy(
const std::vector<ByteArray>& values) {
std::vector<ByteArray> copy;
MemoryPool* pool = default_memory_pool();
for (const ByteArray& ba : values) {
uint8_t* ptr;
PARQUET_THROW_NOT_OK(pool->Allocate(ba.len, &ptr));
SafeMemcpy(ptr, ba.ptr, ba.len);
copy.emplace_back(ba.len, ptr);
}
return copy;
}
template <typename TestType>
void TestStatistics<TestType>::DeepFree(std::vector<typename TestType::c_type>& values) {}
template <>
void TestStatistics<FLBAType>::DeepFree(std::vector<FLBA>& values) {
MemoryPool* pool = default_memory_pool();
for (FLBA& flba : values) {
auto ptr = const_cast<uint8_t*>(flba.ptr);
memset(ptr, 0, FLBA_LENGTH);
pool->Free(ptr, FLBA_LENGTH);
}
}
template <>
void TestStatistics<ByteArrayType>::DeepFree(std::vector<ByteArray>& values) {
MemoryPool* pool = default_memory_pool();
for (ByteArray& ba : values) {
auto ptr = const_cast<uint8_t*>(ba.ptr);
memset(ptr, 0, ba.len);
pool->Free(ptr, ba.len);
}
}
template <>
void TestStatistics<ByteArrayType>::TestMinMaxEncode() {
this->GenerateData(1000);
// Test that we encode min max strings correctly
auto statistics1 = MakeStatistics<ByteArrayType>(this->schema_.Column(0));
statistics1->Update(this->values_ptr_, this->values_.size(), 0);
std::string encoded_min = statistics1->EncodeMin();
std::string encoded_max = statistics1->EncodeMax();
// encoded is same as unencoded
ASSERT_EQ(encoded_min,
std::string(reinterpret_cast<const char*>(statistics1->min().ptr),
statistics1->min().len));
ASSERT_EQ(encoded_max,
std::string(reinterpret_cast<const char*>(statistics1->max().ptr),
statistics1->max().len));
auto statistics2 = MakeStatistics<ByteArrayType>(
this->schema_.Column(0), encoded_min, encoded_max, this->values_.size(),
/*null_count=*/0,
/*distinct_count=*/0, /*has_min_max=*/true, /*has_null_count=*/true,
/*has_distinct_count=*/true, /*is_min_value_exact=*/true,
/*is_max_value_exact=*/true);
ASSERT_EQ(encoded_min, statistics2->EncodeMin());
ASSERT_EQ(encoded_max, statistics2->EncodeMax());
ASSERT_EQ(statistics1->min(), statistics2->min());
ASSERT_EQ(statistics1->max(), statistics2->max());
}
using Types = ::testing::Types<Int32Type, Int64Type, FloatType, DoubleType, ByteArrayType,
FLBAType, BooleanType>;
TYPED_TEST_SUITE(TestStatistics, Types);
TYPED_TEST(TestStatistics, MinMaxEncode) {
this->SetUpSchema(Repetition::REQUIRED);
ASSERT_NO_FATAL_FAILURE(this->TestMinMaxEncode());
}
TYPED_TEST(TestStatistics, Reset) {
this->SetUpSchema(Repetition::OPTIONAL);
ASSERT_NO_FATAL_FAILURE(this->TestReset());
}
TYPED_TEST(TestStatistics, Equals) {
this->SetUpSchema(Repetition::OPTIONAL);
ASSERT_NO_FATAL_FAILURE(this->TestEquals());
}
TYPED_TEST(TestStatistics, FullRoundtrip) {
this->SetUpSchema(Repetition::OPTIONAL);
ASSERT_NO_FATAL_FAILURE(this->TestFullRoundtrip(100, 31));
ASSERT_NO_FATAL_FAILURE(this->TestFullRoundtrip(1000, 415));
ASSERT_NO_FATAL_FAILURE(this->TestFullRoundtrip(10000, 926));
}
template <typename TestType>
class TestNumericStatistics : public TestStatistics<TestType> {};
using NumericTypes = ::testing::Types<Int32Type, Int64Type, FloatType, DoubleType>;
TYPED_TEST_SUITE(TestNumericStatistics, NumericTypes);
TYPED_TEST(TestNumericStatistics, Merge) {
this->SetUpSchema(Repetition::OPTIONAL);
ASSERT_NO_FATAL_FAILURE(this->TestMerge());
}
TYPED_TEST(TestNumericStatistics, Equals) {
this->SetUpSchema(Repetition::OPTIONAL);
ASSERT_NO_FATAL_FAILURE(this->TestEquals());
}
template <typename TestType>
class TestStatisticsHasFlag : public TestStatistics<TestType> {
public:
void SetUp() override {
TestStatistics<TestType>::SetUp();
this->SetUpSchema(Repetition::OPTIONAL);
}
std::optional<int64_t> MergeDistinctCount(
std::optional<int64_t> initial,
const std::vector<std::optional<int64_t>>& subsequent) {
EncodedStatistics encoded_statistics;
if (initial) {
encoded_statistics.has_distinct_count = true;
encoded_statistics.distinct_count = *initial;
}
std::shared_ptr<TypedStatistics<TestType>> statistics =
std::dynamic_pointer_cast<TypedStatistics<TestType>>(
Statistics::Make(this->schema_.Column(0), &encoded_statistics,
/*num_values=*/1000));
for (const auto& distinct_count : subsequent) {
EncodedStatistics next_encoded_statistics;
if (distinct_count) {
next_encoded_statistics.has_distinct_count = true;
next_encoded_statistics.distinct_count = *distinct_count;
}
std::shared_ptr<TypedStatistics<TestType>> next_statistics =
std::dynamic_pointer_cast<TypedStatistics<TestType>>(
Statistics::Make(this->schema_.Column(0), &next_encoded_statistics,
/*num_values=*/1000));
statistics->Merge(*next_statistics);
}
EncodedStatistics final_statistics = statistics->Encode();
EXPECT_EQ(statistics->HasDistinctCount(), final_statistics.has_distinct_count);
if (statistics->HasDistinctCount()) {
EXPECT_EQ(statistics->distinct_count(), final_statistics.distinct_count);
return statistics->distinct_count();
}
return std::nullopt;
}
std::shared_ptr<TypedStatistics<TestType>> MergedStatistics(
const TypedStatistics<TestType>& stats1, const TypedStatistics<TestType>& stats2) {
auto chunk_statistics = MakeStatistics<TestType>(this->schema_.Column(0));
chunk_statistics->Merge(stats1);
chunk_statistics->Merge(stats2);
return chunk_statistics;
}
void VerifyMergedStatistics(
const TypedStatistics<TestType>& stats1, const TypedStatistics<TestType>& stats2,
const std::function<void(TypedStatistics<TestType>*)>& test_fn) {
ASSERT_NO_FATAL_FAILURE(test_fn(MergedStatistics(stats1, stats2).get()));
ASSERT_NO_FATAL_FAILURE(test_fn(MergedStatistics(stats2, stats1).get()));
}
// Distinct count should set to false when Merge is called, unless one of the statistics
// has a zero count.
void TestMergeDistinctCount() {
// Sanity tests.
ASSERT_EQ(std::nullopt, MergeDistinctCount(std::nullopt, {}));
ASSERT_EQ(10, MergeDistinctCount(10, {}));
ASSERT_EQ(std::nullopt, MergeDistinctCount(std::nullopt, {0}));
ASSERT_EQ(std::nullopt, MergeDistinctCount(std::nullopt, {10, 0}));
ASSERT_EQ(10, MergeDistinctCount(10, {0, 0}));
ASSERT_EQ(10, MergeDistinctCount(0, {10, 0}));
ASSERT_EQ(10, MergeDistinctCount(0, {0, 10}));
ASSERT_EQ(10, MergeDistinctCount(0, {0, 10, 0}));
ASSERT_EQ(std::nullopt, MergeDistinctCount(10, {0, 10}));
ASSERT_EQ(std::nullopt, MergeDistinctCount(10, {0, std::nullopt}));
ASSERT_EQ(std::nullopt, MergeDistinctCount(0, {std::nullopt, 0}));
}
// If all values in a page are null or nan, its stats should not set min-max.
// Merging its stats with another page having good min-max stats should not
// drop the valid min-max from the latter page.
void TestMergeMinMax() {
this->GenerateData(1000);
// Create a statistics object without min-max.
std::shared_ptr<TypedStatistics<TestType>> statistics1;
{
statistics1 = MakeStatistics<TestType>(this->schema_.Column(0));
statistics1->Update(this->values_ptr_, /*num_values=*/0,
/*null_count=*/this->values_.size());
auto encoded_stats1 = statistics1->Encode();
EXPECT_FALSE(statistics1->HasMinMax());
EXPECT_FALSE(encoded_stats1.has_min);
EXPECT_FALSE(encoded_stats1.has_max);
EXPECT_EQ(encoded_stats1.is_max_value_exact, std::nullopt);
EXPECT_EQ(encoded_stats1.is_min_value_exact, std::nullopt);
}
// Create a statistics object with min-max.
std::shared_ptr<TypedStatistics<TestType>> statistics2;
{
statistics2 = MakeStatistics<TestType>(this->schema_.Column(0));
statistics2->Update(this->values_ptr_, this->values_.size(), 0);
auto encoded_stats2 = statistics2->Encode();
EXPECT_TRUE(statistics2->HasMinMax());
EXPECT_TRUE(encoded_stats2.has_min);
EXPECT_TRUE(encoded_stats2.has_max);
EXPECT_EQ(encoded_stats2.is_min_value_exact, std::make_optional(true));
EXPECT_EQ(encoded_stats2.is_max_value_exact, std::make_optional(true));
}
VerifyMergedStatistics(*statistics1, *statistics2,
[](TypedStatistics<TestType>* merged_statistics) {
EXPECT_TRUE(merged_statistics->HasMinMax());
EXPECT_TRUE(merged_statistics->Encode().has_min);
EXPECT_TRUE(merged_statistics->Encode().has_max);
EXPECT_EQ(merged_statistics->Encode().is_min_value_exact,
std::make_optional(true));
EXPECT_EQ(merged_statistics->Encode().is_max_value_exact,
std::make_optional(true));
});
}
// Default statistics should have null_count even if no nulls is written.
// However, if statistics is created from thrift message, it might not
// have null_count. Merging statistics from such page will result in an
// invalid null_count as well.
void TestMergeNullCount() {
this->GenerateData(/*num_values=*/1000);
// Page should have null-count even if no nulls
std::shared_ptr<TypedStatistics<TestType>> statistics1;
{
statistics1 = MakeStatistics<TestType>(this->schema_.Column(0));
statistics1->Update(this->values_ptr_, /*num_values=*/this->values_.size(),
/*null_count=*/0);
auto encoded_stats1 = statistics1->Encode();
EXPECT_TRUE(statistics1->HasNullCount());
EXPECT_EQ(0, statistics1->null_count());
EXPECT_TRUE(statistics1->Encode().has_null_count);
}
// Merge with null-count should also have null count
VerifyMergedStatistics(*statistics1, *statistics1,
[](TypedStatistics<TestType>* merged_statistics) {
EXPECT_TRUE(merged_statistics->HasNullCount());
EXPECT_EQ(0, merged_statistics->null_count());
auto encoded = merged_statistics->Encode();
EXPECT_TRUE(encoded.has_null_count);
EXPECT_EQ(0, encoded.null_count);
});
// When loaded from thrift, might not have null count.
std::shared_ptr<TypedStatistics<TestType>> statistics2;
{
EncodedStatistics encoded_statistics2;
encoded_statistics2.has_null_count = false;
statistics2 = std::dynamic_pointer_cast<TypedStatistics<TestType>>(
Statistics::Make(this->schema_.Column(0), &encoded_statistics2,
/*num_values=*/1000));
EXPECT_FALSE(statistics2->Encode().has_null_count);
EXPECT_FALSE(statistics2->HasNullCount());
}
// Merge without null-count should not have null count
VerifyMergedStatistics(*statistics1, *statistics2,
[](TypedStatistics<TestType>* merged_statistics) {
EXPECT_FALSE(merged_statistics->HasNullCount());
EXPECT_FALSE(merged_statistics->Encode().has_null_count);
});
}
// statistics.all_null_value is used to build the page index.
// If statistics doesn't have null count, all_null_value should be false.
void TestMissingNullCount() {
EncodedStatistics encoded_statistics;
encoded_statistics.has_null_count = false;
auto statistics = Statistics::Make(this->schema_.Column(0), &encoded_statistics,
/*num_values=*/1000);
auto typed_stats = std::dynamic_pointer_cast<TypedStatistics<TestType>>(statistics);
EXPECT_FALSE(typed_stats->HasNullCount());
auto encoded = typed_stats->Encode();
EXPECT_FALSE(encoded.all_null_value);
EXPECT_FALSE(encoded.has_null_count);
EXPECT_FALSE(encoded.has_distinct_count);
EXPECT_FALSE(encoded.has_min);
EXPECT_FALSE(encoded.has_max);
EXPECT_FALSE(encoded.is_min_value_exact.has_value());
EXPECT_FALSE(encoded.is_max_value_exact.has_value());
}
};
TYPED_TEST_SUITE(TestStatisticsHasFlag, Types);
TYPED_TEST(TestStatisticsHasFlag, MergeDistinctCount) {
ASSERT_NO_FATAL_FAILURE(this->TestMergeDistinctCount());
}
TYPED_TEST(TestStatisticsHasFlag, MergeNullCount) {
ASSERT_NO_FATAL_FAILURE(this->TestMergeNullCount());
}
TYPED_TEST(TestStatisticsHasFlag, MergeMinMax) {
ASSERT_NO_FATAL_FAILURE(this->TestMergeMinMax());
}
TYPED_TEST(TestStatisticsHasFlag, MissingNullCount) {
ASSERT_NO_FATAL_FAILURE(this->TestMissingNullCount());
}
// Helper for basic statistics tests below
void AssertStatsSet(const ApplicationVersion& version,
std::shared_ptr<parquet::WriterProperties> props,
const ColumnDescriptor* column, bool expected_is_set) {
auto metadata_builder = ColumnChunkMetaDataBuilder::Make(props, column);
auto column_chunk = ColumnChunkMetaData::Make(metadata_builder->contents(), column,
default_reader_properties(), &version);
EncodedStatistics stats;
stats.set_is_signed(false);
metadata_builder->SetStatistics(stats);
ASSERT_EQ(column_chunk->is_stats_set(), expected_is_set);
if (expected_is_set) {
ASSERT_TRUE(column_chunk->encoded_statistics() != nullptr);
} else {
ASSERT_TRUE(column_chunk->encoded_statistics() == nullptr);
}
}
// Statistics are restricted for few types in older parquet version
TEST(CorruptStatistics, Basics) {
std::string created_by = "parquet-mr version 1.8.0";
ApplicationVersion version(created_by);
SchemaDescriptor schema;
schema::NodePtr node;
std::vector<schema::NodePtr> fields;
// Test Physical Types
fields.push_back(schema::PrimitiveNode::Make("col1", Repetition::OPTIONAL, Type::INT32,
ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("col2", Repetition::OPTIONAL,
Type::BYTE_ARRAY, ConvertedType::NONE));
// Test Logical Types
fields.push_back(schema::PrimitiveNode::Make("col3", Repetition::OPTIONAL, Type::INT32,
ConvertedType::DATE));
fields.push_back(schema::PrimitiveNode::Make("col4", Repetition::OPTIONAL, Type::INT32,
ConvertedType::UINT_32));
fields.push_back(schema::PrimitiveNode::Make("col5", Repetition::OPTIONAL,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::INTERVAL, 12));
fields.push_back(schema::PrimitiveNode::Make("col6", Repetition::OPTIONAL,
Type::BYTE_ARRAY, ConvertedType::UTF8));
node = schema::GroupNode::Make("schema", Repetition::REQUIRED, fields);
schema.Init(node);
parquet::WriterProperties::Builder builder;
builder.created_by(created_by);
std::shared_ptr<parquet::WriterProperties> props = builder.build();
AssertStatsSet(version, props, schema.Column(0), true);
AssertStatsSet(version, props, schema.Column(1), false);
AssertStatsSet(version, props, schema.Column(2), true);
AssertStatsSet(version, props, schema.Column(3), false);
AssertStatsSet(version, props, schema.Column(4), false);
AssertStatsSet(version, props, schema.Column(5), false);
}
// Statistics for all types have no restrictions in newer parquet version
TEST(CorrectStatistics, Basics) {
std::string created_by = "parquet-cpp version 1.3.0";
ApplicationVersion version(created_by);
SchemaDescriptor schema;
schema::NodePtr node;
std::vector<schema::NodePtr> fields;
// Test Physical Types
fields.push_back(schema::PrimitiveNode::Make("col1", Repetition::OPTIONAL, Type::INT32,
ConvertedType::NONE));
fields.push_back(schema::PrimitiveNode::Make("col2", Repetition::OPTIONAL,
Type::BYTE_ARRAY, ConvertedType::NONE));
// Test Logical Types
fields.push_back(schema::PrimitiveNode::Make("col3", Repetition::OPTIONAL, Type::INT32,
ConvertedType::DATE));
fields.push_back(schema::PrimitiveNode::Make("col4", Repetition::OPTIONAL, Type::INT32,
ConvertedType::UINT_32));
fields.push_back(schema::PrimitiveNode::Make("col5", Repetition::OPTIONAL,
Type::FIXED_LEN_BYTE_ARRAY,
ConvertedType::INTERVAL, 12));
fields.push_back(schema::PrimitiveNode::Make("col6", Repetition::OPTIONAL,
Type::BYTE_ARRAY, ConvertedType::UTF8));
node = schema::GroupNode::Make("schema", Repetition::REQUIRED, fields);
schema.Init(node);
parquet::WriterProperties::Builder builder;
builder.created_by(created_by);
std::shared_ptr<parquet::WriterProperties> props = builder.build();
AssertStatsSet(version, props, schema.Column(0), true);
AssertStatsSet(version, props, schema.Column(1), true);
AssertStatsSet(version, props, schema.Column(2), true);
AssertStatsSet(version, props, schema.Column(3), true);
AssertStatsSet(version, props, schema.Column(4), true);
AssertStatsSet(version, props, schema.Column(5), true);
}
// Test SortOrder class
static const int NUM_VALUES = 10;
template <typename T>
struct RebindLogical {
using ParquetType = T;
using CType = typename T::c_type;
};
template <>
struct RebindLogical<Float16LogicalType> {
using ParquetType = FLBAType;
using CType = ParquetType::c_type;
};
template <typename T>
class TestStatisticsSortOrder : public ::testing::Test {
public:
using TestType = typename RebindLogical<T>::ParquetType;
using c_type = typename TestType::c_type;
void SetUp() override {
#ifndef ARROW_WITH_SNAPPY
GTEST_SKIP() << "Test requires Snappy compression";
#endif
}
void AddNodes(std::string name) {
fields_.push_back(schema::PrimitiveNode::Make(
name, Repetition::REQUIRED, TestType::type_num, ConvertedType::NONE));
}
void SetUpSchema() {
stats_.resize(fields_.size());
values_.resize(NUM_VALUES);
schema_ = std::static_pointer_cast<GroupNode>(
GroupNode::Make("Schema", Repetition::REQUIRED, fields_));
parquet_sink_ = CreateOutputStream();
}
void SetValues();
void WriteParquet() {
// Add writer properties
parquet::WriterProperties::Builder builder;
builder.compression(parquet::Compression::SNAPPY);
builder.created_by("parquet-cpp version 1.3.0");
std::shared_ptr<parquet::WriterProperties> props = builder.build();
// Create a ParquetFileWriter instance
auto file_writer = parquet::ParquetFileWriter::Open(parquet_sink_, schema_, props);
// Append a RowGroup with a specific number of rows.
auto rg_writer = file_writer->AppendRowGroup();
this->SetValues();
// Insert Values
for (int i = 0; i < static_cast<int>(fields_.size()); i++) {
auto column_writer =
static_cast<parquet::TypedColumnWriter<TestType>*>(rg_writer->NextColumn());
column_writer->WriteBatch(NUM_VALUES, nullptr, nullptr, values_.data());
}
}
void VerifyParquetStats() {
ASSERT_OK_AND_ASSIGN(auto pbuffer, parquet_sink_->Finish());
// Create a ParquetReader instance
std::unique_ptr<parquet::ParquetFileReader> parquet_reader =
parquet::ParquetFileReader::Open(
std::make_shared<::arrow::io::BufferReader>(pbuffer));
// Get the File MetaData
std::shared_ptr<parquet::FileMetaData> file_metadata = parquet_reader->metadata();
std::shared_ptr<parquet::RowGroupMetaData> rg_metadata = file_metadata->RowGroup(0);
for (int i = 0; i < static_cast<int>(fields_.size()); i++) {