Repository navigation
Expand file tree
/
Copy pathrechunk_validation.cpp
More file actions
1093 lines (1024 loc) · 42.8 KB
/
Copy pathrechunk_validation.cpp
File metadata and controls
1093 lines (1024 loc) · 42.8 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
/*
* Copyright 2026 CEA (www.cea.fr)
*
* Licensed 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.
*/
// ============================================================================
// SEQUENTIAL re-chunk validation harness (path C, non-OMP) -- v3.
// Variant-agnostic: tests zero / zero_or_value / zero_any depending on the
// compile-time macro (CHUNK_VARIANT_ZERO*), like shrink_bench.cpp.
// ============================================================================
//
// Proves CONTENT INVARIANCE and, on failure, LOCATES the cause:
// - first checks that the SNAPSHOT (read at the old geometry) is correct;
// - traces the geometry before/after;
// - shows the first mismatches along with the corresponding chunk boundary.
//
// The variant is selected by the macro passed by CMake (one executable per
// variant, linked against the matching dyn lib: chunk_zero_or_value_dyn / chunk_zero_any_dyn /
// chunk_zero_dyn). No std::vector fallback: re-chunk is specific to the chunked
// variants, hence the static_assert.
//
// zero_or_value CONTRACT: the compression-candidate list is indexed by
// second_value (zero_or_value_candidates_map_thr[thr][second_value]),
// populated ONLY by set_second_value. A second_value must therefore be
// declared BEFORE writing, otherwise get_vec_tuple_to_compress_potentially_thr
// asserts (vec == nullptr). This is what the bench does via
// maybe_set_second_value; we reproduce it here for every case. zero_any / zero
// don't need this (no-op).
//
// Compile NON-OMP (or OMP), dyn, check. Exit 0 = every invariant holds.
//
// Each case runs twice by default (--mode both): SERIALLY, as it always did,
// then with its writes and checks in parallel regions (--mode parallel) --
// the candidate lists per rank, the deferred path and the ambient chunk size
// of worker threads around a re-chunk, which the serial pass never reaches.
// rechunk_to() itself is always called outside any region.
//
// rechunk_validation [N [target [rounds]]] [--case NAME] [--mode serial|parallel|both] [--list]
//
// --case runs one case: CMake registers one test per case, so `ctest -j`
// spreads them over the cores (the cases share global re-chunk state -- the
// ambient chunk size, the registries -- so they run in separate processes,
// never side by side in one).
#include <cstdio> // std::fprintf, stderr
#include <cstring> // std::strcmp
#include <functional> // std::function
#include <limits> // std::numeric_limits (index-split)
#include <string> // std::string
#include <vector> // std::vector
#include <cmath> // std::floor, std::sin
#include <type_traits> // std::conditional_t
#include "chunk/internal/chunk_traits.h" // forward decls + default IntType = int
#include "chunk/zero_array.h" // zero::Array
#include "chunk/zero_or_value_array.h" // zero_or_value::Array
#include "chunk/zero_any_array.h" // zero_any::Array
#include "chunk/runtime.h" // Runtime::register_chunk_size, init
#include "chunk/internal/chunk_size_policy.h" // set_active_chunk_size, set_thread_chunk_size
#include "chunk/config.h" // chunk_config::use_zero*
#include "chunk/range_ops.h" // fill_range / copy_range
#include "chunk/phases.h" // finalize_parallel_phase (compression backlog drain)
#include "chunk/internal/env_parse.h" // env_number / arg_number (checked, not atoi)
#include "chunk/print.h" // shrink_array::println
using namespace shrink_array;
#include "chunk/internal/zero_chunk.h" // release_chunk_pools, Runtime::shutdown
#include "validation_harness.h" // self_command; run() is called by validation_driver.cpp
namespace validation::rechunk_validation
{
namespace
{
// ── Compression backlog drain ────────────────────────────────────────────────
// A write only QUEUES its chunk as a compression candidate; the queue is
// drained at phase boundaries. When OMPT is compiled in, its callbacks do it;
// otherwise the application must, which is what shrink_bench.cpp does around
// each of its parallel phases.
//
// This file opens no parallel region, so under OpenMP it must drain the
// backlog itself: otherwise every all-zero chunk stays materialised, and
// compress_int() -- which in embedded-compression mode only DIAGNOSES, it does
// not compress -- reports them round after round ("Should not have compress
// (0) values"); values stay correct, but no compression is exercised past the
// first round. No-op in serial builds
// (finalize_parallel_phase is `if constexpr (use_openmp)`) and skipped under
// OMPT, which already drains.
void drain_compression_backlog()
{
if constexpr (build_config::needs_explicit_phases)
{
shrink_array::finalize_parallel_phase();
}
}
// ── Serial or parallel passes ────────────────────────────────────────────────
bool g_parallel = false; ///< --mode: the pass being run
/// @brief @p func(i) for i in [0, @p count): a plain loop, or a work-shared parallel
/// region (static schedule) followed by the phase-end drain.
template <typename F>
void for_each_index(long count, F&& func)
{
if (!g_parallel)
{
for (long i = 0; i < count; ++i)
{
func(i);
}
return;
}
#pragma omp parallel
{
if constexpr (build_config::needs_explicit_phases)
{
shrink_array::begin_parallel_phase();
}
#pragma omp for schedule(static)
for (long i = 0; i < count; ++i)
{
func(i);
}
}
drain_compression_backlog();
}
/// @brief How many i in [0, @p nindex) satisfy @p bad(i) -- the checks, in the same
/// serial or parallel pass. Details are then printed by a serial scan.
template <typename F>
long count_if_index(long nindex, F&& bad)
{
long count = 0;
if (!g_parallel)
{
for (long i = 0; i < nindex; ++i)
{
count += bad(i) ? 1 : 0;
}
return count;
}
#pragma omp parallel reduction(+ : count)
{
if constexpr (build_config::needs_explicit_phases)
{
shrink_array::begin_parallel_phase();
}
#pragma omp for schedule(static)
for (long i = 0; i < nindex; ++i)
{
count += bad(i) ? 1 : 0;
}
}
drain_compression_backlog();
return count;
}
/// @brief The case label with the pass it runs in.
std::string pass_label(const char* label)
{
return std::string(label) + (g_parallel ? "@par" : "@ser");
}
} // namespace
// --- Active variant selection (same shape as shrink_bench.cpp) -------
static_assert(chunk_config::use_zero || chunk_config::use_zero_or_value || chunk_config::use_zero_any,
"rechunk_validation must be built with CHUNK_VARIANT_ZERO, _ZERO_OR_VALUE or _ZERO_ANY "
"(re-chunk is chunk-only; no std::vector fallback here)");
template <typename T>
using Array =
std::conditional_t<chunk_config::use_zero_any,
zero_any::Array<T>,
std::conditional_t<chunk_config::use_zero_or_value, zero_or_value::Array<T>, zero::Array<T>>>;
constexpr const char* variant_name()
{
if constexpr (chunk_config::use_zero_any)
{
return "zero_any";
}
else if constexpr (chunk_config::use_zero_or_value)
{
return "zero_or_value";
}
else
{
return "zero";
}
}
// set_second_value only exists on zero_or_value / zero_any: no-op elsewhere. REQUIRED
// on zero_or_value before any write (see the contract at the top of the file); also
// exercises the val2 path (second_value preservation + array_m_ptr_const_val2
// queue on growth, for zero_or_value).
template <typename Arr, typename Val>
void maybe_set_second_value(Arr& arr, const Val& value)
{
// bool's second value is true, always: zero_or_value warns on the call.
if constexpr (!std::is_same_v<Val, bool> && requires(Arr probe) { probe.set_second_value(value); })
{
arr.set_second_value(value);
}
}
// sv_value: the value declared as second_value. Choosing a value present in
// the data makes val2 compression actually kick in (a stronger test); any
// value is enough to satisfy the zero_or_value contract (populate the map).
template <typename T>
int check_invariance(const char* label,
long count,
unsigned new_size,
T (*gen)(long),
T sv_value = T(1),
int post_rounds = 0)
{
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
Array<T> arr(count);
maybe_set_second_value(arr, sv_value); // no-op on zero; required on zero_or_value
fprintf(stderr, "[%s/%s] arr built: chunk_size=%u (g_active should be 512)\n", variant_name(), label,
arr.chunk_size());
std::vector<T> ref(count);
for_each_index(count,
[&](long i)
{
const T value = gen(i);
arr[i] = value;
ref[i] = value;
});
const unsigned old_size = arr.chunk_size();
// (a) pre-rechunk DIAGNOSTIC: is the content read at the old geometry correct?
const long pre_bad = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
long pre_first = -1;
for (long i = 0; pre_bad && pre_first < 0 && i < count; ++i)
{
if (arr[i] != ref[i])
{
pre_first = i;
}
}
if (pre_bad)
{
println("[{}/{}] PRE-FAIL: {} mismatches BEFORE rechunk (setup/read bug, not rechunk); "
"first at i={} (chunk #{}, offset {}) got={:g} expected={:g}",
variant_name(), label, pre_bad, pre_first, pre_first / (long)old_size, pre_first % (long)old_size,
(double)arr[pre_first], (double)ref[pre_first]);
return 1;
}
arr.rechunk_to(new_size);
const unsigned got_size = arr.chunk_size();
if (got_size != new_size)
{
println("[{}/{}] FAIL: geometry {} -> {} (expected {})", variant_name(), label, old_size, got_size, new_size);
return 1;
}
if ((long)arr.size() != count)
{
println("[{}/{}] FAIL: size {} -> {}", variant_name(), label, count, (long)arr.size());
return 1;
}
const long mismatches = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
long first = -1;
for (long i = 0, shown = 0; mismatches && shown < 5 && i < count; ++i)
{
if (arr[i] != ref[i])
{
if (first < 0)
{
first = i;
}
println("[{}/{}] MISMATCH i={} got={:.17g} exp={:.17g} (new-chunk #{}, offset {})", variant_name(), label,
i, (double)arr[i], (double)ref[i], i / (long)new_size, i % (long)new_size);
++shown;
}
}
if (mismatches)
{
println("[{}/{}] FAIL: {}/{} mismatches after rechunk {}->{} (first at i={})", variant_name(), label,
mismatches, count, old_size, new_size, first);
return 1;
}
// ── POST-RECHUNK PHASE: rewrite + compress in rounds, mimicking the bench.
// The perf-bench crash appears HERE (writes/compression touching the
// freshly re-chunked geometry), not in rechunk_to itself. Each round
// overwrites with changing data, forces a compression pass, and re-checks
// invariance against the ground-truth ref.
for (int round = 0; round < post_rounds; ++round)
{
for_each_index(count,
[&](long i)
{
const T value = gen(i + ((long)round * 7919));
arr[i] = value;
ref[i] = value;
});
// Hand the queued candidates to the compression pass before asking for
// the result -- see drain_compression_backlog() above.
drain_compression_backlog();
// compress_int signature differs across variants: zero takes a
// verbose bool; zero_or_value / zero_any take none.
if constexpr (requires { arr.compress_int(false); })
{
arr.compress_int(false);
}
else
{
arr.compress_int();
}
const long bad = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
long firstb = -1;
for (long i = 0; bad && firstb < 0 && i < count; ++i)
{
if (arr[i] != ref[i])
{
firstb = i;
}
}
if (bad)
{
println("[{}/{}] POST-FAIL round {}: {}/{} mismatches after compress (first i={}, new-chunk #{} off {})",
variant_name(), label, round, bad, count, firstb, firstb / (long)new_size, firstb % (long)new_size);
return 1;
}
}
println("[{}/{}] OK: {} elements invariant, geometry {}->{} (second_value={:.17g}){}", variant_name(), label, count,
old_size, new_size, (double)sv_value, post_rounds ? " [+post-rechunk compress rounds]" : "");
return 0;
}
// ── COEXISTENCE CASE ─────────────────────────────────────────────────────────
// Every check above exercises ONE array at a time, so all live arrays always
// share a single geometry -- and they all pass. The perf bench does not: the
// advisor re-chunks the arrays it tracks and leaves the others at the original
// size, so arrays of DIFFERENT geometries are alive and written to in the same
// loop. That is what crashes (ASan: heap-buffer-overflow in store_value, a
// 64-element buffer written at index 76), on zero AND on zero_or_value/zero_any alike.
//
// This reproduces that state in the small: two arrays, one re-chunked and one
// left alone, written alternately. Passing means geometry coexistence is safe;
// failing pins the defect down to ~30 lines instead of a 1200-iteration bench.
template <typename T>
int check_coexistence(const char* label, long count, unsigned moved_size, int rounds)
{
using Arr = Array<T>;
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
// `fixed` first: it takes the lower registry index (array_id), so a re-chunk
// of `moved` whose teardown released the wrong row of the per-type flag
// table would pull it from under `fixed` -- the writes below then fault.
Arr fixed(static_cast<int>(count)); // stays at the ambient geometry
Arr moved(static_cast<int>(count)); // will be re-chunked
for_each_index(count,
[&](long i)
{
moved[i] = static_cast<T>((i % 7) ? 0 : i);
fixed[i] = static_cast<T>((i % 5) ? 0 : i);
});
moved.rechunk_to(moved_size);
// Alternate writes between the two geometries, the way the bench's loop does.
for (int r = 0; r < rounds; ++r)
{
for_each_index(count,
[&](long i)
{
moved[i] = static_cast<T>((i + r) % 11 ? 0 : (i + r));
fixed[i] = static_cast<T>((i + r) % 13 ? 0 : (i + r));
});
}
// Verify both arrays still read back what was last written.
const int last_round = rounds - 1;
const long nbad = count_if_index(
count,
[&](long i)
{
return !(static_cast<T>(moved[i]) == static_cast<T>((i + last_round) % 11 ? 0 : (i + last_round))) ||
!(static_cast<T>(fixed[i]) == static_cast<T>((i + last_round) % 13 ? 0 : (i + last_round)));
});
int bad = 0;
for (long i = 0; nbad && i < count && bad < 5; ++i)
{
const T em = static_cast<T>((i + last_round) % 11 ? 0 : (i + last_round));
const T ef = static_cast<T>((i + last_round) % 13 ? 0 : (i + last_round));
if (!(static_cast<T>(moved[i]) == em) || !(static_cast<T>(fixed[i]) == ef))
{
println("[{}/{}] MISMATCH at {}: moved={:g} exp {:g} | fixed={:g} exp {:g}", variant_name(), label, i,
(double)static_cast<T>(moved[i]), (double)em, (double)static_cast<T>(fixed[i]), (double)ef);
++bad;
}
}
if (!bad)
{
println("[{}/{}] OK: {} elements, geometries {} and ambient coexisting", variant_name(), label, count,
moved_size);
}
return bad ? 1 : 0;
}
// ── RANGE OPS ────────────────────────────────────────────────────────────────
// fill_range / copy_range take one decision per CHUNK where operator[] takes one
// per element. Correctness is checked against the element-by-element path on the
// SAME data, so any divergence -- a stale zero counter, a chunk wrongly left
// constant, a boundary off by one -- shows up as a mismatch rather than as a
// slow drift noticed three compression passes later.
template <typename T>
int check_range_ops(const char* label, long count)
{
using Arr = Array<T>;
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
Arr via_range(static_cast<int>(count));
Arr via_elem(static_cast<int>(count));
const auto expected = [](long i) -> T
{
// Long constant runs (so chunks really do compress) with scattered
// non-constant values, which is what makes the two paths diverge if the
// bookkeeping is wrong.
if ((i / 100) % 3 == 0)
{
return static_cast<T>(0);
}
if ((i % 37) == 0)
{
return static_cast<T>(i % 1000);
}
return static_cast<T>(0);
};
// 1) whole-array zero fill: the case where a correct implementation must
// allocate NOTHING (every chunk set constant outright).
shrink_array::fill_range(via_range, 0, static_cast<std::size_t>(count), static_cast<T>(0));
for (long i = 0; i < count; ++i)
{
via_elem[i] = static_cast<T>(0);
}
// 2) scattered writes, both paths identical
for (long i = 0; i < count; ++i)
{
const T want = expected(i);
if (!(want == static_cast<T>(0)))
{
via_range[i] = want;
via_elem[i] = want;
}
}
// 3) partial fills straddling chunk boundaries, deliberately unaligned
const unsigned chunk_sz = via_range.chunk_size();
for (const long off : {1L, (long)chunk_sz - 1, (long)chunk_sz + 1, (long)(2 * chunk_sz) + 3})
{
const auto a0 = static_cast<std::size_t>(off);
const auto b0 = static_cast<std::size_t>(off) + (5 * static_cast<std::size_t>(chunk_sz)) + 7;
if (b0 >= static_cast<std::size_t>(count))
{
continue;
}
shrink_array::fill_range(via_range, a0, b0, static_cast<T>(7));
for (std::size_t i = a0; i < b0; ++i)
{
via_elem[static_cast<long>(i)] = static_cast<T>(7);
}
}
// 4) copy_range from a plain vector -- the generic/overloaded pair in use
std::vector<T> src(static_cast<std::size_t>(count));
for (long i = 0; i < count; ++i)
{
src[static_cast<std::size_t>(i)] = static_cast<T>((i % 11) ? 0 : i);
}
const std::size_t ca = 3;
const std::size_t cb = static_cast<std::size_t>(count) - 3;
shrink_array::copy_range(via_range, ca, cb, src.begin() + 0);
for (std::size_t i = ca; i < cb; ++i)
{
via_elem[static_cast<long>(i)] = src[i - ca];
}
const long nbad =
count_if_index(count, [&](long i) { return !(static_cast<T>(via_range[i]) == static_cast<T>(via_elem[i])); });
int bad = 0;
for (long i = 0; nbad && i < count && bad < 5; ++i)
{
const T got = static_cast<T>(via_range[i]);
const T want = static_cast<T>(via_elem[i]);
if (!(got == want))
{
println("[{}/{}] MISMATCH at {}: range={:g} element={:g}", variant_name(), label, i, (double)got,
(double)want);
++bad;
}
}
if (!bad)
{
println("[{}/{}] OK: {} elements, range ops match the element path", variant_name(), label, count);
}
return bad ? 1 : 0;
}
/// @brief A size that is neither a power of two nor a multiple of 64 (48, 96,
/// 3, S + 1) is refused -- by rechunk_to() on a filled array and on an
/// empty one, and by set_chunk_size() -- and so is set_chunk_size() of a
/// VALID other size on the filled array (it would remap the indices
/// without moving the elements), and, on the empty array,
/// a valid size wider than const_buffer_size (it would read the shared
/// constant buffers out of bounds); geometry, content and the ambient
/// size stay as they were. A legal re-chunk must still work afterwards.
int check_non_pow2_refused(const char* label)
{
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
const long count = 100000;
Array<double> arr(count);
std::vector<double> ref(count);
maybe_set_second_value(arr, 1.0);
for_each_index(count,
[&](long i)
{
const double value = double((i / 700) % 3);
arr[i] = value;
ref[i] = value;
});
const unsigned old_size = arr.chunk_size();
const unsigned ambient = active_chunk_size();
int bad = 0;
for (const unsigned new_size : {48u, 96u, 3u, old_size + 1u})
{
arr.rechunk_to(new_size);
if (arr.chunk_size() != old_size)
{
println("[{}/{}] FAIL: rechunk_to({}) applied: geometry {} -> {}", variant_name(), label, new_size,
old_size, arr.chunk_size());
++bad;
}
}
// A valid size, but the array has chunks: refused (rechunk_to() moves the
// elements; set_chunk_size() would only remap the indices, and make it the
// ambient size).
for (const unsigned new_size : {old_size * 2u, old_size / 2u})
{
arr.set_chunk_size(new_size);
if (arr.chunk_size() != old_size)
{
println("[{}/{}] FAIL: set_chunk_size({}) on a filled array applied: geometry {} -> {}", variant_name(),
label, new_size, old_size, arr.chunk_size());
++bad;
}
}
const long mism = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
if (mism)
{
println("[{}/{}] FAIL: {} element(s) changed by the refused re-chunks", variant_name(), label, mism);
++bad;
}
Array<double> empty(0);
const unsigned e0 = empty.chunk_size();
empty.rechunk_to(48u);
empty.set_chunk_size(96u);
empty.rechunk_to(2u * const_buffer_size);
empty.set_chunk_size(2u * const_buffer_size);
if (empty.chunk_size() != e0)
{
println("[{}/{}] FAIL: empty array: geometry {} -> {}", variant_name(), label, e0, empty.chunk_size());
++bad;
}
if (active_chunk_size() != ambient)
{
println("[{}/{}] FAIL: ambient size {} -> {}", variant_name(), label, ambient, active_chunk_size());
++bad;
}
// The refusals left the array usable: a legal re-chunk, content intact.
arr.rechunk_to(old_size * 2u);
const long after = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
if (arr.chunk_size() != old_size * 2u || after)
{
println("[{}/{}] FAIL: legal rechunk_to({}) afterwards: geometry {}, {} mismatch(es)", variant_name(), label,
old_size * 2u, arr.chunk_size(), after);
++bad;
}
// Back to the case's start geometry for the next pass.
set_active_chunk_size(ambient);
set_thread_chunk_size(ambient);
if (!bad)
{
println("[{}/{}] OK: 48/96/3/{} refused (filled and empty arrays), {} on the empty one, content and "
"geometry kept, {} -> {} still works",
variant_name(), label, old_size + 1u, 2u * const_buffer_size, old_size, old_size * 2u);
}
return bad ? 1 : 0;
}
/// @brief set_active_chunk_size() refuses, in every build, a size that is not
/// a chunk geometry (0: the next DynamicChunkSize divided by 0; 100)
/// or wider than const_buffer_size: the active size is kept, and an
/// array born afterwards has it.
int check_active_size_refused(const char* label)
{
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
const unsigned ambient = active_chunk_size();
int bad = 0;
for (const unsigned new_size : {0u, 100u, 2u * const_buffer_size})
{
set_active_chunk_size(new_size);
if (active_chunk_size() != ambient)
{
println("[{}/{}] FAIL: set_active_chunk_size({}) accepted: active size {}", variant_name(), label, new_size,
active_chunk_size());
++bad;
set_active_chunk_size(ambient);
}
}
Array<double> arr(1000);
if (arr.chunk_size() != ambient)
{
println("[{}/{}] FAIL: array born at {}, not {}", variant_name(), label, arr.chunk_size(), ambient);
++bad;
}
if (!bad)
{
println("[{}/{}] OK: set_active_chunk_size(0 / 100 / {}) refused, {} kept", variant_name(), label,
2u * const_buffer_size, ambient);
}
return bad ? 1 : 0;
}
/// @brief The index split of the run-time geometry (DynamicChunkSize::chunk_of
/// / offset_of: a shift and a mask for a power of two, a magic-number
/// multiplication otherwise) equals i / S and i % S, for every valid
/// size up to 4096 and 32- and 64-bit indexes. A power of two counted
/// as one by mistake (the flag was set from is_valid_chunk_size once it
/// admitted multiples of 64) sent 1000 to chunk 3 at 384.
int check_index_split(const char* label)
{
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
const unsigned ambient = active_chunk_size();
long bad = 0;
long count = 0;
for (unsigned d = 32; d <= 4096; d += (d < 64 ? 32 : 64))
{
if (!is_valid_chunk_size(d))
{
continue;
}
DynamicChunkSize policy;
policy.set_size(d);
const auto one = [&](auto i)
{
using I = decltype(i);
++count;
if (policy.chunk_of(i) != static_cast<I>(i / static_cast<I>(d)) ||
policy.offset_of(i) != static_cast<I>(i % static_cast<I>(d)))
{
if (bad++ < 5)
{
println("[{}/{}] FAIL: size {} index {}: chunk {} offset {}", variant_name(), label, d,
static_cast<long long>(i), static_cast<long long>(policy.chunk_of(i)),
static_cast<long long>(policy.offset_of(i)));
}
}
};
for (int i = 0; i <= 20000; ++i)
{
one(i);
}
for (long k = 1; k < 2000; ++k)
{
one(static_cast<int>((k * 1103515245L) & 0x7fffffffL));
one(static_cast<long>(k) * 4611686018427387L);
}
one(std::numeric_limits<int>::max());
one(std::numeric_limits<long>::max());
}
set_active_chunk_size(ambient); // set_size() moved the process-wide size
set_thread_chunk_size(ambient);
if (!bad)
{
println("[{}/{}] OK: chunk_of / offset_of == / and % for every valid size up to 4096 ({} indexes)",
variant_name(), label, count);
}
return bad ? 1 : 0;
}
/// @brief Re-chunk through sizes that are multiples of 64 but do not divide
/// each other (256 -> 384 -> 192 -> 576 -> ...): the geometry follows
/// and the content survives every step. On zero with OpenMP this drives
/// the refill's early release with old chunks shared by two new ones.
int check_multiple_of_64_chain(const char* label)
{
const std::string lab_s = pass_label(label);
label = lab_s.c_str();
const long count = 200000;
Array<double> arr(count);
std::vector<double> ref(count);
maybe_set_second_value(arr, 1.0);
// Runs of 1000 (not a multiple of any size here): constant chunks and
// chunks straddling two values at every geometry.
for_each_index(count,
[&](long i)
{
const double value = (i / 1000) % 4 == 3 ? double(i % 7) : double((i / 1000) % 3);
arr[i] = value;
ref[i] = value;
});
const unsigned ambient = active_chunk_size();
int bad = 0;
for (const unsigned new_size : {384u, 192u, 576u, 320u, 1024u, 448u, 512u, 256u})
{
arr.rechunk_to(new_size);
const long mism = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
if (arr.chunk_size() != new_size || mism)
{
println("[{}/{}] FAIL: rechunk_to({}): geometry {}, {} mismatch(es)", variant_name(), label, new_size,
arr.chunk_size(), mism);
++bad;
}
}
// Writes and reads at the last geometry, across chunk boundaries.
for (long i = 255; i < count; i += 4093)
{
arr[i] = ref[static_cast<std::size_t>(i)] = double(i % 11);
}
const long after = count_if_index(count, [&](long i) { return arr[i] != ref[i]; });
if (after)
{
println("[{}/{}] FAIL: {} mismatch(es) after writes at {}", variant_name(), label, after, arr.chunk_size());
++bad;
}
set_active_chunk_size(ambient);
set_thread_chunk_size(ambient);
if (!bad)
{
println("[{}/{}] OK: 256 -> 384 -> 192 -> 576 -> 320 -> 1024 -> 448 -> 512 -> 256, content kept",
variant_name(), label);
}
return bad ? 1 : 0;
}
namespace
{
/// @brief One case: its name (--case), the geometry it starts from, its body.
/// bool content for the bool cases: runs of false, runs of true, and varied
/// spans, 3000 elements each.
bool bool_runs(long i)
{
switch ((i / 3000) % 3)
{
case 0:
return false;
case 1:
return true;
default:
return i % 3 == 0;
}
}
/// double content for the sliced-val2 cases: runs of 0, runs of the second
/// value 0.5 and varied data, 2600 elements each (several chunks at every
/// geometry the cases use).
double sliced_val2_mix(long i)
{
switch ((i / 2600) % 5)
{
case 0:
return 0.0;
case 1:
case 3:
return 0.5;
default:
return double(i % 977) + 0.75;
}
}
struct Case
{
const char* name;
unsigned start_size;
std::function<int()> run;
};
/// @brief Declare @p size as the ambient geometry, to the arrays AND to the
/// allocators. set_active_chunk_size() only moves the ARRAY-side
/// geometry: without the registration, arrays report chunk_size() ==
/// size but draw their buffers from whatever size init()
/// primed, and every read past that width returns another chunk's data.
void set_start_geometry(unsigned size)
{
set_active_chunk_size(size);
set_thread_chunk_size(size);
Runtime::register_chunk_size(size);
}
} // namespace
static int run_body(int argc, char** argv)
{
// Positional arguments (the scale repro: N and the 64->target geometry are
// configurable, to hunt a size-dependent rechunk crash under ASan without
// the perf bench's weight): [N (1e6)] [target size (1024)] [rounds (200)]
// Flags: --case NAME, --mode serial|parallel|both (both), --list.
std::vector<const char*> pos;
const char* only = nullptr;
const char* mode = "both";
bool list = false;
for (int a = 1; a < argc; ++a)
{
if (!std::strcmp(argv[a], "--case") && a + 1 < argc)
{
only = argv[++a];
}
else if (!std::strcmp(argv[a], "--mode") && a + 1 < argc)
{
mode = argv[++a];
}
else if (!std::strcmp(argv[a], "--list"))
{
list = true;
}
else
{
pos.push_back(argv[a]);
}
}
const long n_scale = !pos.empty() ? shrink_array::arg_number<long>(pos[0], 1000000L, "N") : 1000000L;
const unsigned tgt = pos.size() > 1 ? shrink_array::arg_number<unsigned>(pos[1], 1024u, "target size") : 1024u;
const int rounds = pos.size() > 2 ? shrink_array::arg_number<int>(pos[2], 200, "rounds") : 200;
const bool run_ser = std::strcmp(mode, "parallel") != 0;
const bool run_par = std::strcmp(mode, "serial") != 0;
if (!run_ser && !run_par)
{
println("unknown --mode '{}' (serial, parallel or both)", mode);
return 2;
}
const long count = 1000000;
// Each case declares a second_value present in its data (value -> val2
// compression actually kicks in). On zero_or_value this is REQUIRED; on zero_any / zero
// it is a no-op. The first three start at 64 (the scale case grows it to
// the target, as the perf bench does), the others at 512.
const std::vector<Case> cases = {
// Coexistence first: it is the cheapest and the one the bench actually hits.
{"coexistence", 64, [] { return check_coexistence<double>("coexistence-64-and-256", 200000L, 256u, 3); }},
{"range-ops", 64, [] { return check_range_ops<double>("range-ops", 200000L); }},
{"scale-64-to-tgt", 64,
[&]
{
return check_invariance<double>(
"scale-64-to-tgt", n_scale, tgt, [](long i) -> double { return double((i / 5000) % 3); },
/*sv_value=*/2.0, /*post_rounds=*/rounds);
}},
{"mostly-constant", 512,
[&]
{
return check_invariance<double>(
"mostly-constant", count, 2048, [](long i) -> double { return double((i / 5000) % 3); },
/*sv_value=*/2.0);
}},
{"sin-quantized", 512,
[&]
{
return check_invariance<double>(
"sin-quantized", count, 4096,
[](long i) -> double { return std::floor(std::sin(double(i) * 0.001) * 4.0); }, /*sv_value=*/1.0);
}},
{"shrink-to-smaller", 512,
[&]
{
return check_invariance<double>(
"shrink-to-smaller", count, 256, [](long i) -> double { return double((i / 1000) % 2); },
/*sv_value=*/1.0);
}},
// 4096, not 8192: rechunk_to() refuses anything above const_buffer_size
// (CHUNK_DYN_MAX_SIZE, 4096 by default) because the shared const_val1/const_val2
// buffers are sized to that ceiling and a wider chunk would read them out of
// bounds. Asking for 8192 makes this case fail ("geometry 512 -> 512",
// with rechunk_to's refusal on stderr). Raise the target here only
// together with -DCHUNK_DYN_MAX_SIZE.
{"all-same", 512,
[&]
{
return check_invariance<double>(
"all-same", count, 4096, [](long) -> double { return 42.0; },
/*sv_value=*/42.0);
}},
{"all-different", 512,
[]
{
return check_invariance<double>(
"all-different", 100000, 1024, [](long i) -> double { return double(i); }, /*sv_value=*/1.0);
}},
// Growth 512 -> 2048 with val2: targets the array_m_ptr_const_val2 queue
// (zero_or_value) + the second_value round-trip.
{"val2-grow", 512,
[&]
{
return check_invariance<double>(
"val2-grow", count, 2048, [](long i) -> double { return double((i / 5000) % 3); }, /*sv_value=*/2.0);
}},
// A size that is neither a power of two nor a multiple of 64: refused, nothing changed.
{"invalid-size-refused", 512, [] { return check_non_pow2_refused("invalid-size-refused"); }},
// set_active_chunk_size: 0, 100 and a size over const_buffer_size refused in every build.
{"active-size-refused", 512, [] { return check_active_size_refused("active-size-refused"); }},
{"multiple-of-64-chain", 256, [] { return check_multiple_of_64_chain("multiple-of-64-chain"); }},
{"index-split", 256, [] { return check_index_split("index-split"); }},
// Shrink with val2 (queue never read past S', must pass).
{"val2-shrink", 512,
[&]
{
return check_invariance<double>(
"val2-shrink", count, 256, [](long i) -> double { return double((i / 1000) % 2); },
/*sv_value=*/1.0);
}},
// The zero refill's SLICED path (fast-alloc OpenMP builds): it slices
// only from 8192 new chunks on (n_new / 4096 slices, up to 16), which
// no case above reaches. Every slice boundary drains the old geometry's
// parked blocks and recycles the slabs they empty into the next slice's
// allocations (always, since CHUNK_RECHUNK_RECYCLE is gone): stale buffers that must come
// back zero-filled where the data is zero, and exact elsewhere. Mostly
// distinct values (no constant chunk to fold) with zero spans; grown
// (4 slices) and shrunk (8 slices), then rewritten and recompressed.
// bool, one byte per element: the refill's bulk read (memcpy per source
// chunk, zero_any's shared array of true filled as a constant). Runs of
// false, runs of true and varied spans; grown, shrunk, and to a size the
// old one does not divide (768), whose new chunks straddle old ones.
{"bool-grow", 512,
[]
{
return check_invariance<bool>("bool-grow-512-to-2048", 1000000L, 2048, bool_runs, /*sv_value=*/true,
/*post_rounds=*/1);
}},
{"bool-shrink", 512,
[] { return check_invariance<bool>("bool-shrink-512-to-64", 1000000L, 64, bool_runs, /*sv_value=*/true); }},
{"bool-uneven", 512,
[] { return check_invariance<bool>("bool-uneven-512-to-768", 1000000L, 768, bool_runs, /*sv_value=*/true); }},
// Array<bool> through the SLICED path (fast-alloc threaded builds): 4M
// bools 64 -> 256, 16384 new chunks, 4 slices. Sources at false (const1),
// at true (the second constant: a shared array, never released) and
// live ones, released during the copy; then rewritten and recompressed.
{"bool-sliced", 64,
[]
{
return check_invariance<bool>("bool-sliced-64-to-256", 4L << 20, 256, bool_runs, /*sv_value=*/true,
/*post_rounds=*/2);
}},
{"sliced-grow", 64,
[]
{
return check_invariance<double>(
"sliced-grow-64-to-256", 4L << 20, 256,
[](long i) -> double { return (i / 3000) % 4 == 0 ? 0.0 : double(i % 977) + 0.5; },
/*sv_value=*/0.5, /*post_rounds=*/2);
}},
{"sliced-shrink", 512,
[]
{
return check_invariance<double>(
"sliced-shrink-512-to-64", 2L << 20, 64,
[](long i) -> double { return (i / 5000) % 3 == 0 ? 0.0 : double(i % 613) + 0.25; },
/*sv_value=*/0.25, /*post_rounds=*/2);