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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
|
// 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/array/validate.h"
#include <vector>
#include "arrow/array.h" // IWYU pragma: keep
#include "arrow/extension_type.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/decimal.h"
#include "arrow/util/int_util_overflow.h"
#include "arrow/util/logging.h"
#include "arrow/util/ree_util.h"
#include "arrow/util/sort.h"
#include "arrow/util/string.h"
#include "arrow/util/unreachable.h"
#include "arrow/util/utf8.h"
#include "arrow/visit_data_inline.h"
#include "arrow/visit_type_inline.h"
namespace arrow20::internal {
namespace {
struct UTF8DataValidator {
const ArrayData& data;
template <typename T>
Status Visit(const T&) {
if constexpr (std::is_same_v<T, StringType> || std::is_same_v<T, LargeStringType> ||
std::is_same_v<T, StringViewType>) {
util::InitializeUTF8();
int64_t i = 0;
return VisitArraySpanInline<T>(
data,
[&](std::string_view v) {
if (ARROW_PREDICT_FALSE(!util::ValidateUTF8(v))) {
return Status::Invalid("Invalid UTF8 sequence at string index ", i);
}
++i;
return Status::OK();
},
[&]() {
++i;
return Status::OK();
});
} else {
Unreachable("utf-8 validation of non string type");
}
}
};
struct BoundsChecker {
const ArrayData& data;
int64_t min_value;
int64_t max_value;
Status Visit(const DataType&) {
// Default, should be unreachable
return Status::NotImplemented("");
}
template <typename IntegerType>
enable_if_integer<IntegerType, Status> Visit(const IntegerType&) {
using c_type = typename IntegerType::c_type;
int64_t i = 0;
return VisitArraySpanInline<IntegerType>(
data,
[&](c_type value) {
const auto v = static_cast<int64_t>(value);
if (ARROW_PREDICT_FALSE(v < min_value || v > max_value)) {
return Status::Invalid("Value at position ", i, " out of bounds: ", v,
" (should be in [", min_value, ", ", max_value, "])");
}
++i;
return Status::OK();
},
[&]() {
++i;
return Status::OK();
});
}
};
struct ValidateArrayImpl {
const ArrayData& data;
const bool full_validation;
Status Validate() {
if (data.type == nullptr) {
return Status::Invalid("Array type is absent");
}
// XXX should we unpack extension types here?
RETURN_NOT_OK(ValidateLayout(*data.type));
// Check nulls *after* validating the buffer sizes, to avoid
// reading out of bounds.
RETURN_NOT_OK(ValidateNulls(*data.type));
// Run type-specific validations
return ValidateWithType(*data.type);
}
Status ValidateWithType(const DataType& type) {
if (type.id() != Type::EXTENSION) {
if (data.child_data.size() != static_cast<size_t>(type.num_fields())) {
return Status::Invalid("Expected ", type.num_fields(),
" child arrays in array "
"of type ",
type.ToString(), ", got ", data.child_data.size());
}
}
return VisitTypeInline(type, this);
}
Status Visit(const NullType&) {
if (data.null_count != data.length) {
return Status::Invalid("Null array null_count unequal to its length");
}
return Status::OK();
}
Status Visit(const FixedWidthType&) { return ValidateFixedWidthBuffers(); }
Status Visit(const Decimal32Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
return ValidateDecimals(type);
}
Status Visit(const Decimal64Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
return ValidateDecimals(type);
}
Status Visit(const Decimal128Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
return ValidateDecimals(type);
}
Status Visit(const Decimal256Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
return ValidateDecimals(type);
}
Status Visit(const StringType& type) {
RETURN_NOT_OK(ValidateBinaryLike(type));
if (full_validation) {
RETURN_NOT_OK(ValidateUTF8(data));
}
return Status::OK();
}
Status Visit(const LargeStringType& type) {
RETURN_NOT_OK(ValidateBinaryLike(type));
if (full_validation) {
RETURN_NOT_OK(ValidateUTF8(data));
}
return Status::OK();
}
Status Visit(const StringViewType& type) {
RETURN_NOT_OK(ValidateBinaryView(type));
if (full_validation) {
RETURN_NOT_OK(ValidateUTF8(data));
}
return Status::OK();
}
Status Visit(const Date64Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
if (full_validation) {
using c_type = typename Date64Type::c_type;
return VisitArraySpanInline<Date64Type>(
data,
[&](c_type date) {
constexpr c_type kFullDayMillis = 1000 * 60 * 60 * 24;
if (date % kFullDayMillis != 0) {
return Status::Invalid(type, " ", date,
" does not represent a whole number of days");
}
return Status::OK();
},
[]() { return Status::OK(); });
}
return Status::OK();
}
Status Visit(const Time32Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
if (full_validation) {
using c_type = typename Time32Type::c_type;
return VisitArraySpanInline<Time32Type>(
data,
[&](c_type time) {
constexpr c_type kFullDaySeconds = 60 * 60 * 24;
constexpr c_type kFullDayMillis = kFullDaySeconds * 1000;
if (type.unit() == TimeUnit::SECOND &&
(time < 0 || time >= kFullDaySeconds)) {
return Status::Invalid(type, " ", time,
" is not within the acceptable range of ", "[0, ",
kFullDaySeconds, ") s");
}
if (type.unit() == TimeUnit::MILLI && (time < 0 || time >= kFullDayMillis)) {
return Status::Invalid(type, " ", time,
" is not within the acceptable range of ", "[0, ",
kFullDayMillis, ") ms");
}
return Status::OK();
},
[]() { return Status::OK(); });
}
return Status::OK();
}
Status Visit(const Time64Type& type) {
RETURN_NOT_OK(ValidateFixedWidthBuffers());
if (full_validation) {
using c_type = typename Time64Type::c_type;
return VisitArraySpanInline<Time64Type>(
data,
[&](c_type time) {
constexpr c_type kFullDayMicro = 1000000LL * 60 * 60 * 24;
constexpr c_type kFullDayNano = kFullDayMicro * 1000;
if (type.unit() == TimeUnit::MICRO && (time < 0 || time >= kFullDayMicro)) {
return Status::Invalid(type, " ", time,
" is not within the acceptable range of ", "[0, ",
kFullDayMicro, ") us");
}
if (type.unit() == TimeUnit::NANO && (time < 0 || time >= kFullDayNano)) {
return Status::Invalid(type, " ", time,
" is not within the acceptable range of ", "[0, ",
kFullDayNano, ") ns");
}
return Status::OK();
},
[]() { return Status::OK(); });
}
return Status::OK();
}
Status Visit(const BinaryType& type) { return ValidateBinaryLike(type); }
Status Visit(const LargeBinaryType& type) { return ValidateBinaryLike(type); }
Status Visit(const BinaryViewType& type) { return ValidateBinaryView(type); }
Status Visit(const ListType& type) { return ValidateListLike(type); }
Status Visit(const LargeListType& type) { return ValidateListLike(type); }
Status Visit(const MapType& type) {
RETURN_NOT_OK(ValidateListLike(type));
return MapArray::ValidateChildData(data.child_data);
}
Status Visit(const ListViewType& type) { return ValidateListView(type); }
Status Visit(const LargeListViewType& type) { return ValidateListView(type); }
Status Visit(const FixedSizeListType& type) {
const ArrayData& values = *data.child_data[0];
const int64_t list_size = type.list_size();
if (list_size < 0) {
return Status::Invalid("Fixed size list has negative list size");
}
int64_t expected_values_length = -1;
if (MultiplyWithOverflow(data.length, list_size, &expected_values_length) ||
values.length < expected_values_length) {
return Status::Invalid("Values length (", values.length,
") is less than the length (", data.length,
") multiplied by the value size (", list_size, ")");
}
const Status child_valid = RecurseInto(values);
if (!child_valid.ok()) {
return Status::Invalid("Fixed size list child array invalid: ",
child_valid.ToString());
}
return Status::OK();
}
Status Visit(const StructType& type) {
for (int i = 0; i < type.num_fields(); ++i) {
const auto& field_data = *data.child_data[i];
// Validate child first, to catch nonsensical length / offset etc.
const Status field_valid = RecurseInto(field_data);
if (!field_valid.ok()) {
return Status::Invalid("Struct child array #", i,
" invalid: ", field_valid.ToString());
}
if (field_data.length < data.length + data.offset) {
return Status::Invalid("Struct child array #", i,
" has length smaller than expected for struct array (",
field_data.length, " < ", data.length + data.offset, ")");
}
const auto& field_type = type.field(i)->type();
if (!field_data.type->Equals(*field_type)) {
return Status::Invalid("Struct child array #", i, " does not match type field: ",
field_data.type->ToString(), " vs ",
field_type->ToString());
}
}
return Status::OK();
}
Status Visit(const UnionType& type) {
for (int i = 0; i < type.num_fields(); ++i) {
const auto& field_data = *data.child_data[i];
// Validate children first, to catch nonsensical length / offset etc.
const Status field_valid = RecurseInto(field_data);
if (!field_valid.ok()) {
return Status::Invalid("Union child array #", i,
" invalid: ", field_valid.ToString());
}
if (type.mode() == UnionMode::SPARSE &&
field_data.length < data.length + data.offset) {
return Status::Invalid("Sparse union child array #", i,
" has length smaller than expected for union array (",
field_data.length, " < ", data.length + data.offset, ")");
}
const auto& field_type = type.field(i)->type();
if (!field_data.type->Equals(*field_type)) {
return Status::Invalid("Union child array #", i, " does not match type field: ",
field_data.type->ToString(), " vs ",
field_type->ToString());
}
}
if (full_validation) {
// Validate all type codes
const auto& child_ids = type.child_ids();
const auto& type_codes_map = type.type_codes();
const int8_t* type_codes = data.GetValues<int8_t>(1);
for (int64_t i = 0; i < data.length; ++i) {
// Note that union arrays never have top-level nulls
const int32_t code = type_codes[i];
if (code < 0 || child_ids[code] == UnionType::kInvalidChildId) {
return Status::Invalid("Union value at position ", i, " has invalid type id ",
code);
}
}
if (type.mode() == UnionMode::DENSE) {
// Validate all offsets
// Map logical type id to child length
std::vector<int64_t> child_lengths(256);
for (int child_id = 0; child_id < type.num_fields(); ++child_id) {
child_lengths[type_codes_map[child_id]] = data.child_data[child_id]->length;
}
// Check offsets are in bounds
std::vector<int64_t> last_child_offsets(256, 0);
const int32_t* offsets = data.GetValues<int32_t>(2);
for (int64_t i = 0; i < data.length; ++i) {
const int32_t code = type_codes[i];
const int32_t offset = offsets[i];
if (offset < 0) {
return Status::Invalid("Union value at position ", i, " has negative offset ",
offset);
}
if (offset >= child_lengths[code]) {
return Status::Invalid("Union value at position ", i,
" has offset larger "
"than child length (",
offset, " >= ", child_lengths[code], ")");
}
if (offset < last_child_offsets[code]) {
return Status::Invalid("Union value at position ", i,
" has non-monotonic offset ", offset);
}
last_child_offsets[code] = offset;
}
}
}
return Status::OK();
}
Status Visit(const DictionaryType& type) {
Type::type index_type_id = type.index_type()->id();
if (!is_integer(index_type_id)) {
return Status::Invalid("Dictionary indices must be integer type");
}
if (!data.dictionary) {
return Status::Invalid("Dictionary values must be non-null");
}
// Validate dictionary
const Status dict_valid = RecurseInto(*data.dictionary);
if (!dict_valid.ok()) {
return Status::Invalid("Dictionary array invalid: ", dict_valid.ToString());
}
// Validate indices
RETURN_NOT_OK(ValidateWithType(*type.index_type()));
if (full_validation) {
// Check indices within dictionary bounds
const Status indices_status =
CheckBounds(*type.index_type(), 0, data.dictionary->length - 1);
if (!indices_status.ok()) {
return Status::Invalid("Dictionary indices invalid: ", indices_status.ToString());
}
}
return Status::OK();
}
Status Visit(const RunEndEncodedType& type) {
switch (type.run_end_type()->id()) {
case Type::INT16:
return ValidateRunEndEncoded<int16_t>(type);
case Type::INT32:
return ValidateRunEndEncoded<int32_t>(type);
case Type::INT64:
return ValidateRunEndEncoded<int64_t>(type);
default:
return Status::Invalid("Run end type must be int16, int32 or int64, but got: ",
type.run_end_type()->ToString());
}
}
Status Visit(const ExtensionType& type) {
// Visit storage
return ValidateWithType(*type.storage_type());
}
private:
bool IsBufferValid(int index) { return IsBufferValid(data, index); }
static bool IsBufferValid(const ArrayData& data, int index) {
return data.buffers[index] != nullptr && data.buffers[index]->address() != 0;
}
Status RecurseInto(const ArrayData& related_data) {
ValidateArrayImpl impl{related_data, full_validation};
return impl.Validate();
}
Status ValidateLayout(const DataType& type) {
// Check the data layout conforms to the spec
const auto layout = type.layout();
if (data.length < 0) {
return Status::Invalid("Array length is negative");
}
if (layout.variadic_spec) {
if (data.buffers.size() < layout.buffers.size()) {
return Status::Invalid("Expected at least ", layout.buffers.size(),
" buffers in array of type ", type.ToString(), ", got ",
data.buffers.size());
}
} else if (data.buffers.size() != layout.buffers.size()) {
return Status::Invalid("Expected ", layout.buffers.size(),
" buffers in array of type ", type.ToString(), ", got ",
data.buffers.size());
}
// This check is required to avoid addition overflow below
int64_t length_plus_offset = -1;
if (AddWithOverflow(data.length, data.offset, &length_plus_offset)) {
return Status::Invalid("Array of type ", type.ToString(),
" has impossibly large length and offset");
}
for (int i = 0; i < static_cast<int>(data.buffers.size()); ++i) {
const auto& buffer = data.buffers[i];
const auto& spec = i < static_cast<int>(layout.buffers.size())
? layout.buffers[i]
: *layout.variadic_spec;
if (buffer == nullptr) {
continue;
}
int64_t min_buffer_size = 0;
switch (spec.kind) {
case DataTypeLayout::BITMAP:
// If length == 0, buffer size can be 0 regardless of offset
if (data.length > 0) {
min_buffer_size = bit_util::BytesForBits(length_plus_offset);
}
break;
case DataTypeLayout::FIXED_WIDTH:
if (data.length > 0 && MultiplyWithOverflow(length_plus_offset, spec.byte_width,
&min_buffer_size)) {
return Status::Invalid("Array of type ", type.ToString(),
" has impossibly large length and offset");
}
break;
case DataTypeLayout::ALWAYS_NULL:
// XXX Should we raise on non-null buffer?
continue;
default:
continue;
}
if (buffer->size() < min_buffer_size) {
return Status::Invalid("Buffer #", i, " too small in array of type ",
type.ToString(), " and length ", data.length,
": expected at least ", min_buffer_size, " byte(s), got ",
buffer->size());
}
}
if (layout.has_dictionary && !data.dictionary) {
return Status::Invalid("Array of type ", type.ToString(),
" must have dictionary values");
}
if (!layout.has_dictionary && data.dictionary) {
return Status::Invalid("Unexpected dictionary values in array of type ",
type.ToString());
}
return Status::OK();
}
Status ValidateNulls(const DataType& type) {
if (type.storage_id() != Type::NA && data.null_count > 0 &&
data.buffers[0] == nullptr) {
return Status::Invalid("Array of type ", type.ToString(), " has ", data.null_count,
" nulls but no null bitmap");
}
if (data.null_count > data.length) {
return Status::Invalid("Null count exceeds array length");
}
if (data.null_count < 0 && data.null_count != kUnknownNullCount) {
return Status::Invalid("Negative null count");
}
if (full_validation) {
if (data.null_count != kUnknownNullCount) {
int64_t actual_null_count;
if (may_have_validity_bitmap(data.type->id()) && data.buffers[0]) {
// Do not call GetNullCount() as it would also set the `null_count` member
actual_null_count = data.length - CountSetBits(data.buffers[0]->data(),
data.offset, data.length);
} else if (data.type->storage_id() == Type::NA) {
actual_null_count = data.length;
} else {
actual_null_count = 0;
}
if (actual_null_count != data.null_count) {
return Status::Invalid("null_count value (", data.null_count,
") doesn't match actual number of nulls in array (",
actual_null_count, ")");
}
}
}
return Status::OK();
}
Status ValidateFixedWidthBuffers() {
if (data.length > 0 && !IsBufferValid(1)) {
return Status::Invalid("Missing values buffer in non-empty fixed-width array");
}
return Status::OK();
}
template <typename BinaryType>
Status ValidateBinaryLike(const BinaryType& type) {
if (!IsBufferValid(2)) {
return Status::Invalid("Value data buffer is null");
}
const Buffer& values = *data.buffers[2];
// First validate offsets, to make sure the accesses below are valid
RETURN_NOT_OK(ValidateOffsetsAndSizes(type, values.size()));
if (data.length > 0 && data.buffers[1]->is_cpu()) {
using offset_type = typename BinaryType::offset_type;
const auto offsets = data.GetValues<offset_type>(1);
const Buffer& values = *data.buffers[2];
const auto first_offset = offsets[0];
const auto last_offset = offsets[data.length];
// This early test avoids undefined behaviour when computing `data_extent`
if (first_offset < 0 || last_offset < 0) {
return Status::Invalid("Negative offsets in binary array");
}
const auto data_extent = last_offset - first_offset;
const auto values_length = values.size();
if (values_length < data_extent) {
return Status::Invalid("Length spanned by binary offsets (", data_extent,
") larger than values array (size ", values_length, ")");
}
// These tests ensure that array concatenation is safe if Validate() succeeds
// (for delta dictionaries)
if (first_offset > values_length || last_offset > values_length) {
return Status::Invalid("First or last binary offset out of bounds");
}
if (first_offset > last_offset) {
return Status::Invalid("First offset larger than last offset in binary array");
}
}
return Status::OK();
}
Status ValidateBinaryView(const BinaryViewType& type) {
int64_t views_byte_size = data.buffers[1]->size();
int64_t required_view_count = data.length + data.offset;
if (static_cast<int64_t>(views_byte_size / BinaryViewType::kSize) <
required_view_count) {
return Status::Invalid("View buffer size (bytes): ", views_byte_size,
" isn't large enough for length: ", data.length,
" and offset: ", data.offset);
}
if (!full_validation) return Status::OK();
auto CheckPrefix = [&](size_t i,
std::array<uint8_t, BinaryViewType::kPrefixSize> prefix,
const uint8_t* data) {
if (std::memcmp(data, prefix.data(), BinaryViewType::kPrefixSize) == 0) {
return Status::OK();
}
return Status::Invalid("View at slot ", i, " has inlined prefix 0x",
HexEncode(prefix.data(), BinaryViewType::kPrefixSize),
" but the out-of-line data begins with 0x",
HexEncode(data, BinaryViewType::kPrefixSize));
};
util::span views(data.GetValues<BinaryViewType::c_type>(1),
static_cast<size_t>(data.length));
util::span data_buffers(data.buffers.data() + 2, data.buffers.size() - 2);
for (size_t i = 0; i < static_cast<size_t>(data.length); ++i) {
if (data.IsNull(i)) continue;
if (views[i].size() < 0) {
return Status::Invalid("View at slot ", i, " has negative size ",
views[i].size());
}
if (views[i].is_inline()) {
auto padding_bytes = util::span(views[i].inlined.data).subspan(views[i].size());
for (auto padding_byte : padding_bytes) {
if (padding_byte != 0) {
return Status::Invalid("View at slot ", i, " was inline with size ",
views[i].size(),
" but its padding bytes were not all zero: ",
HexEncode(padding_bytes.data(), padding_bytes.size()));
}
}
continue;
}
auto [size, prefix, buffer_index, offset] = views[i].ref;
if (buffer_index < 0) {
return Status::Invalid("View at slot ", i, " has negative buffer index ",
buffer_index);
}
if (offset < 0) {
return Status::Invalid("View at slot ", i, " has negative offset ", offset);
}
if (static_cast<size_t>(buffer_index) >= data_buffers.size()) {
return Status::IndexError("View at slot ", i, " references buffer ", buffer_index,
" but there are only ", data_buffers.size(),
" data buffers");
}
const auto& buffer = data_buffers[buffer_index];
if (int64_t end = offset + static_cast<int64_t>(size); end > buffer->size()) {
return Status::IndexError(
"View at slot ", i, " references range ", offset, "-", end, " of buffer ",
buffer_index, " but that buffer is only ", buffer->size(), " bytes long");
}
RETURN_NOT_OK(CheckPrefix(i, prefix, buffer->data() + offset));
}
return Status::OK();
}
template <typename ListType>
Status ValidateListLike(const ListType& type) {
const ArrayData& values = *data.child_data[0];
const Status child_valid = RecurseInto(values);
if (!child_valid.ok()) {
return Status::Invalid("List child array invalid: ", child_valid.ToString());
}
// First validate offsets, to make sure the accesses below are valid
RETURN_NOT_OK(ValidateOffsetsAndSizes(type, values.offset + values.length));
// An empty list array can have 0 offsets
if (data.length > 0 && data.buffers[1]->is_cpu()) {
using offset_type = typename ListType::offset_type;
const auto offsets = data.GetValues<offset_type>(1);
const auto first_offset = offsets[0];
const auto last_offset = offsets[data.length];
// This early test avoids undefined behaviour when computing `data_extent`
if (first_offset < 0 || last_offset < 0) {
return Status::Invalid("Negative offsets in list array");
}
const auto data_extent = last_offset - first_offset;
const auto values_length = values.length;
if (values_length < data_extent) {
return Status::Invalid("Length spanned by list offsets (", data_extent,
") larger than values array (length ", values_length, ")");
}
// These tests ensure that array concatenation is safe if Validate() succeeds
// (for delta dictionaries)
if (first_offset > values_length || last_offset > values_length) {
return Status::Invalid("First or last list offset out of bounds");
}
if (first_offset > last_offset) {
return Status::Invalid("First offset larger than last offset in list array");
}
}
return Status::OK();
}
template <typename ListViewType>
Status ValidateListView(const ListViewType& type) {
const ArrayData& values = *data.child_data[0];
const Status child_valid = RecurseInto(values);
if (!child_valid.ok()) {
return Status::Invalid("List-view child array is invalid: ",
child_valid.ToString());
}
// For list-views, sizes are validated together with offsets.
return ValidateOffsetsAndSizes(type, /*offset_limit=*/values.length);
}
template <typename RunEndCType>
Status ValidateRunEndEncoded(const RunEndEncodedType& type) {
if (data.child_data.size() != 2) {
return Status::Invalid(
"Run end encoded array should have 2 children; this array has ",
data.child_data.size());
}
if (data.buffers.size() > 0 && data.buffers[0] != nullptr) {
return Status::Invalid("Run end encoded array should not have a null bitmap.");
}
const auto& run_ends_data = data.child_data[0];
const auto& values_data = data.child_data[1];
if (!run_ends_data) {
return Status::Invalid("Run ends array is null pointer");
}
if (!values_data) {
return Status::Invalid("Values array is null pointer");
}
// We must validate child array buffers are valid before making additional checks.
const Status run_ends_valid = RecurseInto(*run_ends_data);
if (!run_ends_valid.ok()) {
return Status::Invalid("Run ends array invalid: ", run_ends_valid.message());
}
const Status values_valid = RecurseInto(*values_data);
if (!values_valid.ok()) {
return Status::Invalid("Values array invalid: ", values_valid.message());
}
RETURN_NOT_OK(ree_util::ValidateRunEndEncodedChildren(
type, data.length, run_ends_data, values_data, data.GetNullCount(), data.offset));
if (run_ends_data->length == 0) {
return Status::OK();
}
if (full_validation) {
ArraySpan span(data);
const auto* run_ends = ree_util::RunEnds<RunEndCType>(span);
const int64_t run_ends_length = ree_util::RunEndsArray(span).length;
if (run_ends[0] < 1) {
return Status::Invalid(
"All run ends must be greater than 0 but the first run end is ", run_ends[0]);
}
int64_t last_run_end = run_ends[0];
for (int64_t index = 1; index < run_ends_length; index++) {
const int64_t run_end = run_ends[index];
if (run_end <= last_run_end) {
return Status::Invalid(
"Every run end must be strictly greater than the previous run end, "
"but run_ends[",
index, "] is ", run_end, " and run_ends[", index - 1, "] is ",
last_run_end);
}
last_run_end = run_end;
}
}
return Status::OK();
}
private:
/// \pre basic validation has already been performed
template <typename offset_type>
Status FullyValidateOffsets(int64_t offset_limit) {
const auto* offsets = data.GetValues<offset_type>(1);
auto prev_offset = offsets[0];
if (prev_offset < 0) {
return Status::Invalid("Offset invariant failure: array starts at negative offset ",
prev_offset);
}
for (int64_t i = 1; i <= data.length; ++i) {
const auto current_offset = offsets[i];
if (current_offset < prev_offset) {
return Status::Invalid("Offset invariant failure: non-monotonic offset at slot ",
i, ": ", current_offset, " < ", prev_offset);
}
if (current_offset > offset_limit) {
return Status::Invalid("Offset invariant failure: offset for slot ", i,
" out of bounds: ", current_offset, " > ", offset_limit);
}
prev_offset = current_offset;
}
return Status::OK();
}
template <typename offset_type>
Status OutOfBoundsListViewOffset(int64_t slot, int64_t offset_limit) {
const auto* offsets = data.GetValues<offset_type>(1);
const auto offset = offsets[slot];
return Status::Invalid("Offset invariant failure: offset for slot ", slot,
" out of bounds. Expected ", offset,
" to be at least 0 and less than ", offset_limit);
}
template <typename offset_type>
Status OutOfBoundsListViewSize(int64_t slot, int64_t offset_limit) {
const auto* offsets = data.GetValues<offset_type>(1);
const auto* sizes = data.GetValues<offset_type>(2);
const auto size = sizes[slot];
if (size < 0) {
return Status::Invalid("Offset invariant failure: size for slot ", slot,
" out of bounds: ", size, " < 0");
} else {
const auto offset = offsets[slot];
return Status::Invalid("Offset invariant failure: size for slot ", slot,
" out of bounds: ", offset, " + ", size, " > ",
offset_limit);
}
}
/// \pre basic validation has already been performed
template <typename offset_type>
Status FullyValidateOffsetsAndSizes(int64_t offset_limit) {
const auto* offsets = data.GetValues<offset_type>(1);
const auto* sizes = data.GetValues<offset_type>(2);
for (int64_t i = 0; i < data.length; ++i) {
const auto size = sizes[i];
if (size >= 0) {
const auto offset = offsets[i];
if (offset < 0 || offset > offset_limit) {
return OutOfBoundsListViewOffset<offset_type>(i, offset_limit);
}
if (size > offset_limit - offset) {
return OutOfBoundsListViewSize<offset_type>(i, offset_limit);
}
} else {
return OutOfBoundsListViewSize<offset_type>(i, offset_limit);
}
}
return Status::OK();
}
public:
template <typename TypeClass>
Status ValidateOffsetsAndSizes(const TypeClass&, int64_t offset_limit) {
using offset_type = typename TypeClass::offset_type;
constexpr bool is_list_view = is_list_view_type<TypeClass>::value;
const bool non_empty = data.length > 0;
if constexpr (is_list_view) {
if (!IsBufferValid(1)) {
return Status::Invalid("offsets buffer is null");
}
if (!IsBufferValid(2)) {
return Status::Invalid("sizes buffer is null");
}
} else {
if (!IsBufferValid(1)) {
// For length 0, an empty offsets buffer is accepted (ARROW-544).
return non_empty ? Status::Invalid("Non-empty array but offsets are null")
: Status::OK();
}
}
const auto offsets_byte_size = data.buffers[1]->size();
const auto required_offsets = ((data.length > 0) || (offsets_byte_size > 0))
? data.length + data.offset + (is_list_view ? 0 : 1)
: 0;
if (offsets_byte_size / static_cast<int32_t>(sizeof(offset_type)) <
required_offsets) {
return Status::Invalid("Offsets buffer size (bytes): ", offsets_byte_size,
" isn't large enough for length: ", data.length,
" and offset: ", data.offset);
}
if constexpr (is_list_view) {
const auto required_sizes = data.length + data.offset;
const auto sizes_bytes_size = data.buffers[2]->size();
if (sizes_bytes_size / static_cast<int32_t>(sizeof(offset_type)) < required_sizes) {
return Status::Invalid("Sizes buffer size (bytes): ", sizes_bytes_size,
" isn't large enough for length: ", data.length,
" and offset: ", data.offset);
}
}
if (full_validation && required_offsets > 0) {
if constexpr (is_list_view) {
return FullyValidateOffsetsAndSizes<offset_type>(offset_limit);
} else {
return FullyValidateOffsets<offset_type>(offset_limit);
}
}
return Status::OK();
}
template <typename DecimalType>
Status ValidateDecimals(const DecimalType& type) {
using CType = typename TypeTraits<DecimalType>::CType;
if (full_validation) {
const int32_t precision = type.precision();
return VisitArraySpanInline<DecimalType>(
data,
[&](std::string_view bytes) {
DCHECK_EQ(bytes.size(), DecimalType::kByteWidth);
CType value(reinterpret_cast<const uint8_t*>(bytes.data()));
if (!value.FitsInPrecision(precision)) {
return Status::Invalid("Decimal value ", value.ToIntegerString(),
" does not fit in precision of ", type);
}
return Status::OK();
},
[]() { return Status::OK(); });
}
return Status::OK();
}
Status CheckBounds(const DataType& type, int64_t min_value, int64_t max_value) {
BoundsChecker checker{data, min_value, max_value};
return VisitTypeInline(type, &checker);
}
};
} // namespace
ARROW_EXPORT
Status ValidateArray(const ArrayData& data) {
ValidateArrayImpl validator{data, /*full_validation=*/false};
return validator.Validate();
}
ARROW_EXPORT
Status ValidateArray(const Array& array) { return ValidateArray(*array.data()); }
ARROW_EXPORT
Status ValidateArrayFull(const ArrayData& data) {
return ValidateArrayImpl{data, /*full_validation=*/true}.Validate();
}
ARROW_EXPORT
Status ValidateArrayFull(const Array& array) { return ValidateArrayFull(*array.data()); }
ARROW_EXPORT
Status ValidateUTF8(const ArrayData& data) {
const auto& storage_type =
(data.type->id() == Type::EXTENSION)
? checked_cast<const ExtensionType&>(*data.type).storage_type()
: data.type;
DCHECK(storage_type->id() == Type::STRING || storage_type->id() == Type::STRING_VIEW ||
storage_type->id() == Type::LARGE_STRING);
if (data.type->id() == Type::EXTENSION) {
ArrayData ext_data(data);
ext_data.type = storage_type;
UTF8DataValidator validator{ext_data};
return VisitTypeInline(*storage_type, &validator);
} else {
UTF8DataValidator validator{data};
return VisitTypeInline(*storage_type, &validator);
}
}
ARROW_EXPORT
Status ValidateUTF8(const Array& array) { return ValidateUTF8(*array.data()); }
} // namespace arrow20::internal
|