-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathencoding_test.cc
More file actions
2688 lines (2267 loc) · 106 KB
/
encoding_test.cc
File metadata and controls
2688 lines (2267 loc) · 106 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 <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <span>
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/array/builder_binary.h"
#include "arrow/array/builder_dict.h"
#include "arrow/array/concatenate.h"
#include "arrow/compute/cast.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/testing/util.h"
#include "arrow/type.h"
#include "arrow/type_fwd.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_writer.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/endian.h"
#include "arrow/util/string.h"
#include "parquet/encoding.h"
#include "parquet/platform.h"
#include "parquet/schema.h"
#include "parquet/test_util.h"
#include "parquet/types.h"
using arrow::default_memory_pool;
using arrow::MemoryPool;
using arrow::internal::checked_cast;
namespace bit_util = arrow::bit_util;
namespace parquet::test {
// Validate that `func` succeeds on supported (Type, Encoding) combinations, and
// raises on unsupported ones.
void TestSupportedEncodingsConsistentWith(
std::function<void(Type::type, Encoding::type, const ColumnDescriptor&)> func) {
// Try all possible types and encodings
for (int int_type = 0; int_type < static_cast<int>(Type::UNDEFINED); ++int_type) {
const auto type = static_cast<Type::type>(int_type);
const auto supported_encodings = SupportedEncodings(type);
ARROW_SCOPED_TRACE("Type = ", TypeToString(type));
const auto descr =
ColumnDescriptor(schema::PrimitiveNode::Make("col", Repetition::REQUIRED, type,
ConvertedType::NONE, /*length=*/2),
/*max_definition_level=*/0, /*max_repetition_level=*/0);
for (int int_encoding = 0; int_encoding < static_cast<int>(Encoding::UNDEFINED);
++int_encoding) {
const auto encoding = static_cast<Encoding::type>(int_encoding);
ARROW_SCOPED_TRACE("Encoding = ", EncodingToString(encoding));
if (std::find(supported_encodings.begin(), supported_encodings.end(), encoding) !=
supported_encodings.end()) {
ASSERT_NO_THROW(func(type, encoding, descr));
} else {
ASSERT_THROW(func(type, encoding, descr), ParquetException);
}
}
}
}
TEST(SupportedEncodings, TestMakeDecoder) {
auto make_decoder = [](Type::type type, Encoding::type encoding,
const ColumnDescriptor& descr) {
ARROW_UNUSED(MakeDecoder(type, encoding, &descr));
};
TestSupportedEncodingsConsistentWith(make_decoder);
}
TEST(SupportedEncodings, TestMakeEncoder) {
auto make_encoder = [](Type::type type, Encoding::type encoding,
const ColumnDescriptor& descr) {
ARROW_UNUSED(MakeEncoder(type, encoding, /*use_dictionary=*/false, &descr));
};
TestSupportedEncodingsConsistentWith(make_encoder);
}
TEST(VectorBooleanTest, TestEncodeBoolDecode) {
// PARQUET-454
const int nvalues = 10000;
bool decode_buffer[nvalues] = {false};
int nbytes = static_cast<int>(bit_util::BytesForBits(nvalues));
std::vector<bool> draws;
::arrow::random_is_valid(nvalues, 0.5 /* null prob */, &draws, 0 /* seed */);
std::unique_ptr<BooleanEncoder> encoder =
MakeTypedEncoder<BooleanType>(Encoding::PLAIN);
encoder->Put(draws, nvalues);
std::unique_ptr<BooleanDecoder> decoder =
MakeTypedDecoder<BooleanType>(Encoding::PLAIN);
std::shared_ptr<Buffer> encode_buffer = encoder->FlushValues();
ASSERT_EQ(nbytes, encode_buffer->size());
decoder->SetData(nvalues, encode_buffer->data(),
static_cast<int>(encode_buffer->size()));
int values_decoded = decoder->Decode(&decode_buffer[0], nvalues);
ASSERT_EQ(nvalues, values_decoded);
for (int i = 0; i < nvalues; ++i) {
ASSERT_EQ(draws[i], decode_buffer[i]);
}
}
TEST(VectorBooleanTest, TestEncodeIntDecode) {
// PARQUET-454
int nvalues = 10000;
int nbytes = static_cast<int>(bit_util::BytesForBits(nvalues));
std::vector<bool> draws;
::arrow::random_is_valid(nvalues, 0.5 /* null prob */, &draws, 0 /* seed */);
std::unique_ptr<BooleanEncoder> encoder =
MakeTypedEncoder<BooleanType>(Encoding::PLAIN);
encoder->Put(draws, nvalues);
std::unique_ptr<BooleanDecoder> decoder =
MakeTypedDecoder<BooleanType>(Encoding::PLAIN);
std::shared_ptr<Buffer> encode_buffer = encoder->FlushValues();
ASSERT_EQ(nbytes, encode_buffer->size());
std::vector<uint8_t> decode_buffer(nbytes);
const uint8_t* decode_data = &decode_buffer[0];
decoder->SetData(nvalues, encode_buffer->data(),
static_cast<int>(encode_buffer->size()));
int values_decoded = decoder->Decode(&decode_buffer[0], nvalues);
ASSERT_EQ(nvalues, values_decoded);
for (int i = 0; i < nvalues; ++i) {
ASSERT_EQ(draws[i], ::arrow::bit_util::GetBit(decode_data, i)) << i;
}
}
template <typename T>
void VerifyResults(const T* result, const T* expected, int num_values) {
for (int i = 0; i < num_values; ++i) {
ASSERT_EQ(expected[i], result[i]) << i;
}
}
template <typename T>
void VerifyResultsSpaced(const T* result, const T* expected, int num_values,
const uint8_t* valid_bits, int64_t valid_bits_offset) {
for (auto i = 0; i < num_values; ++i) {
if (bit_util::GetBit(valid_bits, valid_bits_offset + i)) {
ASSERT_EQ(expected[i], result[i]) << i;
}
}
}
template <>
void VerifyResults<FLBA>(const FLBA* result, const FLBA* expected, int num_values) {
for (int i = 0; i < num_values; ++i) {
ASSERT_EQ(0, memcmp(expected[i].ptr, result[i].ptr, kGenerateDataFLBALength)) << i;
}
}
template <>
void VerifyResultsSpaced<FLBA>(const FLBA* result, const FLBA* expected, int num_values,
const uint8_t* valid_bits, int64_t valid_bits_offset) {
for (auto i = 0; i < num_values; ++i) {
if (bit_util::GetBit(valid_bits, valid_bits_offset + i)) {
ASSERT_EQ(0, memcmp(expected[i].ptr, result[i].ptr, kGenerateDataFLBALength)) << i;
}
}
}
// ----------------------------------------------------------------------
// Create some column descriptors
template <typename DType>
std::shared_ptr<ColumnDescriptor> ExampleDescr() {
auto node = schema::PrimitiveNode::Make("name", Repetition::OPTIONAL, DType::type_num);
return std::make_shared<ColumnDescriptor>(node, 0, 0);
}
template <>
std::shared_ptr<ColumnDescriptor> ExampleDescr<FLBAType>() {
auto node = schema::PrimitiveNode::Make(
"name", Repetition::OPTIONAL, Type::FIXED_LEN_BYTE_ARRAY, ConvertedType::DECIMAL,
kGenerateDataFLBALength, 10, 2);
return std::make_shared<ColumnDescriptor>(node, 0, 0);
}
// ----------------------------------------------------------------------
// Plain encoding tests
template <typename Type>
class TestEncodingBase : public ::testing::Test {
public:
using c_type = typename Type::c_type;
static constexpr int TYPE = Type::type_num;
void SetUp() {
descr_ = ExampleDescr<Type>();
type_length_ = descr_->type_length();
unencoded_byte_array_data_bytes_ = 0;
allocator_ = default_memory_pool();
}
void TearDown() {}
virtual void InitData(int nvalues, int repeats) {
num_values_ = nvalues * repeats;
input_bytes_.resize(num_values_ * sizeof(c_type));
output_bytes_.resize(num_values_ * sizeof(c_type));
draws_ = reinterpret_cast<c_type*>(input_bytes_.data());
decode_buf_ = reinterpret_cast<c_type*>(output_bytes_.data());
GenerateData<c_type>(nvalues, draws_, &data_buffer_);
// add some repeated values
for (int j = 1; j < repeats; ++j) {
for (int i = 0; i < nvalues; ++i) {
draws_[nvalues * j + i] = draws_[i];
}
}
InitUnencodedByteArrayDataBytes();
}
virtual void CheckRoundtrip() = 0;
virtual void CheckRoundtripSpaced(const uint8_t* valid_bits,
int64_t valid_bits_offset) {}
void Execute(int nvalues, int repeats) {
InitData(nvalues, repeats);
CheckRoundtrip();
}
void ExecuteSpaced(int nvalues, int repeats, int64_t valid_bits_offset,
double null_probability) {
InitData(nvalues, repeats);
int64_t size = num_values_ + valid_bits_offset;
auto rand = ::arrow::random::RandomArrayGenerator(1923);
const auto array = rand.UInt8(size, 0, 100, null_probability);
const auto valid_bits = array->null_bitmap_data();
if (valid_bits) {
CheckRoundtripSpaced(valid_bits, valid_bits_offset);
}
}
void InitUnencodedByteArrayDataBytes() {
// Calculate expected unencoded bytes based on type
if constexpr (std::is_same_v<Type, ByteArrayType>) {
unencoded_byte_array_data_bytes_ = 0;
for (int i = 0; i < num_values_; i++) {
unencoded_byte_array_data_bytes_ += draws_[i].len;
}
}
}
protected:
MemoryPool* allocator_;
int num_values_;
int type_length_;
c_type* draws_;
c_type* decode_buf_;
std::vector<uint8_t> input_bytes_;
std::vector<uint8_t> output_bytes_;
std::vector<uint8_t> data_buffer_;
std::shared_ptr<Buffer> encode_buffer_;
std::shared_ptr<ColumnDescriptor> descr_;
int64_t unencoded_byte_array_data_bytes_; // unencoded data size for dense values
};
// Member variables are not visible to templated subclasses. Possibly figure
// out an alternative to this class layering at some point
#define USING_BASE_MEMBERS() \
using TestEncodingBase<Type>::allocator_; \
using TestEncodingBase<Type>::descr_; \
using TestEncodingBase<Type>::num_values_; \
using TestEncodingBase<Type>::draws_; \
using TestEncodingBase<Type>::data_buffer_; \
using TestEncodingBase<Type>::type_length_; \
using TestEncodingBase<Type>::encode_buffer_; \
using TestEncodingBase<Type>::decode_buf_;
template <typename Type>
class TestPlainEncoding : public TestEncodingBase<Type> {
public:
using c_type = typename Type::c_type;
static constexpr int TYPE = Type::type_num;
virtual void CheckRoundtrip() {
auto encoder =
MakeTypedEncoder<Type>(Encoding::PLAIN, /*use_dictionary=*/false, descr_.get());
auto decoder = MakeTypedDecoder<Type>(Encoding::PLAIN, descr_.get());
encoder->Put(draws_, num_values_);
encode_buffer_ = encoder->FlushValues();
if constexpr (std::is_same_v<Type, ByteArrayType>) {
ASSERT_EQ(encoder->ReportUnencodedDataBytes(),
this->unencoded_byte_array_data_bytes_);
}
decoder->SetData(num_values_, encode_buffer_->data(),
static_cast<int>(encode_buffer_->size()));
int values_decoded = decoder->Decode(decode_buf_, num_values_);
ASSERT_EQ(num_values_, values_decoded);
ASSERT_NO_FATAL_FAILURE(VerifyResults<c_type>(decode_buf_, draws_, num_values_));
}
void CheckRoundtripSpaced(const uint8_t* valid_bits, int64_t valid_bits_offset) {
auto encoder =
MakeTypedEncoder<Type>(Encoding::PLAIN, /*use_dictionary=*/false, descr_.get());
auto decoder = MakeTypedDecoder<Type>(Encoding::PLAIN, descr_.get());
int null_count = 0;
for (auto i = 0; i < num_values_; i++) {
if (!bit_util::GetBit(valid_bits, valid_bits_offset + i)) {
null_count++;
}
}
encoder->PutSpaced(draws_, num_values_, valid_bits, valid_bits_offset);
encode_buffer_ = encoder->FlushValues();
decoder->SetData(num_values_ - null_count, encode_buffer_->data(),
static_cast<int>(encode_buffer_->size()));
auto values_decoded = decoder->DecodeSpaced(decode_buf_, num_values_, null_count,
valid_bits, valid_bits_offset);
ASSERT_EQ(num_values_, values_decoded);
ASSERT_NO_FATAL_FAILURE(VerifyResultsSpaced<c_type>(decode_buf_, draws_, num_values_,
valid_bits, valid_bits_offset));
}
protected:
USING_BASE_MEMBERS();
};
TYPED_TEST_SUITE(TestPlainEncoding, ParquetTypes);
TYPED_TEST(TestPlainEncoding, BasicRoundTrip) {
ASSERT_NO_FATAL_FAILURE(this->Execute(10000, 1));
// Spaced test with different sizes and offset to guarantee SIMD implementation
constexpr int kAvx512Size = 64; // sizeof(__m512i) for Avx512
constexpr int kSimdSize = kAvx512Size; // Current the max is Avx512
constexpr int kMultiSimdSize = kSimdSize * 33;
for (auto null_prob : {0.001, 0.1, 0.5, 0.9, 0.999}) {
// Test with both size and offset up to 3 Simd block
for (auto i = 1; i < kSimdSize * 3; i++) {
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(i, 1, 0, null_prob));
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(i, 1, i + 1, null_prob));
}
// Large block and offset
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(kMultiSimdSize, 1, 0, null_prob));
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(kMultiSimdSize + 33, 1, 0, null_prob));
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(kMultiSimdSize, 1, 33, null_prob));
ASSERT_NO_FATAL_FAILURE(this->ExecuteSpaced(kMultiSimdSize + 33, 1, 33, null_prob));
}
}
// ----------------------------------------------------------------------
// Dictionary encoding tests
typedef ::testing::Types<Int32Type, Int64Type, Int96Type, FloatType, DoubleType,
ByteArrayType, FLBAType>
DictEncodedTypes;
template <typename Type>
class TestDictionaryEncoding : public TestEncodingBase<Type> {
public:
using c_type = typename Type::c_type;
static constexpr int TYPE = Type::type_num;
void CheckRoundtrip() {
std::vector<uint8_t> valid_bits(::arrow::bit_util::BytesForBits(num_values_) + 1,
255);
auto base_encoder = MakeEncoder(Type::type_num, Encoding::PLAIN, true, descr_.get());
auto encoder =
dynamic_cast<typename EncodingTraits<Type>::Encoder*>(base_encoder.get());
auto dict_traits = dynamic_cast<DictEncoder<Type>*>(base_encoder.get());
ASSERT_NO_THROW(encoder->Put(draws_, num_values_));
dict_buffer_ =
AllocateBuffer(default_memory_pool(), dict_traits->dict_encoded_size());
dict_traits->WriteDict(dict_buffer_->mutable_data());
std::shared_ptr<Buffer> indices = encoder->FlushValues();
if constexpr (std::is_same_v<Type, ByteArrayType>) {
ASSERT_EQ(encoder->ReportUnencodedDataBytes(),
this->unencoded_byte_array_data_bytes_);
}
auto base_spaced_encoder =
MakeEncoder(Type::type_num, Encoding::PLAIN, true, descr_.get());
auto spaced_encoder =
dynamic_cast<typename EncodingTraits<Type>::Encoder*>(base_spaced_encoder.get());
// PutSpaced should lead to the same results
// This also checks the PutSpaced implementation for valid_bits=nullptr
ASSERT_NO_THROW(spaced_encoder->PutSpaced(draws_, num_values_, nullptr, 0));
std::shared_ptr<Buffer> indices_from_spaced = spaced_encoder->FlushValues();
ASSERT_TRUE(indices_from_spaced->Equals(*indices));
auto dict_decoder = MakeTypedDecoder<Type>(Encoding::PLAIN, descr_.get());
dict_decoder->SetData(dict_traits->num_entries(), dict_buffer_->data(),
static_cast<int>(dict_buffer_->size()));
auto decoder = MakeDictDecoder<Type>(descr_.get());
decoder->SetDict(dict_decoder.get());
decoder->SetData(num_values_, indices->data(), static_cast<int>(indices->size()));
int values_decoded = decoder->Decode(decode_buf_, num_values_);
ASSERT_EQ(num_values_, values_decoded);
// TODO(wesm): The DictionaryDecoder must stay alive because the decoded
// values' data is owned by a buffer inside the DictionaryEncoder. We
// should revisit when data lifetime is reviewed more generally.
ASSERT_NO_FATAL_FAILURE(VerifyResults<c_type>(decode_buf_, draws_, num_values_));
// Also test spaced decoding
decoder->SetData(num_values_, indices->data(), static_cast<int>(indices->size()));
// Also tests DecodeSpaced handling for valid_bits=nullptr
values_decoded = decoder->DecodeSpaced(decode_buf_, num_values_, 0, nullptr, 0);
ASSERT_EQ(num_values_, values_decoded);
ASSERT_NO_FATAL_FAILURE(VerifyResults<c_type>(decode_buf_, draws_, num_values_));
}
protected:
USING_BASE_MEMBERS();
std::shared_ptr<ResizableBuffer> dict_buffer_;
};
TYPED_TEST_SUITE(TestDictionaryEncoding, DictEncodedTypes);
TYPED_TEST(TestDictionaryEncoding, BasicRoundTrip) {
ASSERT_NO_FATAL_FAILURE(this->Execute(2500, 2));
}
// Round trip a dictionary encoded boolean column. The dictionary holds two
// booleans, the index stream picks each by position, and the result is read
// back through both the bool buffer and the bit packed uint8_t buffer.
TEST(TestDictionaryEncoding, DictDecodesBoolean) {
const uint8_t dict_bytes[] = {0x02};
auto dict_plain_decoder = MakeTypedDecoder<BooleanType>(Encoding::PLAIN);
dict_plain_decoder->SetData(2, dict_bytes, 1);
auto decoder = MakeDictDecoder<BooleanType>();
decoder->SetDict(dict_plain_decoder.get());
const uint8_t indices[] = {0x01, 0x03, 0x35};
decoder->SetData(8, indices, sizeof(indices));
bool out_bool[8] = {};
ASSERT_EQ(8, decoder->Decode(out_bool, 8));
const bool expected[8] = {true, false, true, false, true, true, false, false};
for (int i = 0; i < 8; ++i) {
EXPECT_EQ(expected[i], out_bool[i]) << " at index " << i;
}
decoder->SetData(8, indices, sizeof(indices));
uint8_t out_packed = 0;
auto* bool_dec = dynamic_cast<BooleanDecoder*>(decoder.get());
ASSERT_NE(bool_dec, nullptr);
ASSERT_EQ(8, bool_dec->Decode(&out_packed, 8));
EXPECT_EQ(0x35, out_packed);
}
// ----------------------------------------------------------------------
// Shared arrow builder decode tests
std::vector<std::shared_ptr<::arrow::DataType>> binary_like_types_for_dense_decoding() {
return {::arrow::binary(), ::arrow::large_binary(), ::arrow::binary_view(),
::arrow::utf8(), ::arrow::large_utf8(), ::arrow::utf8_view()};
}
std::vector<std::shared_ptr<::arrow::DataType>> binary_like_types_for_dict_decoding() {
return {::arrow::binary()};
}
class TestArrowBuilderDecoding : public ::testing::Test {
public:
using DictBuilder = ::arrow::BinaryDictionary32Builder;
void SetUp() override { null_probabilities_ = {0.0, 0.5, 1.0}; }
void TearDown() override {}
void InitTestCase(const std::shared_ptr<::arrow::DataType>& dense_type,
double null_probability, bool create_dict) {
GenerateInputData(dense_type, null_probability, create_dict);
SetupEncoderDecoder();
}
void GenerateInputData(const std::shared_ptr<::arrow::DataType>& dense_type,
double null_probability, bool create_dict) {
constexpr int num_unique = 100;
constexpr int repeat = 100;
constexpr int64_t min_length = 2;
constexpr int64_t max_length = 10;
::arrow::random::RandomArrayGenerator rag(0);
binary_dense_ = rag.BinaryWithRepeats(repeat * num_unique, num_unique, min_length,
max_length, null_probability);
dense_type_ = dense_type;
ASSERT_OK_AND_ASSIGN(expected_dense_,
::arrow::compute::Cast(*binary_dense_, dense_type_));
num_values_ = static_cast<int>(binary_dense_->length());
null_count_ = static_cast<int>(binary_dense_->null_count());
valid_bits_ = binary_dense_->null_bitmap_data();
if (create_dict) {
auto builder = CreateDictBuilder();
ASSERT_OK(builder->AppendArray(*binary_dense_));
ASSERT_OK(builder->Finish(&expected_dict_));
}
// Initialize input_data_ for the encoder from the expected_array_ values
const auto& binary_array = checked_cast<const ::arrow::BinaryArray&>(*binary_dense_);
input_data_.resize(binary_array.length());
for (int64_t i = 0; i < binary_array.length(); ++i) {
input_data_[i] = binary_array.GetView(i);
}
}
std::unique_ptr<DictBuilder> CreateDictBuilder() {
EXPECT_EQ(dense_type_->id(), ::arrow::Type::BINARY)
<< "Only BINARY is supported for dictionary decoding";
return std::make_unique<DictBuilder>(default_memory_pool());
}
// Setup encoder/decoder pair for testing with
virtual void SetupEncoderDecoder() = 0;
void CheckDense(int actual_num_values, const ::arrow::Array& chunk) {
ASSERT_EQ(actual_num_values, num_values_ - null_count_);
ASSERT_OK(chunk.ValidateFull());
ASSERT_ARRAYS_EQUAL(chunk, *expected_dense_);
}
template <typename Builder>
void CheckDict(int actual_num_values, Builder& builder) {
ASSERT_EQ(actual_num_values, num_values_ - null_count_);
std::shared_ptr<::arrow::Array> actual;
ASSERT_OK(builder.Finish(&actual));
ASSERT_OK(actual->ValidateFull());
ASSERT_ARRAYS_EQUAL(*actual, *expected_dict_);
}
void CheckDecodeArrowUsingDenseBuilder() {
for (auto dense_type : binary_like_types_for_dense_decoding()) {
ARROW_SCOPED_TRACE("dense_type = ", *dense_type);
for (auto np : null_probabilities_) {
InitTestCase(dense_type, np, /*create_dict=*/false);
typename EncodingTraits<ByteArrayType>::Accumulator acc;
ASSERT_OK_AND_ASSIGN(acc.builder, ::arrow::MakeBuilder(dense_type_));
auto actual_num_values =
decoder_->DecodeArrow(num_values_, null_count_, valid_bits_, 0, &acc);
std::shared_ptr<::arrow::Array> chunk;
ASSERT_OK(acc.builder->Finish(&chunk));
CheckDense(actual_num_values, *chunk);
}
}
}
void CheckDecodeArrowUsingDictBuilder() {
for (auto dense_type : binary_like_types_for_dict_decoding()) {
ARROW_SCOPED_TRACE("dense_type = ", *dense_type);
for (auto np : null_probabilities_) {
InitTestCase(dense_type, np, /*create_dict=*/true);
auto builder = CreateDictBuilder();
auto actual_num_values = decoder_->DecodeArrow(num_values_, null_count_,
valid_bits_, 0, builder.get());
CheckDict(actual_num_values, *builder);
}
}
}
void CheckDecodeArrowNonNullUsingDenseBuilder() {
for (auto dense_type : binary_like_types_for_dense_decoding()) {
ARROW_SCOPED_TRACE("dense_type = ", *dense_type);
InitTestCase(dense_type, /*null_probability=*/0.0, /*create_dict=*/false);
typename EncodingTraits<ByteArrayType>::Accumulator acc;
ASSERT_OK_AND_ASSIGN(acc.builder, ::arrow::MakeBuilder(dense_type_));
auto actual_num_values = decoder_->DecodeArrowNonNull(num_values_, &acc);
std::shared_ptr<::arrow::Array> chunk;
ASSERT_OK(acc.builder->Finish(&chunk));
CheckDense(actual_num_values, *chunk);
}
}
void CheckDecodeArrowNonNullUsingDictBuilder() {
for (auto dense_type : binary_like_types_for_dict_decoding()) {
ARROW_SCOPED_TRACE("dense_type = ", *dense_type);
InitTestCase(dense_type, /*null_probability=*/0.0, /*create_dict=*/true);
auto builder = CreateDictBuilder();
auto actual_num_values = decoder_->DecodeArrowNonNull(num_values_, builder.get());
CheckDict(actual_num_values, *builder);
}
}
protected:
std::vector<double> null_probabilities_;
std::shared_ptr<::arrow::Array> binary_dense_;
std::shared_ptr<::arrow::DataType> dense_type_;
std::shared_ptr<::arrow::Array> expected_dict_;
std::shared_ptr<::arrow::Array> expected_dense_;
int num_values_;
int null_count_;
std::vector<ByteArray> input_data_;
const uint8_t* valid_bits_;
std::unique_ptr<ByteArrayEncoder> encoder_;
ByteArrayDecoder* decoder_;
std::unique_ptr<ByteArrayDecoder> plain_decoder_;
std::unique_ptr<DictDecoder<ByteArrayType>> dict_decoder_;
std::shared_ptr<Buffer> buffer_;
};
class PlainEncoding : public TestArrowBuilderDecoding {
public:
void SetupEncoderDecoder() override {
encoder_ = MakeTypedEncoder<ByteArrayType>(Encoding::PLAIN);
plain_decoder_ = MakeTypedDecoder<ByteArrayType>(Encoding::PLAIN);
decoder_ = plain_decoder_.get();
if (valid_bits_ != nullptr) {
ASSERT_NO_THROW(
encoder_->PutSpaced(input_data_.data(), num_values_, valid_bits_, 0));
} else {
ASSERT_NO_THROW(encoder_->Put(input_data_.data(), num_values_));
}
buffer_ = encoder_->FlushValues();
decoder_->SetData(num_values_, buffer_->data(), static_cast<int>(buffer_->size()));
}
};
TEST_F(PlainEncoding, CheckDecodeArrowUsingDenseBuilder) {
this->CheckDecodeArrowUsingDenseBuilder();
}
TEST_F(PlainEncoding, CheckDecodeArrowUsingDictBuilder) {
this->CheckDecodeArrowUsingDictBuilder();
}
TEST_F(PlainEncoding, CheckDecodeArrowNonNullDenseBuilder) {
this->CheckDecodeArrowNonNullUsingDenseBuilder();
}
TEST_F(PlainEncoding, CheckDecodeArrowNonNullDictBuilder) {
this->CheckDecodeArrowNonNullUsingDictBuilder();
}
TEST(PlainEncodingAdHoc, ArrowBinaryDirectPut) {
// Implemented as part of ARROW-3246
const int64_t size = 50;
const int32_t min_length = 0;
const int32_t max_length = 10;
const double null_probability = 0.25;
auto CheckSeed = [&](int seed) {
::arrow::random::RandomArrayGenerator rag(seed);
auto values = rag.String(size, min_length, max_length, null_probability);
auto encoder = MakeTypedEncoder<ByteArrayType>(Encoding::PLAIN);
auto decoder = MakeTypedDecoder<ByteArrayType>(Encoding::PLAIN);
ASSERT_NO_THROW(encoder->Put(*values));
// For Plain encoding, the estimated size should be at least the total byte size
auto& string_array = dynamic_cast<const ::arrow::StringArray&>(*values);
EXPECT_GE(encoder->EstimatedDataEncodedSize(), string_array.total_values_length())
<< "Estimated size should be at least the total byte size";
auto buf = encoder->FlushValues();
int num_values = static_cast<int>(values->length() - values->null_count());
decoder->SetData(num_values, buf->data(), static_cast<int>(buf->size()));
typename EncodingTraits<ByteArrayType>::Accumulator acc;
acc.builder = std::make_unique<::arrow::StringBuilder>();
ASSERT_EQ(num_values,
decoder->DecodeArrow(static_cast<int>(values->length()),
static_cast<int>(values->null_count()),
values->null_bitmap_data(), values->offset(), &acc));
std::shared_ptr<::arrow::Array> result;
ASSERT_OK(acc.builder->Finish(&result));
ASSERT_EQ(50, result->length());
::arrow::AssertArraysEqual(*values, *result);
};
for (auto seed : {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) {
CheckSeed(seed);
}
}
// Check that one can put several Arrow arrays into a given encoder
// and decode to the right values (see GH-36939)
TEST(BooleanArrayEncoding, AdHocRoundTrip) {
std::vector<std::shared_ptr<::arrow::Array>> arrays{
::arrow::ArrayFromJSON(::arrow::boolean(), R"([])"),
::arrow::ArrayFromJSON(::arrow::boolean(), R"([false, null, true])"),
::arrow::ArrayFromJSON(::arrow::boolean(), R"([null, null, null])"),
::arrow::ArrayFromJSON(::arrow::boolean(), R"([true, null, false])"),
};
for (auto encoding : {Encoding::PLAIN, Encoding::RLE}) {
auto encoder = MakeTypedEncoder<BooleanType>(encoding,
/*use_dictionary=*/false);
for (const auto& array : arrays) {
encoder->Put(*array);
}
auto buffer = encoder->FlushValues();
auto decoder = MakeTypedDecoder<BooleanType>(encoding);
EXPECT_OK_AND_ASSIGN(auto expected, ::arrow::Concatenate(arrays));
decoder->SetData(static_cast<int>(expected->length()), buffer->data(),
static_cast<int>(buffer->size()));
::arrow::BooleanBuilder builder;
ASSERT_EQ(static_cast<int>(expected->length() - expected->null_count()),
decoder->DecodeArrow(static_cast<int>(expected->length()),
static_cast<int>(expected->null_count()),
expected->null_bitmap_data(), 0, &builder));
std::shared_ptr<::arrow::Array> result;
ASSERT_OK(builder.Finish(&result));
ASSERT_EQ(expected->length(), result->length());
::arrow::AssertArraysEqual(*expected, *result, /*verbose=*/true);
}
}
class TestBooleanArrowDecoding : public ::testing::Test {
public:
// number of values including nulls
constexpr static int kNumValues = 10000;
void SetUp() override {
null_probabilities_ = {0.0, 0.001, 0.5, 0.999, 1.0};
read_batch_sizes_ = {1024, 4096, 10000};
true_probabilities_ = {0.0, 0.001, 0.5, 0.999, 1.0};
}
void TearDown() override {}
void InitTestCase(Encoding::type encoding, double null_probability,
double true_probability) {
GenerateInputData(null_probability, true_probability);
SetupEncoderDecoder(encoding);
}
void GenerateInputData(double null_probability, double true_probability) {
::arrow::random::RandomArrayGenerator rag(0);
expected_dense_ = rag.Boolean(kNumValues, true_probability, null_probability);
null_count_ = static_cast<int>(expected_dense_->null_count());
valid_bits_ = expected_dense_->null_bitmap_data();
// Initialize input_data_ for the encoder from the expected_array_ values
const auto& boolean_array =
checked_cast<const ::arrow::BooleanArray&>(*expected_dense_);
input_data_.resize(boolean_array.length());
for (int64_t i = 0; i < boolean_array.length(); ++i) {
input_data_[i] = boolean_array.Value(i);
}
}
// Setup encoder/decoder pair for testing with boolean encoding
void SetupEncoderDecoder(Encoding::type encoding) {
encoder_ = MakeTypedEncoder<BooleanType>(encoding);
decoder_ = MakeTypedDecoder<BooleanType>(encoding);
const auto* data_ptr = reinterpret_cast<const bool*>(input_data_.data());
if (valid_bits_ != nullptr) {
ASSERT_NO_THROW(encoder_->PutSpaced(data_ptr, kNumValues, valid_bits_, 0));
} else {
ASSERT_NO_THROW(encoder_->Put(data_ptr, kNumValues));
}
buffer_ = encoder_->FlushValues();
ResetTheDecoder();
}
void ResetTheDecoder() {
ASSERT_NE(nullptr, buffer_);
decoder_->SetData(kNumValues, buffer_->data(), static_cast<int>(buffer_->size()));
}
void CheckDense(int actual_num_values, const ::arrow::Array& chunk) {
ASSERT_EQ(actual_num_values, kNumValues - null_count_);
ASSERT_ARRAYS_EQUAL(chunk, *expected_dense_);
}
void CheckDecodeArrow(Encoding::type encoding) {
for (double np : null_probabilities_) {
for (double true_prob : true_probabilities_) {
InitTestCase(encoding, np, true_prob);
for (int read_batch_size : this->read_batch_sizes_) {
ResetTheDecoder();
int num_values_left = kNumValues;
::arrow::BooleanBuilder acc;
int actual_num_not_null_values = 0;
while (num_values_left > 0) {
int batch_size = std::min(num_values_left, read_batch_size);
ASSERT_NE(0, batch_size);
// Counting nulls
int64_t batch_null_count = 0;
if (null_count_ != 0) {
batch_null_count =
batch_size - ::arrow::internal::CountSetBits(
valid_bits_, kNumValues - num_values_left, batch_size);
}
int batch_num_values =
decoder_->DecodeArrow(batch_size, static_cast<int>(batch_null_count),
valid_bits_, kNumValues - num_values_left, &acc);
actual_num_not_null_values += batch_num_values;
num_values_left -= batch_size;
}
std::shared_ptr<::arrow::Array> chunk;
ASSERT_OK(acc.Finish(&chunk));
CheckDense(actual_num_not_null_values, *chunk);
}
}
}
}
void CheckDecodeArrowNonNull(Encoding::type encoding) {
// NonNull skips tests for null_prob != 0.
for (auto true_prob : true_probabilities_) {
InitTestCase(encoding, /*null_probability=*/0, true_prob);
for (int read_batch_size : this->read_batch_sizes_) {
// Resume the decoder
ResetTheDecoder();
::arrow::BooleanBuilder acc;
int actual_num_values = 0;
int num_values_left = kNumValues;
while (num_values_left > 0) {
int batch_size = std::min(num_values_left, read_batch_size);
int batch_num_values = decoder_->DecodeArrowNonNull(batch_size, &acc);
actual_num_values += batch_num_values;
num_values_left -= batch_num_values;
}
std::shared_ptr<::arrow::Array> chunk;
ASSERT_OK(acc.Finish(&chunk));
CheckDense(actual_num_values, *chunk);
}
}
}
protected:
std::vector<double> null_probabilities_;
std::vector<double> true_probabilities_;
std::vector<int> read_batch_sizes_;
std::shared_ptr<::arrow::Array> expected_dense_;
int null_count_{0};
std::vector<uint8_t> input_data_;
const uint8_t* valid_bits_ = NULLPTR;
std::unique_ptr<BooleanEncoder> encoder_;
std::unique_ptr<BooleanDecoder> decoder_;
std::shared_ptr<Buffer> buffer_;
};
TEST_F(TestBooleanArrowDecoding, CheckDecodeArrowUsingPlain) {
this->CheckDecodeArrow(Encoding::PLAIN);
}
TEST_F(TestBooleanArrowDecoding, CheckDecodeArrowNonNullPlain) {
this->CheckDecodeArrowNonNull(Encoding::PLAIN);
}
TEST_F(TestBooleanArrowDecoding, CheckDecodeArrowRle) {
this->CheckDecodeArrow(Encoding::RLE);
}
TEST_F(TestBooleanArrowDecoding, CheckDecodeArrowNonNullRle) {
this->CheckDecodeArrowNonNull(Encoding::RLE);
}
template <typename T>
void GetDictDecoder(DictEncoder<T>* encoder, int64_t num_values,
std::shared_ptr<Buffer>* out_values,
std::shared_ptr<Buffer>* out_dict, const ColumnDescriptor* descr,
std::unique_ptr<TypedDecoder<T>>* out_decoder) {
auto decoder = MakeDictDecoder<T>(descr);
auto buf = encoder->FlushValues();
auto dict_buf = AllocateBuffer(default_memory_pool(), encoder->dict_encoded_size());
encoder->WriteDict(dict_buf->mutable_data());
auto dict_decoder = MakeTypedDecoder<T>(Encoding::PLAIN, descr);
dict_decoder->SetData(encoder->num_entries(), dict_buf->data(),
static_cast<int>(dict_buf->size()));
decoder->SetData(static_cast<int>(num_values), buf->data(),
static_cast<int>(buf->size()));
decoder->SetDict(dict_decoder.get());
*out_values = buf;
*out_dict = dict_buf;
ASSERT_NE(decoder, nullptr);
auto released = dynamic_cast<TypedDecoder<T>*>(decoder.release());
ASSERT_NE(released, nullptr);
*out_decoder = std::unique_ptr<TypedDecoder<T>>(released);
}
template <typename ParquetType>
class EncodingAdHocTyped : public ::testing::Test {
public:
using ArrowType = typename EncodingTraits<ParquetType>::ArrowType;
using EncoderType = typename EncodingTraits<ParquetType>::Encoder;
using DecoderType = typename EncodingTraits<ParquetType>::Decoder;
using BuilderType = typename EncodingTraits<ParquetType>::Accumulator;
using DictBuilderType = typename EncodingTraits<ParquetType>::DictAccumulator;
static const ColumnDescriptor* column_descr() {
static auto column_descr = ExampleDescr<ParquetType>();
return column_descr.get();
}
std::shared_ptr<::arrow::Array> GetValues(int seed);
static std::shared_ptr<::arrow::DataType> arrow_type();
void Plain(int seed, int rounds = 1, int offset = 0) {
auto random_array = GetValues(seed)->Slice(offset);
auto encoder = MakeTypedEncoder<ParquetType>(
Encoding::PLAIN, /*use_dictionary=*/false, column_descr());
auto decoder = MakeTypedDecoder<ParquetType>(Encoding::PLAIN, column_descr());
for (int i = 0; i < rounds; ++i) {
ASSERT_NO_THROW(encoder->Put(*random_array));
}
std::shared_ptr<::arrow::Array> values;
if (rounds == 1) {
values = random_array;
} else {
::arrow::ArrayVector arrays(rounds, random_array);
EXPECT_OK_AND_ASSIGN(values,
::arrow::Concatenate(arrays, ::arrow::default_memory_pool()));
}
auto buf = encoder->FlushValues();
decoder->SetData(static_cast<int>(values->length()), buf->data(),
static_cast<int>(buf->size()));
BuilderType acc(arrow_type(), ::arrow::default_memory_pool());
ASSERT_EQ(static_cast<int>(values->length() - values->null_count()),
decoder->DecodeArrow(static_cast<int>(values->length()),
static_cast<int>(values->null_count()),
values->null_bitmap_data(), values->offset(), &acc));
std::shared_ptr<::arrow::Array> result;
ASSERT_OK(acc.Finish(&result));
ASSERT_OK(result->ValidateFull());
ASSERT_EQ(values->length(), result->length());
::arrow::AssertArraysEqual(*values, *result, /*verbose=*/true);
}
void ByteStreamSplit(int seed) {
if constexpr (!std::is_same_v<ParquetType, FloatType> &&
!std::is_same_v<ParquetType, DoubleType> &&
!std::is_same_v<ParquetType, Int32Type> &&
!std::is_same_v<ParquetType, Int64Type> &&
!std::is_same_v<ParquetType, FLBAType>) {
return;
}
auto values = GetValues(seed);
auto encoder = MakeTypedEncoder<ParquetType>(
Encoding::BYTE_STREAM_SPLIT, /*use_dictionary=*/false, column_descr());
auto decoder =
MakeTypedDecoder<ParquetType>(Encoding::BYTE_STREAM_SPLIT, column_descr());
ASSERT_NO_THROW(encoder->Put(*values));
auto buf = encoder->FlushValues();
int num_values = static_cast<int>(values->length() - values->null_count());
decoder->SetData(num_values, buf->data(), static_cast<int>(buf->size()));