/
reader.cc
2555 lines (2191 loc) · 96.3 KB
/
reader.cc
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 "arrow/ipc/reader.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <numeric>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <flatbuffers/flatbuffers.h> // IWYU pragma: export
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/extension_type.h"
#include "arrow/io/caching.h"
#include "arrow/io/interfaces.h"
#include "arrow/io/memory.h"
#include "arrow/ipc/message.h"
#include "arrow/ipc/metadata_internal.h"
#include "arrow/ipc/reader_internal.h"
#include "arrow/ipc/writer.h"
#include "arrow/record_batch.h"
#include "arrow/sparse_tensor.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_ops.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/compression.h"
#include "arrow/util/endian.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/make_unique.h"
#include "arrow/util/parallel.h"
#include "arrow/util/string.h"
#include "arrow/util/thread_pool.h"
#include "arrow/util/ubsan.h"
#include "arrow/util/vector.h"
#include "arrow/visit_type_inline.h"
#include "generated/File_generated.h" // IWYU pragma: export
#include "generated/Message_generated.h"
#include "generated/Schema_generated.h"
#include "generated/SparseTensor_generated.h"
namespace arrow {
namespace flatbuf = org::apache::arrow::flatbuf;
using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::GetByteWidth;
namespace ipc {
using internal::FileBlock;
using internal::kArrowMagicBytes;
namespace {
enum class DictionaryKind { New, Delta, Replacement };
Status InvalidMessageType(MessageType expected, MessageType actual) {
return Status::IOError("Expected IPC message of type ", FormatMessageType(expected),
" but got ", FormatMessageType(actual));
}
#define CHECK_MESSAGE_TYPE(expected, actual) \
do { \
if ((actual) != (expected)) { \
return InvalidMessageType((expected), (actual)); \
} \
} while (0)
#define CHECK_HAS_BODY(message) \
do { \
if ((message).body() == nullptr) { \
return Status::IOError("Expected body in IPC message of type ", \
FormatMessageType((message).type())); \
} \
} while (0)
#define CHECK_HAS_NO_BODY(message) \
do { \
if ((message).body_length() != 0) { \
return Status::IOError("Unexpected body in IPC message of type ", \
FormatMessageType((message).type())); \
} \
} while (0)
} // namespace
// ----------------------------------------------------------------------
// Record batch read path
/// \brief Structure to keep common arguments to be passed
struct IpcReadContext {
IpcReadContext(DictionaryMemo* memo, const IpcReadOptions& option, bool swap,
MetadataVersion version = MetadataVersion::V5,
Compression::type kind = Compression::UNCOMPRESSED)
: dictionary_memo(memo),
options(option),
metadata_version(version),
compression(kind),
swap_endian(swap) {}
DictionaryMemo* dictionary_memo;
const IpcReadOptions& options;
MetadataVersion metadata_version;
Compression::type compression;
/// \brief LoadRecordBatch() or LoadRecordBatchSubset() swaps endianness of elements
/// if this flag is true
const bool swap_endian;
};
/// A collection of ranges to read and pointers to set to those ranges when they are
/// available. This allows the ArrayLoader to utilize a two pass cache-then-read
/// strategy with a ReadRangeCache
class BatchDataReadRequest {
public:
const std::vector<io::ReadRange>& ranges_to_read() const { return ranges_to_read_; }
void RequestRange(int64_t offset, int64_t length, std::shared_ptr<Buffer>* out) {
ranges_to_read_.push_back({offset, length});
destinations_.push_back(out);
}
void FulfillRequest(const std::vector<std::shared_ptr<Buffer>>& buffers) {
for (std::size_t i = 0; i < buffers.size(); i++) {
*destinations_[i] = buffers[i];
}
}
private:
std::vector<io::ReadRange> ranges_to_read_;
std::vector<std::shared_ptr<Buffer>*> destinations_;
};
/// The field_index and buffer_index are incremented based on how much of the
/// batch is "consumed" (through nested data reconstruction, for example)
class ArrayLoader {
public:
explicit ArrayLoader(const flatbuf::RecordBatch* metadata,
MetadataVersion metadata_version, const IpcReadOptions& options,
io::RandomAccessFile* file)
: metadata_(metadata),
metadata_version_(metadata_version),
file_(file),
file_offset_(0),
max_recursion_depth_(options.max_recursion_depth) {}
explicit ArrayLoader(const flatbuf::RecordBatch* metadata,
MetadataVersion metadata_version, const IpcReadOptions& options,
int64_t file_offset)
: metadata_(metadata),
metadata_version_(metadata_version),
file_(nullptr),
file_offset_(file_offset),
max_recursion_depth_(options.max_recursion_depth) {}
Status ReadBuffer(int64_t offset, int64_t length, std::shared_ptr<Buffer>* out) {
if (skip_io_) {
return Status::OK();
}
if (offset < 0) {
return Status::Invalid("Negative offset for reading buffer ", buffer_index_);
}
if (length < 0) {
return Status::Invalid("Negative length for reading buffer ", buffer_index_);
}
// This construct permits overriding GetBuffer at compile time
if (!bit_util::IsMultipleOf8(offset)) {
return Status::Invalid("Buffer ", buffer_index_,
" did not start on 8-byte aligned offset: ", offset);
}
if (file_) {
return file_->ReadAt(offset, length).Value(out);
} else {
read_request_.RequestRange(offset + file_offset_, length, out);
return Status::OK();
}
}
Status LoadType(const DataType& type) { return VisitTypeInline(type, this); }
Status Load(const Field* field, ArrayData* out) {
if (max_recursion_depth_ <= 0) {
return Status::Invalid("Max recursion depth reached");
}
field_ = field;
out_ = out;
out_->type = field_->type();
return LoadType(*field_->type());
}
Status SkipField(const Field* field) {
ArrayData dummy;
skip_io_ = true;
Status status = Load(field, &dummy);
skip_io_ = false;
return status;
}
Status GetBuffer(int buffer_index, std::shared_ptr<Buffer>* out) {
auto buffers = metadata_->buffers();
CHECK_FLATBUFFERS_NOT_NULL(buffers, "RecordBatch.buffers");
if (buffer_index >= static_cast<int>(buffers->size())) {
return Status::IOError("buffer_index out of range.");
}
const flatbuf::Buffer* buffer = buffers->Get(buffer_index);
if (buffer->length() == 0) {
// Should never return a null buffer here.
// (zero-sized buffer allocations are cheap)
return AllocateBuffer(0).Value(out);
} else {
return ReadBuffer(buffer->offset(), buffer->length(), out);
}
}
Status GetFieldMetadata(int field_index, ArrayData* out) {
auto nodes = metadata_->nodes();
CHECK_FLATBUFFERS_NOT_NULL(nodes, "Table.nodes");
// pop off a field
if (field_index >= static_cast<int>(nodes->size())) {
return Status::Invalid("Ran out of field metadata, likely malformed");
}
const flatbuf::FieldNode* node = nodes->Get(field_index);
out->length = node->length();
out->null_count = node->null_count();
out->offset = 0;
return Status::OK();
}
Status LoadCommon(Type::type type_id) {
// This only contains the length and null count, which we need to figure
// out what to do with the buffers. For example, if null_count == 0, then
// we can skip that buffer without reading from shared memory
RETURN_NOT_OK(GetFieldMetadata(field_index_++, out_));
if (internal::HasValidityBitmap(type_id, metadata_version_)) {
// Extract null_bitmap which is common to all arrays except for unions
// and nulls.
if (out_->null_count != 0) {
RETURN_NOT_OK(GetBuffer(buffer_index_, &out_->buffers[0]));
}
buffer_index_++;
}
return Status::OK();
}
template <typename TYPE>
Status LoadPrimitive(Type::type type_id) {
out_->buffers.resize(2);
RETURN_NOT_OK(LoadCommon(type_id));
if (out_->length > 0) {
RETURN_NOT_OK(GetBuffer(buffer_index_++, &out_->buffers[1]));
} else {
buffer_index_++;
out_->buffers[1].reset(new Buffer(nullptr, 0));
}
return Status::OK();
}
template <typename TYPE>
Status LoadBinary(Type::type type_id) {
out_->buffers.resize(3);
RETURN_NOT_OK(LoadCommon(type_id));
RETURN_NOT_OK(GetBuffer(buffer_index_++, &out_->buffers[1]));
return GetBuffer(buffer_index_++, &out_->buffers[2]);
}
template <typename TYPE>
Status LoadList(const TYPE& type) {
out_->buffers.resize(2);
RETURN_NOT_OK(LoadCommon(type.id()));
RETURN_NOT_OK(GetBuffer(buffer_index_++, &out_->buffers[1]));
const int num_children = type.num_fields();
if (num_children != 1) {
return Status::Invalid("Wrong number of children: ", num_children);
}
return LoadChildren(type.fields());
}
Status LoadChildren(const std::vector<std::shared_ptr<Field>>& child_fields) {
ArrayData* parent = out_;
parent->child_data.resize(child_fields.size());
for (int i = 0; i < static_cast<int>(child_fields.size()); ++i) {
parent->child_data[i] = std::make_shared<ArrayData>();
--max_recursion_depth_;
RETURN_NOT_OK(Load(child_fields[i].get(), parent->child_data[i].get()));
++max_recursion_depth_;
}
out_ = parent;
return Status::OK();
}
Status Visit(const NullType& type) {
out_->buffers.resize(1);
// ARROW-6379: NullType has no buffers in the IPC payload
return GetFieldMetadata(field_index_++, out_);
}
template <typename T>
enable_if_t<std::is_base_of<FixedWidthType, T>::value &&
!std::is_base_of<FixedSizeBinaryType, T>::value &&
!std::is_base_of<DictionaryType, T>::value,
Status>
Visit(const T& type) {
return LoadPrimitive<T>(type.id());
}
template <typename T>
enable_if_base_binary<T, Status> Visit(const T& type) {
return LoadBinary<T>(type.id());
}
Status Visit(const FixedSizeBinaryType& type) {
out_->buffers.resize(2);
RETURN_NOT_OK(LoadCommon(type.id()));
return GetBuffer(buffer_index_++, &out_->buffers[1]);
}
template <typename T>
enable_if_var_size_list<T, Status> Visit(const T& type) {
return LoadList(type);
}
Status Visit(const MapType& type) {
RETURN_NOT_OK(LoadList(type));
return MapArray::ValidateChildData(out_->child_data);
}
Status Visit(const FixedSizeListType& type) {
out_->buffers.resize(1);
RETURN_NOT_OK(LoadCommon(type.id()));
const int num_children = type.num_fields();
if (num_children != 1) {
return Status::Invalid("Wrong number of children: ", num_children);
}
return LoadChildren(type.fields());
}
Status Visit(const StructType& type) {
out_->buffers.resize(1);
RETURN_NOT_OK(LoadCommon(type.id()));
return LoadChildren(type.fields());
}
Status Visit(const UnionType& type) {
int n_buffers = type.mode() == UnionMode::SPARSE ? 2 : 3;
out_->buffers.resize(n_buffers);
RETURN_NOT_OK(LoadCommon(type.id()));
// With metadata V4, we can get a validity bitmap.
// Trying to fix up union data to do without the top-level validity bitmap
// is hairy:
// - type ids must be rewritten to all have valid values (even for former
// null slots)
// - sparse union children must have their validity bitmaps rewritten
// by ANDing the top-level validity bitmap
// - dense union children must be rewritten (at least one of them)
// to insert the required null slots that were formerly omitted
// So instead we bail out.
if (out_->null_count != 0 && out_->buffers[0] != nullptr) {
return Status::Invalid(
"Cannot read pre-1.0.0 Union array with top-level validity bitmap");
}
out_->buffers[0] = nullptr;
out_->null_count = 0;
if (out_->length > 0) {
RETURN_NOT_OK(GetBuffer(buffer_index_, &out_->buffers[1]));
if (type.mode() == UnionMode::DENSE) {
RETURN_NOT_OK(GetBuffer(buffer_index_ + 1, &out_->buffers[2]));
}
}
buffer_index_ += n_buffers - 1;
return LoadChildren(type.fields());
}
Status Visit(const DictionaryType& type) {
// out_->dictionary will be filled later in ResolveDictionaries()
return LoadType(*type.index_type());
}
Status Visit(const ExtensionType& type) { return LoadType(*type.storage_type()); }
BatchDataReadRequest& read_request() { return read_request_; }
private:
const flatbuf::RecordBatch* metadata_;
const MetadataVersion metadata_version_;
io::RandomAccessFile* file_;
int64_t file_offset_;
int max_recursion_depth_;
int buffer_index_ = 0;
int field_index_ = 0;
bool skip_io_ = false;
BatchDataReadRequest read_request_;
const Field* field_ = nullptr;
ArrayData* out_ = nullptr;
};
Result<std::shared_ptr<Buffer>> DecompressBuffer(const std::shared_ptr<Buffer>& buf,
const IpcReadOptions& options,
util::Codec* codec) {
if (buf == nullptr || buf->size() == 0) {
return buf;
}
if (buf->size() < 8) {
return Status::Invalid(
"Likely corrupted message, compressed buffers "
"are larger than 8 bytes by construction");
}
const uint8_t* data = buf->data();
int64_t compressed_size = buf->size() - sizeof(int64_t);
int64_t uncompressed_size = bit_util::FromLittleEndian(util::SafeLoadAs<int64_t>(data));
ARROW_ASSIGN_OR_RAISE(auto uncompressed,
AllocateBuffer(uncompressed_size, options.memory_pool));
ARROW_ASSIGN_OR_RAISE(
int64_t actual_decompressed,
codec->Decompress(compressed_size, data + sizeof(int64_t), uncompressed_size,
uncompressed->mutable_data()));
if (actual_decompressed != uncompressed_size) {
return Status::Invalid("Failed to fully decompress buffer, expected ",
uncompressed_size, " bytes but decompressed ",
actual_decompressed);
}
return std::move(uncompressed);
}
Status DecompressBuffers(Compression::type compression, const IpcReadOptions& options,
ArrayDataVector* fields) {
struct BufferAccumulator {
using BufferPtrVector = std::vector<std::shared_ptr<Buffer>*>;
void AppendFrom(const ArrayDataVector& fields) {
for (const auto& field : fields) {
for (auto& buffer : field->buffers) {
buffers_.push_back(&buffer);
}
AppendFrom(field->child_data);
}
}
BufferPtrVector Get(const ArrayDataVector& fields) && {
AppendFrom(fields);
return std::move(buffers_);
}
BufferPtrVector buffers_;
};
// Flatten all buffers
auto buffers = BufferAccumulator{}.Get(*fields);
std::unique_ptr<util::Codec> codec;
ARROW_ASSIGN_OR_RAISE(codec, util::Codec::Create(compression));
return ::arrow::internal::OptionalParallelFor(
options.use_threads, static_cast<int>(buffers.size()), [&](int i) {
ARROW_ASSIGN_OR_RAISE(*buffers[i],
DecompressBuffer(*buffers[i], options, codec.get()));
return Status::OK();
});
}
Result<std::shared_ptr<RecordBatch>> LoadRecordBatchSubset(
const flatbuf::RecordBatch* metadata, const std::shared_ptr<Schema>& schema,
const std::vector<bool>* inclusion_mask, const IpcReadContext& context,
io::RandomAccessFile* file) {
ArrayLoader loader(metadata, context.metadata_version, context.options, file);
ArrayDataVector columns(schema->num_fields());
ArrayDataVector filtered_columns;
FieldVector filtered_fields;
std::shared_ptr<Schema> filtered_schema;
for (int i = 0; i < schema->num_fields(); ++i) {
const Field& field = *schema->field(i);
if (!inclusion_mask || (*inclusion_mask)[i]) {
// Read field
auto column = std::make_shared<ArrayData>();
RETURN_NOT_OK(loader.Load(&field, column.get()));
if (metadata->length() != column->length) {
return Status::IOError("Array length did not match record batch length");
}
columns[i] = std::move(column);
if (inclusion_mask) {
filtered_columns.push_back(columns[i]);
filtered_fields.push_back(schema->field(i));
}
} else {
// Skip field. This logic must be executed to advance the state of the
// loader to the next field
RETURN_NOT_OK(loader.SkipField(&field));
}
}
// Dictionary resolution needs to happen on the unfiltered columns,
// because fields are mapped structurally (by path in the original schema).
RETURN_NOT_OK(ResolveDictionaries(columns, *context.dictionary_memo,
context.options.memory_pool));
if (inclusion_mask) {
filtered_schema = ::arrow::schema(std::move(filtered_fields), schema->metadata());
columns.clear();
} else {
filtered_schema = schema;
filtered_columns = std::move(columns);
}
if (context.compression != Compression::UNCOMPRESSED) {
RETURN_NOT_OK(
DecompressBuffers(context.compression, context.options, &filtered_columns));
}
// swap endian in a set of ArrayData if necessary (swap_endian == true)
if (context.swap_endian) {
for (int i = 0; i < static_cast<int>(filtered_columns.size()); ++i) {
ARROW_ASSIGN_OR_RAISE(filtered_columns[i],
arrow::internal::SwapEndianArrayData(filtered_columns[i]));
}
}
return RecordBatch::Make(std::move(filtered_schema), metadata->length(),
std::move(filtered_columns));
}
Result<std::shared_ptr<RecordBatch>> LoadRecordBatch(
const flatbuf::RecordBatch* metadata, const std::shared_ptr<Schema>& schema,
const std::vector<bool>& inclusion_mask, const IpcReadContext& context,
io::RandomAccessFile* file) {
if (inclusion_mask.size() > 0) {
return LoadRecordBatchSubset(metadata, schema, &inclusion_mask, context, file);
} else {
return LoadRecordBatchSubset(metadata, schema, /*inclusion_mask=*/nullptr, context,
file);
}
}
// ----------------------------------------------------------------------
// Array loading
Status GetCompression(const flatbuf::RecordBatch* batch, Compression::type* out) {
*out = Compression::UNCOMPRESSED;
const flatbuf::BodyCompression* compression = batch->compression();
if (compression != nullptr) {
if (compression->method() != flatbuf::BodyCompressionMethod::BUFFER) {
// Forward compatibility
return Status::Invalid("This library only supports BUFFER compression method");
}
if (compression->codec() == flatbuf::CompressionType::LZ4_FRAME) {
*out = Compression::LZ4_FRAME;
} else if (compression->codec() == flatbuf::CompressionType::ZSTD) {
*out = Compression::ZSTD;
} else {
return Status::Invalid("Unsupported codec in RecordBatch::compression metadata");
}
return Status::OK();
}
return Status::OK();
}
Status GetCompressionExperimental(const flatbuf::Message* message,
Compression::type* out) {
*out = Compression::UNCOMPRESSED;
if (message->custom_metadata() != nullptr) {
// TODO: Ensure this deserialization only ever happens once
std::shared_ptr<KeyValueMetadata> metadata;
RETURN_NOT_OK(internal::GetKeyValueMetadata(message->custom_metadata(), &metadata));
int index = metadata->FindKey("ARROW:experimental_compression");
if (index != -1) {
// Arrow 0.17 stored string in upper case, internal utils now require lower case
auto name = arrow::internal::AsciiToLower(metadata->value(index));
ARROW_ASSIGN_OR_RAISE(*out, util::Codec::GetCompressionType(name));
}
return internal::CheckCompressionSupported(*out);
}
return Status::OK();
}
static Status ReadContiguousPayload(io::InputStream* file,
std::unique_ptr<Message>* message) {
ARROW_ASSIGN_OR_RAISE(*message, ReadMessage(file));
if (*message == nullptr) {
return Status::Invalid("Unable to read metadata at offset");
}
return Status::OK();
}
Result<std::shared_ptr<RecordBatch>> ReadRecordBatch(
const std::shared_ptr<Schema>& schema, const DictionaryMemo* dictionary_memo,
const IpcReadOptions& options, io::InputStream* file) {
std::unique_ptr<Message> message;
RETURN_NOT_OK(ReadContiguousPayload(file, &message));
CHECK_HAS_BODY(*message);
ARROW_ASSIGN_OR_RAISE(auto reader, Buffer::GetReader(message->body()));
return ReadRecordBatch(*message->metadata(), schema, dictionary_memo, options,
reader.get());
}
Result<std::shared_ptr<RecordBatch>> ReadRecordBatch(
const Message& message, const std::shared_ptr<Schema>& schema,
const DictionaryMemo* dictionary_memo, const IpcReadOptions& options) {
CHECK_MESSAGE_TYPE(MessageType::RECORD_BATCH, message.type());
CHECK_HAS_BODY(message);
ARROW_ASSIGN_OR_RAISE(auto reader, Buffer::GetReader(message.body()));
return ReadRecordBatch(*message.metadata(), schema, dictionary_memo, options,
reader.get());
}
Result<std::shared_ptr<RecordBatch>> ReadRecordBatchInternal(
const Buffer& metadata, const std::shared_ptr<Schema>& schema,
const std::vector<bool>& inclusion_mask, IpcReadContext& context,
io::RandomAccessFile* file) {
const flatbuf::Message* message = nullptr;
RETURN_NOT_OK(internal::VerifyMessage(metadata.data(), metadata.size(), &message));
auto batch = message->header_as_RecordBatch();
if (batch == nullptr) {
return Status::IOError(
"Header-type of flatbuffer-encoded Message is not RecordBatch.");
}
Compression::type compression;
RETURN_NOT_OK(GetCompression(batch, &compression));
if (context.compression == Compression::UNCOMPRESSED &&
message->version() == flatbuf::MetadataVersion::V4) {
// Possibly obtain codec information from experimental serialization format
// in 0.17.x
RETURN_NOT_OK(GetCompressionExperimental(message, &compression));
}
context.compression = compression;
context.metadata_version = internal::GetMetadataVersion(message->version());
return LoadRecordBatch(batch, schema, inclusion_mask, context, file);
}
// If we are selecting only certain fields, populate an inclusion mask for fast lookups.
// Additionally, drop deselected fields from the reader's schema.
Status GetInclusionMaskAndOutSchema(const std::shared_ptr<Schema>& full_schema,
const std::vector<int>& included_indices,
std::vector<bool>* inclusion_mask,
std::shared_ptr<Schema>* out_schema) {
inclusion_mask->clear();
if (included_indices.empty()) {
*out_schema = full_schema;
return Status::OK();
}
inclusion_mask->resize(full_schema->num_fields(), false);
auto included_indices_sorted = included_indices;
std::sort(included_indices_sorted.begin(), included_indices_sorted.end());
FieldVector included_fields;
for (int i : included_indices_sorted) {
// Ignore out of bounds indices
if (i < 0 || i >= full_schema->num_fields()) {
return Status::Invalid("Out of bounds field index: ", i);
}
if (inclusion_mask->at(i)) continue;
inclusion_mask->at(i) = true;
included_fields.push_back(full_schema->field(i));
}
*out_schema = schema(std::move(included_fields), full_schema->endianness(),
full_schema->metadata());
return Status::OK();
}
Status UnpackSchemaMessage(const void* opaque_schema, const IpcReadOptions& options,
DictionaryMemo* dictionary_memo,
std::shared_ptr<Schema>* schema,
std::shared_ptr<Schema>* out_schema,
std::vector<bool>* field_inclusion_mask, bool* swap_endian) {
RETURN_NOT_OK(internal::GetSchema(opaque_schema, dictionary_memo, schema));
// If we are selecting only certain fields, populate the inclusion mask now
// for fast lookups
RETURN_NOT_OK(GetInclusionMaskAndOutSchema(*schema, options.included_fields,
field_inclusion_mask, out_schema));
*swap_endian = options.ensure_native_endian && !out_schema->get()->is_native_endian();
if (*swap_endian) {
// create a new schema with native endianness before swapping endian in ArrayData
*schema = schema->get()->WithEndianness(Endianness::Native);
*out_schema = out_schema->get()->WithEndianness(Endianness::Native);
}
return Status::OK();
}
Status UnpackSchemaMessage(const Message& message, const IpcReadOptions& options,
DictionaryMemo* dictionary_memo,
std::shared_ptr<Schema>* schema,
std::shared_ptr<Schema>* out_schema,
std::vector<bool>* field_inclusion_mask, bool* swap_endian) {
CHECK_MESSAGE_TYPE(MessageType::SCHEMA, message.type());
CHECK_HAS_NO_BODY(message);
return UnpackSchemaMessage(message.header(), options, dictionary_memo, schema,
out_schema, field_inclusion_mask, swap_endian);
}
Result<std::shared_ptr<RecordBatch>> ReadRecordBatch(
const Buffer& metadata, const std::shared_ptr<Schema>& schema,
const DictionaryMemo* dictionary_memo, const IpcReadOptions& options,
io::RandomAccessFile* file) {
std::shared_ptr<Schema> out_schema;
// Empty means do not use
std::vector<bool> inclusion_mask;
IpcReadContext context(const_cast<DictionaryMemo*>(dictionary_memo), options, false);
RETURN_NOT_OK(GetInclusionMaskAndOutSchema(schema, context.options.included_fields,
&inclusion_mask, &out_schema));
return ReadRecordBatchInternal(metadata, schema, inclusion_mask, context, file);
}
Status ReadDictionary(const Buffer& metadata, const IpcReadContext& context,
DictionaryKind* kind, io::RandomAccessFile* file) {
const flatbuf::Message* message = nullptr;
RETURN_NOT_OK(internal::VerifyMessage(metadata.data(), metadata.size(), &message));
const auto dictionary_batch = message->header_as_DictionaryBatch();
if (dictionary_batch == nullptr) {
return Status::IOError(
"Header-type of flatbuffer-encoded Message is not DictionaryBatch.");
}
// The dictionary is embedded in a record batch with a single column
const auto batch_meta = dictionary_batch->data();
CHECK_FLATBUFFERS_NOT_NULL(batch_meta, "DictionaryBatch.data");
Compression::type compression;
RETURN_NOT_OK(GetCompression(batch_meta, &compression));
if (compression == Compression::UNCOMPRESSED &&
message->version() == flatbuf::MetadataVersion::V4) {
// Possibly obtain codec information from experimental serialization format
// in 0.17.x
RETURN_NOT_OK(GetCompressionExperimental(message, &compression));
}
const int64_t id = dictionary_batch->id();
// Look up the dictionary value type, which must have been added to the
// DictionaryMemo already prior to invoking this function
ARROW_ASSIGN_OR_RAISE(auto value_type, context.dictionary_memo->GetDictionaryType(id));
// Load the dictionary data from the dictionary batch
ArrayLoader loader(batch_meta, internal::GetMetadataVersion(message->version()),
context.options, file);
auto dict_data = std::make_shared<ArrayData>();
const Field dummy_field("", value_type);
RETURN_NOT_OK(loader.Load(&dummy_field, dict_data.get()));
if (compression != Compression::UNCOMPRESSED) {
ArrayDataVector dict_fields{dict_data};
RETURN_NOT_OK(DecompressBuffers(compression, context.options, &dict_fields));
}
// swap endian in dict_data if necessary (swap_endian == true)
if (context.swap_endian) {
ARROW_ASSIGN_OR_RAISE(dict_data, ::arrow::internal::SwapEndianArrayData(dict_data));
}
if (dictionary_batch->isDelta()) {
if (kind != nullptr) {
*kind = DictionaryKind::Delta;
}
return context.dictionary_memo->AddDictionaryDelta(id, dict_data);
}
ARROW_ASSIGN_OR_RAISE(bool inserted,
context.dictionary_memo->AddOrReplaceDictionary(id, dict_data));
if (kind != nullptr) {
*kind = inserted ? DictionaryKind::New : DictionaryKind::Replacement;
}
return Status::OK();
}
Status ReadDictionary(const Message& message, const IpcReadContext& context,
DictionaryKind* kind) {
// Only invoke this method if we already know we have a dictionary message
DCHECK_EQ(message.type(), MessageType::DICTIONARY_BATCH);
CHECK_HAS_BODY(message);
ARROW_ASSIGN_OR_RAISE(auto reader, Buffer::GetReader(message.body()));
return ReadDictionary(*message.metadata(), context, kind, reader.get());
}
// ----------------------------------------------------------------------
// RecordBatchStreamReader implementation
class RecordBatchStreamReaderImpl : public RecordBatchStreamReader {
public:
Status Open(std::unique_ptr<MessageReader> message_reader,
const IpcReadOptions& options) {
message_reader_ = std::move(message_reader);
options_ = options;
// Read schema
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Message> message, ReadNextMessage());
if (!message) {
return Status::Invalid("Tried reading schema message, was null or length 0");
}
RETURN_NOT_OK(UnpackSchemaMessage(*message, options, &dictionary_memo_, &schema_,
&out_schema_, &field_inclusion_mask_,
&swap_endian_));
return Status::OK();
}
Status ReadNext(std::shared_ptr<RecordBatch>* batch) override {
if (!have_read_initial_dictionaries_) {
RETURN_NOT_OK(ReadInitialDictionaries());
}
if (empty_stream_) {
// ARROW-6006: Degenerate case where stream contains no data, we do not
// bother trying to read a RecordBatch message from the stream
*batch = nullptr;
return Status::OK();
}
// Continue to read other dictionaries, if any
std::unique_ptr<Message> message;
ARROW_ASSIGN_OR_RAISE(message, ReadNextMessage());
while (message != nullptr && message->type() == MessageType::DICTIONARY_BATCH) {
RETURN_NOT_OK(ReadDictionary(*message));
ARROW_ASSIGN_OR_RAISE(message, ReadNextMessage());
}
if (message == nullptr) {
// End of stream
*batch = nullptr;
return Status::OK();
}
CHECK_HAS_BODY(*message);
ARROW_ASSIGN_OR_RAISE(auto reader, Buffer::GetReader(message->body()));
IpcReadContext context(&dictionary_memo_, options_, swap_endian_);
return ReadRecordBatchInternal(*message->metadata(), schema_, field_inclusion_mask_,
context, reader.get())
.Value(batch);
}
std::shared_ptr<Schema> schema() const override { return out_schema_; }
ReadStats stats() const override { return stats_; }
private:
Result<std::unique_ptr<Message>> ReadNextMessage() {
ARROW_ASSIGN_OR_RAISE(auto message, message_reader_->ReadNextMessage());
if (message) {
++stats_.num_messages;
switch (message->type()) {
case MessageType::RECORD_BATCH:
++stats_.num_record_batches;
break;
case MessageType::DICTIONARY_BATCH:
++stats_.num_dictionary_batches;
break;
default:
break;
}
}
return std::move(message);
}
// Read dictionary from dictionary batch
Status ReadDictionary(const Message& message) {
DictionaryKind kind;
IpcReadContext context(&dictionary_memo_, options_, swap_endian_);
RETURN_NOT_OK(::arrow::ipc::ReadDictionary(message, context, &kind));
switch (kind) {
case DictionaryKind::New:
break;
case DictionaryKind::Delta:
++stats_.num_dictionary_deltas;
break;
case DictionaryKind::Replacement:
++stats_.num_replaced_dictionaries;
break;
}
return Status::OK();
}
Status ReadInitialDictionaries() {
// We must receive all dictionaries before reconstructing the
// first record batch. Subsequent dictionary deltas modify the memo
std::unique_ptr<Message> message;
// TODO(wesm): In future, we may want to reconcile the ids in the stream with
// those found in the schema
const auto num_dicts = dictionary_memo_.fields().num_dicts();
for (int i = 0; i < num_dicts; ++i) {
ARROW_ASSIGN_OR_RAISE(message, ReadNextMessage());
if (!message) {
if (i == 0) {
/// ARROW-6006: If we fail to find any dictionaries in the stream, then
/// it may be that the stream has a schema but no actual data. In such
/// case we communicate that we were unable to find the dictionaries
/// (but there was no failure otherwise), so the caller can decide what
/// to do
empty_stream_ = true;
break;
} else {
// ARROW-6126, the stream terminated before receiving the expected
// number of dictionaries
return Status::Invalid("IPC stream ended without reading the expected number (",
num_dicts, ") of dictionaries");
}
}
if (message->type() != MessageType::DICTIONARY_BATCH) {
return Status::Invalid("IPC stream did not have the expected number (", num_dicts,
") of dictionaries at the start of the stream");
}
RETURN_NOT_OK(ReadDictionary(*message));
}
have_read_initial_dictionaries_ = true;
return Status::OK();
}
std::unique_ptr<MessageReader> message_reader_;
IpcReadOptions options_;
std::vector<bool> field_inclusion_mask_;
bool have_read_initial_dictionaries_ = false;
// Flag to set in case where we fail to observe all dictionaries in a stream,
// and so the reader should not attempt to parse any messages
bool empty_stream_ = false;
ReadStats stats_;
DictionaryMemo dictionary_memo_;
std::shared_ptr<Schema> schema_, out_schema_;
bool swap_endian_;
};
// ----------------------------------------------------------------------
// Stream reader constructors
Result<std::shared_ptr<RecordBatchStreamReader>> RecordBatchStreamReader::Open(
std::unique_ptr<MessageReader> message_reader, const IpcReadOptions& options) {
// Private ctor
auto result = std::make_shared<RecordBatchStreamReaderImpl>();
RETURN_NOT_OK(result->Open(std::move(message_reader), options));
return result;
}
Result<std::shared_ptr<RecordBatchStreamReader>> RecordBatchStreamReader::Open(
io::InputStream* stream, const IpcReadOptions& options) {
return Open(MessageReader::Open(stream), options);
}