-
Notifications
You must be signed in to change notification settings - Fork 465
/
db_test.go
1970 lines (1760 loc) · 53.6 KB
/
db_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"bytes"
"context"
"fmt"
"io"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/cache"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/stretchr/testify/require"
"golang.org/x/exp/rand"
)
// try repeatedly calls f, sleeping between calls with exponential back-off,
// until f returns a nil error or the total sleep time is greater than or equal
// to maxTotalSleep. It always calls f at least once.
func try(initialSleep, maxTotalSleep time.Duration, f func() error) error {
totalSleep := time.Duration(0)
for d := initialSleep; ; d *= 2 {
time.Sleep(d)
totalSleep += d
if err := f(); err == nil || totalSleep >= maxTotalSleep {
return err
}
}
}
func TestTry(t *testing.T) {
c := make(chan struct{})
go func() {
time.Sleep(1 * time.Millisecond)
close(c)
}()
attemptsMu := sync.Mutex{}
attempts := 0
err := try(100*time.Microsecond, 20*time.Second, func() error {
attemptsMu.Lock()
attempts++
attemptsMu.Unlock()
select {
default:
return errors.New("timed out")
case <-c:
return nil
}
})
require.NoError(t, err)
attemptsMu.Lock()
a := attempts
attemptsMu.Unlock()
if a == 0 {
t.Fatalf("attempts: got 0, want > 0")
}
}
func TestBasicReads(t *testing.T) {
t.Skip("TODO")
testCases := []struct {
dirname string
wantMap map[string]string
}{
{
"db-stage-1",
map[string]string{
"aaa": "",
"bar": "",
"baz": "",
"foo": "",
"quux": "",
"zzz": "",
},
},
{
"db-stage-2",
map[string]string{
"aaa": "",
"bar": "",
"baz": "three",
"foo": "four",
"quux": "",
"zzz": "",
},
},
{
"db-stage-3",
map[string]string{
"aaa": "",
"bar": "",
"baz": "three",
"foo": "four",
"quux": "",
"zzz": "",
},
},
{
"db-stage-4",
map[string]string{
"aaa": "",
"bar": "",
"baz": "",
"foo": "five",
"quux": "six",
"zzz": "",
},
},
}
for _, tc := range testCases {
t.Run(tc.dirname, func(t *testing.T) {
fs := vfs.NewMem()
_, err := vfs.Clone(vfs.Default, fs, filepath.Join("testdata", tc.dirname), tc.dirname)
if err != nil {
t.Fatalf("%s: cloneFileSystem failed: %v", tc.dirname, err)
}
d, err := Open(tc.dirname, testingRandomized(t, &Options{
FS: fs,
}))
if err != nil {
t.Fatalf("%s: Open failed: %v", tc.dirname, err)
}
for key, want := range tc.wantMap {
got, closer, err := d.Get([]byte(key))
if err != nil && err != ErrNotFound {
t.Fatalf("%s: Get(%q) failed: %v", tc.dirname, key, err)
}
if string(got) != string(want) {
t.Fatalf("%s: Get(%q): got %q, want %q", tc.dirname, key, got, want)
}
if closer != nil {
closer.Close()
}
}
err = d.Close()
if err != nil {
t.Fatalf("%s: Close failed: %v", tc.dirname, err)
}
})
}
}
func TestBasicWrites(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
names := []string{
"Alatar",
"Gandalf",
"Pallando",
"Radagast",
"Saruman",
"Joe",
}
wantMap := map[string]string{}
inBatch, batch, pending := false, &Batch{}, [][]string(nil)
set0 := func(k, v string) error {
return d.Set([]byte(k), []byte(v), nil)
}
del0 := func(k string) error {
return d.Delete([]byte(k), nil)
}
set1 := func(k, v string) error {
batch.Set([]byte(k), []byte(v), nil)
return nil
}
del1 := func(k string) error {
batch.Delete([]byte(k), nil)
return nil
}
set, del := set0, del0
testCases := []string{
"set Gandalf Grey",
"set Saruman White",
"set Radagast Brown",
"delete Saruman",
"set Gandalf White",
"batch",
" set Alatar AliceBlue",
"apply",
"delete Pallando",
"set Alatar AntiqueWhite",
"set Pallando PapayaWhip",
"batch",
"apply",
"set Pallando PaleVioletRed",
"batch",
" delete Alatar",
" set Gandalf GhostWhite",
" set Saruman Seashell",
" delete Saruman",
" set Saruman SeaGreen",
" set Radagast RosyBrown",
" delete Pallando",
"apply",
"delete Radagast",
"delete Radagast",
"delete Radagast",
"set Gandalf Goldenrod",
"set Pallando PeachPuff",
"batch",
" delete Joe",
" delete Saruman",
" delete Radagast",
" delete Pallando",
" delete Gandalf",
" delete Alatar",
"apply",
"set Joe Plumber",
}
for i, tc := range testCases {
s := strings.Split(strings.TrimSpace(tc), " ")
switch s[0] {
case "set":
if err := set(s[1], s[2]); err != nil {
t.Fatalf("#%d %s: %v", i, tc, err)
}
if inBatch {
pending = append(pending, s)
} else {
wantMap[s[1]] = s[2]
}
case "delete":
if err := del(s[1]); err != nil {
t.Fatalf("#%d %s: %v", i, tc, err)
}
if inBatch {
pending = append(pending, s)
} else {
delete(wantMap, s[1])
}
case "batch":
inBatch, batch, set, del = true, &Batch{}, set1, del1
case "apply":
if err := d.Apply(batch, nil); err != nil {
t.Fatalf("#%d %s: %v", i, tc, err)
}
for _, p := range pending {
switch p[0] {
case "set":
wantMap[p[1]] = p[2]
case "delete":
delete(wantMap, p[1])
}
}
inBatch, pending, set, del = false, nil, set0, del0
default:
t.Fatalf("#%d %s: bad test case: %q", i, tc, s)
}
fail := false
for _, name := range names {
g, closer, err := d.Get([]byte(name))
if err != nil && err != ErrNotFound {
t.Errorf("#%d %s: Get(%q): %v", i, tc, name, err)
fail = true
}
got, gOK := string(g), err == nil
want, wOK := wantMap[name]
if got != want || gOK != wOK {
t.Errorf("#%d %s: Get(%q): got %q, %t, want %q, %t",
i, tc, name, got, gOK, want, wOK)
fail = true
}
if closer != nil {
closer.Close()
}
}
if fail {
return
}
}
require.NoError(t, d.Close())
}
func TestRandomWrites(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
MemTableSize: 8 * 1024,
}))
require.NoError(t, err)
keys := [64][]byte{}
wants := [64]int{}
for k := range keys {
keys[k] = []byte(strconv.Itoa(k))
wants[k] = -1
}
xxx := bytes.Repeat([]byte("x"), 512)
rng := rand.New(rand.NewSource(123))
const N = 1000
for i := 0; i < N; i++ {
k := rng.Intn(len(keys))
if rng.Intn(20) != 0 {
wants[k] = rng.Intn(len(xxx) + 1)
if err := d.Set(keys[k], xxx[:wants[k]], nil); err != nil {
t.Fatalf("i=%d: Set: %v", i, err)
}
} else {
wants[k] = -1
if err := d.Delete(keys[k], nil); err != nil {
t.Fatalf("i=%d: Delete: %v", i, err)
}
}
if i != N-1 || rng.Intn(50) != 0 {
continue
}
for k := range keys {
got := -1
if v, closer, err := d.Get(keys[k]); err != nil {
if err != ErrNotFound {
t.Fatalf("Get: %v", err)
}
} else {
got = len(v)
closer.Close()
}
if got != wants[k] {
t.Errorf("i=%d, k=%d: got %d, want %d", i, k, got, wants[k])
}
}
}
require.NoError(t, d.Close())
}
func TestLargeBatch(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
MemTableSize: 1400,
MemTableStopWritesThreshold: 100,
}))
require.NoError(t, err)
verifyLSM := func(expected string) func() error {
return func() error {
d.mu.Lock()
s := d.mu.versions.currentVersion().String()
d.mu.Unlock()
if expected != s {
if testing.Verbose() {
fmt.Println(strings.TrimSpace(s))
}
return errors.Errorf("expected %s, but found %s", expected, s)
}
return nil
}
}
logNum := func() base.DiskFileNum {
d.mu.Lock()
defer d.mu.Unlock()
return d.mu.log.queue[len(d.mu.log.queue)-1].fileNum
}
fileSize := func(fileNum base.DiskFileNum) int64 {
info, err := d.opts.FS.Stat(base.MakeFilepath(d.opts.FS, "", fileTypeLog, fileNum))
require.NoError(t, err)
return info.Size()
}
memTableCreationSeqNum := func() uint64 {
d.mu.Lock()
defer d.mu.Unlock()
return d.mu.mem.mutable.logSeqNum
}
startLogNum := logNum()
startLogStartSize := fileSize(startLogNum)
startSeqNum := d.mu.versions.logSeqNum.Load()
// Write a key with a value larger than the memtable size.
require.NoError(t, d.Set([]byte("a"), bytes.Repeat([]byte("a"), 512), nil))
// Verify that the large batch was written to the WAL that existed before it
// was committed. We verify that WAL rotation occurred, where the large batch
// was written to, and that the new WAL is empty.
endLogNum := logNum()
if startLogNum == endLogNum {
t.Fatal("expected WAL rotation")
}
startLogEndSize := fileSize(startLogNum)
if startLogEndSize == startLogStartSize {
t.Fatalf("expected large batch to be written to %s.log, but file size unchanged at %d",
startLogNum, startLogEndSize)
}
endLogSize := fileSize(endLogNum)
if endLogSize != 0 {
t.Fatalf("expected %s.log to be empty, but found %d", endLogNum, endLogSize)
}
if creationSeqNum := memTableCreationSeqNum(); creationSeqNum <= startSeqNum {
t.Fatalf("expected memTable.logSeqNum=%d > largeBatch.seqNum=%d", creationSeqNum, startSeqNum)
}
// Verify this results in one L0 table being created.
require.NoError(t, try(100*time.Microsecond, 20*time.Second,
verifyLSM("0.0:\n 000005:[a#10,SET-a#10,SET]\n")))
require.NoError(t, d.Set([]byte("b"), bytes.Repeat([]byte("b"), 512), nil))
// Verify this results in a second L0 table being created.
require.NoError(t, try(100*time.Microsecond, 20*time.Second,
verifyLSM("0.0:\n 000005:[a#10,SET-a#10,SET]\n 000007:[b#11,SET-b#11,SET]\n")))
// Allocate a bunch of batches to exhaust the batchPool. None of these
// batches should have a non-zero count.
for i := 0; i < 10; i++ {
b := d.NewBatch()
require.EqualValues(t, 0, b.Count())
}
require.NoError(t, d.Close())
}
func TestGetNoCache(t *testing.T) {
cache := NewCache(0)
defer cache.Unref()
d, err := Open("", testingRandomized(t, &Options{
Cache: cache,
FS: vfs.NewMem(),
}))
require.NoError(t, err)
require.NoError(t, d.Set([]byte("a"), []byte("aa"), nil))
require.NoError(t, d.Flush())
verifyGet(t, d, []byte("a"), []byte("aa"))
require.NoError(t, d.Close())
}
func TestGetMerge(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
key := []byte("a")
verify := func(expected string) {
val, closer, err := d.Get(key)
require.NoError(t, err)
if expected != string(val) {
t.Fatalf("expected %s, but got %s", expected, val)
}
closer.Close()
}
const val = "1"
for i := 1; i <= 3; i++ {
require.NoError(t, d.Merge(key, []byte(val), nil))
expected := strings.Repeat(val, i)
verify(expected)
require.NoError(t, d.Flush())
verify(expected)
}
require.NoError(t, d.Close())
}
func TestMergeOrderSameAfterFlush(t *testing.T) {
// Ensure compaction iterator (used by flush) and user iterator process merge
// operands in the same order
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
key := []byte("a")
verify := func(expected string) {
iter, _ := d.NewIter(nil)
if !iter.SeekGE([]byte("a")) {
t.Fatal("expected one value, but got empty iterator")
}
if expected != string(iter.Value()) {
t.Fatalf("expected %s, but got %s", expected, string(iter.Value()))
}
if !iter.SeekLT([]byte("b")) {
t.Fatal("expected one value, but got empty iterator")
}
if expected != string(iter.Value()) {
t.Fatalf("expected %s, but got %s", expected, string(iter.Value()))
}
require.NoError(t, iter.Close())
}
require.NoError(t, d.Merge(key, []byte("0"), nil))
require.NoError(t, d.Merge(key, []byte("1"), nil))
verify("01")
require.NoError(t, d.Flush())
verify("01")
require.NoError(t, d.Close())
}
type closableMerger struct {
lastBuf []byte
closed bool
}
func (m *closableMerger) MergeNewer(value []byte) error {
m.lastBuf = append(m.lastBuf[:0], value...)
return nil
}
func (m *closableMerger) MergeOlder(value []byte) error {
m.lastBuf = append(m.lastBuf[:0], value...)
return nil
}
func (m *closableMerger) Finish(includesBase bool) ([]byte, io.Closer, error) {
return m.lastBuf, m, nil
}
func (m *closableMerger) Close() error {
m.closed = true
return nil
}
func TestMergerClosing(t *testing.T) {
m := &closableMerger{}
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
Merger: &Merger{
Merge: func(key, value []byte) (base.ValueMerger, error) {
return m, m.MergeNewer(value)
},
},
}))
require.NoError(t, err)
defer func() {
require.NoError(t, d.Close())
}()
err = d.Merge([]byte("a"), []byte("b"), nil)
require.NoError(t, err)
require.False(t, m.closed)
val, closer, err := d.Get([]byte("a"))
require.NoError(t, err)
require.Equal(t, []byte("b"), val)
require.NotNil(t, closer)
require.False(t, m.closed)
_ = closer.Close()
require.True(t, m.closed)
}
func TestLogData(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
defer func() {
require.NoError(t, d.Close())
}()
require.NoError(t, d.LogData([]byte("foo"), Sync))
require.NoError(t, d.LogData([]byte("bar"), Sync))
// TODO(itsbilal): Confirm that we wrote some bytes to the WAL.
// For now, LogData proceeding ahead without a panic is good enough.
}
func TestSingleDeleteGet(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
defer func() {
require.NoError(t, d.Close())
}()
key := []byte("key")
val := []byte("val")
require.NoError(t, d.Set(key, val, nil))
verifyGet(t, d, key, val)
key2 := []byte("key2")
val2 := []byte("val2")
require.NoError(t, d.Set(key2, val2, nil))
verifyGet(t, d, key2, val2)
require.NoError(t, d.SingleDelete(key2, nil))
verifyGetNotFound(t, d, key2)
}
func TestSingleDeleteFlush(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
defer func() {
require.NoError(t, d.Close())
}()
key := []byte("key")
valFirst := []byte("first")
valSecond := []byte("second")
key2 := []byte("key2")
val2 := []byte("val2")
require.NoError(t, d.Set(key, valFirst, nil))
require.NoError(t, d.Set(key2, val2, nil))
require.NoError(t, d.Flush())
require.NoError(t, d.SingleDelete(key, nil))
require.NoError(t, d.Set(key, valSecond, nil))
require.NoError(t, d.Delete(key2, nil))
require.NoError(t, d.Set(key2, val2, nil))
require.NoError(t, d.Flush())
require.NoError(t, d.SingleDelete(key, nil))
require.NoError(t, d.Delete(key2, nil))
require.NoError(t, d.Flush())
verifyGetNotFound(t, d, key)
verifyGetNotFound(t, d, key2)
}
func TestUnremovableSingleDelete(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
L0CompactionThreshold: 8,
}))
require.NoError(t, err)
defer func() {
require.NoError(t, d.Close())
}()
key := []byte("key")
valFirst := []byte("valFirst")
valSecond := []byte("valSecond")
require.NoError(t, d.Set(key, valFirst, nil))
ss := d.NewSnapshot()
defer ss.Close()
require.NoError(t, d.SingleDelete(key, nil))
require.NoError(t, d.Set(key, valSecond, nil))
require.NoError(t, d.Flush())
verifyGet(t, ss, key, valFirst)
verifyGet(t, d, key, valSecond)
require.NoError(t, d.SingleDelete(key, nil))
verifyGet(t, ss, key, valFirst)
verifyGetNotFound(t, d, key)
require.NoError(t, d.Flush())
verifyGet(t, ss, key, valFirst)
verifyGetNotFound(t, d, key)
}
func TestIterLeak(t *testing.T) {
for _, leak := range []bool{true, false} {
t.Run(fmt.Sprintf("leak=%t", leak), func(t *testing.T) {
for _, flush := range []bool{true, false} {
t.Run(fmt.Sprintf("flush=%t", flush), func(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
require.NoError(t, d.Set([]byte("a"), []byte("a"), nil))
if flush {
require.NoError(t, d.Flush())
}
iter, _ := d.NewIter(nil)
iter.First()
if !leak {
require.NoError(t, iter.Close())
require.NoError(t, d.Close())
} else {
defer iter.Close()
if err := d.Close(); err == nil {
t.Fatalf("expected failure, but found success")
} else if !strings.HasPrefix(err.Error(), "leaked iterators:") {
t.Fatalf("expected leaked iterators, but found %+v", err)
} else {
t.Log(err.Error())
}
}
})
}
})
}
}
// Make sure that we detect an iter leak when only one DB closes
// while the second db still holds a reference to the TableCache.
func TestIterLeakSharedCache(t *testing.T) {
for _, leak := range []bool{true, false} {
t.Run(fmt.Sprintf("leak=%t", leak), func(t *testing.T) {
for _, flush := range []bool{true, false} {
t.Run(fmt.Sprintf("flush=%t", flush), func(t *testing.T) {
d1, err := Open("", &Options{
FS: vfs.NewMem(),
})
require.NoError(t, err)
d2, err := Open("", &Options{
FS: vfs.NewMem(),
})
require.NoError(t, err)
require.NoError(t, d1.Set([]byte("a"), []byte("a"), nil))
if flush {
require.NoError(t, d1.Flush())
}
require.NoError(t, d2.Set([]byte("a"), []byte("a"), nil))
if flush {
require.NoError(t, d2.Flush())
}
// Check if leak detection works with only one db closing.
{
iter1, _ := d1.NewIter(nil)
iter1.First()
if !leak {
require.NoError(t, iter1.Close())
require.NoError(t, d1.Close())
} else {
defer iter1.Close()
if err := d1.Close(); err == nil {
t.Fatalf("expected failure, but found success")
} else if !strings.HasPrefix(err.Error(), "leaked iterators:") {
t.Fatalf("expected leaked iterators, but found %+v", err)
} else {
t.Log(err.Error())
}
}
}
{
iter2, _ := d2.NewIter(nil)
iter2.First()
if !leak {
require.NoError(t, iter2.Close())
require.NoError(t, d2.Close())
} else {
defer iter2.Close()
if err := d2.Close(); err == nil {
t.Fatalf("expected failure, but found success")
} else if !strings.HasPrefix(err.Error(), "leaked iterators:") {
t.Fatalf("expected leaked iterators, but found %+v", err)
} else {
t.Log(err.Error())
}
}
}
})
}
})
}
}
func TestMemTableReservation(t *testing.T) {
opts := &Options{
Cache: NewCache(128 << 10 /* 128 KB */),
MemTableSize: initialMemTableSize,
FS: vfs.NewMem(),
}
defer opts.Cache.Unref()
opts.testingRandomized(t)
opts.EnsureDefaults()
// We're going to be looking at and asserting the global memtable reservation
// amount below so we don't want to race with any triggered stats collections.
opts.private.disableTableStats = true
// Add a block to the cache. Note that the memtable size is larger than the
// cache size, so opening the DB should cause this block to be evicted.
tmpID := opts.Cache.NewID()
helloWorld := []byte("hello world")
value := cache.Alloc(len(helloWorld))
copy(value.Buf(), helloWorld)
opts.Cache.Set(tmpID, base.FileNum(0).DiskFileNum(), 0, value).Release()
d, err := Open("", opts)
require.NoError(t, err)
checkReserved := func(expected int64) {
t.Helper()
if reserved := d.memTableReserved.Load(); expected != reserved {
t.Fatalf("expected %d reserved, but found %d", expected, reserved)
}
}
checkReserved(int64(opts.MemTableSize))
if refs := d.mu.mem.queue[len(d.mu.mem.queue)-1].readerRefs.Load(); refs != 2 {
t.Fatalf("expected 2 refs, but found %d", refs)
}
// Verify the memtable reservation has caused our test block to be evicted.
if h := opts.Cache.Get(tmpID, base.FileNum(0).DiskFileNum(), 0); h.Get() != nil {
t.Fatalf("expected failure, but found success: %s", h.Get())
}
// Flush the memtable. The memtable reservation should double because old
// memtable will be recycled, saved for the next memtable allocation.
require.NoError(t, d.Flush())
checkReserved(int64(2 * opts.MemTableSize))
// Flush again. The memtable reservation should be unchanged because at most
// 1 memtable may be preserved for recycling.
// Flush in the presence of an active iterator. The iterator will hold a
// reference to a readState which will in turn hold a reader reference to the
// memtable.
iter, _ := d.NewIter(nil)
require.NoError(t, d.Flush())
// The flush moved the recycled memtable into position as an active mutable
// memtable. There are now two allocated memtables: 1 mutable and 1 pinned
// by the iterator's read state.
checkReserved(2 * int64(opts.MemTableSize))
// Flushing again should increase the reservation total to 3x: 1 active
// mutable, 1 for recycling, 1 pinned by iterator's read state.
require.NoError(t, d.Flush())
checkReserved(3 * int64(opts.MemTableSize))
// Closing the iterator will release the iterator's read state, and the old
// memtable will be moved into position as the next memtable to recycle.
// There was already a memtable ready to be recycled, so that memtable will
// be freed and the overall reservation total is reduced to 2x.
require.NoError(t, iter.Close())
checkReserved(2 * int64(opts.MemTableSize))
require.NoError(t, d.Close())
}
func TestMemTableReservationLeak(t *testing.T) {
d, err := Open("", &Options{FS: vfs.NewMem()})
require.NoError(t, err)
d.mu.Lock()
last := d.mu.mem.queue[len(d.mu.mem.queue)-1]
last.readerRef()
defer func() {
last.readerUnref(true)
}()
d.mu.Unlock()
if err := d.Close(); err == nil {
t.Fatalf("expected failure, but found success")
} else if !strings.HasPrefix(err.Error(), "leaked memtable reservation:") {
t.Fatalf("expected leaked memtable reservation, but found %+v", err)
} else {
t.Log(err.Error())
}
}
func TestCacheEvict(t *testing.T) {
cache := NewCache(10 << 20)
defer cache.Unref()
d, err := Open("", &Options{
Cache: cache,
FS: vfs.NewMem(),
})
require.NoError(t, err)
for i := 0; i < 1000; i++ {
key := []byte(fmt.Sprintf("%04d", i))
require.NoError(t, d.Set(key, key, nil))
}
require.NoError(t, d.Flush())
iter, _ := d.NewIter(nil)
for iter.First(); iter.Valid(); iter.Next() {
}
require.NoError(t, iter.Close())
if size := cache.Size(); size == 0 {
t.Fatalf("expected non-zero cache size")
}
for i := 0; i < 1000; i++ {
key := []byte(fmt.Sprintf("%04d", i))
require.NoError(t, d.Delete(key, nil))
}
require.NoError(t, d.Compact([]byte("0"), []byte("1"), false))
require.NoError(t, d.Close())
if size := cache.Size(); size != 0 {
t.Fatalf("expected empty cache, but found %d", size)
}
}
func TestFlushEmpty(t *testing.T) {
d, err := Open("", testingRandomized(t, &Options{
FS: vfs.NewMem(),
}))
require.NoError(t, err)
// Flushing an empty memtable should not fail.
require.NoError(t, d.Flush())
require.NoError(t, d.Close())
}
func TestRollManifest(t *testing.T) {
toPreserve := rand.Int31n(5) + 1
opts := &Options{
MaxManifestFileSize: 1,
L0CompactionThreshold: 10,
L0StopWritesThreshold: 1000,
FS: vfs.NewMem(),
NumPrevManifest: int(toPreserve),
}
opts.DisableAutomaticCompactions = true
opts.testingRandomized(t)
d, err := Open("", opts)
require.NoError(t, err)
manifestFileNumber := func() base.DiskFileNum {
d.mu.Lock()
defer d.mu.Unlock()
return d.mu.versions.manifestFileNum
}
sizeRolloverState := func() (int64, int64) {
d.mu.Lock()
defer d.mu.Unlock()
return d.mu.versions.rotationHelper.DebugInfo()
}
current := func() string {
desc, err := Peek(d.dirname, d.opts.FS)
require.NoError(t, err)
return desc.ManifestFilename
}
lastManifestNum := manifestFileNumber()
manifestNums := []base.DiskFileNum{lastManifestNum}
for i := 0; i < 5; i++ {
// MaxManifestFileSize is 1, but the rollover logic also counts edits
// since the last snapshot to decide on rollover, so do as many flushes as
// it demands.
lastSnapshotCount, editsSinceSnapshotCount := sizeRolloverState()
var expectedLastSnapshotCount, expectedEditsSinceSnapshotCount int64
switch i {
case 0:
// DB is empty.
expectedLastSnapshotCount, expectedEditsSinceSnapshotCount = 0, 0
case 1:
// First edit that caused rollover is not in the snapshot.
expectedLastSnapshotCount, expectedEditsSinceSnapshotCount = 0, 1
case 2:
// One flush is in the snapshot. One flush in the edit.
expectedLastSnapshotCount, expectedEditsSinceSnapshotCount = 1, 1
case 3:
// Two flushes in the snapshot. One flush in the edit. Will need to do
// two more flushes, the first of which will be in the next snapshot.
expectedLastSnapshotCount, expectedEditsSinceSnapshotCount = 2, 1
case 4:
// Four flushes in the snapshot. One flush in the edit. Will need to do
// four more flushes, three of which will be in the snapshot.
expectedLastSnapshotCount, expectedEditsSinceSnapshotCount = 4, 1
}
require.Equal(t, expectedLastSnapshotCount, lastSnapshotCount)
require.Equal(t, expectedEditsSinceSnapshotCount, editsSinceSnapshotCount)
// Number of flushes to do to trigger the rollover.
steps := int(lastSnapshotCount - editsSinceSnapshotCount + 1)
// Steps can be <= 0, but we need to do at least one edit to trigger the
// rollover logic.
if steps <= 0 {
steps = 1
}
for j := 0; j < steps; j++ {