forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec_test.cc
More file actions
1375 lines (1121 loc) · 49.1 KB
/
Copy pathexec_test.cc
File metadata and controls
1375 lines (1121 loc) · 49.1 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 <cstring>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/random.h"
#include "arrow/array/array_base.h"
#include "arrow/array/data.h"
#include "arrow/buffer.h"
#include "arrow/chunked_array.h"
#include "arrow/compute/exec.h"
#include "arrow/compute/exec_internal.h"
#include "arrow/compute/function.h"
#include "arrow/compute/function_internal.h"
#include "arrow/compute/kernel.h"
#include "arrow/compute/registry.h"
#include "arrow/memory_pool.h"
#include "arrow/record_batch.h"
#include "arrow/scalar.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_ops.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/cpu_info.h"
#include "arrow/util/logging.h"
namespace arrow {
using internal::checked_cast;
namespace compute {
namespace detail {
using ::arrow::internal::BitmapEquals;
using ::arrow::internal::CopyBitmap;
using ::arrow::internal::CountSetBits;
TEST(ExecBatch, SliceBasics) {
int64_t length = 4, cut_length = 2, left_length = length - cut_length;
ExecBatch batch{{Int32Scalar(0), ArrayFromJSON(utf8(), R"(["a", "b", "c", "d"])"),
ChunkedArrayFromJSON(float64(), {"[1.1]", "[2.2]", "[3.3]", "[4.4]"})},
length};
std::vector<ExecBatch> expected_sliced{
{{Int32Scalar(0), ArrayFromJSON(utf8(), R"(["a", "b"])"),
ChunkedArrayFromJSON(float64(), {"[1.1]", "[2.2]"})},
cut_length},
{{Int32Scalar(0), ArrayFromJSON(utf8(), R"(["c", "d"])"),
ChunkedArrayFromJSON(float64(), {"[3.3]", "[4.4]"})},
left_length}};
std::vector<ExecBatch> actual_sliced = {batch.Slice(0, cut_length),
batch.Slice(cut_length, left_length)};
for (size_t i = 0; i < expected_sliced.size(); i++) {
ASSERT_EQ(expected_sliced[i].length, actual_sliced[i].length);
ASSERT_EQ(expected_sliced[i].values.size(), actual_sliced[i].values.size());
for (size_t j = 0; j < expected_sliced[i].values.size(); j++) {
AssertDatumsEqual(expected_sliced[i].values[j], actual_sliced[i].values[j]);
}
ASSERT_EQ(expected_sliced[i].ToString(), actual_sliced[i].ToString());
}
}
TEST(ExecBatch, ToRecordBatch) {
auto i32_array = ArrayFromJSON(int32(), "[0, 1, 2]");
auto utf8_array = ArrayFromJSON(utf8(), R"(["a", "b", "c"])");
ExecBatch exec_batch({Datum(i32_array), Datum(utf8_array)}, 3);
auto right_schema = schema({field("a", int32()), field("b", utf8())});
ASSERT_OK_AND_ASSIGN(auto right_record_batch, exec_batch.ToRecordBatch(right_schema));
ASSERT_OK(right_record_batch->ValidateFull());
auto expected_batch = RecordBatchFromJSON(right_schema, R"([
{"a": 0, "b": "a"},
{"a": 1, "b": "b"},
{"a": 2, "b": "c"}
])");
AssertBatchesEqual(*right_record_batch, *expected_batch);
// With a scalar column
auto utf8_scalar = ScalarFromJSON(utf8(), R"("z")");
exec_batch = ExecBatch({Datum(i32_array), Datum(utf8_scalar)}, 3);
ASSERT_OK_AND_ASSIGN(right_record_batch, exec_batch.ToRecordBatch(right_schema));
ASSERT_OK(right_record_batch->ValidateFull());
expected_batch = RecordBatchFromJSON(right_schema, R"([
{"a": 0, "b": "z"},
{"a": 1, "b": "z"},
{"a": 2, "b": "z"}
])");
AssertBatchesEqual(*right_record_batch, *expected_batch);
// Wrong number of fields in schema
auto reject_schema =
schema({field("a", int32()), field("b", utf8()), field("c", float64())});
ASSERT_RAISES(Invalid, exec_batch.ToRecordBatch(reject_schema));
// Wrong-kind exec batch (not really valid, but test it here anyway)
ExecBatch miskinded_batch({Datum()}, 0);
auto null_schema = schema({field("a", null())});
ASSERT_RAISES(TypeError, miskinded_batch.ToRecordBatch(null_schema));
}
TEST(ExecContext, BasicWorkings) {
{
ExecContext ctx;
ASSERT_EQ(GetFunctionRegistry(), ctx.func_registry());
ASSERT_EQ(default_memory_pool(), ctx.memory_pool());
ASSERT_EQ(std::numeric_limits<int64_t>::max(), ctx.exec_chunksize());
ASSERT_TRUE(ctx.use_threads());
ASSERT_EQ(arrow::internal::CpuInfo::GetInstance(), ctx.cpu_info());
}
// Now, let's customize all the things
LoggingMemoryPool my_pool(default_memory_pool());
std::unique_ptr<FunctionRegistry> custom_reg = FunctionRegistry::Make();
ExecContext ctx(&my_pool, /*executor=*/nullptr, custom_reg.get());
ASSERT_EQ(custom_reg.get(), ctx.func_registry());
ASSERT_EQ(&my_pool, ctx.memory_pool());
ctx.set_exec_chunksize(1 << 20);
ASSERT_EQ(1 << 20, ctx.exec_chunksize());
ctx.set_use_threads(false);
ASSERT_FALSE(ctx.use_threads());
}
TEST(SelectionVector, Basics) {
auto indices = ArrayFromJSON(int32(), "[0, 3]");
auto sel_vector = std::make_shared<SelectionVector>(*indices);
ASSERT_EQ(indices->length(), sel_vector->length());
ASSERT_EQ(3, sel_vector->indices()[1]);
}
void AssertValidityZeroExtraBits(const uint8_t* data, int64_t length, int64_t offset) {
const int64_t bit_extent = ((offset + length + 7) / 8) * 8;
for (int64_t i = offset + length; i < bit_extent; ++i) {
EXPECT_FALSE(bit_util::GetBit(data, i)) << i;
}
}
void AssertValidityZeroExtraBits(const ArraySpan& arr) {
return AssertValidityZeroExtraBits(arr.buffers[0].data, arr.length, arr.offset);
}
void AssertValidityZeroExtraBits(const ArrayData& arr) {
const Buffer& buf = *arr.buffers[0];
return AssertValidityZeroExtraBits(buf.data(), arr.length, arr.offset);
}
class TestComputeInternals : public ::testing::Test {
public:
void SetUp() {
rng_.reset(new random::RandomArrayGenerator(/*seed=*/0));
ResetContexts();
}
void ResetContexts() {
exec_ctx_.reset(new ExecContext(default_memory_pool()));
ctx_.reset(new KernelContext(exec_ctx_.get()));
}
std::shared_ptr<Array> GetUInt8Array(int64_t size, double null_probability = 0.1) {
return rng_->UInt8(size, /*min=*/0, /*max=*/100, null_probability);
}
std::shared_ptr<Array> GetInt32Array(int64_t size, double null_probability = 0.1) {
return rng_->Int32(size, /*min=*/0, /*max=*/1000, null_probability);
}
std::shared_ptr<Array> GetFloat64Array(int64_t size, double null_probability = 0.1) {
return rng_->Float64(size, /*min=*/0, /*max=*/1000, null_probability);
}
std::shared_ptr<ChunkedArray> GetInt32Chunked(const std::vector<int>& sizes) {
std::vector<std::shared_ptr<Array>> chunks;
for (auto size : sizes) {
chunks.push_back(GetInt32Array(size));
}
return std::make_shared<ChunkedArray>(std::move(chunks));
}
protected:
std::unique_ptr<ExecContext> exec_ctx_;
std::unique_ptr<KernelContext> ctx_;
std::unique_ptr<random::RandomArrayGenerator> rng_;
};
// ----------------------------------------------------------------------
// Test PropagateNulls
class TestPropagateNulls : public TestComputeInternals {};
TEST_F(TestPropagateNulls, UnknownNullCountWithNullsZeroCopies) {
const int64_t length = 16;
constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
ArrayData output(boolean(), length, {nullptr, nullptr});
ArrayData input(boolean(), length, {nulls, nullptr}, kUnknownNullCount);
ExecBatch batch({input}, length);
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(nulls.get(), output.buffers[0].get());
ASSERT_EQ(kUnknownNullCount, output.null_count);
ASSERT_EQ(9, output.GetNullCount());
}
TEST_F(TestPropagateNulls, UnknownNullCountWithoutNulls) {
const int64_t length = 16;
constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
ArrayData output(boolean(), length, {nullptr, nullptr});
ArrayData input(boolean(), length, {nulls, nullptr}, kUnknownNullCount);
ExecBatch batch({input}, length);
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
EXPECT_EQ(-1, output.null_count);
EXPECT_EQ(nulls.get(), output.buffers[0].get());
}
TEST_F(TestPropagateNulls, SetAllNulls) {
const int64_t length = 16;
auto CheckSetAllNull = [&](std::vector<Datum> values, bool preallocate) {
// Make fresh bitmap with all 1's
uint8_t bitmap_data[2] = {255, 255};
auto preallocated_mem = std::make_shared<MutableBuffer>(bitmap_data, 2);
std::vector<std::shared_ptr<Buffer>> buffers(2);
if (preallocate) {
buffers[0] = preallocated_mem;
}
ArrayData output(boolean(), length, buffers);
ExecBatch batch(values, length);
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
if (preallocate) {
// Ensure that buffer object the same when we pass in preallocated memory
ASSERT_EQ(preallocated_mem.get(), output.buffers[0].get());
}
ASSERT_NE(nullptr, output.buffers[0]);
uint8_t expected[2] = {0, 0};
const Buffer& out_buf = *output.buffers[0];
ASSERT_EQ(0, std::memcmp(out_buf.data(), expected, out_buf.size()));
};
// There is a null scalar
std::shared_ptr<Scalar> i32_val = std::make_shared<Int32Scalar>(3);
std::vector<Datum> vals = {i32_val, MakeNullScalar(boolean())};
CheckSetAllNull(vals, true);
CheckSetAllNull(vals, false);
const double true_prob = 0.5;
vals[0] = rng_->Boolean(length, true_prob);
CheckSetAllNull(vals, true);
CheckSetAllNull(vals, false);
auto arr_all_nulls = rng_->Boolean(length, true_prob, /*null_probability=*/1);
// One value is all null
vals = {rng_->Boolean(length, true_prob, /*null_probability=*/0.5), arr_all_nulls};
CheckSetAllNull(vals, true);
CheckSetAllNull(vals, false);
// A value is NullType
std::shared_ptr<Array> null_arr = std::make_shared<NullArray>(length);
vals = {rng_->Boolean(length, true_prob), null_arr};
CheckSetAllNull(vals, true);
CheckSetAllNull(vals, false);
// Other nitty-gritty scenarios
{
// An all-null bitmap is zero-copied over, even though there is a
// null-scalar earlier in the batch
ArrayData output(boolean(), length, {nullptr, nullptr});
ExecBatch batch({MakeNullScalar(boolean()), arr_all_nulls}, length);
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(arr_all_nulls->data()->buffers[0].get(), output.buffers[0].get());
}
}
TEST_F(TestPropagateNulls, SingleValueWithNulls) {
// Input offset is non-zero (0 mod 8 and nonzero mod 8 cases)
const int64_t length = 100;
auto arr = rng_->Boolean(length, 0.5, /*null_probability=*/0.5);
auto CheckSliced = [&](int64_t offset, bool preallocate = false,
int64_t out_offset = 0) {
// Unaligned bitmap, zero copy not possible
auto sliced = arr->Slice(offset);
std::vector<Datum> vals = {sliced};
ArrayData output(boolean(), vals[0].length(), {nullptr, nullptr});
output.offset = out_offset;
ExecBatch batch(vals, vals[0].length());
std::shared_ptr<Buffer> preallocated_bitmap;
if (preallocate) {
ASSERT_OK_AND_ASSIGN(
preallocated_bitmap,
AllocateBuffer(bit_util::BytesForBits(sliced->length() + out_offset)));
std::memset(preallocated_bitmap->mutable_data(), 0, preallocated_bitmap->size());
output.buffers[0] = preallocated_bitmap;
} else {
ASSERT_EQ(0, output.offset);
}
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
if (!preallocate) {
const Buffer* parent_buf = arr->data()->buffers[0].get();
if (offset == 0) {
// Validity bitmap same, no slice
ASSERT_EQ(parent_buf, output.buffers[0].get());
} else if (offset % 8 == 0) {
// Validity bitmap sliced
ASSERT_NE(parent_buf, output.buffers[0].get());
ASSERT_EQ(parent_buf, output.buffers[0]->parent().get());
} else {
// New memory for offset not 0 mod 8
ASSERT_NE(parent_buf, output.buffers[0].get());
ASSERT_EQ(nullptr, output.buffers[0]->parent());
}
} else {
// preallocated, so check that the validity bitmap is unbothered
ASSERT_EQ(preallocated_bitmap.get(), output.buffers[0].get());
}
ASSERT_EQ(arr->Slice(offset)->null_count(), output.GetNullCount());
ASSERT_TRUE(BitmapEquals(output.buffers[0]->data(), output.offset,
sliced->null_bitmap_data(), sliced->offset(),
output.length));
AssertValidityZeroExtraBits(output);
};
CheckSliced(8);
CheckSliced(7);
CheckSliced(8, /*preallocated=*/true);
CheckSliced(7, true);
CheckSliced(8, true, /*offset=*/4);
CheckSliced(7, true, 4);
}
TEST_F(TestPropagateNulls, ZeroCopyWhenZeroNullsOnOneInput) {
const int64_t length = 16;
constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
ArrayData some_nulls(boolean(), 16, {nulls, nullptr}, /*null_count=*/9);
ArrayData no_nulls(boolean(), length, {nullptr, nullptr}, /*null_count=*/0);
ArrayData output(boolean(), length, {nullptr, nullptr});
ExecBatch batch({some_nulls, no_nulls}, length);
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(nulls.get(), output.buffers[0].get());
ASSERT_EQ(9, output.null_count);
// Flip order of args
output = ArrayData(boolean(), length, {nullptr, nullptr});
batch.values = {no_nulls, no_nulls, some_nulls};
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(nulls.get(), output.buffers[0].get());
ASSERT_EQ(9, output.null_count);
// Check that preallocated memory is not clobbered
uint8_t bitmap_data[2] = {0, 0};
auto preallocated_mem = std::make_shared<MutableBuffer>(bitmap_data, 2);
output.null_count = kUnknownNullCount;
output.buffers[0] = preallocated_mem;
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(preallocated_mem.get(), output.buffers[0].get());
ASSERT_EQ(9, output.null_count);
ASSERT_EQ(254, bitmap_data[0]);
ASSERT_EQ(0, bitmap_data[1]);
}
TEST_F(TestPropagateNulls, IntersectsNulls) {
const int64_t length = 16;
// 0b01111111 0b11001111
constexpr uint8_t bitmap1[8] = {127, 207, 0, 0, 0, 0, 0, 0};
// 0b11111110 0b01111111
constexpr uint8_t bitmap2[8] = {254, 127, 0, 0, 0, 0, 0, 0};
// 0b11101111 0b11111110
constexpr uint8_t bitmap3[8] = {239, 254, 0, 0, 0, 0, 0, 0};
ArrayData arr1(boolean(), length, {std::make_shared<Buffer>(bitmap1, 8), nullptr});
ArrayData arr2(boolean(), length, {std::make_shared<Buffer>(bitmap2, 8), nullptr});
ArrayData arr3(boolean(), length, {std::make_shared<Buffer>(bitmap3, 8), nullptr});
auto CheckCase = [&](std::vector<Datum> values, int64_t ex_null_count,
const uint8_t* ex_bitmap, bool preallocate = false,
int64_t output_offset = 0) {
ExecBatch batch(values, length);
std::shared_ptr<Buffer> nulls;
if (preallocate) {
// Make the buffer one byte bigger so we can have non-zero offsets
ASSERT_OK_AND_ASSIGN(nulls, AllocateBuffer(3));
std::memset(nulls->mutable_data(), 0, nulls->size());
} else {
// non-zero output offset not permitted unless the output memory is
// preallocated
ASSERT_EQ(0, output_offset);
}
ArrayData output(boolean(), length, {nulls, nullptr});
output.offset = output_offset;
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
// Preallocated memory used
if (preallocate) {
ASSERT_EQ(nulls.get(), output.buffers[0].get());
}
EXPECT_EQ(kUnknownNullCount, output.null_count);
EXPECT_EQ(ex_null_count, output.GetNullCount());
const auto& out_buffer = *output.buffers[0];
ASSERT_TRUE(BitmapEquals(out_buffer.data(), output_offset, ex_bitmap,
/*ex_offset=*/0, length));
// Now check that the rest of the bits in out_buffer are still 0
AssertValidityZeroExtraBits(output);
};
// 0b01101110 0b01001110
uint8_t expected1[2] = {110, 78};
CheckCase({arr1, arr2, arr3}, 7, expected1);
CheckCase({arr1, arr2, arr3}, 7, expected1, /*preallocate=*/true);
CheckCase({arr1, arr2, arr3}, 7, expected1, /*preallocate=*/true,
/*output_offset=*/4);
// 0b01111110 0b01001111
uint8_t expected2[2] = {126, 79};
CheckCase({arr1, arr2}, 5, expected2);
CheckCase({arr1, arr2}, 5, expected2, /*preallocate=*/true,
/*output_offset=*/4);
}
TEST_F(TestPropagateNulls, NullOutputTypeNoop) {
// Ensure we leave the buffers alone when the output type is null()
const int64_t length = 100;
ExecBatch batch({rng_->Boolean(100, 0.5, 0.5)}, length);
ArrayData output(null(), length, {nullptr});
ASSERT_OK(PropagateNulls(ctx_.get(), ExecSpan(batch), &output));
ASSERT_EQ(nullptr, output.buffers[0]);
}
// ----------------------------------------------------------------------
// Test PropagateNullsSpans (new span-based implementation). Some of
// the tests above had to be rewritten because the span-based
// implementation does not deal with zero-copy optimizations right now
class TestPropagateNullsSpans : public TestComputeInternals {};
TEST_F(TestPropagateNullsSpans, UnknownNullCountWithNullsZeroCopies) {
const int64_t length = 16;
const uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
auto ty = boolean();
ArrayData input(ty, length, {nulls, nullptr}, kUnknownNullCount);
uint8_t validity_bitmap2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
auto nulls2 = std::make_shared<Buffer>(validity_bitmap2, 8);
ArraySpan output(ty.get(), length);
output.buffers[0].data = validity_bitmap2;
output.buffers[0].size = 0;
ExecSpan span(ExecBatch({input}, length));
PropagateNullsSpans(span, &output);
ASSERT_EQ(kUnknownNullCount, output.null_count);
ASSERT_EQ(9, output.GetNullCount());
}
TEST_F(TestPropagateNullsSpans, UnknownNullCountWithoutNulls) {
const int64_t length = 16;
constexpr uint8_t validity_bitmap[8] = {255, 255, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
auto ty = boolean();
ArrayData input(ty, length, {nulls, nullptr}, kUnknownNullCount);
uint8_t validity_bitmap2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
auto nulls2 = std::make_shared<Buffer>(validity_bitmap2, 8);
ArraySpan output(ty.get(), length);
output.buffers[0].data = validity_bitmap2;
output.buffers[0].size = 0;
ExecSpan span(ExecBatch({input}, length));
PropagateNullsSpans(span, &output);
ASSERT_EQ(kUnknownNullCount, output.null_count);
ASSERT_EQ(0, output.GetNullCount());
}
TEST_F(TestPropagateNullsSpans, SetAllNulls) {
const int64_t length = 16;
auto CheckSetAllNull = [&](std::vector<Datum> values) {
// Make fresh bitmap with all 1's
uint8_t bitmap_data[2] = {255, 255};
auto buf = std::make_shared<MutableBuffer>(bitmap_data, 2);
auto ty = boolean();
ArraySpan output(ty.get(), length);
output.SetBuffer(0, buf);
ExecSpan span(ExecBatch(values, length));
PropagateNullsSpans(span, &output);
uint8_t expected[2] = {0, 0};
ASSERT_EQ(0, std::memcmp(output.buffers[0].data, expected, output.buffers[0].size));
};
// There is a null scalar
std::shared_ptr<Scalar> i32_val = std::make_shared<Int32Scalar>(3);
std::vector<Datum> vals = {i32_val, MakeNullScalar(boolean())};
CheckSetAllNull(vals);
const double true_prob = 0.5;
vals[0] = rng_->Boolean(length, true_prob);
CheckSetAllNull(vals);
auto arr_all_nulls = rng_->Boolean(length, true_prob, /*null_probability=*/1);
// One value is all null
vals = {rng_->Boolean(length, true_prob, /*null_probability=*/0.5), arr_all_nulls};
CheckSetAllNull(vals);
// A value is NullType
std::shared_ptr<Array> null_arr = std::make_shared<NullArray>(length);
vals = {rng_->Boolean(length, true_prob), null_arr};
CheckSetAllNull(vals);
}
TEST_F(TestPropagateNullsSpans, SingleValueWithNulls) {
// Input offset is non-zero (0 mod 8 and nonzero mod 8 cases)
const int64_t length = 100;
auto arr = rng_->Boolean(length, 0.5, /*null_probability=*/0.5);
auto CheckSliced = [&](int64_t offset, int64_t out_offset = 0) {
// Unaligned bitmap, zero copy not possible
auto sliced = arr->Slice(offset);
std::vector<Datum> vals = {sliced};
auto ty = boolean();
ArraySpan output(ty.get(), vals[0].length());
output.offset = out_offset;
std::shared_ptr<Buffer> preallocated_bitmap;
ASSERT_OK_AND_ASSIGN(
preallocated_bitmap,
AllocateBuffer(bit_util::BytesForBits(sliced->length() + out_offset)));
std::memset(preallocated_bitmap->mutable_data(), 0, preallocated_bitmap->size());
output.SetBuffer(0, preallocated_bitmap);
ExecBatch batch(vals, vals[0].length());
PropagateNullsSpans(ExecSpan(batch), &output);
ASSERT_EQ(arr->Slice(offset)->null_count(), output.GetNullCount());
ASSERT_TRUE(BitmapEquals(output.buffers[0].data, output.offset,
sliced->null_bitmap_data(), sliced->offset(),
output.length));
AssertValidityZeroExtraBits(output);
};
CheckSliced(8);
CheckSliced(7);
CheckSliced(8, /*offset=*/4);
CheckSliced(7, /*offset=*/4);
}
TEST_F(TestPropagateNullsSpans, CasesThatUsedToBeZeroCopy) {
// ARROW-16576: testing behaviors that used to be zero copy but are
// not anymore
const int64_t length = 16;
auto ty = boolean();
constexpr uint8_t validity_bitmap[8] = {254, 0, 0, 0, 0, 0, 0, 0};
auto nulls = std::make_shared<Buffer>(validity_bitmap, 8);
ArraySpan some_nulls(ty.get(), length);
some_nulls.SetBuffer(0, nulls);
some_nulls.null_count = 9;
ArraySpan no_nulls(ty.get(), length);
no_nulls.null_count = 0;
{
uint8_t bitmap_data[2] = {0, 0};
auto preallocated_mem = std::make_shared<Buffer>(bitmap_data, 2);
ArraySpan output(ty.get(), length);
output.SetBuffer(0, preallocated_mem);
PropagateNullsSpans(ExecSpan({some_nulls, no_nulls}, length), &output);
ASSERT_EQ(
0, std::memcmp(output.buffers[0].data, validity_bitmap, output.buffers[0].size));
ASSERT_EQ(output.buffers[0].owner, &preallocated_mem);
ASSERT_EQ(9, output.GetNullCount());
}
// Flip order of args
{
uint8_t bitmap_data[2] = {0, 0};
auto preallocated_mem = std::make_shared<Buffer>(bitmap_data, 2);
ArraySpan output(ty.get(), length);
output.SetBuffer(0, preallocated_mem);
PropagateNullsSpans(ExecSpan({no_nulls, no_nulls, some_nulls}, length), &output);
ASSERT_EQ(
0, std::memcmp(output.buffers[0].data, validity_bitmap, output.buffers[0].size));
ASSERT_EQ(output.buffers[0].owner, &preallocated_mem);
ASSERT_EQ(9, output.GetNullCount());
}
}
TEST_F(TestPropagateNullsSpans, IntersectsNulls) {
const int64_t length = 16;
// 0b01111111 0b11001111
constexpr uint8_t bitmap1[8] = {127, 207, 0, 0, 0, 0, 0, 0};
auto buffer1 = std::make_shared<Buffer>(bitmap1, 8);
// 0b11111110 0b01111111
constexpr uint8_t bitmap2[8] = {254, 127, 0, 0, 0, 0, 0, 0};
auto buffer2 = std::make_shared<Buffer>(bitmap2, 8);
// 0b11101111 0b11111110
constexpr uint8_t bitmap3[8] = {239, 254, 0, 0, 0, 0, 0, 0};
auto buffer3 = std::make_shared<Buffer>(bitmap3, 8);
auto ty = boolean();
ArraySpan arr1(ty.get(), length);
arr1.SetBuffer(0, buffer1);
ArraySpan arr2(ty.get(), length);
arr2.SetBuffer(0, buffer2);
ArraySpan arr3(ty.get(), length);
arr3.SetBuffer(0, buffer3);
auto CheckCase = [&](std::vector<ExecValue> values, int64_t ex_null_count,
const uint8_t* ex_bitmap, int64_t output_offset = 0) {
ExecSpan batch(values, length);
std::shared_ptr<Buffer> nulls;
// Make the buffer one byte bigger so we can have non-zero offsets
ASSERT_OK_AND_ASSIGN(nulls, AllocateBuffer(3));
std::memset(nulls->mutable_data(), 0, nulls->size());
ArraySpan output(ty.get(), length);
output.SetBuffer(0, nulls);
output.offset = output_offset;
PropagateNullsSpans(batch, &output);
ASSERT_EQ(&nulls, output.buffers[0].owner);
EXPECT_EQ(kUnknownNullCount, output.null_count);
EXPECT_EQ(ex_null_count, output.GetNullCount());
ASSERT_TRUE(BitmapEquals(output.buffers[0].data, output_offset, ex_bitmap,
/*ex_offset=*/0, length));
// Now check that the rest of the bits in out_buffer are still 0
AssertValidityZeroExtraBits(output);
};
// 0b01101110 0b01001110
uint8_t expected1[2] = {110, 78};
CheckCase({arr1, arr2, arr3}, 7, expected1);
CheckCase({arr1, arr2, arr3}, 7, expected1, /*output_offset=*/4);
// 0b01111110 0b01001111
uint8_t expected2[2] = {126, 79};
CheckCase({arr1, arr2}, 5, expected2, /*output_offset=*/4);
}
TEST_F(TestPropagateNullsSpans, NullOutputTypeNoop) {
// Ensure we leave the buffers alone when the output type is null()
// TODO(wesm): is this test useful? Can probably delete
const int64_t length = 100;
ExecBatch batch({rng_->Boolean(100, 0.5, 0.5)}, length);
auto ty = null();
ArraySpan result(ty.get(), length);
PropagateNullsSpans(ExecSpan(batch), &result);
ASSERT_EQ(nullptr, result.buffers[0].data);
}
// ----------------------------------------------------------------------
// ExecSpanIterator tests
class TestExecSpanIterator : public TestComputeInternals {
public:
void SetupIterator(const ExecBatch& batch,
int64_t max_chunksize = kDefaultMaxChunksize) {
ASSERT_OK(iterator_.Init(batch, max_chunksize));
}
void CheckIteration(const ExecBatch& input, int chunksize,
const std::vector<int>& ex_batch_sizes) {
SetupIterator(input, chunksize);
ExecSpan batch;
int64_t position = 0;
for (size_t i = 0; i < ex_batch_sizes.size(); ++i) {
ASSERT_EQ(position, iterator_.position());
ASSERT_TRUE(iterator_.Next(&batch));
ASSERT_EQ(ex_batch_sizes[i], batch.length);
for (size_t j = 0; j < input.values.size(); ++j) {
switch (input[j].kind()) {
case Datum::SCALAR:
ASSERT_TRUE(input[j].scalar()->Equals(*batch[j].scalar));
break;
case Datum::ARRAY:
AssertArraysEqual(*input[j].make_array()->Slice(position, batch.length),
*batch[j].array.ToArray());
break;
case Datum::CHUNKED_ARRAY: {
const ChunkedArray& carr = *input[j].chunked_array();
if (batch.length == 0) {
ASSERT_EQ(0, carr.length());
} else {
auto arg_slice = carr.Slice(position, batch.length);
// The sliced ChunkedArrays should only ever be 1 chunk
ASSERT_EQ(1, arg_slice->num_chunks());
AssertArraysEqual(*arg_slice->chunk(0), *batch[j].array.ToArray());
}
} break;
default:
break;
}
}
position += ex_batch_sizes[i];
}
// Ensure that the iterator is exhausted
ASSERT_FALSE(iterator_.Next(&batch));
ASSERT_EQ(iterator_.length(), iterator_.position());
}
protected:
ExecSpanIterator iterator_;
};
TEST_F(TestExecSpanIterator, Basics) {
const int64_t length = 100;
ExecBatch input;
input.length = 100;
// Simple case with a single chunk
input.values = {Datum(GetInt32Array(length)), Datum(GetFloat64Array(length)),
Datum(std::make_shared<Int32Scalar>(3))};
SetupIterator(input);
ExecSpan batch;
ASSERT_TRUE(iterator_.Next(&batch));
ASSERT_EQ(3, batch.values.size());
ASSERT_EQ(3, batch.num_values());
ASSERT_EQ(length, batch.length);
AssertArraysEqual(*input[0].make_array(), *batch[0].array.ToArray());
AssertArraysEqual(*input[1].make_array(), *batch[1].array.ToArray());
ASSERT_TRUE(input[2].scalar()->Equals(*batch[2].scalar));
ASSERT_EQ(length, iterator_.position());
ASSERT_FALSE(iterator_.Next(&batch));
// Split into chunks of size 16
CheckIteration(input, /*chunksize=*/16, {16, 16, 16, 16, 16, 16, 4});
}
TEST_F(TestExecSpanIterator, InputValidation) {
ExecSpanIterator iterator;
ExecBatch batch({Datum(GetInt32Array(10)), Datum(GetInt32Array(9))}, 10);
ASSERT_RAISES(Invalid, iterator.Init(batch));
batch.values = {Datum(GetInt32Array(9)), Datum(GetInt32Array(10))};
ASSERT_RAISES(Invalid, iterator.Init(batch));
batch.values = {Datum(GetInt32Array(10))};
ASSERT_OK(iterator.Init(batch));
}
TEST_F(TestExecSpanIterator, ChunkedArrays) {
ExecBatch batch({Datum(GetInt32Chunked({0, 20, 10})), Datum(GetInt32Chunked({15, 15})),
Datum(GetInt32Array(30)), Datum(std::make_shared<Int32Scalar>(5)),
Datum(MakeNullScalar(boolean()))},
30);
CheckIteration(batch, /*chunksize=*/10, {10, 5, 5, 10});
CheckIteration(batch, /*chunksize=*/20, {15, 5, 10});
CheckIteration(batch, /*chunksize=*/30, {15, 5, 10});
}
TEST_F(TestExecSpanIterator, ZeroLengthInputs) {
auto carr = std::make_shared<ChunkedArray>(ArrayVector{}, int32());
auto CheckArgs = [&](const ExecBatch& batch) {
ExecSpanIterator iterator;
ASSERT_OK(iterator.Init(batch));
ExecSpan iter_span;
ASSERT_TRUE(iterator.Next(&iter_span));
ASSERT_EQ(0, iter_span.length);
ASSERT_FALSE(iterator.Next(&iter_span));
};
ExecBatch input;
input.length = 0;
// Zero-length ChunkedArray with zero chunks
input.values = {Datum(carr)};
CheckArgs(input);
// Zero-length array
input.values = {Datum(GetInt32Array(0))};
CheckArgs(input);
// ChunkedArray with single empty chunk
input.values = {Datum(GetInt32Chunked({0}))};
CheckArgs(input);
}
// ----------------------------------------------------------------------
// Scalar function execution
Status ExecCopyArrayData(KernelContext*, const ExecSpan& batch, ExecResult* out) {
DCHECK_EQ(1, batch.num_values());
int value_size = batch[0].type()->byte_width();
const ArraySpan& arg0 = batch[0].array;
ArrayData* out_arr = out->array_data().get();
uint8_t* dst = out_arr->buffers[1]->mutable_data() + out_arr->offset * value_size;
const uint8_t* src = arg0.buffers[1].data + arg0.offset * value_size;
std::memcpy(dst, src, batch.length * value_size);
return Status::OK();
}
Status ExecCopyArraySpan(KernelContext*, const ExecSpan& batch, ExecResult* out) {
DCHECK_EQ(1, batch.num_values());
int value_size = batch[0].type()->byte_width();
const ArraySpan& arg0 = batch[0].array;
ArraySpan* out_arr = out->array_span();
uint8_t* dst = out_arr->buffers[1].data + out_arr->offset * value_size;
const uint8_t* src = arg0.buffers[1].data + arg0.offset * value_size;
std::memcpy(dst, src, batch.length * value_size);
return Status::OK();
}
Status ExecComputedBitmap(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) {
// Propagate nulls not used. Check that the out bitmap isn't the same already
// as the input bitmap
const ArraySpan& arg0 = batch[0].array;
ArraySpan* out_arr = out->array_span();
if (CountSetBits(arg0.buffers[0].data, arg0.offset, batch.length) > 0) {
// Check that the bitmap has not been already copied over
DCHECK(!BitmapEquals(arg0.buffers[0].data, arg0.offset, out_arr->buffers[0].data,
out_arr->offset, batch.length));
}
CopyBitmap(arg0.buffers[0].data, arg0.offset, batch.length, out_arr->buffers[0].data,
out_arr->offset);
return ExecCopyArraySpan(ctx, batch, out);
}
Status ExecNoPreallocatedData(KernelContext* ctx, const ExecSpan& batch,
ExecResult* out) {
// Validity preallocated, but not the data
ArrayData* out_arr = out->array_data().get();
DCHECK_EQ(0, out_arr->offset);
int value_size = batch[0].type()->byte_width();
Status s = (ctx->Allocate(out_arr->length * value_size).Value(&out_arr->buffers[1]));
DCHECK_OK(s);
return ExecCopyArrayData(ctx, batch, out);
}
Status ExecNoPreallocatedAnything(KernelContext* ctx, const ExecSpan& batch,
ExecResult* out) {
// Neither validity nor data preallocated
ArrayData* out_arr = out->array_data().get();
DCHECK_EQ(0, out_arr->offset);
Status s = (ctx->AllocateBitmap(out_arr->length).Value(&out_arr->buffers[0]));
DCHECK_OK(s);
const ArraySpan& arg0 = batch[0].array;
CopyBitmap(arg0.buffers[0].data, arg0.offset, batch.length,
out_arr->buffers[0]->mutable_data(), /*offset=*/0);
// Reuse the kernel that allocates the data
return ExecNoPreallocatedData(ctx, batch, out);
}
class ExampleOptions : public FunctionOptions {
public:
explicit ExampleOptions(std::shared_ptr<Scalar> value);
std::shared_ptr<Scalar> value;
};
class ExampleOptionsType : public FunctionOptionsType {
public:
static const FunctionOptionsType* GetInstance() {
static std::unique_ptr<FunctionOptionsType> instance(new ExampleOptionsType());
return instance.get();
}
const char* type_name() const override { return "example"; }
std::string Stringify(const FunctionOptions& options) const override {
return type_name();
}
bool Compare(const FunctionOptions& options,
const FunctionOptions& other) const override {
return true;
}
std::unique_ptr<FunctionOptions> Copy(const FunctionOptions& options) const override {
const auto& opts = static_cast<const ExampleOptions&>(options);
return std::make_unique<ExampleOptions>(opts.value);
}
};
ExampleOptions::ExampleOptions(std::shared_ptr<Scalar> value)
: FunctionOptions(ExampleOptionsType::GetInstance()), value(std::move(value)) {}
struct ExampleState : public KernelState {
std::shared_ptr<Scalar> value;
explicit ExampleState(std::shared_ptr<Scalar> value) : value(std::move(value)) {}
};
Result<std::unique_ptr<KernelState>> InitStateful(KernelContext*,
const KernelInitArgs& args) {
auto func_options = static_cast<const ExampleOptions*>(args.options);
return std::make_unique<ExampleState>(func_options ? func_options->value : nullptr);
}
Status ExecStateful(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) {
// We take the value from the state and multiply the data in batch[0] with it
ExampleState* state = static_cast<ExampleState*>(ctx->state());
int32_t multiplier = checked_cast<const Int32Scalar&>(*state->value).value;
const ArraySpan& arg0 = batch[0].array;
ArraySpan* out_arr = out->array_span();
const int32_t* arg0_data = arg0.GetValues<int32_t>(1);
int32_t* dst = out_arr->GetValues<int32_t>(1);
for (int64_t i = 0; i < arg0.length; ++i) {
dst[i] = arg0_data[i] * multiplier;
}
return Status::OK();
}
Status ExecAddInt32(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) {
const int32_t* left_data = batch[0].array.GetValues<int32_t>(1);
const int32_t* right_data = batch[1].array.GetValues<int32_t>(1);
int32_t* out_data = out->array_span()->GetValues<int32_t>(1);
for (int64_t i = 0; i < batch.length; ++i) {
*out_data++ = *left_data++ + *right_data++;
}
return Status::OK();
}
class TestCallScalarFunction : public TestComputeInternals {
protected:
static bool initialized_;
void SetUp() {
TestComputeInternals::SetUp();
if (!initialized_) {
initialized_ = true;
AddCopyFunctions();
AddNoPreallocateFunctions();