forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_write_test.cc
More file actions
3275 lines (2726 loc) · 124 KB
/
read_write_test.cc
File metadata and controls
3275 lines (2726 loc) · 124 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 <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <numeric>
#include <ostream>
#include <string>
#include <unordered_set>
#include <flatbuffers/flatbuffers.h>
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include "arrow/array.h"
#include "arrow/array/builder_primitive.h"
#include "arrow/buffer_builder.h"
#include "arrow/io/file.h"
#include "arrow/io/memory.h"
#include "arrow/io/test_common.h"
#include "arrow/ipc/message.h"
#include "arrow/ipc/metadata_internal.h"
#include "arrow/ipc/reader.h"
#include "arrow/ipc/reader_internal.h"
#include "arrow/ipc/test_common.h"
#include "arrow/ipc/writer.h"
#include "arrow/record_batch.h"
#include "arrow/status.h"
#include "arrow/table.h"
#include "arrow/testing/extension_type.h"
#include "arrow/testing/future_util.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/testing/util.h"
#include "arrow/type_fwd.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/io_util.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/ubsan.h"
#include "generated/Message_generated.h" // IWYU pragma: keep
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::TemporaryDir;
namespace ipc {
using internal::FieldPosition;
using internal::IoRecordedRandomAccessFile;
using MetadataVector = std::vector<std::shared_ptr<KeyValueMetadata>>;
namespace test {
const std::vector<MetadataVersion> kMetadataVersions = {MetadataVersion::V4,
MetadataVersion::V5};
class TestMessage : public ::testing::TestWithParam<MetadataVersion> {
public:
void SetUp() {
version_ = GetParam();
fb_version_ = internal::MetadataVersionToFlatbuffer(version_);
options_ = IpcWriteOptions::Defaults();
options_.metadata_version = version_;
}
protected:
MetadataVersion version_;
flatbuf::MetadataVersion fb_version_;
IpcWriteOptions options_;
};
TEST(TestMessage, Equals) {
std::string metadata = "foo";
std::string body = "bar";
auto b1 = std::make_shared<Buffer>(metadata);
auto b2 = std::make_shared<Buffer>(metadata);
auto b3 = std::make_shared<Buffer>(body);
auto b4 = std::make_shared<Buffer>(body);
Message msg1(b1, b3);
Message msg2(b2, b4);
Message msg3(b1, nullptr);
Message msg4(b2, nullptr);
ASSERT_TRUE(msg1.Equals(msg2));
ASSERT_TRUE(msg3.Equals(msg4));
ASSERT_FALSE(msg1.Equals(msg3));
ASSERT_FALSE(msg3.Equals(msg1));
// same metadata as msg1, different body
Message msg5(b2, b1);
ASSERT_FALSE(msg1.Equals(msg5));
ASSERT_FALSE(msg5.Equals(msg1));
}
TEST_P(TestMessage, SerializeTo) {
const int64_t body_length = 64;
flatbuffers::FlatBufferBuilder fbb;
fbb.Finish(flatbuf::CreateMessage(fbb, fb_version_,
flatbuf::MessageHeader::MessageHeader_RecordBatch,
0 /* header */, body_length));
std::shared_ptr<Buffer> metadata;
ASSERT_OK_AND_ASSIGN(metadata, internal::WriteFlatbufferBuilder(fbb));
std::string body = "abcdef";
ASSERT_OK_AND_ASSIGN(std::unique_ptr<Message> message,
Message::Open(metadata, std::make_shared<Buffer>(body)));
auto CheckWithAlignment = [&](int32_t alignment) {
options_.alignment = alignment;
const int32_t prefix_size = 8;
int64_t output_length = 0;
ASSERT_OK_AND_ASSIGN(auto stream, io::BufferOutputStream::Create(1 << 10));
ASSERT_OK(message->SerializeTo(stream.get(), options_, &output_length));
ASSERT_EQ(bit_util::RoundUp(metadata->size() + prefix_size, alignment) + body_length,
output_length);
ASSERT_OK_AND_EQ(output_length, stream->Tell());
ASSERT_OK_AND_ASSIGN(auto buffer, stream->Finish());
// check whether length is written in little endian
auto buffer_ptr = buffer.get()->data();
ASSERT_EQ(output_length - body_length - prefix_size,
bit_util::FromLittleEndian(*(uint32_t*)(buffer_ptr + 4)));
};
CheckWithAlignment(8);
CheckWithAlignment(64);
}
TEST_P(TestMessage, SerializeCustomMetadata) {
std::vector<std::shared_ptr<KeyValueMetadata>> cases = {
nullptr, key_value_metadata({}, {}),
key_value_metadata({"foo", "bar"}, {"fizz", "buzz"})};
for (auto metadata : cases) {
std::shared_ptr<Buffer> serialized;
ASSERT_OK(internal::WriteRecordBatchMessage(
/*length=*/0, /*body_length=*/0, metadata,
/*nodes=*/{},
/*buffers=*/{}, /*variadic_counts=*/{}, options_, &serialized));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<Message> message,
Message::Open(serialized, /*body=*/nullptr));
if (metadata) {
ASSERT_TRUE(message->custom_metadata()->Equals(*metadata));
} else {
ASSERT_EQ(nullptr, message->custom_metadata());
}
}
}
void BuffersOverlapEquals(const Buffer& left, const Buffer& right) {
ASSERT_GT(left.size(), 0);
ASSERT_GT(right.size(), 0);
ASSERT_TRUE(left.Equals(right, std::min(left.size(), right.size())));
}
TEST_P(TestMessage, LegacyIpcBackwardsCompatibility) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK(MakeIntBatchSized(36, &batch));
auto RoundtripWithOptions = [&](std::shared_ptr<Buffer>* out_serialized,
std::unique_ptr<Message>* out) {
IpcPayload payload;
ASSERT_OK(GetRecordBatchPayload(*batch, options_, &payload));
ASSERT_OK_AND_ASSIGN(auto stream, io::BufferOutputStream::Create(1 << 20));
int32_t metadata_length = -1;
ASSERT_OK(WriteIpcPayload(payload, options_, stream.get(), &metadata_length));
ASSERT_OK_AND_ASSIGN(*out_serialized, stream->Finish());
io::BufferReader io_reader(*out_serialized);
ASSERT_OK(ReadMessage(&io_reader).Value(out));
};
std::shared_ptr<Buffer> serialized, legacy_serialized;
std::unique_ptr<Message> message, legacy_message;
RoundtripWithOptions(&serialized, &message);
// First 4 bytes 0xFFFFFFFF Continuation marker
ASSERT_EQ(-1, util::SafeLoadAs<int32_t>(serialized->data()));
options_.write_legacy_ipc_format = true;
RoundtripWithOptions(&legacy_serialized, &legacy_message);
// Check that the continuation marker is not written
ASSERT_NE(-1, util::SafeLoadAs<int32_t>(legacy_serialized->data()));
// Have to use the smaller size to exclude padding
BuffersOverlapEquals(*legacy_message->metadata(), *message->metadata());
ASSERT_TRUE(legacy_message->body()->Equals(*message->body()));
}
TEST(TestMessage, Verify) {
std::string metadata = "invalid";
std::string body = "abcdef";
Message message(std::make_shared<Buffer>(metadata), std::make_shared<Buffer>(body));
ASSERT_FALSE(message.Verify());
}
INSTANTIATE_TEST_SUITE_P(TestMessage, TestMessage,
::testing::ValuesIn(kMetadataVersions));
class TestSchemaMetadata : public ::testing::Test {
public:
void SetUp() {}
void CheckSchemaRoundtrip(const Schema& schema) {
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Buffer> buffer, SerializeSchema(schema));
io::BufferReader reader(buffer);
DictionaryMemo in_memo;
ASSERT_OK_AND_ASSIGN(auto actual_schema, ReadSchema(&reader, &in_memo));
AssertSchemaEqual(schema, *actual_schema, /* check_metadata= */ true);
}
};
TEST_F(TestSchemaMetadata, PrimitiveFields) {
CheckSchemaRoundtrip(Schema({
field("f0", int8()),
field("f1", int16(), false),
field("f2", int32()),
field("f3", int64()),
field("f4", uint8()),
field("f5", uint16()),
field("f6", uint32()),
field("f7", uint64()),
field("f8", float32()),
field("f9", float64(), false),
field("f10", boolean()),
}));
}
TEST_F(TestSchemaMetadata, BinaryFields) {
CheckSchemaRoundtrip(Schema({
field("f0", utf8()),
field("f1", binary()),
field("f2", large_utf8()),
field("f3", large_binary()),
field("f4", utf8_view()),
field("f5", binary_view()),
field("f6", fixed_size_binary(3)),
field("f7", fixed_size_binary(33)),
}));
}
TEST_F(TestSchemaMetadata, PrimitiveFieldsWithKeyValueMetadata) {
auto f1 = field("f1", std::make_shared<Int64Type>(), false,
key_value_metadata({"k1"}, {"v1"}));
auto f2 = field("f2", std::make_shared<StringType>(), true,
key_value_metadata({"k2"}, {"v2"}));
Schema schema({f1, f2});
CheckSchemaRoundtrip(schema);
}
TEST_F(TestSchemaMetadata, NestedFields) {
CheckSchemaRoundtrip(Schema({
field("f0", list(int32())),
field("f1", struct_({
field("k1", int32()),
field("k2", int32()),
field("k3", int32()),
})),
}));
}
// Verify that nullable=false is well-preserved for child fields of map type.
TEST_F(TestSchemaMetadata, MapField) {
auto key = field("key", int32(), false);
auto item = field("value", int32(), false);
auto f0 = field("f0", std::make_shared<MapType>(key, item));
Schema schema({f0});
CheckSchemaRoundtrip(schema);
}
// Verify that key value metadata is well-preserved for child fields of nested type.
TEST_F(TestSchemaMetadata, NestedFieldsWithKeyValueMetadata) {
auto metadata = key_value_metadata({"foo"}, {"bar"});
auto inner_field = field("inner", int32(), false, metadata);
auto f0 = field("f0", list(inner_field), false, metadata);
auto f1 = field("f1", struct_({inner_field}), false, metadata);
auto f2 = field("f2",
std::make_shared<MapType>(field("key", int32(), false, metadata),
field("value", int32(), false, metadata)),
false, metadata);
Schema schema({f0, f1, f2});
CheckSchemaRoundtrip(schema);
}
TEST_F(TestSchemaMetadata, DictionaryFields) {
{
auto dict_type = dictionary(int8(), int32(), /*ordered=*/true);
CheckSchemaRoundtrip(Schema({
field("f0", dict_type),
field("f1", list(dict_type)),
}));
}
{
auto dict_type = dictionary(int8(), list(int32()));
CheckSchemaRoundtrip(Schema({field("f0", dict_type)}));
}
}
TEST_F(TestSchemaMetadata, NestedDictionaryFields) {
{
auto inner_dict_type = dictionary(int8(), int32(), /*ordered=*/true);
auto dict_type = dictionary(int16(), list(inner_dict_type));
CheckSchemaRoundtrip(Schema({field("f0", dict_type)}));
}
{
auto dict_type1 = dictionary(int8(), utf8(), /*ordered=*/true);
auto dict_type2 = dictionary(int32(), fixed_size_binary(24));
auto dict_type3 = dictionary(int32(), binary());
auto dict_type4 = dictionary(int8(), decimal128(19, 7));
auto struct_type1 = struct_({field("s1", dict_type1), field("s2", dict_type2)});
auto struct_type2 = struct_({field("s3", dict_type3), field("s4", dict_type4)});
Schema schema({field("f1", dictionary(int32(), struct_type1)),
field("f2", dictionary(int32(), struct_type2))});
CheckSchemaRoundtrip(schema);
}
}
TEST_F(TestSchemaMetadata, KeyValueMetadata) {
auto field_metadata = key_value_metadata({{"key", "value"}});
auto schema_metadata = key_value_metadata({{"foo", "bar"}, {"bizz", "buzz"}});
auto f0 = field("f0", std::make_shared<Int8Type>());
auto f1 = field("f1", std::make_shared<Int16Type>(), false, field_metadata);
Schema schema({f0, f1}, schema_metadata);
CheckSchemaRoundtrip(schema);
}
TEST_F(TestSchemaMetadata, MetadataVersionForwardCompatibility) {
// ARROW-9399
std::string root;
ASSERT_OK(GetTestResourceRoot(&root));
// schema_v6.arrow with currently nonexistent MetadataVersion::V6
std::stringstream schema_v6_path;
schema_v6_path << root << "/forward-compatibility/schema_v6.arrow";
ASSERT_OK_AND_ASSIGN(auto schema_v6_file, io::ReadableFile::Open(schema_v6_path.str()));
DictionaryMemo placeholder_memo;
ASSERT_RAISES(Invalid, ReadSchema(schema_v6_file.get(), &placeholder_memo));
}
const std::vector<test::MakeRecordBatch*> kBatchCases = {
&MakeIntRecordBatch,
&MakeListRecordBatch,
&MakeListViewRecordBatch,
&MakeFixedSizeListRecordBatch,
&MakeNonNullRecordBatch,
&MakeZeroLengthRecordBatch,
&MakeDeeplyNestedList,
&MakeDeeplyNestedListView,
&MakeStringTypesRecordBatchWithNulls,
&MakeStruct,
&MakeUnion,
&MakeDictionary,
&MakeNestedDictionary,
&MakeMap,
&MakeMapOfDictionary,
&MakeDates,
&MakeTimestamps,
&MakeTimes,
&MakeFWBinary,
&MakeNull,
&MakeDecimal,
&MakeBooleanBatch,
&MakeFloatBatch,
&MakeIntervals,
&MakeUuid,
&MakeComplex128,
&MakeDictExtension};
static int g_file_number = 0;
class ExtensionTypesMixin {
public:
// Register the extension types required to ensure roundtripping
ExtensionTypesMixin() : ext_guard_({uuid(), dict_extension_type(), complex128()}) {}
protected:
ExtensionTypeGuard ext_guard_;
};
class IpcTestFixture : public io::MemoryMapFixture, public ExtensionTypesMixin {
public:
void SetUp() {
options_ = IpcWriteOptions::Defaults();
ASSERT_OK_AND_ASSIGN(temp_dir_, TemporaryDir::Make("ipc-test-"));
}
std::string TempFile(std::string_view file) {
return temp_dir_->path().Join(std::string(file)).ValueOrDie().ToString();
}
void DoSchemaRoundTrip(const Schema& schema, std::shared_ptr<Schema>* result) {
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Buffer> serialized_schema,
SerializeSchema(schema, options_.memory_pool));
DictionaryMemo in_memo;
io::BufferReader buf_reader(serialized_schema);
ASSERT_OK_AND_ASSIGN(*result, ReadSchema(&buf_reader, &in_memo));
}
Result<std::shared_ptr<RecordBatch>> DoStandardRoundTrip(
const RecordBatch& batch, const IpcWriteOptions& options,
DictionaryMemo* dictionary_memo,
const IpcReadOptions& read_options = IpcReadOptions::Defaults()) {
ARROW_ASSIGN_OR_RAISE(std::shared_ptr<Buffer> serialized_batch,
SerializeRecordBatch(batch, options));
io::BufferReader buf_reader(serialized_batch);
return ReadRecordBatch(batch.schema(), dictionary_memo, read_options, &buf_reader);
}
Result<std::shared_ptr<RecordBatch>> DoLargeRoundTrip(const RecordBatch& batch,
bool zero_data) {
if (zero_data) {
RETURN_NOT_OK(ZeroMemoryMap(mmap_.get()));
}
RETURN_NOT_OK(mmap_->Seek(0));
auto options = options_;
options.allow_64bit = true;
ARROW_ASSIGN_OR_RAISE(auto file_writer,
MakeFileWriter(mmap_, batch.schema(), options));
RETURN_NOT_OK(file_writer->WriteRecordBatch(batch));
RETURN_NOT_OK(file_writer->Close());
ARROW_ASSIGN_OR_RAISE(int64_t offset, mmap_->Tell());
std::shared_ptr<RecordBatchFileReader> file_reader;
ARROW_ASSIGN_OR_RAISE(file_reader, RecordBatchFileReader::Open(mmap_.get(), offset));
return file_reader->ReadRecordBatch(0);
}
void CheckReadResult(const RecordBatch& result, const RecordBatch& expected) {
ASSERT_OK(result.ValidateFull());
EXPECT_EQ(expected.num_rows(), result.num_rows());
ASSERT_TRUE(expected.schema()->Equals(*result.schema()));
ASSERT_EQ(expected.num_columns(), result.num_columns())
<< expected.schema()->ToString() << " result: " << result.schema()->ToString();
CompareBatchColumnsDetailed(result, expected);
}
void CheckRoundtrip(const RecordBatch& batch,
IpcWriteOptions options = IpcWriteOptions::Defaults(),
IpcReadOptions read_options = IpcReadOptions::Defaults(),
int64_t buffer_size = 1 << 20) {
std::stringstream ss;
ss << "test-write-row-batch-" << g_file_number++;
ASSERT_OK_AND_ASSIGN(
mmap_, io::MemoryMapFixture::InitMemoryMap(buffer_size, TempFile(ss.str())));
std::shared_ptr<Schema> schema_result;
DoSchemaRoundTrip(*batch.schema(), &schema_result);
ASSERT_TRUE(batch.schema()->Equals(*schema_result));
DictionaryMemo dictionary_memo;
ASSERT_OK(::arrow::ipc::internal::CollectDictionaries(batch, &dictionary_memo));
ASSERT_OK_AND_ASSIGN(
auto result, DoStandardRoundTrip(batch, options, &dictionary_memo, read_options));
CheckReadResult(*result, batch);
ASSERT_OK_AND_ASSIGN(result, DoLargeRoundTrip(batch, /*zero_data=*/true));
CheckReadResult(*result, batch);
}
void CheckRoundtrip(const std::shared_ptr<Array>& array,
IpcWriteOptions options = IpcWriteOptions::Defaults(),
int64_t buffer_size = 1 << 20) {
auto f0 = arrow::field("f0", array->type());
std::vector<std::shared_ptr<Field>> fields = {f0};
auto schema = std::make_shared<Schema>(fields);
auto batch = RecordBatch::Make(schema, array->length(), {array});
CheckRoundtrip(*batch, options, IpcReadOptions::Defaults(), buffer_size);
}
protected:
std::shared_ptr<io::MemoryMappedFile> mmap_;
IpcWriteOptions options_;
std::unique_ptr<TemporaryDir> temp_dir_;
};
TEST(MetadataVersion, ForwardsCompatCheck) {
// Verify UBSAN is ok with casting out of range metadata version.
EXPECT_LT(flatbuf::MetadataVersion::MetadataVersion_MAX,
static_cast<flatbuf::MetadataVersion>(72));
}
class TestWriteRecordBatch : public ::testing::Test, public IpcTestFixture {
public:
void SetUp() override { IpcTestFixture::SetUp(); }
void TearDown() override { IpcTestFixture::TearDown(); }
};
class TestIpcRoundTrip : public ::testing::TestWithParam<MakeRecordBatch*>,
public IpcTestFixture {
public:
void SetUp() override { IpcTestFixture::SetUp(); }
void TearDown() override { IpcTestFixture::TearDown(); }
void TestMetadataVersion(MetadataVersion expected_version) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK(MakeIntRecordBatch(&batch));
mmap_.reset(); // Ditch previous mmap view, to avoid errors on Windows
ASSERT_OK_AND_ASSIGN(mmap_,
io::MemoryMapFixture::InitMemoryMap(1 << 16, "test-metadata"));
int32_t metadata_length;
int64_t body_length;
const int64_t buffer_offset = 0;
ASSERT_OK(WriteRecordBatch(*batch, buffer_offset, mmap_.get(), &metadata_length,
&body_length, options_));
ASSERT_OK_AND_ASSIGN(std::unique_ptr<Message> message,
ReadMessage(0, metadata_length, mmap_.get()));
ASSERT_EQ(expected_version, message->metadata_version());
}
};
TEST_P(TestIpcRoundTrip, RoundTrip) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK((*GetParam())(&batch)); // NOLINT clang-tidy gtest issue
for (const auto version : kMetadataVersions) {
options_.metadata_version = version;
CheckRoundtrip(*batch);
}
}
TEST_F(TestIpcRoundTrip, DefaultMetadataVersion) {
TestMetadataVersion(MetadataVersion::V5);
}
TEST_F(TestIpcRoundTrip, SpecificMetadataVersion) {
options_.metadata_version = MetadataVersion::V4;
TestMetadataVersion(MetadataVersion::V4);
options_.metadata_version = MetadataVersion::V5;
TestMetadataVersion(MetadataVersion::V5);
}
TEST_F(TestIpcRoundTrip, ListWithSlicedValues) {
// This tests serialization of a sliced ListArray that got sliced "the Rust
// way": by slicing the value_offsets buffer, but keeping top-level offset at
// 0.
auto child_data = ArrayFromJSON(int32(), "[1, 2, 3, 4, 5]")->data();
// Offsets buffer [2, 5]
TypedBufferBuilder<int32_t> offsets_builder;
ASSERT_OK(offsets_builder.Reserve(2));
ASSERT_OK(offsets_builder.Append(2));
ASSERT_OK(offsets_builder.Append(5));
ASSERT_OK_AND_ASSIGN(auto offsets_buffer, offsets_builder.Finish());
auto list_data = ArrayData::Make(list(int32()),
/*num_rows=*/1,
/*buffers=*/{nullptr, offsets_buffer});
list_data->child_data = {child_data};
std::shared_ptr<Array> list_array = MakeArray(list_data);
ASSERT_OK(list_array->ValidateFull());
CheckRoundtrip(list_array);
}
TEST(TestReadMessage, CorruptedSmallInput) {
std::string data = "abc";
auto reader = io::BufferReader::FromString(data);
ASSERT_RAISES(Invalid, ReadMessage(reader.get()));
// But no error on unsignaled EOS
auto reader2 = io::BufferReader::FromString("");
ASSERT_OK_AND_ASSIGN(auto message, ReadMessage(reader2.get()));
ASSERT_EQ(nullptr, message);
}
TEST(TestMetadata, GetMetadataVersion) {
ASSERT_EQ(MetadataVersion::V1, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_V1));
ASSERT_EQ(MetadataVersion::V2, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_V2));
ASSERT_EQ(MetadataVersion::V3, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_V3));
ASSERT_EQ(MetadataVersion::V4, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_V4));
ASSERT_EQ(MetadataVersion::V5, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_V5));
ASSERT_EQ(MetadataVersion::V1, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_MIN));
ASSERT_EQ(MetadataVersion::V5, ipc::internal::GetMetadataVersion(
flatbuf::MetadataVersion::MetadataVersion_MAX));
}
TEST_P(TestIpcRoundTrip, SliceRoundTrip) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK((*GetParam())(&batch)); // NOLINT clang-tidy gtest issue
// Skip the zero-length case
if (batch->num_rows() < 2) {
return;
}
auto sliced_batch = batch->Slice(2, 10);
CheckRoundtrip(*sliced_batch);
}
TEST_P(TestIpcRoundTrip, ZeroLengthArrays) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK((*GetParam())(&batch)); // NOLINT clang-tidy gtest issue
std::shared_ptr<RecordBatch> zero_length_batch;
if (batch->num_rows() > 2) {
zero_length_batch = batch->Slice(2, 0);
} else {
zero_length_batch = batch->Slice(0, 0);
}
CheckRoundtrip(*zero_length_batch);
// ARROW-544: check binary array
ASSERT_OK_AND_ASSIGN(auto value_offsets,
AllocateBuffer(sizeof(int32_t), options_.memory_pool));
*reinterpret_cast<int32_t*>(value_offsets->mutable_data()) = 0;
std::shared_ptr<Array> bin_array = std::make_shared<BinaryArray>(
0, std::move(value_offsets), std::make_shared<Buffer>(nullptr, 0),
std::make_shared<Buffer>(nullptr, 0));
// null value_offsets
std::shared_ptr<Array> bin_array2 = std::make_shared<BinaryArray>(0, nullptr, nullptr);
CheckRoundtrip(bin_array);
CheckRoundtrip(bin_array2);
}
TEST_F(TestIpcRoundTrip, SparseUnionOfStructsWithReusedBuffers) {
auto storage_type = struct_({
field("i", int32()),
field("f", float32()),
field("s", utf8()),
});
auto storage = checked_pointer_cast<StructArray>(ArrayFromJSON(storage_type,
R"([
{"i": 0, "f": 0.0, "s": "a"},
{"i": 1, "f": 0.5, "s": "b"},
{"i": 2, "f": 1.5, "s": "c"},
{"i": 3, "f": 3.0, "s": "d"}
])"));
ASSERT_OK_AND_ASSIGN(
auto m01, StructArray::Make({storage->field(0), storage->field(1)},
{storage_type->field(0), storage_type->field(1)}));
ASSERT_OK_AND_ASSIGN(
auto m12, StructArray::Make({storage->field(1), storage->field(2)},
{storage_type->field(1), storage_type->field(2)}));
ASSERT_OK_AND_ASSIGN(
auto m20, StructArray::Make({storage->field(2), storage->field(0)},
{storage_type->field(2), storage_type->field(0)}));
auto ids = ArrayFromJSON(int8(), "[1, 12, 20, 1]");
ASSERT_OK_AND_ASSIGN(
auto sparse,
SparseUnionArray::Make(*ids, {m01, m12, m20}, {"m01", "m12", "m20"}, {01, 12, 20}));
auto expected = ArrayFromJSON(sparse_union(
{
field("m01", m01->type()),
field("m12", m12->type()),
field("m20", m20->type()),
},
{01, 12, 20}),
R"([
[1, {"i": 0, "f": 0.0}],
[12, {"f": 0.5, "s": "b"}],
[20, {"s": "c", "i": 2 }],
[1, {"i": 3, "f": 3.0}]
])");
AssertArraysEqual(*expected, *sparse, /*verbose=*/true);
DictionaryMemo ignored;
ASSERT_OK_AND_ASSIGN(
auto roundtripped_batch,
DoStandardRoundTrip(*RecordBatch::Make(schema({field("", sparse->type())}),
sparse->length(), {sparse}),
IpcWriteOptions::Defaults(), &ignored));
auto roundtripped =
checked_pointer_cast<SparseUnionArray>(roundtripped_batch->column(0));
AssertArraysEqual(*expected, *roundtripped, /*verbose=*/true);
auto roundtripped_m01 = checked_pointer_cast<StructArray>(roundtripped->field(0));
auto roundtripped_m12 = checked_pointer_cast<StructArray>(roundtripped->field(1));
auto roundtripped_m20 = checked_pointer_cast<StructArray>(roundtripped->field(2));
// The IPC writer does not take advantage of reusable buffers
ASSERT_NE(roundtripped_m01->field(0)->data()->buffers,
roundtripped_m20->field(1)->data()->buffers);
ASSERT_NE(roundtripped_m01->field(1)->data()->buffers,
roundtripped_m12->field(0)->data()->buffers);
ASSERT_NE(roundtripped_m12->field(1)->data()->buffers,
roundtripped_m20->field(0)->data()->buffers);
}
TEST_F(TestWriteRecordBatch, WriteWithCompression) {
random::RandomArrayGenerator rg(/*seed=*/0);
// Generate both regular and dictionary encoded because the dictionary batch
// gets compressed also
int64_t length = 500;
int dict_size = 50;
std::shared_ptr<Array> dict = rg.String(dict_size, /*min_length=*/5, /*max_length=*/5,
/*null_probability=*/0);
std::shared_ptr<Array> indices = rg.Int32(length, /*min=*/0, /*max=*/dict_size - 1,
/*null_probability=*/0.1);
auto dict_type = dictionary(int32(), utf8());
auto dict_field = field("f1", dict_type);
ASSERT_OK_AND_ASSIGN(auto dict_array,
DictionaryArray::FromArrays(dict_type, indices, dict));
auto schema = ::arrow::schema({field("f0", utf8()), dict_field});
auto batch =
RecordBatch::Make(schema, length, {rg.String(500, 0, 10, 0.1), dict_array});
std::vector<Compression::type> codecs = {Compression::LZ4_FRAME, Compression::ZSTD};
for (auto codec : codecs) {
if (!util::Codec::IsAvailable(codec)) {
continue;
}
IpcWriteOptions write_options = IpcWriteOptions::Defaults();
ASSERT_OK_AND_ASSIGN(write_options.codec, util::Codec::Create(codec));
CheckRoundtrip(*batch, write_options);
// Check non-parallel read and write
IpcReadOptions read_options = IpcReadOptions::Defaults();
write_options.use_threads = false;
read_options.use_threads = false;
CheckRoundtrip(*batch, write_options, read_options);
}
std::vector<Compression::type> disallowed_codecs = {
Compression::BROTLI, Compression::BZ2, Compression::LZ4, Compression::GZIP,
Compression::SNAPPY};
for (auto codec : disallowed_codecs) {
if (!util::Codec::IsAvailable(codec)) {
continue;
}
IpcWriteOptions write_options = IpcWriteOptions::Defaults();
ASSERT_OK_AND_ASSIGN(write_options.codec, util::Codec::Create(codec));
ASSERT_RAISES(Invalid, SerializeRecordBatch(*batch, write_options));
}
}
TEST_F(TestWriteRecordBatch, WriteWithCompressionAndMinSavings) {
// A small batch that's known to be compressible
auto batch = RecordBatchFromJSON(schema({field("n", int64())}), R"([
{"n":0},{"n":1},{"n":2},{"n":3},{"n":4},
{"n":5},{"n":6},{"n":7},{"n":8},{"n":9}])");
auto prefixed_size = [](const Buffer& buffer) -> int64_t {
if (buffer.size() < int64_t(sizeof(int64_t))) return 0;
return bit_util::FromLittleEndian(util::SafeLoadAs<int64_t>(buffer.data()));
};
auto content_size = [](const Buffer& buffer) -> int64_t {
return buffer.size() - sizeof(int64_t);
};
for (auto codec : {Compression::LZ4_FRAME, Compression::ZSTD}) {
if (!util::Codec::IsAvailable(codec)) {
continue;
}
auto write_options = IpcWriteOptions::Defaults();
ASSERT_OK_AND_ASSIGN(write_options.codec, util::Codec::Create(codec));
auto read_options = IpcReadOptions::Defaults();
IpcPayload payload;
ASSERT_OK(GetRecordBatchPayload(*batch, write_options, &payload));
ASSERT_EQ(payload.body_buffers.size(), 2);
// Compute the savings when body buffers are compressed unconditionally. We also
// validate that our test batch is indeed compressible.
const int64_t uncompressed_size = prefixed_size(*payload.body_buffers[1]);
const int64_t compressed_size = content_size(*payload.body_buffers[1]);
ASSERT_LT(compressed_size, uncompressed_size);
ASSERT_GT(compressed_size, 0);
const double expected_savings =
1.0 - static_cast<double>(compressed_size) / uncompressed_size;
// Using the known savings % as the minimum should yield the same outcome.
write_options.min_space_savings = expected_savings;
payload = IpcPayload();
ASSERT_OK(GetRecordBatchPayload(*batch, write_options, &payload));
ASSERT_EQ(payload.body_buffers.size(), 2);
ASSERT_EQ(prefixed_size(*payload.body_buffers[1]), uncompressed_size);
ASSERT_EQ(content_size(*payload.body_buffers[1]), compressed_size);
CheckRoundtrip(*batch, write_options, read_options);
// Slightly bump the threshold. The body buffer should now be prefixed with -1 and its
// content left uncompressed.
write_options.min_space_savings = std::nextafter(expected_savings, 1.0);
payload = IpcPayload();
ASSERT_OK(GetRecordBatchPayload(*batch, write_options, &payload));
ASSERT_EQ(payload.body_buffers.size(), 2);
ASSERT_EQ(prefixed_size(*payload.body_buffers[1]), -1);
ASSERT_EQ(content_size(*payload.body_buffers[1]), uncompressed_size);
CheckRoundtrip(*batch, write_options, read_options);
for (double out_of_range : {std::nextafter(1.0, 2.0), std::nextafter(0.0, -1.0)}) {
write_options.min_space_savings = out_of_range;
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::StartsWith("Invalid: min_space_savings not in range [0,1]"),
SerializeRecordBatch(*batch, write_options));
}
}
}
TEST_F(TestWriteRecordBatch, SliceTruncatesBinaryOffsets) {
// ARROW-6046
std::shared_ptr<Array> array;
ASSERT_OK(MakeRandomStringArray(500, false, default_memory_pool(), &array));
auto f0 = field("f0", array->type());
auto schema = ::arrow::schema({f0});
auto batch = RecordBatch::Make(schema, array->length(), {array});
auto sliced_batch = batch->Slice(0, 5);
ASSERT_OK_AND_ASSIGN(
mmap_, io::MemoryMapFixture::InitMemoryMap(/*buffer_size=*/1 << 20,
TempFile("test-truncate-offsets")));
DictionaryMemo dictionary_memo;
ASSERT_OK_AND_ASSIGN(
auto result,
DoStandardRoundTrip(*sliced_batch, IpcWriteOptions::Defaults(), &dictionary_memo));
ASSERT_EQ(6 * sizeof(int32_t), result->column(0)->data()->buffers[1]->size());
}
TEST_F(TestWriteRecordBatch, SliceTruncatesBuffers) {
auto CheckArray = [this](const std::shared_ptr<Array>& array) {
auto f0 = field("f0", array->type());
auto schema = ::arrow::schema({f0});
auto batch = RecordBatch::Make(schema, array->length(), {array});
auto sliced_batch = batch->Slice(0, 5);
int64_t full_size;
int64_t sliced_size;
ASSERT_OK(GetRecordBatchSize(*batch, &full_size));
ASSERT_OK(GetRecordBatchSize(*sliced_batch, &sliced_size));
ASSERT_TRUE(sliced_size < full_size) << sliced_size << " " << full_size;
// make sure we can write and read it
this->CheckRoundtrip(*sliced_batch);
};
std::shared_ptr<Array> a0, a1;
auto pool = default_memory_pool();
// Integer
ASSERT_OK(MakeRandomInt32Array(500, false, pool, &a0));
CheckArray(a0);
// String / Binary
{
auto s = MakeRandomStringArray(500, false, pool, &a0);
ASSERT_TRUE(s.ok());
}
CheckArray(a0);
// Boolean
ASSERT_OK(MakeRandomBooleanArray(10000, false, &a0));
CheckArray(a0);
// List
ASSERT_OK(MakeRandomInt32Array(500, false, pool, &a0));
ASSERT_OK(MakeRandomListArray(a0, 200, false, pool, &a1));
CheckArray(a1);
// Struct
auto struct_type = struct_({field("f0", a0->type())});
std::vector<std::shared_ptr<Array>> struct_children = {a0};
a1 = std::make_shared<StructArray>(struct_type, a0->length(), struct_children);
CheckArray(a1);
// Sparse Union
auto union_type = sparse_union({field("f0", a0->type())}, {0});
std::vector<int32_t> type_ids(a0->length());
std::shared_ptr<Buffer> ids_buffer;
ASSERT_OK(CopyBufferFromVector(type_ids, default_memory_pool(), &ids_buffer));
a1 = std::make_shared<SparseUnionArray>(union_type, a0->length(), struct_children,
ids_buffer);
CheckArray(a1);
// Dense union
auto dense_union_type = dense_union({field("f0", a0->type())}, {0});
std::vector<int32_t> type_offsets;
for (int32_t i = 0; i < a0->length(); ++i) {
type_offsets.push_back(i);
}
std::shared_ptr<Buffer> offsets_buffer;
ASSERT_OK(CopyBufferFromVector(type_offsets, default_memory_pool(), &offsets_buffer));
a1 = std::make_shared<DenseUnionArray>(dense_union_type, a0->length(), struct_children,
ids_buffer, offsets_buffer);
CheckArray(a1);
}
TEST_F(TestWriteRecordBatch, RoundtripPreservesBufferSizes) {
// ARROW-7975: deserialized buffers should have logically exact size (no padding)
random::RandomArrayGenerator rg(/*seed=*/0);
constexpr int64_t kLength = 30;
auto arr =
rg.String(kLength, /*min_length=*/0, /*max_length=*/10, /*null_probability=*/0.3);
ASSERT_NE(arr->null_count(), 0); // required for validity bitmap size assertion below
auto batch = RecordBatch::Make(::arrow::schema({field("f0", utf8())}), kLength, {arr});
DictionaryMemo dictionary_memo;
ASSERT_OK_AND_ASSIGN(
auto result,
DoStandardRoundTrip(*batch, IpcWriteOptions::Defaults(), &dictionary_memo));
// Make sure that the validity bitmap has expected size
ASSERT_EQ(bit_util::BytesForBits(kLength), arr->data()->buffers[0]->size());
for (size_t i = 0; i < arr->data()->buffers.size(); ++i) {
ASSERT_EQ(arr->data()->buffers[i]->size(),
result->column(0)->data()->buffers[i]->size());
}
}
void TestGetRecordBatchSize(const IpcWriteOptions& options,
std::shared_ptr<RecordBatch> batch) {
io::MockOutputStream mock;
ipc::IpcPayload payload;
int32_t mock_metadata_length = -1;
int64_t mock_body_length = -1;
int64_t size = -1;
ASSERT_OK(WriteRecordBatch(*batch, 0, &mock, &mock_metadata_length, &mock_body_length,
options));
ASSERT_OK(GetRecordBatchPayload(*batch, options, &payload));
int64_t payload_size = GetPayloadSize(payload, options);
ASSERT_OK(GetRecordBatchSize(*batch, options, &size));
ASSERT_EQ(mock.GetExtentBytesWritten(), size);
ASSERT_EQ(mock.GetExtentBytesWritten(), payload_size);
}
TEST_F(TestWriteRecordBatch, IntegerGetRecordBatchSize) {
std::shared_ptr<RecordBatch> batch;
ASSERT_OK(MakeIntRecordBatch(&batch));
TestGetRecordBatchSize(options_, batch);