forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
open_test.go
1343 lines (1197 loc) · 36.9 KB
/
open_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"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync/atomic"
"syscall"
"testing"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/cache"
"github.com/cockroachdb/pebble/internal/errorfs"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/pebble/vfs/atomicfs"
"github.com/cockroachdb/redact"
"github.com/kr/pretty"
"github.com/stretchr/testify/require"
)
func TestOpenSharedTableCache(t *testing.T) {
c := cache.New(cacheDefaultSize)
tc := NewTableCache(c, 16, 100)
defer tc.Unref()
defer c.Unref()
d0, err := Open("", testingRandomized(&Options{
FS: vfs.NewMem(),
Cache: c,
TableCache: tc,
}))
if err != nil {
t.Errorf("d0 Open: %s", err.Error())
}
defer d0.Close()
d1, err := Open("", testingRandomized(&Options{
FS: vfs.NewMem(),
Cache: c,
TableCache: tc,
}))
if err != nil {
t.Errorf("d1 Open: %s", err.Error())
}
defer d1.Close()
// Make sure that the Open function is using the passed in table cache
// when the TableCache option is set.
require.Equalf(
t, d0.tableCache.tableCache, d1.tableCache.tableCache,
"expected tableCache for both d0 and d1 to be the same",
)
}
func TestErrorIfExists(t *testing.T) {
opts := testingRandomized(&Options{
FS: vfs.NewMem(),
ErrorIfExists: true,
})
defer ensureFilesClosed(t, opts)()
d0, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d0.Close())
if _, err := Open("", opts); !errors.Is(err, ErrDBAlreadyExists) {
t.Fatalf("expected db-already-exists error, got %v", err)
}
opts.ErrorIfExists = false
d1, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d1.Close())
}
func TestErrorIfNotExists(t *testing.T) {
opts := testingRandomized(&Options{
FS: vfs.NewMem(),
ErrorIfNotExists: true,
})
defer ensureFilesClosed(t, opts)()
_, err := Open("", opts)
if !errors.Is(err, ErrDBDoesNotExist) {
t.Fatalf("expected db-does-not-exist error, got %v", err)
}
// Create the DB and try again.
opts.ErrorIfNotExists = false
d0, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d0.Close())
opts.ErrorIfNotExists = true
d1, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d1.Close())
}
func TestErrorIfNotPristine(t *testing.T) {
opts := testingRandomized(&Options{
FS: vfs.NewMem(),
ErrorIfNotPristine: true,
})
defer ensureFilesClosed(t, opts)()
d0, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d0.Close())
// Store is pristine; ok to open.
d1, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d1.Set([]byte("foo"), []byte("bar"), Sync))
require.NoError(t, d1.Close())
if _, err := Open("", opts); !errors.Is(err, ErrDBNotPristine) {
t.Fatalf("expected db-not-pristine error, got %v", err)
}
// Run compaction and make sure we're still not allowed to open.
opts.ErrorIfNotPristine = false
d2, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d2.Compact([]byte("a"), []byte("z"), false /* parallelize */))
require.NoError(t, d2.Close())
opts.ErrorIfNotPristine = true
if _, err := Open("", opts); !errors.Is(err, ErrDBNotPristine) {
t.Fatalf("expected db-already-exists error, got %v", err)
}
}
func TestOpenAlreadyLocked(t *testing.T) {
runTest := func(t *testing.T, dirname string, fs vfs.FS) {
opts := testingRandomized(&Options{FS: fs})
var err error
opts.Lock, err = LockDirectory(dirname, fs)
require.NoError(t, err)
d, err := Open(dirname, opts)
require.NoError(t, err)
require.NoError(t, d.Set([]byte("foo"), []byte("bar"), Sync))
// Try to open the same database reusing the Options containing the same
// Lock. It should error when it observes that it's already referenced.
_, err = Open(dirname, opts)
require.Error(t, err)
// Close the database.
require.NoError(t, d.Close())
// Now Opening should succeed again.
d, err = Open(dirname, opts)
require.NoError(t, err)
require.NoError(t, d.Close())
require.NoError(t, opts.Lock.Close())
// There should be no more remaining references.
require.Equal(t, int32(0), opts.Lock.refs.Load())
}
t.Run("memfs", func(t *testing.T) {
runTest(t, "", vfs.NewMem())
})
t.Run("disk", func(t *testing.T) {
runTest(t, t.TempDir(), vfs.Default)
})
}
func TestNewDBFilenames(t *testing.T) {
versions := map[FormatMajorVersion][]string{
FormatMostCompatible: {
"000002.log",
"CURRENT",
"LOCK",
"MANIFEST-000001",
"OPTIONS-000003",
},
FormatNewest: {
"000002.log",
"CURRENT",
"LOCK",
"MANIFEST-000001",
"OPTIONS-000003",
"marker.format-version.000013.014",
"marker.manifest.000001.MANIFEST-000001",
},
}
for formatVers, want := range versions {
t.Run(fmt.Sprintf("vers=%s", formatVers), func(t *testing.T) {
mem := vfs.NewMem()
fooBar := mem.PathJoin("foo", "bar")
d, err := Open(fooBar, &Options{
FS: mem,
FormatMajorVersion: formatVers,
})
if err != nil {
t.Fatalf("Open: %v", err)
}
if err := d.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
got, err := mem.List(fooBar)
if err != nil {
t.Fatalf("List: %v", err)
}
sort.Strings(got)
if !reflect.DeepEqual(got, want) {
t.Errorf("\ngot %v\nwant %v", got, want)
}
})
}
}
func testOpenCloseOpenClose(t *testing.T, fs vfs.FS, root string) {
opts := testingRandomized(&Options{FS: fs})
for _, startFromEmpty := range []bool{false, true} {
for _, walDirname := range []string{"", "wal"} {
for _, length := range []int{-1, 0, 1, 1000, 10000, 100000} {
dirname := "sharedDatabase" + walDirname
if startFromEmpty {
dirname = "startFromEmpty" + walDirname + strconv.Itoa(length)
}
dirname = fs.PathJoin(root, dirname)
if walDirname == "" {
opts.WALDir = ""
} else {
opts.WALDir = fs.PathJoin(dirname, walDirname)
}
got, xxx := []byte(nil), ""
if length >= 0 {
xxx = strings.Repeat("x", length)
}
d0, err := Open(dirname, opts)
if err != nil {
t.Fatalf("sfe=%t, length=%d: Open #0: %v",
startFromEmpty, length, err)
continue
}
if length >= 0 {
err = d0.Set([]byte("key"), []byte(xxx), nil)
if err != nil {
t.Errorf("sfe=%t, length=%d: Set: %v",
startFromEmpty, length, err)
continue
}
}
err = d0.Close()
if err != nil {
t.Errorf("sfe=%t, length=%d: Close #0: %v",
startFromEmpty, length, err)
continue
}
d1, err := Open(dirname, opts)
if err != nil {
t.Errorf("sfe=%t, length=%d: Open #1: %v",
startFromEmpty, length, err)
continue
}
if length >= 0 {
var closer io.Closer
got, closer, err = d1.Get([]byte("key"))
if err != nil {
t.Errorf("sfe=%t, length=%d: Get: %v",
startFromEmpty, length, err)
continue
}
got = append([]byte(nil), got...)
closer.Close()
}
err = d1.Close()
if err != nil {
t.Errorf("sfe=%t, length=%d: Close #1: %v",
startFromEmpty, length, err)
continue
}
if length >= 0 && string(got) != xxx {
t.Errorf("sfe=%t, length=%d: got value differs from set value",
startFromEmpty, length)
continue
}
{
got, err := opts.FS.List(dirname)
if err != nil {
t.Fatalf("List: %v", err)
}
var optionsCount int
for _, s := range got {
if t, _, ok := base.ParseFilename(opts.FS, s); ok && t == fileTypeOptions {
optionsCount++
}
}
if optionsCount != 1 {
t.Fatalf("expected 1 OPTIONS file, but found %d", optionsCount)
}
}
}
}
}
}
func TestOpenCloseOpenClose(t *testing.T) {
for _, fstype := range []string{"disk", "mem"} {
t.Run(fstype, func(t *testing.T) {
var fs vfs.FS
var dir string
switch fstype {
case "disk":
var err error
dir, err = os.MkdirTemp("", "open-close")
require.NoError(t, err)
defer func() {
_ = os.RemoveAll(dir)
}()
fs = vfs.Default
case "mem":
dir = ""
fs = vfs.NewMem()
}
testOpenCloseOpenClose(t, fs, dir)
})
}
}
func TestOpenOptionsCheck(t *testing.T) {
mem := vfs.NewMem()
opts := &Options{FS: mem}
d, err := Open("", opts)
require.NoError(t, err)
require.NoError(t, d.Close())
opts = &Options{
Comparer: &Comparer{Name: "foo"},
FS: mem,
}
_, err = Open("", opts)
require.Regexp(t, `comparer name from file.*!=.*`, err)
opts = &Options{
Merger: &Merger{Name: "bar"},
FS: mem,
}
_, err = Open("", opts)
require.Regexp(t, `merger name from file.*!=.*`, err)
}
func TestOpenCrashWritingOptions(t *testing.T) {
memFS := vfs.NewMem()
d, err := Open("", &Options{FS: memFS})
require.NoError(t, err)
require.NoError(t, d.Close())
// Open the database again, this time with a mocked filesystem that
// will only succeed in partially writing the OPTIONS file.
fs := optionsTornWriteFS{FS: memFS}
_, err = Open("", &Options{FS: fs})
require.Error(t, err)
// Re-opening the database must succeed.
d, err = Open("", &Options{FS: memFS})
require.NoError(t, err)
require.NoError(t, d.Close())
}
type optionsTornWriteFS struct {
vfs.FS
}
func (fs optionsTornWriteFS) Create(name string) (vfs.File, error) {
file, err := fs.FS.Create(name)
if file != nil {
file = optionsTornWriteFile{File: file}
}
return file, err
}
type optionsTornWriteFile struct {
vfs.File
}
func (f optionsTornWriteFile) Write(b []byte) (int, error) {
// Look for the OPTIONS-XXXXXX file's `comparer=` field.
comparerKey := []byte("comparer=")
i := bytes.Index(b, comparerKey)
if i == -1 {
return f.File.Write(b)
}
// Write only the contents through `comparer=` and return an error.
n, _ := f.File.Write(b[:i+len(comparerKey)])
return n, syscall.EIO
}
func TestOpenReadOnly(t *testing.T) {
mem := vfs.NewMem()
{
// Opening a non-existent DB in read-only mode should result in no mutable
// filesystem operations.
var memLog base.InMemLogger
_, err := Open("non-existent", testingRandomized(&Options{
FS: vfs.WithLogging(mem, memLog.Infof),
ReadOnly: true,
WALDir: "non-existent-waldir",
}))
if err == nil {
t.Fatalf("expected error, but found success")
}
const expected = `open-dir: non-existent`
if trimmed := strings.TrimSpace(memLog.String()); expected != trimmed {
t.Fatalf("expected %q, but found %q", expected, trimmed)
}
}
{
// Opening a DB with a non-existent WAL dir in read-only mode should result
// in no mutable filesystem operations other than the LOCK.
var memLog base.InMemLogger
_, err := Open("", testingRandomized(&Options{
FS: vfs.WithLogging(mem, memLog.Infof),
ReadOnly: true,
WALDir: "non-existent-waldir",
}))
if err == nil {
t.Fatalf("expected error, but found success")
}
const expected = "open-dir: \nopen-dir: non-existent-waldir\nclose:"
if trimmed := strings.TrimSpace(memLog.String()); expected != trimmed {
t.Fatalf("expected %q, but found %q", expected, trimmed)
}
}
var contents []string
{
// Create a new DB and populate it with a small amount of data.
d, err := Open("", testingRandomized(&Options{
FS: mem,
}))
require.NoError(t, err)
require.NoError(t, d.Set([]byte("test"), nil, nil))
require.NoError(t, d.Close())
contents, err = mem.List("")
require.NoError(t, err)
sort.Strings(contents)
}
{
// Re-open the DB read-only. The directory contents should be unchanged.
d, err := Open("", testingRandomized(&Options{
FS: mem,
ReadOnly: true,
}))
require.NoError(t, err)
// Verify various write operations fail in read-only mode.
require.EqualValues(t, ErrReadOnly, d.Compact(nil, []byte("\xff"), false))
require.EqualValues(t, ErrReadOnly, d.Flush())
require.EqualValues(t, ErrReadOnly, func() error { _, err := d.AsyncFlush(); return err }())
require.EqualValues(t, ErrReadOnly, d.Delete(nil, nil))
require.EqualValues(t, ErrReadOnly, d.DeleteRange(nil, nil, nil))
require.EqualValues(t, ErrReadOnly, d.Ingest(nil))
require.EqualValues(t, ErrReadOnly, d.LogData(nil, nil))
require.EqualValues(t, ErrReadOnly, d.Merge(nil, nil, nil))
require.EqualValues(t, ErrReadOnly, d.Set(nil, nil, nil))
// Verify we can still read in read-only mode.
require.NoError(t, func() error {
_, closer, err := d.Get([]byte("test"))
if closer != nil {
closer.Close()
}
return err
}())
checkIter := func(iter *Iterator) {
t.Helper()
var keys []string
for valid := iter.First(); valid; valid = iter.Next() {
keys = append(keys, string(iter.Key()))
}
require.NoError(t, iter.Close())
expectedKeys := []string{"test"}
if diff := pretty.Diff(keys, expectedKeys); diff != nil {
t.Fatalf("%s\n%s", strings.Join(diff, "\n"), keys)
}
}
checkIter(d.NewIter(nil))
b := d.NewIndexedBatch()
checkIter(b.NewIter(nil))
require.EqualValues(t, ErrReadOnly, b.Commit(nil))
require.EqualValues(t, ErrReadOnly, d.Apply(b, nil))
s := d.NewSnapshot()
checkIter(s.NewIter(nil))
require.NoError(t, s.Close())
require.NoError(t, d.Close())
newContents, err := mem.List("")
require.NoError(t, err)
sort.Strings(newContents)
if diff := pretty.Diff(contents, newContents); diff != nil {
t.Fatalf("%s", strings.Join(diff, "\n"))
}
}
}
func TestOpenWALReplay(t *testing.T) {
largeValue := []byte(strings.Repeat("a", 100<<10))
hugeValue := []byte(strings.Repeat("b", 10<<20))
checkIter := func(iter *Iterator) {
t.Helper()
var keys []string
for valid := iter.First(); valid; valid = iter.Next() {
keys = append(keys, string(iter.Key()))
}
require.NoError(t, iter.Close())
expectedKeys := []string{"1", "2", "3", "4", "5"}
if diff := pretty.Diff(keys, expectedKeys); diff != nil {
t.Fatalf("%s\n%s", strings.Join(diff, "\n"), keys)
}
}
for _, readOnly := range []bool{false, true} {
t.Run(fmt.Sprintf("read-only=%t", readOnly), func(t *testing.T) {
// Create a new DB and populate it with some data.
const dir = ""
mem := vfs.NewMem()
d, err := Open(dir, testingRandomized(&Options{
FS: mem,
MemTableSize: 32 << 20,
}))
require.NoError(t, err)
// All these values will fit in a single memtable, so on closing the db there
// will be no sst and all the data is in a single WAL.
require.NoError(t, d.Set([]byte("1"), largeValue, nil))
require.NoError(t, d.Set([]byte("2"), largeValue, nil))
require.NoError(t, d.Set([]byte("3"), largeValue, nil))
require.NoError(t, d.Set([]byte("4"), hugeValue, nil))
require.NoError(t, d.Set([]byte("5"), largeValue, nil))
checkIter(d.NewIter(nil))
require.NoError(t, d.Close())
files, err := mem.List(dir)
require.NoError(t, err)
sort.Strings(files)
logCount, sstCount := 0, 0
for _, fname := range files {
if strings.HasSuffix(fname, ".sst") {
sstCount++
}
if strings.HasSuffix(fname, ".log") {
logCount++
}
}
require.Equal(t, 0, sstCount)
// The memtable size starts at 256KB and doubles up to 32MB so we expect 5
// logs (one for each doubling).
require.Equal(t, 7, logCount)
// Re-open the DB with a smaller memtable. Values for 1, 2 will fit in the first memtable;
// value for 3 will go in the next memtable; value for 4 will be in a flushable batch
// which will cause the previous memtable to be flushed; value for 5 will go in the next
// memtable
d, err = Open(dir, testingRandomized(&Options{
FS: mem,
MemTableSize: 300 << 10,
ReadOnly: readOnly,
}))
require.NoError(t, err)
if readOnly {
m := d.Metrics()
require.Equal(t, int64(logCount), m.WAL.Files)
d.mu.Lock()
require.NotNil(t, d.mu.mem.mutable)
d.mu.Unlock()
}
checkIter(d.NewIter(nil))
require.NoError(t, d.Close())
})
}
}
// Reproduction for https://github.com/cockroachdb/pebble/issues/2234.
func TestWALReplaySequenceNumBug(t *testing.T) {
mem := vfs.NewMem()
d, err := Open("", testingRandomized(&Options{
FS: mem,
}))
require.NoError(t, err)
d.mu.Lock()
// Disable any flushes.
d.mu.compact.flushing = true
d.mu.Unlock()
require.NoError(t, d.Set([]byte("1"), nil, nil))
require.NoError(t, d.Set([]byte("2"), nil, nil))
// Write a large batch. This should go to a separate memtable.
largeValue := []byte(strings.Repeat("a", d.largeBatchThreshold))
require.NoError(t, d.Set([]byte("1"), largeValue, nil))
// This write should go the mutable memtable after the large batch in the
// memtable queue.
d.Set([]byte("1"), nil, nil)
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
// Make sure none of the flushables have been flushed.
require.Equal(t, 3, len(d.mu.mem.queue))
// Close the db. This doesn't cause a flush of the memtables, so they'll
// have to be replayed when the db is reopened.
require.NoError(t, d.Close())
files, err := mem.List("")
require.NoError(t, err)
sort.Strings(files)
sstCount := 0
for _, fname := range files {
if strings.HasSuffix(fname, ".sst") {
sstCount++
}
}
require.Equal(t, 0, sstCount)
// Reopen db in read only mode to force read only wal replay.
d, err = Open("", &Options{
FS: mem,
ReadOnly: true,
})
require.NoError(t, err)
val, c, _ := d.Get([]byte("1"))
require.Equal(t, []byte{}, val)
c.Close()
require.NoError(t, d.Close())
}
// Similar to TestOpenWALReplay, except we test replay behavior after a
// memtable has been flushed. We test all 3 reasons for flushing: forced, size,
// and large-batch.
func TestOpenWALReplay2(t *testing.T) {
for _, readOnly := range []bool{false, true} {
t.Run(fmt.Sprintf("read-only=%t", readOnly), func(t *testing.T) {
for _, reason := range []string{"forced", "size", "large-batch"} {
t.Run(reason, func(t *testing.T) {
mem := vfs.NewMem()
d, err := Open("", testingRandomized(&Options{
FS: mem,
MemTableSize: 256 << 10,
}))
require.NoError(t, err)
switch reason {
case "forced":
require.NoError(t, d.Set([]byte("1"), nil, nil))
require.NoError(t, d.Flush())
require.NoError(t, d.Set([]byte("2"), nil, nil))
case "size":
largeValue := []byte(strings.Repeat("a", 100<<10))
require.NoError(t, d.Set([]byte("1"), largeValue, nil))
require.NoError(t, d.Set([]byte("2"), largeValue, nil))
require.NoError(t, d.Set([]byte("3"), largeValue, nil))
case "large-batch":
largeValue := []byte(strings.Repeat("a", d.largeBatchThreshold))
require.NoError(t, d.Set([]byte("1"), nil, nil))
require.NoError(t, d.Set([]byte("2"), largeValue, nil))
require.NoError(t, d.Set([]byte("3"), nil, nil))
}
require.NoError(t, d.Close())
files, err := mem.List("")
require.NoError(t, err)
sort.Strings(files)
sstCount := 0
for _, fname := range files {
if strings.HasSuffix(fname, ".sst") {
sstCount++
}
}
require.Equal(t, 1, sstCount)
// Re-open the DB with a smaller memtable. Values for 1, 2 will fit in the first memtable;
// value for 3 will go in the next memtable; value for 4 will be in a flushable batch
// which will cause the previous memtable to be flushed; value for 5 will go in the next
// memtable
d, err = Open("", testingRandomized(&Options{
FS: mem,
MemTableSize: 300 << 10,
ReadOnly: readOnly,
}))
require.NoError(t, err)
require.NoError(t, d.Close())
})
}
})
}
}
// TestTwoWALReplayCorrupt tests WAL-replay behavior when the first of the two
// WALs is corrupted with an sstable checksum error. Replay must stop at the
// first WAL because otherwise we may violate point-in-time recovery
// semantics. See #864.
func TestTwoWALReplayCorrupt(t *testing.T) {
// Use the real filesystem so that we can seek and overwrite WAL data
// easily.
dir, err := os.MkdirTemp("", "wal-replay")
require.NoError(t, err)
defer os.RemoveAll(dir)
d, err := Open(dir, testingRandomized(&Options{
MemTableStopWritesThreshold: 4,
MemTableSize: 2048,
}))
require.NoError(t, err)
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
require.NoError(t, d.Set([]byte("1"), []byte(strings.Repeat("a", 1024)), nil))
require.NoError(t, d.Set([]byte("2"), nil, nil))
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
require.NoError(t, d.Close())
// We should have two WALs.
var logs []string
ls, err := vfs.Default.List(dir)
require.NoError(t, err)
for _, name := range ls {
if filepath.Ext(name) == ".log" {
logs = append(logs, name)
}
}
sort.Strings(logs)
if len(logs) < 2 {
t.Fatalf("expected at least two log files, found %d", len(logs))
}
// Corrupt the (n-1)th WAL by zeroing four bytes, 100 bytes from the end
// of the file.
f, err := os.OpenFile(filepath.Join(dir, logs[len(logs)-2]), os.O_RDWR, os.ModePerm)
require.NoError(t, err)
off, err := f.Seek(-100, 2)
require.NoError(t, err)
_, err = f.Write([]byte{0, 0, 0, 0})
require.NoError(t, err)
require.NoError(t, f.Close())
t.Logf("zeored four bytes in %s at offset %d\n", logs[len(logs)-2], off)
// Re-opening the database should detect and report the corruption.
_, err = Open(dir, nil)
require.Error(t, err, "pebble: corruption")
}
// TestTwoWALReplayCorrupt tests WAL-replay behavior when the first of the two
// WALs is corrupted with an sstable checksum error and the OPTIONS file does
// not enable the private strict_wal_tail option, indicating that the WAL was
// produced by a database that did not guarantee clean WAL tails. See #864.
func TestTwoWALReplayPermissive(t *testing.T) {
// Use the real filesystem so that we can seek and overwrite WAL data
// easily.
dir, err := os.MkdirTemp("", "wal-replay")
require.NoError(t, err)
defer os.RemoveAll(dir)
opts := &Options{
MemTableStopWritesThreshold: 4,
MemTableSize: 2048,
}
opts.testingRandomized()
opts.EnsureDefaults()
d, err := Open(dir, opts)
require.NoError(t, err)
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
require.NoError(t, d.Set([]byte("1"), []byte(strings.Repeat("a", 1024)), nil))
require.NoError(t, d.Set([]byte("2"), nil, nil))
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
require.NoError(t, d.Close())
// We should have two WALs.
var logs []string
var optionFilename string
ls, err := vfs.Default.List(dir)
require.NoError(t, err)
for _, name := range ls {
if filepath.Ext(name) == ".log" {
logs = append(logs, name)
}
if strings.HasPrefix(filepath.Base(name), "OPTIONS") {
optionFilename = name
}
}
sort.Strings(logs)
if len(logs) < 2 {
t.Fatalf("expected at least two log files, found %d", len(logs))
}
// Corrupt the (n-1)th WAL by zeroing four bytes, 100 bytes from the end
// of the file.
f, err := os.OpenFile(filepath.Join(dir, logs[len(logs)-2]), os.O_RDWR, os.ModePerm)
require.NoError(t, err)
off, err := f.Seek(-100, 2)
require.NoError(t, err)
_, err = f.Write([]byte{0, 0, 0, 0})
require.NoError(t, err)
require.NoError(t, f.Close())
t.Logf("zeored four bytes in %s at offset %d\n", logs[len(logs)-2], off)
// Remove the OPTIONS file containing the strict_wal_tail option.
require.NoError(t, vfs.Default.Remove(filepath.Join(dir, optionFilename)))
// Re-opening the database should not report the corruption.
d, err = Open(dir, nil)
require.NoError(t, err)
require.NoError(t, d.Close())
}
// TestCrashOpenCrashAfterWALCreation tests a database that exits
// ungracefully, begins recovery, creates the new WAL but promptly exits
// ungracefully again.
//
// This sequence has the potential to be problematic with the strict_wal_tail
// behavior because the first crash's WAL has an unclean tail. By the time the
// new WAL is created, the current manifest's MinUnflushedLogNum must be
// higher than the previous WAL.
func TestCrashOpenCrashAfterWALCreation(t *testing.T) {
fs := vfs.NewStrictMem()
getLogs := func() (logs []string) {
ls, err := fs.List("")
require.NoError(t, err)
for _, name := range ls {
if filepath.Ext(name) == ".log" {
logs = append(logs, name)
}
}
return logs
}
{
d, err := Open("", testingRandomized(&Options{FS: fs}))
require.NoError(t, err)
require.NoError(t, d.Set([]byte("abc"), nil, Sync))
// Ignore syncs during close to simulate a crash. This will leave the WAL
// without an EOF trailer. It won't be an 'unclean tail' yet since the
// log file was not recycled, but we'll fix that down below.
fs.SetIgnoreSyncs(true)
require.NoError(t, d.Close())
fs.ResetToSyncedState()
fs.SetIgnoreSyncs(false)
}
// There should be one WAL.
logs := getLogs()
if len(logs) != 1 {
t.Fatalf("expected one log file, found %d", len(logs))
}
// The one WAL file doesn't have an EOF trailer, but since it wasn't
// recycled it won't have garbage at the end. Rewrite it so that it has
// the same contents it currently has, followed by garbage.
{
f, err := fs.Open(logs[0])
require.NoError(t, err)
b, err := io.ReadAll(f)
require.NoError(t, err)
require.NoError(t, f.Close())
f, err = fs.Create(logs[0])
require.NoError(t, err)
_, err = f.Write(b)
require.NoError(t, err)
_, err = f.Write([]byte{0xde, 0xad, 0xbe, 0xef})
require.NoError(t, err)
require.NoError(t, f.Sync())
require.NoError(t, f.Close())
dir, err := fs.OpenDir("")
require.NoError(t, err)
require.NoError(t, dir.Sync())
require.NoError(t, dir.Close())
}
// Open the database again (with syncs respected again). Wrap the
// filesystem with an errorfs that will turn off syncs after a new .log
// file is created and after a subsequent directory sync occurs. This
// simulates a crash after the new log file is created and synced.
{
var walCreated, dirSynced atomic.Bool
d, err := Open("", &Options{
FS: errorfs.Wrap(fs, errorfs.InjectorFunc(func(op errorfs.Op, path string) error {
if dirSynced.Load() {
fs.SetIgnoreSyncs(true)
}
if op == errorfs.OpCreate && filepath.Ext(path) == ".log" {
walCreated.Store(true)
}
// Record when there's a sync of the data directory after the
// WAL was created. The data directory will have an empty
// path because that's what we passed into Open.
if op == errorfs.OpFileSync && path == "" && walCreated.Load() {
dirSynced.Store(true)
}
return nil
})),
})
require.NoError(t, err)
require.NoError(t, d.Close())
}
fs.ResetToSyncedState()
fs.SetIgnoreSyncs(false)
if n := len(getLogs()); n != 2 {
t.Fatalf("expected two logs, found %d\n", n)
}
// Finally, open the database with syncs enabled.
d, err := Open("", testingRandomized(&Options{FS: fs}))
require.NoError(t, err)
require.NoError(t, d.Close())
}
// TestOpenWALReplayReadOnlySeqNums tests opening a database:
// - in read-only mode
// - with multiple unflushed log files that must replayed
// - a MANIFEST that sets the last sequence number to a number greater than
// the unflushed log files
//
// See cockroachdb/cockroach#48660.
func TestOpenWALReplayReadOnlySeqNums(t *testing.T) {
const root = ""
mem := vfs.NewMem()
copyFiles := func(srcDir, dstDir string) {
files, err := mem.List(srcDir)
require.NoError(t, err)
for _, f := range files {
require.NoError(t, vfs.Copy(mem, mem.PathJoin(srcDir, f), mem.PathJoin(dstDir, f)))
}
}
// Create a new database under `/original` with a couple sstables.
dir := mem.PathJoin(root, "original")
d, err := Open(dir, testingRandomized(&Options{FS: mem}))
require.NoError(t, err)
require.NoError(t, d.Set([]byte("a"), nil, nil))
require.NoError(t, d.Flush())
require.NoError(t, d.Set([]byte("a"), nil, nil))
require.NoError(t, d.Flush())
// Prevent flushes so that multiple unflushed log files build up.
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
require.NoError(t, d.Set([]byte("b"), nil, nil))
d.AsyncFlush()
require.NoError(t, d.Set([]byte("c"), nil, nil))
d.AsyncFlush()
require.NoError(t, d.Set([]byte("e"), nil, nil))
// Manually compact some of the key space so that the latest `logSeqNum` is
// written to the MANIFEST. This produces a MANIFEST where the `logSeqNum`