Repository navigation
Expand file tree
/
Copy pathregression_test.go
More file actions
873 lines (823 loc) · 26.7 KB
/
Copy pathregression_test.go
File metadata and controls
873 lines (823 loc) · 26.7 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
package extsort
// Regression tests for correctness bugs in the sort pipeline. Several of them inject
// failing temp files through package internals, so they live in package extsort.
import (
"bufio"
"bytes"
"cmp"
"context"
"encoding/binary"
"errors"
"io"
"math/rand"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"testing/iotest"
"time"
"github.com/lanrat/extsort/tempfile"
)
func itoaBytes(i int) ([]byte, error) { return []byte(strconv.Itoa(i)), nil }
func atoiBytes(b []byte) (int, error) { return strconv.Atoi(string(b)) }
// descendingInts sends n..1 on an unbuffered channel, then closes it.
func descendingInts(n int) chan int {
ch := make(chan int)
go func() {
defer close(ch)
for i := n; i > 0; i-- {
ch <- i
}
}()
return ch
}
// runSort calls Sort, drains the output, then reads the error channel.
// It fails the test if that does not finish in time.
func runSort[E any](t *testing.T, ctx context.Context, s *GenericSorter[E]) ([]E, error) {
t.Helper()
type result struct {
got []E
err error
}
done := make(chan result, 1)
go func() {
s.Sort(ctx)
var got []E
for v := range s.mergeChunkChan {
got = append(got, v)
}
done <- result{got, <-s.mergeErrChan}
}()
select {
case r := <-done:
return r.got, r.err
case <-time.After(10 * time.Second):
t.Fatal("sort did not finish within 10s")
return nil, nil
}
}
// drainWithTimeout reads out until it closes, then reads errc.
func drainWithTimeout[E any](t *testing.T, out <-chan E, errc <-chan error) ([]E, error) {
t.Helper()
var got []E
timeout := time.After(10 * time.Second)
for {
select {
case v, ok := <-out:
if !ok {
return got, <-errc
}
got = append(got, v)
case <-timeout:
t.Fatal("sort did not finish within 10s")
}
}
}
// trackedTemp hands out in-memory temp files and counts how many the sorter
// leaves open. readErr and closeErr inject failures.
type trackedTemp struct {
readErr map[int]error // section index -> error returned when reading it
readErrAfter map[int]int64 // section index -> bytes it reads before its readErr, 0 if unset
closeErr error // returned by the reader's Close
mu sync.Mutex
created int
closed int
sections int // Size of the last reader returned by Save
}
func (tt *trackedTemp) newWriter() (tempfile.TempWriter, error) {
tt.mu.Lock()
defer tt.mu.Unlock()
tt.created++
return &trackedWriter{TempWriter: tempfile.Mock(0), tt: tt}, nil
}
func (tt *trackedTemp) markClosed() {
tt.mu.Lock()
defer tt.mu.Unlock()
tt.closed++
}
func (tt *trackedTemp) createdCount() int {
tt.mu.Lock()
defer tt.mu.Unlock()
return tt.created
}
// open returns how many temp files were created but not closed exactly once.
func (tt *trackedTemp) open() int {
tt.mu.Lock()
defer tt.mu.Unlock()
return tt.created - tt.closed
}
type trackedWriter struct {
tempfile.TempWriter
tt *trackedTemp
}
func (w *trackedWriter) Close() error {
w.tt.markClosed()
return w.TempWriter.Close()
}
func (w *trackedWriter) Save() (tempfile.TempReader, error) {
r, err := w.TempWriter.Save()
if err != nil {
return nil, err
}
w.tt.mu.Lock()
w.tt.sections = r.Size()
w.tt.mu.Unlock()
return &trackedReader{TempReader: r, tt: w.tt}, nil
}
type trackedReader struct {
tempfile.TempReader
tt *trackedTemp
}
func (r *trackedReader) Read(i int) *bufio.Reader {
if err, ok := r.tt.readErr[i]; ok {
valid := io.LimitReader(r.TempReader.Read(i), r.tt.readErrAfter[i])
return bufio.NewReader(io.MultiReader(valid, iotest.ErrReader(err)))
}
return r.TempReader.Read(i)
}
func (r *trackedReader) Close() error {
r.tt.markClosed()
if err := r.TempReader.Close(); err != nil {
return err
}
return r.tt.closeErr
}
// newTrackedSorter returns an int sorter whose temp files are tracked by tt.
func newTrackedSorter(input <-chan int, toBytes ToBytesGeneric[int], compare CompareGeneric[int], config *Config, tt *trackedTemp) *GenericSorter[int] {
s := newSorter(input, atoiBytes, toBytes, compare, config)
s.newTempWriter = tt.newWriter
return s
}
// A failing save stage used to leave the sort workers blocked on saveChunkChan,
// so Sort never returned once the input spanned more than 2+2*NumWorkers chunks.
func TestSaveErrorDoesNotDeadlock(t *testing.T) {
errEncode := errors.New("encode failed")
failing := func(int) ([]byte, error) { return nil, errEncode }
for _, n := range []int{6, 7, 1000} {
t.Run(strconv.Itoa(n)+" chunks", func(t *testing.T) {
tt := &trackedTemp{}
s := newTrackedSorter(descendingInts(n), failing, cmp.Compare[int], &Config{ChunkSize: 1, NumWorkers: 2, ChanBuffSize: 16}, tt)
_, err := runSort(t, context.Background(), s)
var serErr *SerializationError
if !errors.As(err, &serErr) || !errors.Is(err, errEncode) {
t.Fatalf("got error %v, want a SerializationError wrapping %q", err, errEncode)
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
})
}
}
// An error in the sort stage used to make Sort return without closing saveChunkChan,
// leaking the save goroutine and its temp file.
func TestSortErrorStopsSaveStage(t *testing.T) {
tt := &trackedTemp{}
created := make(chan struct{})
var once sync.Once
// Chunks are [6 5] [4 3] [2 1]. Sorting [2 1] fails, but only after the
// first two chunks reached the save stage and it created the temp file.
compare := func(a, b int) int {
if a == 1 || b == 1 {
select {
case <-created:
case <-time.After(5 * time.Second):
}
panic("comparison failed")
}
return cmp.Compare(a, b)
}
s := newTrackedSorter(descendingInts(6), itoaBytes, compare, &Config{ChunkSize: 2, NumWorkers: 2}, tt)
s.newTempWriter = func() (tempfile.TempWriter, error) {
defer once.Do(func() { close(created) })
return tt.newWriter()
}
_, err := runSort(t, context.Background(), s)
var cmpErr *ComparisonError
if !errors.As(err, &cmpErr) {
t.Fatalf("got error %v, want a ComparisonError", err)
}
if tt.createdCount() != 1 {
t.Fatalf("temp file created %d times, want 1", tt.createdCount())
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
buf := make([]byte, 1<<20)
for deadline := time.Now().Add(2 * time.Second); ; {
stacks := string(buf[:runtime.Stack(buf, true)])
if !strings.Contains(stacks, "saveChunksOptimized") {
break
}
if time.Now().After(deadline) {
t.Fatal("save goroutine still running after Sort returned")
}
time.Sleep(10 * time.Millisecond)
}
}
// A read error on a chunk's first record used to be treated as an empty chunk,
// silently dropping that chunk's records.
func TestMergeReportsChunkReadErrors(t *testing.T) {
errDisk := errors.New("disk read error")
for _, tc := range []struct {
name string
workers int
section int
}{
// 15 records in chunks of 5 make three chunks. NumWorkers 3 merges them
// single-threaded; NumWorkers 2 merges them in parallel.
{"single-threaded first chunk", 3, 0},
{"single-threaded second chunk", 3, 1},
{"parallel first chunk", 2, 0},
{"parallel second chunk", 2, 1},
} {
t.Run(tc.name, func(t *testing.T) {
tt := &trackedTemp{readErr: map[int]error{tc.section: errDisk}}
s := newTrackedSorter(descendingInts(15), itoaBytes, cmp.Compare[int], &Config{ChunkSize: 5, NumWorkers: tc.workers}, tt)
got, err := runSort(t, context.Background(), s)
if !errors.Is(err, errDisk) {
t.Fatalf("got %d records and error %v, want error %q", len(got), err, errDisk)
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
})
}
}
// getNext used to treat a length header without its payload as a clean end of chunk.
func TestGetNextTruncatedRecord(t *testing.T) {
for _, tc := range []struct {
name string
data []byte
wantOK bool
want error
}{
{"end of chunk", nil, false, nil},
{"complete record", []byte{1, '7'}, true, nil},
{"header without payload", []byte{5}, false, io.ErrUnexpectedEOF},
{"partial payload", []byte{5, '1', '2'}, false, io.ErrUnexpectedEOF},
{"partial header", []byte{0x80}, false, io.ErrUnexpectedEOF},
} {
t.Run(tc.name, func(t *testing.T) {
m := &mergeFile[int]{fromBytes: atoiBytes, reader: bufio.NewReader(bytes.NewReader(tc.data))}
_, ok, err := m.getNext()
if ok != tc.wantOK || !errors.Is(err, tc.want) {
t.Fatalf("getNext() = ok %v, err %v; want ok %v, err %v", ok, err, tc.wantOK, tc.want)
}
if ok && m.nextRec != 7 {
t.Errorf("getNext() read %d, want 7", m.nextRec)
}
})
}
}
type legacyInt int
func (v legacyInt) ToBytes() []byte { return []byte(strconv.Itoa(int(v))) }
// The legacy FromBytes wrapper recovered panics into a local variable that was
// never returned, so a panicking FromBytes produced (nil, nil) and nil records.
func TestLegacyFromBytesPanicIsReported(t *testing.T) {
fromBytes := makeSortTypeFromBytes(func([]byte) SortType { panic("corrupt record") })
var deserErr *DeserializationError
if v, err := fromBytes([]byte("x")); v != nil || !errors.As(err, &deserErr) {
t.Fatalf("got (%v, %v), want (nil, DeserializationError)", v, err)
}
in := make(chan SortType, 10)
for i := 10; i > 0; i-- {
in <- legacyInt(i)
}
close(in)
panicOn5 := func(b []byte) SortType {
n, _ := strconv.Atoi(string(b))
if n == 5 {
panic("corrupt record")
}
return legacyInt(n)
}
less := func(a, b SortType) bool { // tolerates nil so the old behavior shows up as output
ai, aok := a.(legacyInt)
bi, bok := b.(legacyInt)
if !aok || !bok {
return !aok && bok
}
return ai < bi
}
sorter, out, errc := NewMock(in, panicOn5, less, &Config{ChunkSize: 2}, 0)
sorter.Sort(context.Background())
got, err := drainWithTimeout(t, out, errc)
if !errors.As(err, &deserErr) {
t.Errorf("got error %v, want a DeserializationError", err)
}
if slices.Contains(got, nil) {
t.Errorf("output contains nil records: %v", got)
}
}
// Panics in user callbacks during the save and merge stages used to crash the
// process. Each must be reported on the error channel instead.
func TestCallbackPanicsBecomeErrors(t *testing.T) {
panicCompare := func(a, b int) int { panic("compare failed") }
panicFromBytes := func([]byte) (int, error) { panic("decode failed") }
panicToBytes := func(int) ([]byte, error) { panic("encode failed") }
var cmpErr *ComparisonError
var deserErr *DeserializationError
var serErr *SerializationError
for _, tc := range []struct {
name string
n int
workers int
fromBytes FromBytesGeneric[int]
toBytes ToBytesGeneric[int]
compare CompareGeneric[int]
target any
}{
// With ChunkSize 1, sorting a chunk never calls compare: the first call is in the merge.
{"compare in single-threaded merge", 3, 4, atoiBytes, itoaBytes, panicCompare, &cmpErr},
{"compare in parallel merge", 20, 2, atoiBytes, itoaBytes, panicCompare, &cmpErr},
{"fromBytes in merge", 5, 2, panicFromBytes, itoaBytes, cmp.Compare[int], &deserErr},
{"toBytes in save", 50, 2, atoiBytes, panicToBytes, cmp.Compare[int], &serErr},
} {
t.Run(tc.name, func(t *testing.T) {
sorter, out, errc := MockGeneric(descendingInts(tc.n), tc.fromBytes, tc.toBytes, tc.compare, &Config{ChunkSize: 1, NumWorkers: tc.workers}, 0)
sorter.Sort(context.Background())
if _, err := drainWithTimeout(t, out, errc); !errors.As(err, tc.target) {
t.Fatalf("got error %v, want %T", err, tc.target)
}
})
}
t.Run("compare in final merge", func(t *testing.T) {
s := newSorter(nil, atoiBytes, itoaBytes, panicCompare, nil)
a, b := newMergeStream[int](), newMergeStream[int]()
a.batches <- []int{1}
b.batches <- []int{2}
close(a.batches)
close(b.batches)
if err := s.finalMergeSimple(context.Background(), []mergeStream[int]{a, b}); !errors.As(err, &cmpErr) {
t.Fatalf("got error %v, want a ComparisonError", err)
}
})
}
// A failing tempReader.Close used to panic with "send on closed channel", because
// the deferred Close ran after the deferred close(mergeErrChan).
func TestTempFileCloseErrorIsReported(t *testing.T) {
errClose := errors.New("close failed")
for _, workers := range []int{3, 2} { // three chunks: single-threaded and parallel merge
t.Run("NumWorkers "+strconv.Itoa(workers), func(t *testing.T) {
tt := &trackedTemp{closeErr: errClose}
s := newTrackedSorter(descendingInts(15), itoaBytes, cmp.Compare[int], &Config{ChunkSize: 5, NumWorkers: workers}, tt)
got, err := runSort(t, context.Background(), s)
if !errors.Is(err, errClose) {
t.Fatalf("got error %v, want %q", err, errClose)
}
if len(got) != 15 || !slices.IsSorted(got) {
t.Errorf("got %v, want 1..15 in order", got)
}
})
}
}
// The temp file used to be created in the constructor and never closed on the empty,
// single-chunk and error paths. It is now only created for multi-chunk sorts, and
// released on every path.
func TestTempFileLifecycle(t *testing.T) {
errEncode := errors.New("encode failed")
failing := func(int) ([]byte, error) { return nil, errEncode }
for _, tc := range []struct {
name string
n int
toBytes ToBytesGeneric[int]
wantCreated int
wantErr error
}{
{"empty input", 0, itoaBytes, 0, nil},
{"single chunk", 10, itoaBytes, 0, nil},
{"multiple chunks", 100, itoaBytes, 1, nil},
{"save error", 100, failing, 1, errEncode},
} {
t.Run(tc.name, func(t *testing.T) {
tt := &trackedTemp{}
s := newTrackedSorter(descendingInts(tc.n), tc.toBytes, cmp.Compare[int], &Config{ChunkSize: 10}, tt)
got, err := runSort(t, context.Background(), s)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("got error %v, want %v", err, tc.wantErr)
}
if tc.wantErr == nil && (len(got) != tc.n || !slices.IsSorted(got)) {
t.Errorf("got %d records (sorted: %v), want %d sorted", len(got), slices.IsSorted(got), tc.n)
}
if tt.createdCount() != tc.wantCreated {
t.Errorf("temp file created %d times, want %d", tt.createdCount(), tc.wantCreated)
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
})
}
t.Run("cancelled while saving", func(t *testing.T) {
tt := &trackedTemp{}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
in := make(chan int)
go func() { // endless input, stopped by the cancellation
defer close(in)
for i := 0; ; i++ {
select {
case in <- i:
case <-ctx.Done():
return
}
}
}()
s := newTrackedSorter(in, itoaBytes, cmp.Compare[int], &Config{ChunkSize: 10}, tt)
var once sync.Once
s.newTempWriter = func() (tempfile.TempWriter, error) {
defer once.Do(cancel)
return tt.newWriter()
}
if _, err := runSort(t, ctx, s); !errors.Is(err, context.Canceled) {
t.Fatalf("got error %v, want %v", err, context.Canceled)
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
})
t.Run("cancelled while merging", func(t *testing.T) {
tt := &trackedTemp{}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := newTrackedSorter(descendingInts(100), itoaBytes, cmp.Compare[int], &Config{ChunkSize: 10}, tt)
s.Sort(ctx)
for i := 0; i < 5; i++ {
<-s.mergeChunkChan
}
cancel()
if _, err := drainWithTimeout(t, s.mergeChunkChan, s.mergeErrChan); !errors.Is(err, context.Canceled) {
t.Fatalf("got error %v, want %v", err, context.Canceled)
}
if open := tt.open(); open != 0 {
t.Errorf("%d temp file(s) left open", open)
}
})
}
// Temp files on disk must be closed, and on Windows removed, on success and on error.
func TestTempFilesReleasedOnDisk(t *testing.T) {
errEncode := errors.New("encode failed")
failOn50 := func(i int) ([]byte, error) {
if i == 50 {
return nil, errEncode
}
return itoaBytes(i)
}
for _, tc := range []struct {
name string
toBytes ToBytesGeneric[int]
wantErr error
}{
{"success", itoaBytes, nil},
{"save error", failOn50, errEncode},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
s, _, _ := Generic(descendingInts(100), atoiBytes, tc.toBytes, cmp.Compare[int], &Config{ChunkSize: 10, TempFilesDir: dir})
if _, err := runSort(t, context.Background(), s); !errors.Is(err, tc.wantErr) {
t.Fatalf("got error %v, want %v", err, tc.wantErr)
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
t.Errorf("temp file left on disk: %s", e.Name())
}
if n := openFilesUnder(dir); n > 0 {
t.Errorf("%d temp file(s) still open", n)
}
})
}
}
// openFilesUnder counts this process's open files under dir. It needs /proc/self/fd
// (Linux) and returns 0 where that is unavailable.
func openFilesUnder(dir string) int {
fds, err := os.ReadDir("/proc/self/fd")
if err != nil {
return 0
}
if resolved, err := filepath.EvalSymlinks(dir); err == nil {
dir = resolved
}
n := 0
for _, fd := range fds {
target, err := os.Readlink(filepath.Join("/proc/self/fd", fd.Name()))
if err == nil && strings.HasPrefix(target, dir+string(filepath.Separator)) {
n++
}
}
return n
}
// When the temp file could not be created, the constructors used to return a nil
// sorter, so the README pattern `go sorter.Sort(ctx)` crashed instead of reporting
// the error on the error channel.
func TestTempFileCreationErrorIsReportedOnErrChan(t *testing.T) {
notADir := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(notADir, nil, 0o600); err != nil {
t.Fatal(err)
}
config := func() *Config { return &Config{ChunkSize: 2, TempFilesDir: notADir} }
strs := func(n int) chan string {
ch := make(chan string)
go func() {
defer close(ch)
for i := n; i > 0; i-- {
ch <- strconv.Itoa(i)
}
}()
return ch
}
legacy := func(n int) chan SortType {
ch := make(chan SortType)
go func() {
defer close(ch)
for i := n; i > 0; i-- {
ch <- legacyInt(i)
}
}()
return ch
}
legacyLess := func(a, b SortType) bool { return a.(legacyInt) < b.(legacyInt) }
legacyFromBytes := func(b []byte) SortType {
n, _ := strconv.Atoi(string(b))
return legacyInt(n)
}
wantErr := func(t *testing.T, err error) {
t.Helper()
if err == nil {
t.Fatal("got nil error, want the temp file creation error")
}
}
t.Run("Generic", func(t *testing.T) {
sorter, out, errc := Generic(descendingInts(10), atoiBytes, itoaBytes, cmp.Compare[int], config())
if sorter == nil {
t.Fatal("constructor returned a nil sorter")
}
go sorter.Sort(context.Background())
_, err := drainWithTimeout(t, out, errc)
wantErr(t, err)
})
t.Run("Ordered", func(t *testing.T) {
sorter, out, errc := Ordered(descendingInts(10), config())
if sorter == nil {
t.Fatal("constructor returned a nil sorter")
}
go sorter.Sort(context.Background())
_, err := drainWithTimeout(t, out, errc)
wantErr(t, err)
})
t.Run("Strings", func(t *testing.T) {
sorter, out, errc := Strings(strs(10), config())
if sorter == nil {
t.Fatal("constructor returned a nil sorter")
}
go sorter.Sort(context.Background())
_, err := drainWithTimeout(t, out, errc)
wantErr(t, err)
})
t.Run("New", func(t *testing.T) {
sorter, out, errc := New(legacy(10), legacyFromBytes, legacyLess, config())
if sorter == nil {
t.Fatal("constructor returned a nil sorter")
}
go sorter.Sort(context.Background())
_, err := drainWithTimeout(t, out, errc)
wantErr(t, err)
})
t.Run("single chunk needs no temp file", func(t *testing.T) {
sorter, out, errc := Ordered(descendingInts(2), config())
go sorter.Sort(context.Background())
got, err := drainWithTimeout(t, out, errc)
if err != nil || !slices.Equal(got, []int{1, 2}) {
t.Fatalf("got %v, %v; want [1 2], nil", got, err)
}
})
}
// buildChunks used to keep looping up to ChunkSize times on the closed input,
// because a plain break inside the select only left the select.
func TestBuildChunksStopsWhenInputCloses(t *testing.T) {
in := make(chan struct{}, 1)
in <- struct{}{}
close(in)
// Chunks of struct{} need no memory, so a huge ChunkSize only costs loop iterations
s := newSorter(in,
func([]byte) (struct{}, error) { return struct{}{}, nil },
func(struct{}) ([]byte, error) { return nil, nil },
func(a, b struct{}) int { return 0 },
&Config{ChunkSize: 1 << 30, ChanBuffSize: 1})
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // stops a spinning buildChunks once the test is over
s.sortCtx = ctx
done := make(chan error, 1)
go func() { done <- s.buildChunks() }()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("buildChunks still running 1s after the input closed")
}
if c := <-s.chunkChan; c == nil || len(c.data) != 1 {
t.Fatalf("got chunk %v, want one chunk with the record", c)
}
if _, ok := <-s.chunkChan; ok {
t.Error("buildChunks sent more than one chunk")
}
}
// BenchmarkSortTenRecords measures a small sort with the default config. The loop
// on the closed input used to add about 2x ChunkSize (1M) iterations to every sort.
func BenchmarkSortTenRecords(b *testing.B) {
for b.Loop() {
in := make(chan int, 10)
for i := 10; i > 0; i-- {
in <- i
}
close(in)
s, out, errc := Generic(in, atoiBytes, itoaBytes, cmp.Compare[int], nil)
s.Sort(context.Background())
for range out {
}
if err := <-errc; err != nil {
b.Fatal(err)
}
}
}
// mergeConfig used to write defaults into the caller's Config, which raced when one
// Config was shared by several sorters (run with -race) and surprised callers.
func TestConfigIsNotModified(t *testing.T) {
shared := &Config{} // every zero field used to be overwritten
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
s, out, errc := MockGeneric(descendingInts(3), atoiBytes, itoaBytes, cmp.Compare[int], shared, 0)
s.Sort(context.Background())
if _, err := drainWithTimeout(t, out, errc); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
if *shared != (Config{}) {
t.Errorf("caller's Config was modified: %+v", *shared)
}
}
// Zero buffer sizes mean unbuffered channels; nil and negative values mean the defaults.
func TestConfigBufferSizes(t *testing.T) {
for _, tc := range []struct {
name string
config *Config
wantChunk, wantOutput int
}{
{"nil config", nil, 1, 1000},
{"zero values", &Config{}, 0, 0},
{"negative values", &Config{ChanBuffSize: -1, SortedChanBuffSize: -1}, 1, 1000},
{"explicit values", &Config{ChanBuffSize: 3, SortedChanBuffSize: 7}, 3, 7},
} {
t.Run(tc.name, func(t *testing.T) {
s := newSorter[int](nil, atoiBytes, itoaBytes, cmp.Compare[int], tc.config)
if got := cap(s.chunkChan); got != tc.wantChunk {
t.Errorf("chunk channel buffer = %d, want %d", got, tc.wantChunk)
}
if got := cap(s.mergeChunkChan); got != tc.wantOutput {
t.Errorf("output channel buffer = %d, want %d", got, tc.wantOutput)
}
})
}
}
// The parallel merge (v1.1.0) calls FromBytes from several goroutines at once, which
// broke legacy FromBytes functions written for v1.0 that are not safe for concurrent
// use. New and NewMock now serialize the calls.
func TestLegacyFromBytesIsNotCalledConcurrently(t *testing.T) {
const n = 200
in := make(chan SortType, n)
for i := n; i > 0; i-- {
in <- legacyInt(i)
}
close(in)
var inFlight, maxInFlight atomic.Int32
fromBytes := func(b []byte) SortType {
now := inFlight.Add(1)
defer inFlight.Add(-1)
for {
seen := maxInFlight.Load()
if now <= seen || maxInFlight.CompareAndSwap(seen, now) {
break
}
}
time.Sleep(20 * time.Microsecond) // widen the window for overlapping calls
v, _ := strconv.Atoi(string(b))
return legacyInt(v)
}
less := func(a, b SortType) bool { return a.(legacyInt) < b.(legacyInt) }
// One record per chunk and 4 workers: the parallel merge reads 4 chunks at once
sorter, out, errc := NewMock(in, fromBytes, less, &Config{ChunkSize: 1, NumWorkers: 4}, 0)
sorter.Sort(context.Background())
got, err := drainWithTimeout(t, out, errc)
if err != nil {
t.Fatal(err)
}
if len(got) != n {
t.Fatalf("got %d records, want %d", len(got), n)
}
if m := maxInFlight.Load(); m != 1 {
t.Errorf("FromBytes ran %d calls at once, want 1", m)
}
}
// Save used to append an empty section after the last chunk, so the merge saw one more
// chunk than was written and chose the parallel merge for exactly NumWorkers chunks.
func TestTempFileHasOneSectionPerChunk(t *testing.T) {
for _, chunks := range []int{2, 3, 10} {
t.Run(strconv.Itoa(chunks)+" chunks", func(t *testing.T) {
tt := &trackedTemp{}
s := newTrackedSorter(descendingInts(chunks*5), itoaBytes, cmp.Compare[int], &Config{ChunkSize: 5}, tt)
got, err := runSort(t, context.Background(), s)
if err != nil || len(got) != chunks*5 {
t.Fatalf("got %d records, error %v", len(got), err)
}
tt.mu.Lock()
defer tt.mu.Unlock()
if tt.sections != chunks {
t.Errorf("temp file has %d sections, want %d", tt.sections, chunks)
}
})
}
}
// BenchmarkSortManyChunks sorts 200k records in 2,000 chunks. Save used to allocate a
// 64 KiB read buffer for every chunk up front (125 MiB here); they are now sized to the chunk.
func BenchmarkSortManyChunks(b *testing.B) {
const n = 200_000
dir := b.TempDir()
for b.Loop() {
in := make(chan int, 1000)
go func() {
defer close(in)
for i := n; i > 0; i-- {
in <- i
}
}()
s, out, errc := Generic(in, atoiBytes, itoaBytes, cmp.Compare[int], &Config{ChunkSize: 100, TempFilesDir: dir})
s.Sort(context.Background())
for range out {
}
if err := <-errc; err != nil {
b.Fatal(err)
}
}
}
// benchmarkInts sorts 1M random ints in chunks of 100k with the sorter that newSorter returns.
func benchmarkInts(b *testing.B, newSorter func(in chan int, config *Config) (Sorter, <-chan int, <-chan error)) {
r := rand.New(rand.NewSource(1))
data := make([]int, 1_000_000)
for i := range data {
data[i] = r.Int()
}
config := DefaultConfig()
config.ChunkSize = 100_000
config.TempFilesDir = b.TempDir()
b.ResetTimer()
for b.Loop() {
in := make(chan int, 1000)
go func() {
defer close(in)
for _, v := range data {
in <- v
}
}()
s, out, errc := newSorter(in, config)
s.Sort(context.Background())
for range out {
}
if err := <-errc; err != nil {
b.Fatal(err)
}
}
}
// BenchmarkOrderedInts sorts 1M ints with Ordered. Ordered used to gob-encode every record
// with a new encoder and decoder, which made it much slower than Generic.
func BenchmarkOrderedInts(b *testing.B) {
benchmarkInts(b, func(in chan int, config *Config) (Sorter, <-chan int, <-chan error) {
return Ordered(in, config)
})
}
// BenchmarkGenericVarintInts is BenchmarkOrderedInts using Generic with a varint codec.
func BenchmarkGenericVarintInts(b *testing.B) {
toBytes := func(v int) ([]byte, error) { return binary.AppendVarint(nil, int64(v)), nil }
fromBytes := func(d []byte) (int, error) {
v, n := binary.Varint(d)
if n <= 0 {
return 0, errors.New("bad varint")
}
return int(v), nil
}
benchmarkInts(b, func(in chan int, config *Config) (Sorter, <-chan int, <-chan error) {
return Generic(in, fromBytes, toBytes, cmp.Compare[int], config)
})
}