Debian Codegraph @

reedsolomon_test.go

raw ◀ ▶
1 Debian patch touch this file
1 /**
2 * Unit tests for ReedSolomon
3 *
4 * Copyright 2015, Klaus Post
5 * Copyright 2015, Backblaze, Inc. All rights reserved.
6 */
7
8 package reedsolomon
9
10 import (
11 "bytes"
12 "errors"
13 "flag"
14 "fmt"
15 "math/rand"
16 "os"
17 "runtime"
•18 "slices"
19 "strconv"
20 "testing"
21 "time"
22 )
23
24 var noSSE2 = flag.Bool("no-sse2", !defaultOptions.useSSE2, "Disable SSE2")
25 var noSSSE3 = flag.Bool("no-ssse3", !defaultOptions.useSSSE3, "Disable SSSE3")
26 var noAVX2 = flag.Bool("no-avx2", !defaultOptions.useAVX2, "Disable AVX2")
27 var noAVX512 = flag.Bool("no-avx512", !defaultOptions.useAVX512, "Disable AVX512")
28 var noGNFI = flag.Bool("no-gfni", !defaultOptions.useAvx512GFNI, "Disable AVX512+GFNI")
29 var noAVX2GNFI = flag.Bool("no-avx-gfni", !defaultOptions.useAvxGNFI, "Disable AVX+GFNI")
•30 var noNEON = flag.Bool("no-neon", !defaultOptions.useNEON, "Disable NEON")
31 var noSVE = flag.Bool("no-sve", !defaultOptions.useSVE, "Disable SVE")
32
33 func TestMain(m *testing.M) {
34 flag.Parse()
35 rs, _ := New(10, 3, testOptions()...)
36 if rs != nil {
37 if rst, ok := rs.(*reedSolomon); ok {
38 fmt.Println("Using", rst.o.cpuOptions())
39 }
40 }
41 os.Exit(m.Run())
42 }
43
•44 // isaOptions returns the instruction set overrides requested with -no-* flags.
45 // These must be applied last, so they win over any explicitly enabled set.
46 func isaOptions() []Option {
47 var o []Option
48 if *noSSSE3 {
49 o = append(o, WithSSSE3(false))
50 }
51 if *noSSE2 {
52 o = append(o, WithSSE2(false))
53 }
54 if *noAVX2 {
55 o = append(o, WithAVX2(false))
56 }
57 if *noAVX512 {
58 o = append(o, WithAVX512(false))
59 }
60 if *noGNFI {
61 o = append(o, WithGFNI(false))
62 }
63 if *noAVX2GNFI {
64 o = append(o, WithAVXGFNI(false))
65 }
•66 if *noNEON {
67 o = append(o, WithNEON(false))
68 }
69 if *noSVE {
70 o = append(o, WithSVE(false))
71 }
72 return o
73 }
74
•75 func testOptions(o ...Option) []Option {
76 o = append(o, WithFastOneParityMatrix())
77 return append(o, isaOptions()...)
78 }
79
80 func isIncreasingAndContainsDataRow(indices []int) bool {
81 cols := len(indices)
82 for i := 0; i < cols-1; i++ {
83 if indices[i] >= indices[i+1] {
84 return false
85 }
86 }
87 // Data rows are in the upper square portion of the matrix.
88 return indices[0] < cols
89 }
90
91 func incrementIndices(indices []int, indexBound int) (valid bool) {
92 for i := len(indices) - 1; i >= 0; i-- {
93 indices[i]++
94 if indices[i] < indexBound {
95 break
96 }
97
98 if i == 0 {
99 return false
100 }
101
102 indices[i] = 0
103 }
104
105 return true
106 }
107
108 func incrementIndicesUntilIncreasingAndContainsDataRow(
109 indices []int, maxIndex int) bool {
110 for {
111 valid := incrementIndices(indices, maxIndex)
112 if !valid {
113 return false
114 }
115
116 if isIncreasingAndContainsDataRow(indices) {
117 return true
118 }
119 }
120 }
121
122 func findSingularSubMatrix(m matrix) (matrix, error) {
123 rows := len(m)
124 cols := len(m[0])
125 rowIndices := make([]int, cols)
126 for incrementIndicesUntilIncreasingAndContainsDataRow(rowIndices, rows) {
127 subMatrix, _ := newMatrix(cols, cols)
128 for i, r := range rowIndices {
129 for c := range cols {
130 subMatrix[i][c] = m[r][c]
131 }
132 }
133
134 _, err := subMatrix.Invert()
135 if err == errSingular {
136 return subMatrix, nil
137 } else if err != nil {
138 return nil, err
139 }
140 }
141
142 return nil, nil
143 }
144
145 func TestBuildMatrixJerasure(t *testing.T) {
146 totalShards := 12
147 dataShards := 8
148 m, err := buildMatrixJerasure(dataShards, totalShards)
149 if err != nil {
150 t.Fatal(err)
151 }
152 refMatrix := matrix{
153 {1, 1, 1, 1, 1, 1, 1, 1},
154 {1, 55, 39, 73, 84, 181, 225, 217},
155 {1, 39, 217, 161, 92, 60, 172, 90},
156 {1, 172, 70, 235, 143, 34, 200, 101},
157 }
158 for i := range 8 {
159 for j := range 8 {
160 if i != j && m[i][j] != 0 || i == j && m[i][j] != 1 {
161 t.Fatal("Top part of the matrix is not identity")
162 }
163 }
164 }
165 for i := range 4 {
166 for j := range 8 {
167 if m[8+i][j] != refMatrix[i][j] {
168 t.Fatal("Coding matrix for EC 8+4 differs from Jerasure")
169 }
170 }
171 }
172 }
173
174 func TestBuildMatrixPAR1Singular(t *testing.T) {
175 totalShards := 8
176 dataShards := 4
177 m, err := buildMatrixPAR1(dataShards, totalShards)
178 if err != nil {
179 t.Fatal(err)
180 }
181
182 singularSubMatrix, err := findSingularSubMatrix(m)
183 if err != nil {
184 t.Fatal(err)
185 }
186
187 if singularSubMatrix == nil {
188 t.Fatal("No singular sub-matrix found")
189 }
190
191 t.Logf("matrix %s has singular sub-matrix %s", m, singularSubMatrix)
192 }
193
•194 // withISA appends the -no-* overrides to every set. The base sets inherit
195 // whatever was detected, so the flags only take effect if applied to all of them.
196 func withISA(opts [][]Option) [][]Option {
197 isa := isaOptions()
198 if len(isa) == 0 {
199 return opts
200 }
201 for i, o := range opts {
202 opts[i] = append(slices.Clone(o), isa...)
203 }
204 return opts
205 }
206
207 // isaSets are the instruction sets ordered weakest to strongest, each with the
208 // option that turns it off. The amd64 and arm64 sets are independent; levels for
209 // the other architecture collapse into pure Go and get dropped.
210 var isaSets = []Option{
211 WithSSE2(false),
212 WithSSSE3(false),
213 WithAVX2(false),
214 WithAVX512(false),
215 WithAVXGFNI(false),
216 WithGFNI(false),
217 WithNEON(false),
218 WithSVE(false),
219 }
220
221 // isaLadder returns instruction set configurations from pure Go up to everything
222 // the CPU supports. Level i disables every set from i upwards, so the result
223 // never depends on what was detected and never enables something the CPU lacks.
224 // Levels that collapse into another one - unsupported, or turned off with a
225 // -no-* flag - are dropped.
226 func isaLadder() [][]Option {
227 var out [][]Option
228 seen := map[string]bool{}
229 for i := range len(isaSets) + 1 {
230 level := slices.Clone(isaSets[i:])
231 o := defaultOptions
232 for _, f := range append(slices.Clone(level), isaOptions()...) {
233 f(&o)
234 }
235 if k := o.cpuOptions(); !seen[k] {
236 seen[k] = true
237 out = append(out, level)
238 }
239 }
240 return out
241 }
242
243 func testOpts() [][]Option {
244 if testing.Short() {
•245 return withISA([][]Option{
246 {WithCauchyMatrix()}, {WithLeopardGF16(true)}, {WithLeopardGF(true)},
•247 })
248 }
•249 base := [][]Option{
250 {WithPAR1Matrix()}, {WithCauchyMatrix()},
251 {WithFastOneParityMatrix()}, {WithPAR1Matrix(), WithFastOneParityMatrix()}, {WithCauchyMatrix(), WithFastOneParityMatrix()},
•252 {WithMaxGoroutines(1), WithMinSplitSize(500)},
253 {WithMaxGoroutines(5000), WithMinSplitSize(50)},
254 {WithMaxGoroutines(5000), WithMinSplitSize(500000)},
255 {WithMaxGoroutines(1), WithMinSplitSize(500000)},
256 {WithAutoGoroutines(50000), WithMinSplitSize(500)},
257 {WithInversionCache(false)},
258 {WithJerasureMatrix()},
259 {WithLeopardGF16(true)},
260 {WithLeopardGF(true)},
261 }
262
•263 ladder := isaLadder()
264 opts := make([][]Option, 0, len(base)*len(ladder))
265 for _, b := range base {
266 for _, isa := range ladder {
267 opts = append(opts, append(slices.Clone(b), isa...))
268 }
269 }
•270 return withISA(opts)
271 }
272
273 func parallelIfNotShort(t *testing.T) {
274 if !testing.Short() {
275 t.Parallel()
276 }
277 }
278
279 func TestEncoding(t *testing.T) {
280 t.Run("default", func(t *testing.T) {
281 parallelIfNotShort(t)
282 testEncoding(t, testOptions()...)
283 })
284 t.Run("default-idx", func(t *testing.T) {
285 parallelIfNotShort(t)
286 testEncodingIdx(t, testOptions()...)
287 })
288 if testing.Short() {
289 return
290 }
291 // Spread somewhat, but don't overload...
292 to := testOpts()
293 to2 := to[len(to)/2:]
294 to = to[:len(to)/2]
295 t.Run("reg", func(t *testing.T) {
296 parallelIfNotShort(t)
297 for i, o := range to {
298 t.Run(fmt.Sprintf("opt-%d", i), func(t *testing.T) {
299 testEncoding(t, o...)
300 })
301 }
302 })
303 t.Run("reg2", func(t *testing.T) {
304 parallelIfNotShort(t)
305 for i, o := range to2 {
306 t.Run(fmt.Sprintf("opt-%d", i), func(t *testing.T) {
307 testEncoding(t, o...)
308 })
309 }
310 })
311 if !testing.Short() {
312 t.Run("idx", func(t *testing.T) {
313 parallelIfNotShort(t)
314 for i, o := range to {
315 t.Run(fmt.Sprintf("idx-opt-%d", i), func(t *testing.T) {
316 testEncodingIdx(t, o...)
317 })
318 }
319 })
320 t.Run("idx2", func(t *testing.T) {
321 parallelIfNotShort(t)
322 for i, o := range to2 {
323 t.Run(fmt.Sprintf("idx-opt-%d", i), func(t *testing.T) {
324 testEncodingIdx(t, o...)
325 })
326 }
327 })
328
329 }
330 }
331
332 // matrix sizes to test.
333 // note that par1 matrix will fail on some combinations.
334 func testSizes() [][2]int {
335 if testing.Short() {
336 return [][2]int{
337 {3, 0},
338 {1, 1}, {1, 2}, {8, 4}, {10, 30}, {41, 17},
339 {256, 20}, {500, 300},
340 }
341 }
342 return [][2]int{
343 {1, 0}, {10, 0}, {12, 0}, {49, 0},
344 {1, 1}, {1, 2}, {3, 3}, {3, 1}, {5, 3}, {8, 4}, {10, 30}, {12, 10}, {14, 7}, {41, 17}, {49, 1}, {5, 20},
345 {256, 20}, {500, 300}, {2945, 129},
346 }
347 }
348
349 var testDataSizes = []int{10, 100, 1000, 10001, 100003, 1000055}
350 var testDataSizesShort = []int{10, 10001, 100003}
351
352 func testEncoding(t *testing.T, o ...Option) {
353 for _, size := range testSizes() {
354 data, parity := size[0], size[1]
355 rng := rand.New(rand.NewSource(0xabadc0cac01a))
356 t.Run(fmt.Sprintf("%dx%d", data, parity), func(t *testing.T) {
357 sz := testDataSizes
358 if testing.Short() || data+parity > 256 {
359 sz = testDataSizesShort
360 if raceEnabled {
361 sz = testDataSizesShort[:1]
362 }
363 }
364 for _, perShard := range sz {
365 r, err := New(data, parity, testOptions(o...)...)
366 if err != nil {
367 t.Fatal(err)
368 }
369 x := r.(Extensions)
370 if want, got := data, x.DataShards(); want != got {
371 t.Errorf("DataShards returned %d, want %d", got, want)
372 }
373 if want, got := parity, x.ParityShards(); want != got {
374 t.Errorf("ParityShards returned %d, want %d", got, want)
375 }
376 if want, got := parity+data, x.TotalShards(); want != got {
377 t.Errorf("TotalShards returned %d, want %d", got, want)
378 }
379 mul := x.ShardSizeMultiple()
380 if mul <= 0 {
381 t.Fatalf("Got unexpected ShardSizeMultiple: %d", mul)
382 }
383 perShard = ((perShard + mul - 1) / mul) * mul
384
385 t.Run(fmt.Sprint(perShard), func(t *testing.T) {
386
387 shards := make([][]byte, data+parity)
388 for s := range shards {
389 shards[s] = make([]byte, perShard)
390 }
391
392 for s := range shards {
393 rng.Read(shards[s])
394 }
395
396 err = r.Encode(shards)
397 if err != nil {
398 t.Fatal(err)
399 }
400 ok, err := r.Verify(shards)
401 if err != nil {
402 t.Fatal(err)
403 }
404 if !ok {
405 t.Fatal("Verification failed")
406 }
407
408 if parity == 0 {
409 // Check that Reconstruct and ReconstructData do nothing
410 err = r.ReconstructData(shards)
411 if err != nil {
412 t.Fatal(err)
413 }
414 err = r.Reconstruct(shards)
415 if err != nil {
416 t.Fatal(err)
417 }
418
419 // Skip integrity checks
420 return
421 }
422
423 // Delete one in data
424 idx := rng.Intn(data)
425 want := shards[idx]
426 shards[idx] = nil
427
428 err = r.ReconstructData(shards)
429 if err != nil {
430 t.Fatal(err)
431 }
432 if !bytes.Equal(shards[idx], want) {
433 t.Fatal("did not ReconstructData correctly")
434 }
435
436 // Delete one randomly
437 idx = rng.Intn(data + parity)
438 want = shards[idx]
439 shards[idx] = nil
440 err = r.Reconstruct(shards)
441 if err != nil {
442 t.Fatal(err)
443 }
444 if !bytes.Equal(shards[idx], want) {
445 t.Fatal("did not Reconstruct correctly")
446 }
447
448 err = r.Encode(make([][]byte, 1))
449 if err != ErrTooFewShards {
450 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
451 }
452
453 // Make one too short.
454 shards[idx] = shards[idx][:perShard-1]
455 err = r.Encode(shards)
456 if err != ErrShardSize {
457 t.Errorf("expected %v, got %v", ErrShardSize, err)
458 }
459 })
460 }
461 })
462
463 }
464 }
465
466 func testEncodingIdx(t *testing.T, o ...Option) {
467 for _, size := range testSizes() {
468 data, parity := size[0], size[1]
469 rng := rand.New(rand.NewSource(0xabadc0cac01a))
470 t.Run(fmt.Sprintf("%dx%d", data, parity), func(t *testing.T) {
471
472 sz := testDataSizes
473 if testing.Short() {
474 sz = testDataSizesShort
475 }
476 for _, perShard := range sz {
477 r, err := New(data, parity, testOptions(o...)...)
478 if err != nil {
479 t.Fatal(err)
480 }
481 if err := r.EncodeIdx(nil, 0, nil); err == ErrNotSupported {
482 t.Skip(err)
483 return
484 }
485 mul := r.(Extensions).ShardSizeMultiple()
486 perShard = ((perShard + mul - 1) / mul) * mul
487
488 t.Run(fmt.Sprint(perShard), func(t *testing.T) {
489
490 shards := AllocAligned(data+parity, perShard)
491 shuffle := make([]int, data)
492 for i := range shuffle {
493 shuffle[i] = i
494 }
495 rng.Shuffle(len(shuffle), func(i, j int) { shuffle[i], shuffle[j] = shuffle[j], shuffle[i] })
496
497 // Send shards in random order.
498 for s := range data {
499 s := shuffle[s]
500 rng.Read(shards[s])
501 err = r.EncodeIdx(shards[s], s, shards[data:])
502 if err != nil {
503 t.Fatal(err)
504 }
505 }
506
507 ok, err := r.Verify(shards)
508 if err != nil {
509 t.Fatal(err)
510 }
511 if !ok {
512 t.Fatal("Verification failed")
513 }
514
515 if parity == 0 {
516 // Check that Reconstruct and ReconstructData do nothing
517 err = r.ReconstructData(shards)
518 if err != nil {
519 t.Fatal(err)
520 }
521 err = r.Reconstruct(shards)
522 if err != nil {
523 t.Fatal(err)
524 }
525
526 // Skip integrity checks
527 return
528 }
529
530 // Delete one in data
531 idx := rng.Intn(data)
532 want := shards[idx]
533 shards[idx] = nil
534
535 err = r.ReconstructData(shards)
536 if err != nil {
537 t.Fatal(err)
538 }
539 if !bytes.Equal(shards[idx], want) {
540 t.Fatal("did not ReconstructData correctly")
541 }
542
543 // Delete one randomly
544 idx = rng.Intn(data + parity)
545 want = shards[idx]
546 shards[idx] = nil
547 err = r.Reconstruct(shards)
548 if err != nil {
549 t.Fatal(err)
550 }
551 if !bytes.Equal(shards[idx], want) {
552 t.Fatal("did not Reconstruct correctly")
553 }
554
555 err = r.Encode(make([][]byte, 1))
556 if err != ErrTooFewShards {
557 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
558 }
559
560 // Make one too short.
561 shards[idx] = shards[idx][:perShard-1]
562 err = r.Encode(shards)
563 if err != ErrShardSize {
564 t.Errorf("expected %v, got %v", ErrShardSize, err)
565 }
566 })
567 }
568 })
569
570 }
571 }
572
573 func TestUpdate(t *testing.T) {
574 parallelIfNotShort(t)
575 for i, o := range testOpts() {
576 t.Run(fmt.Sprintf("options %d", i), func(t *testing.T) {
577 testUpdate(t, o...)
578 })
579 }
580 }
581
582 func testUpdate(t *testing.T, o ...Option) {
583 for _, size := range [][2]int{{10, 3}, {17, 2}} {
584 data, parity := size[0], size[1]
585 t.Run(fmt.Sprintf("%dx%d", data, parity), func(t *testing.T) {
586 sz := testDataSizesShort
587 if testing.Short() {
588 sz = []int{50000}
589 }
590 for _, perShard := range sz {
591 r, err := New(data, parity, testOptions(o...)...)
592 if err != nil {
593 t.Fatal(err)
594 }
595 mul := r.(Extensions).ShardSizeMultiple()
596 perShard = ((perShard + mul - 1) / mul) * mul
597
598 t.Run(fmt.Sprint(perShard), func(t *testing.T) {
599
600 shards := make([][]byte, data+parity)
601 for s := range shards {
602 shards[s] = make([]byte, perShard)
603 }
604
605 for s := range shards {
606 fillRandom(shards[s])
607 }
608
609 err = r.Encode(shards)
610 if err != nil {
611 t.Fatal(err)
612 }
613 ok, err := r.Verify(shards)
614 if err != nil {
615 t.Fatal(err)
616 }
617 if !ok {
618 t.Fatal("Verification failed")
619 }
620
621 newdatashards := make([][]byte, data)
622 for s := range newdatashards {
623 newdatashards[s] = make([]byte, perShard)
624 fillRandom(newdatashards[s])
625 err = r.Update(shards, newdatashards)
626 if err != nil {
627 if errors.Is(err, ErrNotSupported) {
628 t.Skip(err)
629 return
630 }
631 t.Fatal(err)
632 }
633 shards[s] = newdatashards[s]
634 ok, err := r.Verify(shards)
635 if err != nil {
636 t.Fatal(err)
637 }
638 if !ok {
639 t.Fatal("Verification failed")
640 }
641 newdatashards[s] = nil
642 }
643 for s := 0; s < len(newdatashards)-1; s++ {
644 newdatashards[s] = make([]byte, perShard)
645 newdatashards[s+1] = make([]byte, perShard)
646 fillRandom(newdatashards[s])
647 fillRandom(newdatashards[s+1])
648 err = r.Update(shards, newdatashards)
649 if err != nil {
650 t.Fatal(err)
651 }
652 shards[s] = newdatashards[s]
653 shards[s+1] = newdatashards[s+1]
654 ok, err := r.Verify(shards)
655 if err != nil {
656 t.Fatal(err)
657 }
658 if !ok {
659 t.Fatal("Verification failed")
660 }
661 newdatashards[s] = nil
662 newdatashards[s+1] = nil
663 }
664 for newNum := 1; newNum <= data; newNum++ {
665 for s := 0; s <= data-newNum; s++ {
666 for i := 0; i < newNum; i++ {
667 newdatashards[s+i] = make([]byte, perShard)
668 fillRandom(newdatashards[s+i])
669 }
670 err = r.Update(shards, newdatashards)
671 if err != nil {
672 t.Fatal(err)
673 }
674 for i := 0; i < newNum; i++ {
675 shards[s+i] = newdatashards[s+i]
676 }
677 ok, err := r.Verify(shards)
678 if err != nil {
679 t.Fatal(err)
680 }
681 if !ok {
682 t.Fatal("Verification failed")
683 }
684 for i := 0; i < newNum; i++ {
685 newdatashards[s+i] = nil
686 }
687 }
688 }
689 })
690 }
691 })
692 }
693 }
694
695 func TestReconstruct(t *testing.T) {
696 parallelIfNotShort(t)
697 testReconstruct(t)
698 for i, o := range testOpts() {
699 t.Run(fmt.Sprintf("options %d", i), func(t *testing.T) {
700 testReconstruct(t, o...)
701 })
702 }
703 }
704
705 func testReconstruct(t *testing.T, o ...Option) {
706 perShard := 50000
707 r, err := New(10, 3, testOptions(o...)...)
708 if err != nil {
709 t.Fatal(err)
710 }
711 xt := r.(Extensions)
712 mul := xt.ShardSizeMultiple()
713 perShard = ((perShard + mul - 1) / mul) * mul
714
715 t.Log(perShard)
716 shards := make([][]byte, 13)
717 for s := range shards {
718 shards[s] = make([]byte, perShard)
719 }
720
721 for s := range 13 {
722 fillRandom(shards[s])
723 }
724
725 err = r.Encode(shards)
726 if err != nil {
727 t.Fatal(err)
728 }
729
730 // Reconstruct with all shards present
731 err = r.Reconstruct(shards)
732 if err != nil {
733 t.Fatal(err)
734 }
735
736 // Reconstruct with 10 shards present. Use pre-allocated memory for one of them.
737 shards[0] = nil
738 shards[7] = nil
739 shard11 := shards[11]
740 shards[11] = shard11[:0]
741 fillRandom(shard11)
742
743 err = r.Reconstruct(shards)
744 if err != nil {
745 t.Fatal(err)
746 }
747
748 ok, err := r.Verify(shards)
749 if err != nil {
750 t.Fatal(err)
751 }
752 if !ok {
753 t.Fatal("Verification failed")
754 }
755
756 if &shard11[0] != &shards[11][0] {
757 t.Errorf("Shard was not reconstructed into pre-allocated memory")
758 }
759
760 // Reconstruct with 9 shards present (should fail)
761 shards[0] = nil
762 shards[4] = nil
763 shards[7] = nil
764 shards[11] = nil
765
766 err = r.Reconstruct(shards)
767 if err != ErrTooFewShards {
768 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
769 }
770
771 err = r.Reconstruct(make([][]byte, 1))
772 if err != ErrTooFewShards {
773 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
774 }
775 err = r.Reconstruct(make([][]byte, 13))
776 if err != ErrShardNoData {
777 t.Errorf("expected %v, got %v", ErrShardNoData, err)
778 }
779 }
780
781 func TestReconstructCustom(t *testing.T) {
782 perShard := 50000
783 r, err := New(4, 3, WithCustomMatrix([][]byte{
784 {1, 1, 0, 0},
785 {0, 0, 1, 1},
786 {1, 2, 3, 4},
787 }))
788 if err != nil {
789 t.Fatal(err)
790 }
791 shards := make([][]byte, 7)
792 for s := range shards {
793 shards[s] = make([]byte, perShard)
794 }
795
796 for s := range shards {
797 fillRandom(shards[s])
798 }
799
800 err = r.Encode(shards)
801 if err != nil {
802 t.Fatal(err)
803 }
804
805 // Reconstruct with 1 shard absent.
806 shards1 := make([][]byte, len(shards))
807 copy(shards1, shards)
808 shards1[0] = nil
809
810 err = r.Reconstruct(shards1)
811 if err != nil {
812 t.Fatal(err)
813 }
814
815 ok, err := r.Verify(shards)
816 if err != nil {
817 t.Fatal(err)
818 }
819 if !ok {
820 t.Fatal("Verification failed")
821 }
822
823 // Reconstruct with 3 shards absent.
824 copy(shards1, shards)
825 shards1[0] = nil
826 shards1[1] = nil
827 shards1[2] = nil
828
829 err = r.Reconstruct(shards1)
830 if err != nil {
831 t.Fatal(err)
832 }
833
834 ok, err = r.Verify(shards)
835 if err != nil {
836 t.Fatal(err)
837 }
838 if !ok {
839 t.Fatal("Verification failed")
840 }
841 }
842
843 func TestReconstructData(t *testing.T) {
844 parallelIfNotShort(t)
845 testReconstructData(t)
846 for i, o := range testOpts() {
847 t.Run(fmt.Sprintf("options %d", i), func(t *testing.T) {
848 testReconstructData(t, o...)
849 })
850 }
851 }
852
853 func testReconstructData(t *testing.T, o ...Option) {
854 perShard := 100000
855 r, err := New(8, 5, testOptions(o...)...)
856 if err != nil {
857 t.Fatal(err)
858 }
859 mul := r.(Extensions).ShardSizeMultiple()
860 perShard = ((perShard + mul - 1) / mul) * mul
861
862 shards := make([][]byte, 13)
863 for s := range shards {
864 shards[s] = make([]byte, perShard)
865 }
866
867 for s := range 13 {
868 fillRandom(shards[s], int64(s))
869 }
870
871 err = r.Encode(shards)
872 if err != nil {
873 t.Fatal(err)
874 }
875
876 // Reconstruct with all shards present
877 err = r.ReconstructData(shards)
878 if err != nil {
879 t.Fatal(err)
880 }
881
882 // Reconstruct parity shards from data
883 shardsCopy := make([][]byte, 13)
884 for i := range 8 {
885 shardsCopy[i] = shards[i]
886 }
887
888 shardsRequired := make([]bool, 13)
889 shardsRequired[10] = true
890
891 err = r.ReconstructSome(shardsCopy, shardsRequired)
892 if err != nil {
893 t.Fatal(err)
894 }
895
896 if !bytes.Equal(shardsCopy[10], shards[10]) {
897 t.Fatal("ReconstructSome did not reconstruct required shards correctly")
898 }
899
900 // Reconstruct 3 shards with 3 data and 5 parity shards
901 shardsCopy = make([][]byte, 13)
902 copy(shardsCopy, shards)
903 shardsCopy[2] = nil
904 shardsCopy[3] = nil
905 shardsCopy[4] = nil
906 shardsCopy[5] = nil
907 shardsCopy[6] = nil
908
909 shardsRequired = make([]bool, 8)
910 shardsRequired[3] = true
911 shardsRequired[4] = true
912 err = r.ReconstructSome(shardsCopy, shardsRequired)
913 if err != nil {
914 t.Fatal(err)
915 }
916
917 if 0 != bytes.Compare(shardsCopy[3], shards[3]) ||
918 0 != bytes.Compare(shardsCopy[4], shards[4]) {
919 t.Fatal("ReconstructSome did not reconstruct required shards correctly")
920 }
921
922 if shardsCopy[2] != nil || shardsCopy[5] != nil || shardsCopy[6] != nil {
923 // This is expected in some cases.
924 t.Log("ReconstructSome reconstructed extra shards")
925 }
926
927 // Reconstruct with 10 shards present. Use pre-allocated memory for one of them.
928 shards[0] = nil
929 shards[2] = nil
930 shard4 := shards[4]
931 shards[4] = shard4[:0]
932 fillRandom(shard4, 4)
933
934 err = r.ReconstructData(shards)
935 if err != nil {
936 t.Fatal(err)
937 }
938
939 // Since all parity shards are available, verification will succeed
940 ok, err := r.Verify(shards)
941 if err != nil {
942 t.Fatal(err)
943 }
944 if !ok {
945 t.Fatal("Verification failed")
946 }
947
948 if &shard4[0] != &shards[4][0] {
949 t.Errorf("Shard was not reconstructed into pre-allocated memory")
950 }
951
952 // Reconstruct with 6 data and 4 parity shards
953 shards[0] = nil
954 shards[2] = nil
955 shards[12] = nil
956
957 err = r.ReconstructData(shards)
958 if err != nil {
959 t.Fatal(err)
960 }
961
962 // Verification will fail now due to absence of a parity block
963 _, err = r.Verify(shards)
964 if err != ErrShardSize {
965 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
966 }
967
968 // Reconstruct with 7 data and 1 parity shards
969 shards[0] = nil
970 shards[9] = nil
971 shards[10] = nil
972 shards[11] = nil
973 shards[12] = nil
974
975 err = r.ReconstructData(shards)
976 if err != nil {
977 t.Fatal(err)
978 }
979
980 _, err = r.Verify(shards)
981 if err != ErrShardSize {
982 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
983 }
984
985 // Reconstruct with 6 data and 1 parity shards (should fail)
986 shards[0] = nil
987 shards[1] = nil
988 shards[9] = nil
989 shards[10] = nil
990 shards[11] = nil
991 shards[12] = nil
992
993 err = r.ReconstructData(shards)
994 if err != ErrTooFewShards {
995 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
996 }
997
998 err = r.ReconstructData(make([][]byte, 1))
999 if err != ErrTooFewShards {
1000 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
1001 }
1002 err = r.ReconstructData(make([][]byte, 13))
1003 if err != ErrShardNoData {
1004 t.Errorf("expected %v, got %v", ErrShardNoData, err)
1005 }
1006 }
1007
1008 func TestReconstructPAR1Singular(t *testing.T) {
1009 parallelIfNotShort(t)
1010 perShard := 50
1011 r, err := New(4, 4, testOptions(WithPAR1Matrix())...)
1012 if err != nil {
1013 t.Fatal(err)
1014 }
1015 shards := make([][]byte, 8)
1016 for s := range shards {
1017 shards[s] = make([]byte, perShard)
1018 }
1019
1020 for s := range 8 {
1021 fillRandom(shards[s])
1022 }
1023
1024 err = r.Encode(shards)
1025 if err != nil {
1026 t.Fatal(err)
1027 }
1028
1029 // Reconstruct with only the last data shard present, and the
1030 // first, second, and fourth parity shard present (based on
1031 // the result of TestBuildMatrixPAR1Singular). This should
1032 // fail.
1033 shards[0] = nil
1034 shards[1] = nil
1035 shards[2] = nil
1036 shards[6] = nil
1037
1038 err = r.Reconstruct(shards)
1039 if err != errSingular {
1040 t.Fatal(err)
1041 t.Errorf("expected %v, got %v", errSingular, err)
1042 }
1043 }
1044
1045 func TestVerify(t *testing.T) {
1046 parallelIfNotShort(t)
1047 testVerify(t)
1048 for i, o := range testOpts() {
1049 t.Run(fmt.Sprintf("options %d", i), func(t *testing.T) {
1050 testVerify(t, o...)
1051 })
1052 }
1053 }
1054
1055 func testVerify(t *testing.T, o ...Option) {
1056 perShard := 33333
1057 r, err := New(10, 4, testOptions(o...)...)
1058 if err != nil {
1059 t.Fatal(err)
1060 }
1061 mul := r.(Extensions).ShardSizeMultiple()
1062 perShard = ((perShard + mul - 1) / mul) * mul
1063
1064 shards := make([][]byte, 14)
1065 for s := range shards {
1066 shards[s] = make([]byte, perShard)
1067 }
1068
1069 for s := range 10 {
1070 fillRandom(shards[s], 0)
1071 }
1072
1073 err = r.Encode(shards)
1074 if err != nil {
1075 t.Fatal(err)
1076 }
1077 ok, err := r.Verify(shards)
1078 if err != nil {
1079 t.Fatal(err)
1080 }
1081 if !ok {
1082 t.Error("Verification failed")
1083 return
1084 }
1085
1086 // Put in random data. Verification should fail
1087 fillRandom(shards[10], 1)
1088 ok, err = r.Verify(shards)
1089 if err != nil {
1090 t.Fatal(err)
1091 }
1092 if ok {
1093 t.Fatal("Verification did not fail")
1094 }
1095 // Re-encode
1096 err = r.Encode(shards)
1097 if err != nil {
1098 t.Fatal(err)
1099 }
1100 // Fill a data segment with random data
1101 fillRandom(shards[0], 2)
1102 ok, err = r.Verify(shards)
1103 if err != nil {
1104 t.Fatal(err)
1105 }
1106 if ok {
1107 t.Fatal("Verification did not fail")
1108 }
1109
1110 _, err = r.Verify(make([][]byte, 1))
1111 if err != ErrTooFewShards {
1112 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
1113 }
1114
1115 _, err = r.Verify(make([][]byte, 14))
1116 if err != ErrShardNoData {
1117 t.Errorf("expected %v, got %v", ErrShardNoData, err)
1118 }
1119 }
1120
1121 func TestOneEncode(t *testing.T) {
1122 codec, err := New(5, 5, testOptions()...)
1123 if err != nil {
1124 t.Fatal(err)
1125 }
1126 shards := [][]byte{
1127 {0, 1},
1128 {4, 5},
1129 {2, 3},
1130 {6, 7},
1131 {8, 9},
1132 {0, 0},
1133 {0, 0},
1134 {0, 0},
1135 {0, 0},
1136 {0, 0},
1137 }
1138 codec.Encode(shards)
1139 if shards[5][0] != 12 || shards[5][1] != 13 {
1140 t.Fatal("shard 5 mismatch")
1141 }
1142 if shards[6][0] != 10 || shards[6][1] != 11 {
1143 t.Fatal("shard 6 mismatch")
1144 }
1145 if shards[7][0] != 14 || shards[7][1] != 15 {
1146 t.Fatal("shard 7 mismatch")
1147 }
1148 if shards[8][0] != 90 || shards[8][1] != 91 {
1149 t.Fatal("shard 8 mismatch")
1150 }
1151 if shards[9][0] != 94 || shards[9][1] != 95 {
1152 t.Fatal("shard 9 mismatch")
1153 }
1154
1155 ok, err := codec.Verify(shards)
1156 if err != nil {
1157 t.Fatal(err)
1158 }
1159 if !ok {
1160 t.Fatal("did not verify")
1161 }
1162 shards[8][0]++
1163 ok, err = codec.Verify(shards)
1164 if err != nil {
1165 t.Fatal(err)
1166 }
1167 if ok {
1168 t.Fatal("verify did not fail as expected")
1169 }
1170
1171 }
1172
1173 func fillRandom(p []byte, seed ...int64) {
1174 src := rand.NewSource(time.Now().UnixNano())
1175 if len(seed) > 0 {
1176 src = rand.NewSource(seed[0])
1177 }
1178 rng := rand.New(src)
1179 for i := 0; i < len(p); i += 7 {
1180 val := rng.Int63()
1181 for j := 0; i+j < len(p) && j < 7; j++ {
1182 p[i+j] = byte(val)
1183 val >>= 8
1184 }
1185 }
1186 }
1187
1188 func benchmarkEncode(b *testing.B, dataShards, parityShards, shardSize int, opts ...Option) {
1189 opts = append(testOptions(WithAutoGoroutines(shardSize)), opts...)
1190 r, err := New(dataShards, parityShards, opts...)
1191 if err != nil {
1192 b.Fatal(err)
1193 }
1194
1195 shards := r.(Extensions).AllocAligned(shardSize)
1196 for s := range dataShards {
1197 fillRandom(shards[s])
1198 }
1199 // Warm up so initialization is eliminated.
1200 err = r.Encode(shards)
1201 if err != nil {
1202 b.Fatal(err)
1203 }
1204
1205 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1206 b.ResetTimer()
1207 b.ReportAllocs()
1208 for i := 0; i < b.N; i++ {
1209 err = r.Encode(shards)
1210 if err != nil {
1211 b.Fatal(err)
1212 }
1213 }
1214 }
1215
1216 func benchmarkDecode(b *testing.B, dataShards, parityShards, shardSize, deleteShards int, opts ...Option) {
1217 opts = append(testOptions(WithAutoGoroutines(shardSize)), opts...)
1218 r, err := New(dataShards, parityShards, opts...)
1219 if err != nil {
1220 b.Fatal(err)
1221 }
1222
1223 shards := r.(Extensions).AllocAligned(shardSize)
1224 for s := range dataShards {
1225 fillRandom(shards[s])
1226 }
1227 if err := r.Encode(shards); err != nil {
1228 b.Fatal(err)
1229 }
1230
1231 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1232 b.ResetTimer()
1233 b.ReportAllocs()
1234 for i := 0; i < b.N; i++ {
1235 // Clear maximum number of data shards.
1236 for s := range deleteShards {
1237 shards[s] = nil
1238 }
1239
1240 err = r.Reconstruct(shards)
1241 if err != nil {
1242 b.Fatal(err)
1243 }
1244 }
1245 }
1246
1247 func BenchmarkEncode2x1x1M(b *testing.B) {
1248 benchmarkEncode(b, 2, 1, 1024*1024)
1249 }
1250
1251 // Benchmark 800 data slices with 200 parity slices
1252 func BenchmarkEncode800x200(b *testing.B) {
1253 for size := 64; size <= 1<<20; size *= 4 {
1254 b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
1255 benchmarkEncode(b, 800, 200, size)
1256 })
1257 }
1258 }
1259
1260 // Benchmark 1K encode with symmetric shard sizes.
1261 func BenchmarkEncode1K(b *testing.B) {
1262 for shards := 4; shards < 65536; shards *= 2 {
1263 b.Run(fmt.Sprintf("%v+%v", shards, shards), func(b *testing.B) {
1264 if shards*2 <= 256 {
1265 b.Run(fmt.Sprint("cauchy"), func(b *testing.B) {
1266 benchmarkEncode(b, shards, shards, 1024, WithCauchyMatrix())
1267 })
1268 b.Run(fmt.Sprint("leopard-gf8"), func(b *testing.B) {
1269 benchmarkEncode(b, shards, shards, 1024, WithLeopardGF(true))
1270 })
1271 }
1272 b.Run(fmt.Sprint("leopard-gf16"), func(b *testing.B) {
1273 benchmarkEncode(b, shards, shards, 1024, WithLeopardGF16(true))
1274 })
1275 })
1276 }
1277 }
1278
1279 // Benchmark 1K decode with symmetric shard sizes.
1280 func BenchmarkDecode1K(b *testing.B) {
1281 for shards := 4; shards < 65536; shards *= 2 {
1282 b.Run(fmt.Sprintf("%v+%v", shards, shards), func(b *testing.B) {
1283 if shards*2 <= 256 {
1284 b.Run(fmt.Sprint("cauchy"), func(b *testing.B) {
1285 benchmarkDecode(b, shards, shards, 1024, shards, WithCauchyMatrix(), WithInversionCache(false))
1286 })
1287 b.Run(fmt.Sprint("cauchy-inv"), func(b *testing.B) {
1288 benchmarkDecode(b, shards, shards, 1024, shards, WithCauchyMatrix(), WithInversionCache(true))
1289 })
1290 b.Run(fmt.Sprint("cauchy-single"), func(b *testing.B) {
1291 benchmarkDecode(b, shards, shards, 1024, 1, WithCauchyMatrix(), WithInversionCache(false))
1292 })
1293 b.Run(fmt.Sprint("cauchy-single-inv"), func(b *testing.B) {
1294 benchmarkDecode(b, shards, shards, 1024, 1, WithCauchyMatrix(), WithInversionCache(true))
1295 })
1296 b.Run(fmt.Sprint("leopard-gf8"), func(b *testing.B) {
1297 benchmarkDecode(b, shards, shards, 1024, shards, WithLeopardGF(true), WithInversionCache(false))
1298 })
1299 b.Run(fmt.Sprint("leopard-gf8-inv"), func(b *testing.B) {
1300 benchmarkDecode(b, shards, shards, 1024, shards, WithLeopardGF(true), WithInversionCache(true))
1301 })
1302 b.Run(fmt.Sprint("leopard-gf8-single"), func(b *testing.B) {
1303 benchmarkDecode(b, shards, shards, 1024, 1, WithLeopardGF(true), WithInversionCache(false))
1304 })
1305 b.Run(fmt.Sprint("leopard-gf8-single-inv"), func(b *testing.B) {
1306 benchmarkDecode(b, shards, shards, 1024, 1, WithLeopardGF(true), WithInversionCache(true))
1307 })
1308 }
1309 b.Run(fmt.Sprint("leopard-gf16"), func(b *testing.B) {
1310 benchmarkDecode(b, shards, shards, 1024, shards, WithLeopardGF16(true))
1311 })
1312 b.Run(fmt.Sprint("leopard-gf16-single"), func(b *testing.B) {
1313 benchmarkDecode(b, shards, shards, 1024, 1, WithLeopardGF16(true))
1314 })
1315 })
1316 }
1317 }
1318
1319 func BenchmarkEncodeLeopard(b *testing.B) {
1320 size := (64 << 20) / 800 / 64 * 64
1321 b.Run(strconv.Itoa(size), func(b *testing.B) {
1322 benchmarkEncode(b, 800, 200, size)
1323 })
1324 }
1325
1326 func BenchmarkEncode10x2x10000(b *testing.B) {
1327 benchmarkEncode(b, 10, 2, 10000)
1328 }
1329
1330 func BenchmarkEncode100x20x10000(b *testing.B) {
1331 benchmarkEncode(b, 100, 20, 10000)
1332 }
1333
1334 func BenchmarkEncode17x3x1M(b *testing.B) {
1335 benchmarkEncode(b, 17, 3, 1024*1024)
1336 }
1337
1338 // Benchmark 10 data shards and 4 parity shards with 16MB each.
1339 func BenchmarkEncode10x4x16M(b *testing.B) {
1340 benchmarkEncode(b, 10, 4, 16*1024*1024)
1341 }
1342
1343 // Benchmark 5 data shards and 2 parity shards with 1MB each.
1344 func BenchmarkEncode5x2x1M(b *testing.B) {
1345 benchmarkEncode(b, 5, 2, 1024*1024)
1346 }
1347
1348 // Benchmark 1 data shards and 2 parity shards with 1MB each.
1349 func BenchmarkEncode10x2x1M(b *testing.B) {
1350 benchmarkEncode(b, 10, 2, 1024*1024)
1351 }
1352
1353 // Benchmark 10 data shards and 4 parity shards with 1MB each.
1354 func BenchmarkEncode10x4x1M(b *testing.B) {
1355 benchmarkEncode(b, 10, 4, 1024*1024)
1356 }
1357
1358 // Benchmark 50 data shards and 20 parity shards with 1M each.
1359 func BenchmarkEncode50x20x1M(b *testing.B) {
1360 benchmarkEncode(b, 50, 20, 1024*1024)
1361 }
1362
1363 // Benchmark 50 data shards and 20 parity shards with 1M each.
1364 func BenchmarkEncodeLeopard50x20x1M(b *testing.B) {
1365 benchmarkEncode(b, 50, 20, 1024*1024, WithLeopardGF(true))
1366 }
1367
1368 // Benchmark 17 data shards and 3 parity shards with 16MB each.
1369 func BenchmarkEncode17x3x16M(b *testing.B) {
1370 benchmarkEncode(b, 17, 3, 16*1024*1024)
1371 }
1372
1373 func BenchmarkEncode_8x4x8M(b *testing.B) { benchmarkEncode(b, 8, 4, 8*1024*1024) }
1374 func BenchmarkEncode_12x4x12M(b *testing.B) { benchmarkEncode(b, 12, 4, 12*1024*1024) }
1375 func BenchmarkEncode_16x4x16M(b *testing.B) { benchmarkEncode(b, 16, 4, 16*1024*1024) }
1376 func BenchmarkEncode_16x4x32M(b *testing.B) { benchmarkEncode(b, 16, 4, 32*1024*1024) }
1377 func BenchmarkEncode_16x4x64M(b *testing.B) { benchmarkEncode(b, 16, 4, 64*1024*1024) }
1378
1379 func BenchmarkEncode_8x5x8M(b *testing.B) { benchmarkEncode(b, 8, 5, 8*1024*1024) }
1380 func BenchmarkEncode_8x6x8M(b *testing.B) { benchmarkEncode(b, 8, 6, 8*1024*1024) }
1381 func BenchmarkEncode_8x7x8M(b *testing.B) { benchmarkEncode(b, 8, 7, 8*1024*1024) }
1382 func BenchmarkEncode_8x9x8M(b *testing.B) { benchmarkEncode(b, 8, 9, 8*1024*1024) }
1383 func BenchmarkEncode_8x10x8M(b *testing.B) { benchmarkEncode(b, 8, 10, 8*1024*1024) }
1384 func BenchmarkEncode_8x11x8M(b *testing.B) { benchmarkEncode(b, 8, 11, 8*1024*1024) }
1385
1386 func BenchmarkEncode_8x8x05M(b *testing.B) { benchmarkEncode(b, 8, 8, 1*1024*1024/2) }
1387 func BenchmarkEncode_8x8x1M(b *testing.B) { benchmarkEncode(b, 8, 8, 1*1024*1024) }
1388 func BenchmarkEncode_8x8x8M(b *testing.B) { benchmarkEncode(b, 8, 8, 8*1024*1024) }
1389 func BenchmarkEncode_8x8x32M(b *testing.B) { benchmarkEncode(b, 8, 8, 32*1024*1024) }
1390
1391 func BenchmarkEncode_24x8x24M(b *testing.B) { benchmarkEncode(b, 24, 8, 24*1024*1024) }
1392 func BenchmarkEncode_24x8x48M(b *testing.B) { benchmarkEncode(b, 24, 8, 48*1024*1024) }
1393
1394 func BenchmarkEncodeLeopardGF16Chunking(b *testing.B) {
1395 // Tests GF16 encoder across shard sizes where L3 cache chunking matters.
1396 for _, tc := range []struct {
1397 data, parity int
1398 }{
1399 {800, 200},
1400 {500, 500},
1401 {50, 20},
1402 } {
1403 const maxBytes = 1 << 30
1404 for _, sz := range []int{
1405 64 << 10, 256 << 10, 1 << 20, 4 << 20, 16 << 20,
1406 } {
1407 sz = min(sz, maxBytes/(tc.data+tc.parity))
1408 sz = sz / 64 * 64
1409 if sz == 0 {
1410 continue
1411 }
1412 name := fmt.Sprintf("%dx%d/%dK", tc.data, tc.parity, sz>>10)
1413 b.Run(name, func(b *testing.B) {
1414 benchmarkEncode(b, tc.data, tc.parity, sz, WithLeopardGF16(true))
1415 })
1416 }
1417 }
1418 }
1419
1420 func benchmarkVerify(b *testing.B, dataShards, parityShards, shardSize int) {
1421 r, err := New(dataShards, parityShards, testOptions(WithAutoGoroutines(shardSize))...)
1422 if err != nil {
1423 b.Fatal(err)
1424 }
1425 shards := r.(Extensions).AllocAligned(shardSize)
1426
1427 for s := range dataShards {
1428 fillRandom(shards[s])
1429 }
1430 err = r.Encode(shards)
1431 if err != nil {
1432 b.Fatal(err)
1433 }
1434
1435 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1436 b.ResetTimer()
1437 b.ReportAllocs()
1438 for i := 0; i < b.N; i++ {
1439 _, err = r.Verify(shards)
1440 if err != nil {
1441 b.Fatal(err)
1442 }
1443 }
1444 }
1445
1446 // Benchmark 800 data slices with 200 parity slices
1447 func BenchmarkVerify800x200(b *testing.B) {
1448 for size := 64; size <= 1<<20; size *= 4 {
1449 b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
1450 benchmarkVerify(b, 800, 200, size)
1451 })
1452 }
1453 }
1454
1455 // Benchmark 10 data slices with 2 parity slices holding 10000 bytes each
1456 func BenchmarkVerify10x2x10000(b *testing.B) {
1457 benchmarkVerify(b, 10, 2, 10000)
1458 }
1459
1460 // Benchmark 50 data slices with 5 parity slices holding 100000 bytes each
1461 func BenchmarkVerify50x5x100000(b *testing.B) {
1462 benchmarkVerify(b, 50, 5, 100000)
1463 }
1464
1465 // Benchmark 10 data slices with 2 parity slices holding 1MB bytes each
1466 func BenchmarkVerify10x2x1M(b *testing.B) {
1467 benchmarkVerify(b, 10, 2, 1024*1024)
1468 }
1469
1470 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1471 func BenchmarkVerify5x2x1M(b *testing.B) {
1472 benchmarkVerify(b, 5, 2, 1024*1024)
1473 }
1474
1475 // Benchmark 10 data slices with 4 parity slices holding 1MB bytes each
1476 func BenchmarkVerify10x4x1M(b *testing.B) {
1477 benchmarkVerify(b, 10, 4, 1024*1024)
1478 }
1479
1480 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1481 func BenchmarkVerify50x20x1M(b *testing.B) {
1482 benchmarkVerify(b, 50, 20, 1024*1024)
1483 }
1484
1485 // Benchmark 10 data slices with 4 parity slices holding 16MB bytes each
1486 func BenchmarkVerify10x4x16M(b *testing.B) {
1487 benchmarkVerify(b, 10, 4, 16*1024*1024)
1488 }
1489
1490 func corruptRandom(shards [][]byte, dataShards, parityShards int) {
1491 shardsToCorrupt := rand.Intn(parityShards) + 1
1492 for range shardsToCorrupt {
1493 n := rand.Intn(dataShards + parityShards)
1494 shards[n] = shards[n][:0]
1495 }
1496 }
1497
1498 func benchmarkReconstruct(b *testing.B, dataShards, parityShards, shardSize int, opts ...Option) {
1499 o := []Option{WithAutoGoroutines(shardSize)}
1500 o = append(o, opts...)
1501 r, err := New(dataShards, parityShards, testOptions(o...)...)
1502 if err != nil {
1503 b.Fatal(err)
1504 }
1505 shards := r.(Extensions).AllocAligned(shardSize)
1506
1507 for s := range dataShards {
1508 fillRandom(shards[s])
1509 }
1510 err = r.Encode(shards)
1511 if err != nil {
1512 b.Fatal(err)
1513 }
1514
1515 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1516 b.ResetTimer()
1517 b.ReportAllocs()
1518 for i := 0; i < b.N; i++ {
1519 corruptRandom(shards, dataShards, parityShards)
1520
1521 err = r.Reconstruct(shards)
1522 if err != nil {
1523 b.Fatal(err)
1524 }
1525 }
1526 }
1527
1528 // Benchmark 10 data slices with 2 parity slices holding 10000 bytes each
1529 func BenchmarkReconstruct10x2x10000(b *testing.B) {
1530 benchmarkReconstruct(b, 10, 2, 10000)
1531 }
1532
1533 // Benchmark 800 data slices with 200 parity slices
1534 func BenchmarkReconstruct800x200(b *testing.B) {
1535 for size := 64; size <= 1<<20; size *= 4 {
1536 b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
1537 benchmarkReconstruct(b, 800, 200, size)
1538 })
1539 }
1540 }
1541
1542 // Benchmark 50 data slices with 5 parity slices holding 100000 bytes each
1543 func BenchmarkReconstruct50x5x50000(b *testing.B) {
1544 benchmarkReconstruct(b, 50, 5, 100000)
1545 }
1546
1547 // Benchmark 10 data slices with 2 parity slices holding 1MB bytes each
1548 func BenchmarkReconstruct10x2x1M(b *testing.B) {
1549 benchmarkReconstruct(b, 10, 2, 1024*1024)
1550 }
1551
1552 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1553 func BenchmarkReconstruct5x2x1M(b *testing.B) {
1554 benchmarkReconstruct(b, 5, 2, 1024*1024)
1555 }
1556
1557 // Benchmark 10 data slices with 4 parity slices holding 1MB bytes each
1558 func BenchmarkReconstruct10x4x1M(b *testing.B) {
1559 benchmarkReconstruct(b, 10, 4, 1024*1024)
1560 }
1561
1562 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1563 func BenchmarkReconstruct50x20x1M(b *testing.B) {
1564 benchmarkReconstruct(b, 50, 20, 1024*1024)
1565 }
1566
1567 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1568 func BenchmarkReconstructLeopard50x20x1M(b *testing.B) {
1569 benchmarkReconstruct(b, 50, 20, 1024*1024, WithLeopardGF(true), WithInversionCache(true))
1570 }
1571
1572 func BenchmarkReconstructDataLeopardGF16(b *testing.B) {
1573 b.Run("sparse-data-only", func(b *testing.B) {
1574 benchmarkReconstructDataSparse(b, 1024, 3072, 4096, WithLeopardGF16(true))
1575 })
1576 }
1577
1578 // Benchmark 10 data slices with 4 parity slices holding 16MB bytes each
1579 func BenchmarkReconstruct10x4x16M(b *testing.B) {
1580 benchmarkReconstruct(b, 10, 4, 16*1024*1024)
1581 }
1582
1583 func corruptRandomData(shards [][]byte, dataShards, parityShards int) {
1584 shardsToCorrupt := rand.Intn(parityShards) + 1
1585 for i := 1; i <= shardsToCorrupt; i++ {
1586 n := rand.Intn(dataShards)
1587 shards[n] = shards[n][:0]
1588 }
1589 }
1590
1591 func benchmarkReconstructData(b *testing.B, dataShards, parityShards, shardSize int) {
1592 r, err := New(dataShards, parityShards, testOptions(WithAutoGoroutines(shardSize))...)
1593 if err != nil {
1594 b.Fatal(err)
1595 }
1596 shards := r.(Extensions).AllocAligned(shardSize)
1597
1598 for s := range dataShards {
1599 fillRandom(shards[s])
1600 }
1601 err = r.Encode(shards)
1602 if err != nil {
1603 b.Fatal(err)
1604 }
1605
1606 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1607 b.ResetTimer()
1608 b.ReportAllocs()
1609 for i := 0; i < b.N; i++ {
1610 corruptRandomData(shards, dataShards, parityShards)
1611
1612 err = r.ReconstructData(shards)
1613 if err != nil {
1614 b.Fatal(err)
1615 }
1616 }
1617 }
1618
1619 func benchmarkReconstructDataSparse(b *testing.B, dataShards, parityShards, shardSize int, opts ...Option) {
1620 o := []Option{WithAutoGoroutines(shardSize)}
1621 o = append(o, opts...)
1622 r, err := New(dataShards, parityShards, testOptions(o...)...)
1623 if err != nil {
1624 b.Fatal(err)
1625 }
1626 shards := r.(Extensions).AllocAligned(shardSize)
1627
1628 for s := range dataShards {
1629 fillRandom(shards[s])
1630 }
1631 if err := r.Encode(shards); err != nil {
1632 b.Fatal(err)
1633 }
1634
1635 presentData := dataShards / 4
1636 presentParity := dataShards - presentData
1637 if presentParity > parityShards {
1638 b.Fatalf("need %d parity shards, have %d", presentParity, parityShards)
1639 }
1640 for s := dataShards + presentParity; s < dataShards+parityShards; s++ {
1641 shards[s] = nil
1642 }
1643
1644 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1645 b.ResetTimer()
1646 b.ReportAllocs()
1647 for i := 0; i < b.N; i++ {
1648 for s := presentData; s < dataShards; s++ {
1649 shards[s] = shards[s][:0]
1650 }
1651 if err := r.ReconstructData(shards); err != nil {
1652 b.Fatal(err)
1653 }
1654 }
1655 }
1656
1657 // Benchmark 10 data slices with 2 parity slices holding 10000 bytes each
1658 func BenchmarkReconstructData10x2x10000(b *testing.B) {
1659 benchmarkReconstructData(b, 10, 2, 10000)
1660 }
1661
1662 // Benchmark 800 data slices with 200 parity slices
1663 func BenchmarkReconstructData800x200(b *testing.B) {
1664 for size := 64; size <= 1<<20; size *= 4 {
1665 b.Run(fmt.Sprintf("%v", size), func(b *testing.B) {
1666 benchmarkReconstructData(b, 800, 200, size)
1667 })
1668 }
1669 }
1670
1671 // Benchmark 50 data slices with 5 parity slices holding 100000 bytes each
1672 func BenchmarkReconstructData50x5x50000(b *testing.B) {
1673 benchmarkReconstructData(b, 50, 5, 100000)
1674 }
1675
1676 // Benchmark 10 data slices with 2 parity slices holding 1MB bytes each
1677 func BenchmarkReconstructData10x2x1M(b *testing.B) {
1678 benchmarkReconstructData(b, 10, 2, 1024*1024)
1679 }
1680
1681 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1682 func BenchmarkReconstructData5x2x1M(b *testing.B) {
1683 benchmarkReconstructData(b, 5, 2, 1024*1024)
1684 }
1685
1686 // Benchmark 10 data slices with 4 parity slices holding 1MB bytes each
1687 func BenchmarkReconstructData10x4x1M(b *testing.B) {
1688 benchmarkReconstructData(b, 10, 4, 1024*1024)
1689 }
1690
1691 // Benchmark 5 data slices with 2 parity slices holding 1MB bytes each
1692 func BenchmarkReconstructData50x20x1M(b *testing.B) {
1693 benchmarkReconstructData(b, 50, 20, 1024*1024)
1694 }
1695
1696 // Benchmark 10 data slices with 4 parity slices holding 16MB bytes each
1697 func BenchmarkReconstructData10x4x16M(b *testing.B) {
1698 benchmarkReconstructData(b, 10, 4, 16*1024*1024)
1699 }
1700
1701 func benchmarkReconstructP(b *testing.B, dataShards, parityShards, shardSize int) {
1702 r, err := New(dataShards, parityShards, testOptions(WithMaxGoroutines(1))...)
1703 if err != nil {
1704 b.Fatal(err)
1705 }
1706
1707 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
1708 b.ResetTimer()
1709 b.ReportAllocs()
1710
1711 b.RunParallel(func(pb *testing.PB) {
1712 shards := r.(Extensions).AllocAligned(shardSize)
1713
1714 for s := range dataShards {
1715 fillRandom(shards[s])
1716 }
1717 err = r.Encode(shards)
1718 if err != nil {
1719 b.Fatal(err)
1720 }
1721 b.ResetTimer()
1722 for pb.Next() {
1723 corruptRandom(shards, dataShards, parityShards)
1724
1725 err = r.Reconstruct(shards)
1726 if err != nil {
1727 b.Fatal(err)
1728 }
1729 }
1730 })
1731 }
1732
1733 // Benchmark 10 data slices with 2 parity slices holding 10000 bytes each
1734 func BenchmarkReconstructP10x2x10000(b *testing.B) {
1735 benchmarkReconstructP(b, 10, 2, 10000)
1736 }
1737
1738 // Benchmark 10 data slices with 5 parity slices holding 20000 bytes each
1739 func BenchmarkReconstructP10x5x20000(b *testing.B) {
1740 benchmarkReconstructP(b, 10, 5, 20000)
1741 }
1742
1743 func TestEncoderReconstruct(t *testing.T) {
1744 parallelIfNotShort(t)
1745 testEncoderReconstruct(t)
1746 for _, o := range testOpts() {
1747 testEncoderReconstruct(t, o...)
1748 }
1749 }
1750
1751 func testEncoderReconstruct(t *testing.T, o ...Option) {
1752 // Create some sample data
1753 var data = make([]byte, 250<<10)
1754 fillRandom(data)
1755
1756 // Create 5 data slices of 50000 elements each
1757 enc, err := New(7, 6, testOptions(o...)...)
1758 if err != nil {
1759 t.Fatal(err)
1760 }
1761 shards, err := enc.Split(data)
1762 if err != nil {
1763 t.Fatal(err)
1764 }
1765 err = enc.Encode(shards)
1766 if err != nil {
1767 t.Fatal(err)
1768 }
1769
1770 // Check that it verifies
1771 ok, err := enc.Verify(shards)
1772 if !ok || err != nil {
1773 t.Fatal("not ok:", ok, "err:", err)
1774 }
1775
1776 // Delete a shard
1777 shards[0] = nil
1778
1779 // Should reconstruct
1780 err = enc.Reconstruct(shards)
1781 if err != nil {
1782 t.Fatal(err)
1783 }
1784
1785 // Check that it verifies
1786 ok, err = enc.Verify(shards)
1787 if !ok || err != nil {
1788 t.Fatal("not ok:", ok, "err:", err)
1789 }
1790
1791 // Recover original bytes
1792 buf := new(bytes.Buffer)
1793 err = enc.Join(buf, shards, len(data))
1794 if err != nil {
1795 t.Fatal(err)
1796 }
1797 if !bytes.Equal(buf.Bytes(), data) {
1798 t.Fatal("recovered bytes do not match")
1799 }
1800
1801 // Corrupt a shard
1802 shards[0] = nil
1803 shards[1][0], shards[1][500] = 75, 75
1804
1805 // Should reconstruct (but with corrupted data)
1806 err = enc.Reconstruct(shards)
1807 if err != nil {
1808 t.Fatal(err)
1809 }
1810
1811 // Check that it verifies
1812 ok, err = enc.Verify(shards)
1813 if ok || err != nil {
1814 t.Fatal("error or ok:", ok, "err:", err)
1815 }
1816
1817 // Recovered data should not match original
1818 buf.Reset()
1819 err = enc.Join(buf, shards, len(data))
1820 if err != nil {
1821 t.Fatal(err)
1822 }
1823 if bytes.Equal(buf.Bytes(), data) {
1824 t.Fatal("corrupted data matches original")
1825 }
1826 }
1827
1828 func TestSplitJoin(t *testing.T) {
1829 opts := [][]Option{
1830 testOptions(),
1831 append(testOptions(), WithLeopardGF(true)),
1832 append(testOptions(), WithLeopardGF16(true)),
1833 }
1834 for i, opts := range opts {
1835 t.Run("opt-"+strconv.Itoa(i), func(t *testing.T) {
1836 for _, dp := range [][2]int{{1, 0}, {5, 0}, {5, 1}, {12, 4}, {2, 15}, {17, 1}} {
1837 enc, _ := New(dp[0], dp[1], opts...)
1838 ext := enc.(Extensions)
1839
1840 _, err := enc.Split([]byte{})
1841 if err != ErrShortData {
1842 t.Errorf("expected %v, got %v", ErrShortData, err)
1843 }
1844
1845 buf := new(bytes.Buffer)
1846 err = enc.Join(buf, [][]byte{}, 0)
1847 if err != ErrTooFewShards {
1848 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
1849 }
1850 for _, size := range []int{ext.DataShards(), 1337, 2699} {
1851 for _, extra := range []int{0, 1, ext.ShardSizeMultiple(), ext.ShardSizeMultiple() * ext.DataShards(), ext.ShardSizeMultiple()*ext.ParityShards() + 1, 255} {
1852 buf.Reset()
1853 t.Run(fmt.Sprintf("d-%d-p-%d-sz-%d-cap%d", ext.DataShards(), ext.ParityShards(), size, extra), func(t *testing.T) {
1854 var data = make([]byte, size, size+extra)
1855 var ref = make([]byte, size, size)
1856 fillRandom(data)
1857 copy(ref, data)
1858
1859 shards, err := enc.Split(data)
1860 if err != nil {
1861 t.Fatal(err)
1862 }
1863 err = enc.Encode(shards)
1864 if err != nil {
1865 t.Fatal(err)
1866 }
1867 _, err = enc.Verify(shards)
1868 if err != nil {
1869 t.Fatal(err)
1870 }
1871 for i := range shards[:ext.ParityShards()] {
1872 // delete data shards up to parity
1873 shards[i] = nil
1874 }
1875 err = enc.Reconstruct(shards)
1876 if err != nil {
1877 t.Fatal(err)
1878 }
1879
1880 // Rejoin....
1881 err = enc.Join(buf, shards, size)
1882 if err != nil {
1883 t.Fatal(err)
1884 }
1885 if !bytes.Equal(buf.Bytes(), ref) {
1886 t.Log("")
1887 t.Fatal("recovered data does match original")
1888 }
1889
1890 err = enc.Join(buf, shards, len(data)+ext.DataShards()*ext.ShardSizeMultiple())
1891 if err != ErrShortData {
1892 t.Errorf("expected %v, got %v", ErrShortData, err)
1893 }
1894
1895 shards[0] = nil
1896 err = enc.Join(buf, shards, len(data))
1897 if err != ErrReconstructRequired {
1898 t.Errorf("expected %v, got %v", ErrReconstructRequired, err)
1899 }
1900 })
1901 }
1902 }
1903 }
1904 })
1905 }
1906 }
1907
1908 func TestCodeSomeShards(t *testing.T) {
1909 var data = make([]byte, 250000)
1910 fillRandom(data)
1911 enc, _ := New(5, 3, testOptions()...)
1912 r := enc.(*reedSolomon) // need to access private methods
1913 shards, _ := enc.Split(data)
1914
1915 old := runtime.GOMAXPROCS(1)
1916 r.codeSomeShards(r.parity, shards[:r.dataShards], shards[r.dataShards:r.dataShards+r.parityShards], len(shards[0]), true)
1917
1918 // hopefully more than 1 CPU
1919 runtime.GOMAXPROCS(runtime.NumCPU())
1920 r.codeSomeShards(r.parity, shards[:r.dataShards], shards[r.dataShards:r.dataShards+r.parityShards], len(shards[0]), true)
1921
1922 // reset MAXPROCS, otherwise testing complains
1923 runtime.GOMAXPROCS(old)
1924 }
1925
1926 func TestStandardMatrices(t *testing.T) {
1927 if testing.Short() || runtime.GOMAXPROCS(0) < 4 {
1928 // Runtime ~15s.
1929 t.Skip("Skipping slow matrix check")
1930 }
1931 for i := 1; i < 256; i++ {
1932 i := i
1933 t.Run(fmt.Sprintf("x%d", i), func(t *testing.T) {
1934 parallelIfNotShort(t)
1935 // i == n.o. datashards
1936 var shards = make([][]byte, 255)
1937 for p := range shards {
1938 v := byte(i)
1939 shards[p] = []byte{v}
1940 }
1941 rng := rand.New(rand.NewSource(0))
1942 for j := 1; j < 256; j++ {
1943 // j == n.o. parity shards
1944 if i+j > 255 {
1945 continue
1946 }
1947 sh := shards[:i+j]
1948 r, err := New(i, j, testOptions(WithFastOneParityMatrix())...)
1949 if err != nil {
1950 // We are not supposed to write to t from goroutines.
1951 t.Fatal("creating matrix size", i, j, ":", err)
1952 }
1953 err = r.Encode(sh)
1954 if err != nil {
1955 t.Fatal("encoding", i, j, ":", err)
1956 }
1957 for k := 0; k < j; k++ {
1958 // Remove random shard.
1959 r := int(rng.Int63n(int64(i + j)))
1960 sh[r] = sh[r][:0]
1961 }
1962 err = r.Reconstruct(sh)
1963 if err != nil {
1964 t.Fatal("reconstructing", i, j, ":", err)
1965 }
1966 ok, err := r.Verify(sh)
1967 if err != nil {
1968 t.Fatal("verifying", i, j, ":", err)
1969 }
1970 if !ok {
1971 t.Fatal(i, j, ok)
1972 }
1973 for k := range sh {
1974 if k == i {
1975 // Only check data shards
1976 break
1977 }
1978 if sh[k][0] != byte(i) {
1979 t.Fatal("does not match", i, j, k, sh[0], sh[k])
1980 }
1981 }
1982 }
1983 })
1984 }
1985 }
1986
1987 func TestCauchyMatrices(t *testing.T) {
1988 if testing.Short() || runtime.GOMAXPROCS(0) < 4 {
1989 // Runtime ~15s.
1990 t.Skip("Skipping slow matrix check")
1991 }
1992 for i := 1; i < 256; i++ {
1993 i := i
1994 t.Run(fmt.Sprintf("x%d", i), func(t *testing.T) {
1995 parallelIfNotShort(t)
1996 var shards = make([][]byte, 255)
1997 for p := range shards {
1998 v := byte(i)
1999 shards[p] = []byte{v}
2000 }
2001 rng := rand.New(rand.NewSource(0))
2002 for j := 1; j < 256; j++ {
2003 // j == n.o. parity shards
2004 if i+j > 255 {
2005 continue
2006 }
2007 sh := shards[:i+j]
2008 r, err := New(i, j, testOptions(WithCauchyMatrix(), WithFastOneParityMatrix())...)
2009 if err != nil {
2010 // We are not supposed to write to t from goroutines.
2011 t.Fatal("creating matrix size", i, j, ":", err)
2012 }
2013 err = r.Encode(sh)
2014 if err != nil {
2015 t.Fatal("encoding", i, j, ":", err)
2016 }
2017 for k := 0; k < j; k++ {
2018 // Remove random shard.
2019 r := int(rng.Int63n(int64(i + j)))
2020 sh[r] = sh[r][:0]
2021 }
2022 err = r.Reconstruct(sh)
2023 if err != nil {
2024 t.Fatal("reconstructing", i, j, ":", err)
2025 }
2026 ok, err := r.Verify(sh)
2027 if err != nil {
2028 t.Fatal("verifying", i, j, ":", err)
2029 }
2030 if !ok {
2031 t.Fatal(i, j, ok)
2032 }
2033 for k := range sh {
2034 if k == i {
2035 // Only check data shards
2036 break
2037 }
2038 if sh[k][0] != byte(i) {
2039 t.Fatal("does not match", i, j, k, sh[0], sh[k])
2040 }
2041 }
2042 }
2043 })
2044 }
2045 }
2046
2047 func TestPar1Matrices(t *testing.T) {
2048 if testing.Short() || runtime.GOMAXPROCS(0) < 4 {
2049 // Runtime ~15s.
2050 t.Skip("Skipping slow matrix check")
2051 }
2052 for i := 1; i < 256; i++ {
2053 i := i
2054 t.Run(fmt.Sprintf("x%d", i), func(t *testing.T) {
2055 parallelIfNotShort(t)
2056 var shards = make([][]byte, 255)
2057 for p := range shards {
2058 v := byte(i)
2059 shards[p] = []byte{v}
2060 }
2061 rng := rand.New(rand.NewSource(0))
2062 for j := 1; j < 256; j++ {
2063 // j == n.o. parity shards
2064 if i+j > 255 {
2065 continue
2066 }
2067 sh := shards[:i+j]
2068 r, err := New(i, j, testOptions(WithPAR1Matrix())...)
2069 if err != nil {
2070 // We are not supposed to write to t from goroutines.
2071 t.Fatal("creating matrix size", i, j, ":", err)
2072 }
2073 err = r.Encode(sh)
2074 if err != nil {
2075 t.Fatal("encoding", i, j, ":", err)
2076 }
2077 for k := 0; k < j; k++ {
2078 // Remove random shard.
2079 r := int(rng.Int63n(int64(i + j)))
2080 sh[r] = sh[r][:0]
2081 }
2082 err = r.Reconstruct(sh)
2083 if err != nil {
2084 if err == errSingular {
2085 t.Logf("Singular: %d (data), %d (parity)", i, j)
2086 for p := range sh {
2087 if len(sh[p]) == 0 {
2088 shards[p] = []byte{byte(i)}
2089 }
2090 }
2091 continue
2092 }
2093 t.Fatal("reconstructing", i, j, ":", err)
2094 }
2095 ok, err := r.Verify(sh)
2096 if err != nil {
2097 t.Fatal("verifying", i, j, ":", err)
2098 }
2099 if !ok {
2100 t.Fatal(i, j, ok)
2101 }
2102 for k := range sh {
2103 if k == i {
2104 // Only check data shards
2105 break
2106 }
2107 if sh[k][0] != byte(i) {
2108 t.Fatal("does not match", i, j, k, sh[0], sh[k])
2109 }
2110 }
2111 }
2112 })
2113 }
2114 }
2115
2116 func TestNew(t *testing.T) {
2117 tests := []struct {
2118 data, parity int
2119 err error
2120 }{
2121 {127, 127, nil},
2122 {128, 128, nil},
2123 {255, 1, nil},
2124 {255, 0, nil},
2125 {1, 0, nil},
2126 {65536, 65536, ErrMaxShardNum},
2127
2128 {0, 1, ErrInvShardNum},
2129 {1, -1, ErrInvShardNum},
2130 {65636, 1, ErrMaxShardNum},
2131
2132 // overflow causes r.Shards to be negative
2133 {256, int(^uint(0) >> 1), errInvalidRowSize},
2134 }
2135 for _, test := range tests {
2136 _, err := New(test.data, test.parity, testOptions()...)
2137 if err != test.err {
2138 t.Errorf("New(%v, %v): expected %v, got %v", test.data, test.parity, test.err, err)
2139 }
2140 }
2141 }
2142
2143 func TestSplitZero(t *testing.T) {
2144 data := make([]byte, 512)
2145 for _, opts := range testOpts() {
2146 ecctest, err := New(1, 0, opts...)
2147 if err != nil {
2148 t.Fatal(err)
2149 }
2150 _, err = ecctest.Split(data)
2151 if err != nil {
2152 t.Fatal(err)
2153 }
2154 }
2155 }
2156
2157 // Benchmark 10 data shards and 4 parity shards and 160MB data.
2158 func BenchmarkSplit10x4x160M(b *testing.B) {
2159 benchmarkSplit(b, 10, 4, 160*1024*1024)
2160 }
2161
2162 // Benchmark 5 data shards and 2 parity shards with 5MB data.
2163 func BenchmarkSplit5x2x5M(b *testing.B) {
2164 benchmarkSplit(b, 5, 2, 5*1024*1024)
2165 }
2166
2167 // Benchmark 1 data shards and 2 parity shards with 1MB data.
2168 func BenchmarkSplit10x2x1M(b *testing.B) {
2169 benchmarkSplit(b, 10, 2, 1024*1024)
2170 }
2171
2172 // Benchmark 10 data shards and 4 parity shards with 10MB data.
2173 func BenchmarkSplit10x4x10M(b *testing.B) {
2174 benchmarkSplit(b, 10, 4, 10*1024*1024)
2175 }
2176
2177 // Benchmark 50 data shards and 20 parity shards with 50MB data.
2178 func BenchmarkSplit50x20x50M(b *testing.B) {
2179 benchmarkSplit(b, 50, 20, 50*1024*1024)
2180 }
2181
2182 // Benchmark 17 data shards and 3 parity shards with 272MB data.
2183 func BenchmarkSplit17x3x272M(b *testing.B) {
2184 benchmarkSplit(b, 17, 3, 272*1024*1024)
2185 }
2186
2187 func benchmarkSplit(b *testing.B, shards, parity, dataSize int) {
2188 r, err := New(shards, parity, testOptions(WithAutoGoroutines(dataSize))...)
2189 if err != nil {
2190 b.Fatal(err)
2191 }
2192
2193 data := make([]byte, dataSize)
2194 b.ReportAllocs()
2195 b.ResetTimer()
2196 for i := 0; i < b.N; i++ {
2197 _, err = r.Split(data)
2198 if err != nil {
2199 b.Fatal(err)
2200 }
2201 }
2202 }
2203
2204 func benchmarkParallel(b *testing.B, dataShards, parityShards, shardSize int) {
2205 // Run max 1 goroutine per operation.
2206 r, err := New(dataShards, parityShards, testOptions(WithMaxGoroutines(1))...)
2207 if err != nil {
2208 b.Fatal(err)
2209 }
2210 c := runtime.GOMAXPROCS(0)
2211
2212 // Note that concurrency also affects total data size and will make caches less effective.
2213 if testing.Verbose() {
2214 b.Log("Total data:", (c*dataShards*shardSize)>>20, "MiB", "parity:", (c*parityShards*shardSize)>>20, "MiB")
2215 }
2216 // Create independent shards
2217 shardsCh := make(chan [][]byte, c)
2218 for range c {
2219 shards := r.(Extensions).AllocAligned(shardSize)
2220
2221 for s := range dataShards {
2222 fillRandom(shards[s])
2223 }
2224 shardsCh <- shards
2225 }
2226
2227 b.SetBytes(int64(shardSize * (dataShards + parityShards)))
2228 b.SetParallelism(c)
2229 b.ReportAllocs()
2230 b.ResetTimer()
2231
2232 b.RunParallel(func(pb *testing.PB) {
2233 for pb.Next() {
2234 shards := <-shardsCh
2235 err = r.Encode(shards)
2236 if err != nil {
2237 b.Fatal(err)
2238 }
2239 shardsCh <- shards
2240 }
2241 })
2242 }
2243
2244 func BenchmarkParallel_8x8x64K(b *testing.B) { benchmarkParallel(b, 8, 8, 64<<10) }
2245 func BenchmarkParallel_8x8x05M(b *testing.B) { benchmarkParallel(b, 8, 8, 512<<10) }
2246 func BenchmarkParallel_20x10x05M(b *testing.B) { benchmarkParallel(b, 20, 10, 512<<10) }
2247 func BenchmarkParallel_8x8x1M(b *testing.B) { benchmarkParallel(b, 8, 8, 1<<20) }
2248 func BenchmarkParallel_8x8x8M(b *testing.B) { benchmarkParallel(b, 8, 8, 8<<20) }
2249 func BenchmarkParallel_8x8x32M(b *testing.B) { benchmarkParallel(b, 8, 8, 32<<20) }
2250
2251 func BenchmarkParallel_8x3x1M(b *testing.B) { benchmarkParallel(b, 8, 3, 1<<20) }
2252 func BenchmarkParallel_8x4x1M(b *testing.B) { benchmarkParallel(b, 8, 4, 1<<20) }
2253 func BenchmarkParallel_8x5x1M(b *testing.B) { benchmarkParallel(b, 8, 5, 1<<20) }
2254
2255 func TestReentrant(t *testing.T) {
2256 for optN, o := range testOpts() {
2257 t.Run(fmt.Sprintf("opt-%d", optN), func(t *testing.T) {
2258 parallelIfNotShort(t)
2259 for _, size := range testSizes() {
2260 data, parity := size[0], size[1]
2261 rng := rand.New(rand.NewSource(0xabadc0cac01a))
2262 t.Run(fmt.Sprintf("size-%dx%d", data, parity), func(t *testing.T) {
2263 perShard := 1024 + 1
2264 if testing.Short() {
2265 perShard = 256 + 1
2266 }
2267 r, err := New(data, parity, testOptions(o...)...)
2268 if err != nil {
2269 t.Fatal(err)
2270 }
2271 x := r.(Extensions)
2272 if want, got := data, x.DataShards(); want != got {
2273 t.Errorf("DataShards returned %d, want %d", got, want)
2274 }
2275 if want, got := parity, x.ParityShards(); want != got {
2276 t.Errorf("ParityShards returned %d, want %d", got, want)
2277 }
2278 if want, got := parity+data, x.TotalShards(); want != got {
2279 t.Errorf("TotalShards returned %d, want %d", got, want)
2280 }
2281 mul := x.ShardSizeMultiple()
2282 if mul <= 0 {
2283 t.Fatalf("Got unexpected ShardSizeMultiple: %d", mul)
2284 }
2285 perShard = ((perShard + mul - 1) / mul) * mul
2286 runs := 10
2287 if testing.Short() {
2288 runs = 2
2289 }
2290 for i := 0; i < runs; i++ {
2291 shards := AllocAligned(data+parity, perShard)
2292 for s := range data {
2293 rng.Read(shards[s])
2294 }
2295 err = r.Encode(shards)
2296 if err != nil {
2297 t.Fatal(err)
2298 }
2299 ok, err := r.Verify(shards)
2300 if err != nil {
2301 t.Fatal(err)
2302 }
2303 if !ok {
2304 t.Fatal("Verification failed")
2305 }
2306
2307 if parity == 0 {
2308 // Check that Reconstruct and ReconstructData do nothing
2309 err = r.ReconstructData(shards)
2310 if err != nil {
2311 t.Fatal(err)
2312 }
2313 err = r.Reconstruct(shards)
2314 if err != nil {
2315 t.Fatal(err)
2316 }
2317
2318 // Skip integrity checks
2319 continue
2320 }
2321
2322 // Delete one in data
2323 idx := rng.Intn(data)
2324 want := shards[idx]
2325 shards[idx] = nil
2326
2327 err = r.ReconstructData(shards)
2328 if err != nil {
2329 t.Fatal(err)
2330 }
2331 if !bytes.Equal(shards[idx], want) {
2332 t.Fatal("did not ReconstructData correctly")
2333 }
2334
2335 // Delete one randomly
2336 idx = rng.Intn(data + parity)
2337 want = shards[idx]
2338 shards[idx] = nil
2339 err = r.Reconstruct(shards)
2340 if err != nil {
2341 t.Fatal(err)
2342 }
2343 if !bytes.Equal(shards[idx], want) {
2344 t.Fatal("did not Reconstruct correctly")
2345 }
2346
2347 err = r.Encode(make([][]byte, 1))
2348 if err != ErrTooFewShards {
2349 t.Errorf("expected %v, got %v", ErrTooFewShards, err)
2350 }
2351
2352 // Make one too short.
2353 shards[idx] = shards[idx][:perShard-1]
2354 err = r.Encode(shards)
2355 if err != ErrShardSize {
2356 t.Errorf("expected %v, got %v", ErrShardSize, err)
2357 }
2358 }
2359 })
2360 }
2361 })
2362 }
2363 }
2364
2365 func TestRSReconstructSome(t *testing.T) {
2366 const (
2367 dataShards = 3
2368 parityShards = 2
2369 sectorSize = 1 << 20 // 1 MiB
2370 )
2371 stripedSplit := func(data []byte, dataShards [][]byte) {
2372 const leafSize = 64
2373 buf := bytes.NewBuffer(data)
2374 for off := 0; buf.Len() > 0; off += leafSize {
2375 for _, shard := range dataShards {
2376 copy(shard[off:], buf.Next(leafSize))
2377 }
2378 }
2379 }
2380
2381 // prepare random data
2382 buf := make([]byte, sectorSize*dataShards)
2383 rand.Read(buf)
2384
2385 // prepare shards
2386 shards := make([][]byte, dataShards+parityShards)
2387 for i := range shards {
2388 shards[i] = make([]byte, sectorSize)
2389 }
2390
2391 for i, o := range testOpts() {
2392 toFill := []int{0, 1, 2, 3, 4}
2393 t.Run(fmt.Sprintf("options %d", i), func(t *testing.T) {
2394 // Shuffle the indices to fill
2395 rand.Shuffle(len(toFill), func(i, j int) {
2396 toFill[i], toFill[j] = toFill[j], toFill[i]
2397 })
2398 stripedSplit(buf, shards[:dataShards])
2399 // encode shards
2400 enc, err := New(dataShards, parityShards, o...)
2401 if err != nil {
2402 t.Fatal(err)
2403 }
2404 err = enc.Encode(shards)
2405 if err != nil {
2406 t.Fatal(err)
2407 }
2408
2409 for _, required := range [][]bool{
2410 {false, false, false, false, true},
2411 {false, false, false, true, true},
2412 {false, false, true, false, true},
2413 {false, false, true, true, true},
2414 {false, true, false, false, true},
2415 {false, true, false, true, true},
2416 {false, true, true, false, true},
2417 {false, true, true, true, true},
2418 {true, false, false, false, true},
2419 {true, false, false, true, true},
2420 {true, false, true, false, true},
2421 {true, false, true, true, true},
2422 {true, true, false, false, true},
2423 {true, true, false, true, true},
2424 {true, true, true, false, true},
2425 {true, true, true, true, true},
2426
2427 {false, false, false, false, false},
2428 {false, false, false, true, false},
2429 {false, false, true, false, false},
2430 {false, false, true, true, false},
2431 {false, true, false, false, false},
2432 {false, true, false, true, false},
2433 {false, true, true, false, false},
2434 {false, true, true, true, false},
2435 {true, false, false, false, false},
2436 {true, false, false, true, false},
2437 {true, false, true, false, false},
2438 {true, false, true, true, false},
2439 {true, true, false, false, false},
2440 {true, true, false, true, false},
2441 {true, true, true, false, false},
2442 {true, true, true, true, false},
2443 } {
2444 downloaded := make([][]byte, len(shards))
2445 downloaded[toFill[0]] = append([]byte{}, shards[toFill[0]]...)
2446 downloaded[toFill[1]] = append([]byte{}, shards[toFill[1]]...)
2447 downloaded[toFill[2]] = append([]byte{}, shards[toFill[2]]...)
2448 err = enc.ReconstructSome(downloaded, required)
2449 if err != nil {
2450 t.Fatal(err)
2451 }
2452 for i, shard := range downloaded {
2453 if shard == nil && required[i] {
2454 t.Errorf("shard idx %d should not be nil", i)
2455 }
2456 if !required[i] && shard == nil {
2457 // Ignore, if it wasn't reconstructed
2458 continue
2459 }
2460 if len(shard) != sectorSize {
2461 t.Errorf("shard idx %d has wrong size: %d, want %d", i, len(shard), sectorSize)
2462 }
2463 if !bytes.Equal(shard, shards[i]) {
2464 t.Errorf("shard idx %d does not match original", i)
2465 }
2466 }
2467 }
2468 })
2469 }
2470 }