-
Notifications
You must be signed in to change notification settings - Fork 468
/
ingest_test.go
3832 lines (3477 loc) · 105 KB
/
ingest_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 2018 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"
"math"
"math/rand/v2"
"os"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/pebble/bloom"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/cockroachdb/pebble/internal/testkeys"
"github.com/cockroachdb/pebble/objstorage"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/objstorage/remote"
"github.com/cockroachdb/pebble/record"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/sstable/block"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/pebble/vfs/errorfs"
"github.com/kr/pretty"
"github.com/stretchr/testify/require"
)
func TestSSTableKeyCompare(t *testing.T) {
var buf bytes.Buffer
datadriven.RunTest(t, "testdata/sstable_key_compare", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "cmp":
buf.Reset()
for _, line := range strings.Split(td.Input, "\n") {
fields := strings.Fields(line)
a := base.ParseInternalKey(fields[0])
b := base.ParseInternalKey(fields[1])
got := sstableKeyCompare(testkeys.Comparer.Compare, a, b)
fmt.Fprintf(&buf, "%38s", fmt.Sprint(a.Pretty(base.DefaultFormatter)))
switch got {
case -1:
fmt.Fprint(&buf, " < ")
case +1:
fmt.Fprint(&buf, " > ")
case 0:
fmt.Fprint(&buf, " = ")
}
fmt.Fprintf(&buf, "%s\n", fmt.Sprint(b.Pretty(base.DefaultFormatter)))
}
return buf.String()
default:
return fmt.Sprintf("unrecognized command %q", td.Cmd)
}
})
}
func TestIngestLoad(t *testing.T) {
mem := vfs.NewMem()
datadriven.RunTest(t, "testdata/ingest_load", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "load":
writerOpts := sstable.WriterOptions{}
var dbVersion FormatMajorVersion
for _, cmdArgs := range td.CmdArgs {
v, err := strconv.Atoi(cmdArgs.Vals[0])
if err != nil {
return err.Error()
}
switch k := cmdArgs.Key; k {
case "writer-version":
fmv := FormatMajorVersion(v)
writerOpts.TableFormat = fmv.MaxTableFormat()
case "db-version":
dbVersion = FormatMajorVersion(v)
default:
return fmt.Sprintf("unknown cmd %s\n", k)
}
}
f, err := mem.Create("ext", vfs.WriteCategoryUnspecified)
if err != nil {
return err.Error()
}
w := sstable.NewRawWriter(objstorageprovider.NewFileWritable(f), writerOpts)
for _, data := range strings.Split(td.Input, "\n") {
if strings.HasPrefix(data, "EncodeSpan: ") {
data = strings.TrimPrefix(data, "EncodeSpan: ")
err := w.EncodeSpan(keyspan.ParseSpan(data))
if err != nil {
return err.Error()
}
continue
}
j := strings.Index(data, ":")
if j < 0 {
return fmt.Sprintf("malformed input: %s\n", data)
}
key := base.ParseInternalKey(data[:j])
value := []byte(data[j+1:])
if err := w.AddWithForceObsolete(key, value, false /* forceObsolete */); err != nil {
return err.Error()
}
}
if err := w.Close(); err != nil {
return err.Error()
}
opts := (&Options{
Comparer: DefaultComparer,
FS: mem,
}).WithFSDefaults()
lr, err := ingestLoad(context.Background(), opts, dbVersion, []string{"ext"}, nil, nil, 0, []base.FileNum{1})
if err != nil {
return err.Error()
}
var buf bytes.Buffer
for _, m := range lr.local {
fmt.Fprintf(&buf, "%d: %s-%s\n", m.FileNum, m.Smallest, m.Largest)
fmt.Fprintf(&buf, " points: %s-%s\n", m.SmallestPointKey, m.LargestPointKey)
fmt.Fprintf(&buf, " ranges: %s-%s\n", m.SmallestRangeKey, m.LargestRangeKey)
}
return buf.String()
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestIngestLoadRand(t *testing.T) {
mem := vfs.NewMem()
rng := rand.New(rand.NewPCG(0, uint64(time.Now().UnixNano())))
cmp := DefaultComparer.Compare
version := internalFormatNewest
randBytes := func(size int) []byte {
data := make([]byte, size)
for i := range data {
data[i] = byte(rng.Int() & 0xff)
}
return data
}
paths := make([]string, 1+rng.IntN(10))
pending := make([]base.FileNum, len(paths))
expected := make([]ingestLocalMeta, len(paths))
for i := range paths {
paths[i] = fmt.Sprint(i)
pending[i] = base.FileNum(rng.Uint64())
expected[i] = ingestLocalMeta{
fileMetadata: &fileMetadata{
FileNum: pending[i],
},
path: paths[i],
}
expected[i].fileMetadata.Stats.CompressionType = block.SnappyCompression
expected[i].StatsMarkValid()
func() {
f, err := mem.Create(paths[i], vfs.WriteCategoryUnspecified)
require.NoError(t, err)
keys := make([]InternalKey, 1+rng.IntN(100))
for i := range keys {
keys[i] = base.MakeInternalKey(
randBytes(1+rng.IntN(10)),
0,
InternalKeyKindSet)
}
slices.SortFunc(keys, func(a, b base.InternalKey) int {
return base.InternalCompare(cmp, a, b)
})
expected[i].ExtendPointKeyBounds(cmp, keys[0], keys[len(keys)-1])
w := sstable.NewRawWriter(objstorageprovider.NewFileWritable(f), sstable.WriterOptions{
TableFormat: version.MaxTableFormat(),
})
var count uint64
for i := range keys {
if i > 0 && base.InternalCompare(cmp, keys[i-1], keys[i]) == 0 {
// Duplicate key, ignore.
continue
}
require.NoError(t, w.AddWithForceObsolete(keys[i], nil, false /* forceObsolete */))
count++
}
expected[i].Stats.NumEntries = count
require.NoError(t, w.Close())
meta, err := w.Metadata()
require.NoError(t, err)
expected[i].Size = meta.Size
expected[i].InitPhysicalBacking()
}()
}
opts := (&Options{
Comparer: base.DefaultComparer,
FS: mem,
}).WithFSDefaults().EnsureDefaults()
lr, err := ingestLoad(context.Background(), opts, version, paths, nil, nil, 0, pending)
require.NoError(t, err)
for _, m := range lr.local {
m.CreationTime = 0
}
t.Log(strings.Join(pretty.Diff(expected, lr.local), "\n"))
require.Equal(t, expected, lr.local)
}
func TestIngestLoadInvalid(t *testing.T) {
mem := vfs.NewMem()
f, err := mem.Create("invalid", vfs.WriteCategoryUnspecified)
require.NoError(t, err)
require.NoError(t, f.Close())
opts := (&Options{
Comparer: DefaultComparer,
FS: mem,
}).WithFSDefaults()
if _, err := ingestLoad(context.Background(), opts, internalFormatNewest, []string{"invalid"}, nil, nil, 0, []base.FileNum{1}); err == nil {
t.Fatalf("expected error, but found success")
}
}
func TestIngestSortAndVerify(t *testing.T) {
comparers := map[string]Compare{
"default": DefaultComparer.Compare,
"reverse": func(a, b []byte) int {
return DefaultComparer.Compare(b, a)
},
}
t.Run("", func(t *testing.T) {
datadriven.RunTest(t, "testdata/ingest_sort_and_verify", func(t *testing.T, d *datadriven.TestData) string {
switch d.Cmd {
case "ingest":
var buf bytes.Buffer
var meta []ingestLocalMeta
var cmpName string
d.ScanArgs(t, "cmp", &cmpName)
cmp := comparers[cmpName]
if cmp == nil {
return fmt.Sprintf("%s unknown comparer: %s", d.Cmd, cmpName)
}
for i, data := range strings.Split(d.Input, "\n") {
parts := strings.Split(data, "-")
if len(parts) != 2 {
return fmt.Sprintf("malformed test case: %s", d.Input)
}
smallest := base.ParseInternalKey(parts[0])
largest := base.ParseInternalKey(parts[1])
if cmp(smallest.UserKey, largest.UserKey) > 0 {
return fmt.Sprintf("range %v-%v is not valid", smallest, largest)
}
m := (&fileMetadata{}).ExtendPointKeyBounds(cmp, smallest, largest)
m.InitPhysicalBacking()
meta = append(meta, ingestLocalMeta{
fileMetadata: m,
path: strconv.Itoa(i),
})
}
lr := ingestLoadResult{local: meta}
err := ingestSortAndVerify(cmp, lr, KeyRange{})
if err != nil {
return fmt.Sprintf("%v\n", err)
}
for i := range meta {
fmt.Fprintf(&buf, "%s: %v-%v\n", meta[i].path, meta[i].Smallest, meta[i].Largest)
}
return buf.String()
default:
return fmt.Sprintf("unknown command: %s", d.Cmd)
}
})
})
}
func TestIngestLink(t *testing.T) {
// Test linking of tables into the DB directory. Test cleanup when one of the
// tables cannot be linked.
const dir = "db"
const count = 10
for i := 0; i <= count; i++ {
t.Run("", func(t *testing.T) {
opts := &Options{FS: vfs.NewMem()}
opts.EnsureDefaults().WithFSDefaults()
require.NoError(t, opts.FS.MkdirAll(dir, 0755))
objProvider, err := objstorageprovider.Open(objstorageprovider.DefaultSettings(opts.FS, dir))
require.NoError(t, err)
defer objProvider.Close()
meta := make([]ingestLocalMeta, 10)
contents := make([][]byte, len(meta))
for j := range meta {
meta[j].path = fmt.Sprintf("external%d", j)
meta[j].fileMetadata = &fileMetadata{}
meta[j].FileNum = FileNum(j)
meta[j].InitPhysicalBacking()
f, err := opts.FS.Create(meta[j].path, vfs.WriteCategoryUnspecified)
require.NoError(t, err)
contents[j] = []byte(fmt.Sprintf("data%d", j))
// memFile.Write will modify the supplied buffer when invariants are
// enabled, so provide a throw-away copy.
_, err = f.Write(append([]byte(nil), contents[j]...))
require.NoError(t, err)
require.NoError(t, f.Close())
}
if i < count {
opts.FS.Remove(meta[i].path)
}
err = ingestLinkLocal(context.Background(), 0 /* jobID */, opts, objProvider, meta)
if i < count {
if err == nil {
t.Fatalf("expected error, but found success")
}
} else {
require.NoError(t, err)
}
files, err := opts.FS.List(dir)
require.NoError(t, err)
sort.Strings(files)
if i < count {
if len(files) > 0 {
t.Fatalf("expected all of the files to be cleaned up, but found:\n%s",
strings.Join(files, "\n"))
}
} else {
if len(files) != count {
t.Fatalf("expected %d files, but found:\n%s", count, strings.Join(files, "\n"))
}
for j := range files {
ftype, fileNum, ok := base.ParseFilename(opts.FS, files[j])
if !ok {
t.Fatalf("unable to parse filename: %s", files[j])
}
if fileTypeTable != ftype {
t.Fatalf("expected table, but found %d", ftype)
}
if j != int(fileNum) {
t.Fatalf("expected table %d, but found %d", j, fileNum)
}
f, err := opts.FS.Open(opts.FS.PathJoin(dir, files[j]))
require.NoError(t, err)
data, err := io.ReadAll(f)
require.NoError(t, err)
require.NoError(t, f.Close())
if !bytes.Equal(contents[j], data) {
t.Fatalf("expected %s, but found %s", contents[j], data)
}
}
}
})
}
}
func TestIngestLinkFallback(t *testing.T) {
// Verify that ingestLink succeeds if linking fails by falling back to
// copying.
mem := vfs.NewMem()
src, err := mem.Create("source", vfs.WriteCategoryUnspecified)
require.NoError(t, err)
opts := &Options{FS: errorfs.Wrap(mem, errorfs.ErrInjected.If(errorfs.OnIndex(1)))}
opts.EnsureDefaults().WithFSDefaults()
objSettings := objstorageprovider.DefaultSettings(opts.FS, "")
// Prevent the provider from listing the dir (where we may get an injected error).
objSettings.FSDirInitialListing = []string{}
objProvider, err := objstorageprovider.Open(objSettings)
require.NoError(t, err)
defer objProvider.Close()
meta := &fileMetadata{FileNum: 1}
meta.InitPhysicalBacking()
err = ingestLinkLocal(context.Background(), 0, opts, objProvider, []ingestLocalMeta{{fileMetadata: meta, path: "source"}})
require.NoError(t, err)
dest, err := mem.Open("000001.sst")
require.NoError(t, err)
// We should be able to write bytes to src, and not have them show up in
// dest.
_, _ = src.Write([]byte("test"))
data, err := io.ReadAll(dest)
require.NoError(t, err)
if len(data) != 0 {
t.Fatalf("expected copy, but files appear to be hard linked: [%s] unexpectedly found", data)
}
}
func TestOverlappingIngestedSSTs(t *testing.T) {
dir := ""
var (
mem *vfs.MemFS
crashClone *vfs.MemFS
d *DB
opts *Options
closed = false
blockFlush = false
)
cache := NewCache(0)
defer func() {
if d != nil && !closed {
require.NoError(t, d.Close())
}
cache.Unref()
}()
var fsLog struct {
sync.Mutex
buf bytes.Buffer
}
reset := func(strictMem bool) {
if d != nil && !closed {
require.NoError(t, d.Close())
d = nil
}
blockFlush = false
if strictMem {
mem = vfs.NewCrashableMem()
} else {
mem = vfs.NewMem()
}
require.NoError(t, mem.MkdirAll("ext", 0755))
opts = (&Options{
FS: vfs.WithLogging(mem, func(format string, args ...interface{}) {
fsLog.Lock()
defer fsLog.Unlock()
fmt.Fprintf(&fsLog.buf, format+"\n", args...)
}),
Cache: cache,
MemTableStopWritesThreshold: 4,
L0CompactionThreshold: 100,
L0StopWritesThreshold: 100,
DebugCheck: DebugCheckLevels,
FormatMajorVersion: internalFormatNewest,
Logger: testLogger{t},
}).WithFSDefaults()
opts.Experimental.EnableColumnarBlocks = func() bool { return true }
if testing.Verbose() {
lel := MakeLoggingEventListener(DefaultLogger)
opts.EventListener = &lel
}
opts.EnsureDefaults()
// Some of the tests require bloom filters.
opts.Levels[0].FilterPolicy = bloom.FilterPolicy(10)
// Disable automatic compactions because otherwise we'll race with
// delete-only compactions triggered by ingesting range tombstones.
opts.DisableAutomaticCompactions = true
var err error
d, err = Open(dir, opts)
require.NoError(t, err)
closed = false
d.TestOnlyWaitForCleaning()
}
waitForFlush := func() {
if d == nil {
return
}
d.mu.Lock()
for d.mu.compact.flushing {
d.mu.compact.cond.Wait()
}
d.mu.Unlock()
}
reset(false)
datadriven.RunTest(t, "testdata/flushable_ingest", func(t *testing.T, td *datadriven.TestData) (result string) {
if td.HasArg("with-fs-logging") {
fsLog.Lock()
fsLog.buf.Reset()
fsLog.Unlock()
defer func() {
fsLog.Lock()
defer fsLog.Unlock()
result = fsLog.buf.String() + result
}()
}
switch td.Cmd {
case "reset":
reset(td.HasArg("strictMem"))
return ""
case "crash-clone":
crashClone = mem.CrashClone(vfs.CrashCloneCfg{UnsyncedDataPercent: 0})
return ""
case "reset-to-crash-clone":
mem = crashClone
crashClone = nil
files, err := mem.List(dir)
sort.Strings(files)
require.NoError(t, err)
return strings.Join(files, "\n")
case "batch":
b := d.NewIndexedBatch()
if err := runBatchDefineCmd(td, b); err != nil {
return err.Error()
}
if err := b.Commit(nil); err != nil {
return err.Error()
}
return ""
case "build":
if err := runBuildCmd(td, d, mem); err != nil {
return err.Error()
}
return ""
case "ingest":
if err := runIngestCmd(td, d, mem); err != nil {
return err.Error()
}
if !blockFlush {
waitForFlush()
}
return ""
case "iter":
iter, _ := d.NewIter(nil)
return runIterCmd(td, iter, true)
case "lsm":
return runLSMCmd(td, d)
case "close":
if closed {
return "already closed"
}
require.NoError(t, d.Close())
closed = true
return ""
case "ls":
files, err := mem.List(dir)
sort.Strings(files)
require.NoError(t, err)
return strings.Join(files, "\n")
case "open":
opts.ReadOnly = td.HasArg("readOnly")
var err error
d, err = Open(dir, opts)
closed = false
require.NoError(t, err)
waitForFlush()
d.TestOnlyWaitForCleaning()
return ""
case "blockFlush":
blockFlush = true
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
return ""
case "allowFlush":
blockFlush = false
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
return ""
case "flush":
d.maybeScheduleFlush()
waitForFlush()
d.TestOnlyWaitForCleaning()
return ""
case "get":
return runGetCmd(t, td, d)
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestExcise(t *testing.T) {
var mem vfs.FS
var d *DB
var flushed bool
var efos map[string]*EventuallyFileOnlySnapshot
defer func() {
for _, e := range efos {
require.NoError(t, e.Close())
}
require.NoError(t, d.Close())
}()
clearFlushed := func() {
d.mu.Lock()
defer d.mu.Unlock()
// Wait for any ongoing flushes to stop first, otherwise the
// EventListener may set flushed=true due to a flush that was already in
// progress.
for d.mu.compact.flushing {
d.mu.compact.cond.Wait()
}
flushed = false
}
var opts *Options
reset := func(blockSize int) {
for _, e := range efos {
require.NoError(t, e.Close())
}
if d != nil {
require.NoError(t, d.Close())
}
efos = make(map[string]*EventuallyFileOnlySnapshot)
mem = vfs.NewMem()
require.NoError(t, mem.MkdirAll("ext", 0755))
opts = &Options{
BlockPropertyCollectors: []func() BlockPropertyCollector{
sstable.NewTestKeysBlockPropertyCollector,
},
Comparer: testkeys.Comparer,
FS: mem,
L0CompactionThreshold: 100,
L0StopWritesThreshold: 100,
DebugCheck: DebugCheckLevels,
EventListener: &EventListener{FlushEnd: func(info FlushInfo) {
flushed = true
}},
FormatMajorVersion: FormatFlushableIngestExcises,
Logger: testLogger{t},
}
if blockSize != 0 {
opts.Levels = append(opts.Levels, LevelOptions{BlockSize: blockSize, IndexBlockSize: 32 << 10})
}
// Disable automatic compactions because otherwise we'll race with
// delete-only compactions triggered by ingesting range tombstones.
opts.DisableAutomaticCompactions = true
// Set this to true to add some testing for the virtual sstable validation
// code paths.
opts.Experimental.ValidateOnIngest = true
var err error
d, err = Open("", opts)
require.NoError(t, err)
}
reset(0 /* blockSize */)
datadriven.RunTest(t, "testdata/excise", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "reset":
var blockSize int
for i := range td.CmdArgs {
switch td.CmdArgs[i].Key {
case "tiny-blocks":
blockSize = 1
default:
return fmt.Sprintf("unexpected arg: %s", td.CmdArgs[i].Key)
}
}
reset(blockSize)
return ""
case "reopen":
require.NoError(t, d.Close())
var err error
d, err = Open("", opts)
require.NoError(t, err)
return ""
case "batch":
b := d.NewIndexedBatch()
if err := runBatchDefineCmd(td, b); err != nil {
return err.Error()
}
if err := b.Commit(nil); err != nil {
return err.Error()
}
return ""
case "build":
if err := runBuildCmd(td, d, mem); err != nil {
return err.Error()
}
return ""
case "flush":
if err := d.Flush(); err != nil {
return err.Error()
}
return ""
case "block-flush":
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
return ""
case "allow-flush":
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
return ""
case "ingest":
noWait := td.HasArg("no-wait")
if !noWait {
clearFlushed()
}
if err := runIngestCmd(td, d, mem); err != nil {
return err.Error()
}
if noWait {
return ""
}
// Wait for a possible flush.
d.mu.Lock()
for d.mu.compact.flushing {
d.mu.compact.cond.Wait()
}
d.mu.Unlock()
if flushed {
return "memtable flushed"
}
return ""
case "ingest-and-excise":
var prevFlushableIngests uint64
noWait := td.HasArg("no-wait")
if !noWait {
clearFlushed()
d.mu.Lock()
prevFlushableIngests = d.mu.versions.metrics.Flush.AsIngestCount
d.mu.Unlock()
}
if err := runIngestAndExciseCmd(td, d, mem); err != nil {
return err.Error()
}
if noWait {
return ""
}
// Wait for a possible flush.
d.mu.Lock()
for d.mu.compact.flushing {
d.mu.compact.cond.Wait()
}
flushableIngests := d.mu.versions.metrics.Flush.AsIngestCount
d.mu.Unlock()
if flushed {
if prevFlushableIngests < flushableIngests {
return "flushable ingest"
}
return "memtable flushed"
}
return ""
case "file-only-snapshot":
if len(td.CmdArgs) != 1 {
panic("insufficient args for file-only-snapshot command")
}
name := td.CmdArgs[0].Key
var keyRanges []KeyRange
for _, line := range strings.Split(td.Input, "\n") {
fields := strings.Fields(line)
if len(fields) != 2 {
return "expected two fields for file-only snapshot KeyRanges"
}
kr := KeyRange{Start: []byte(fields[0]), End: []byte(fields[1])}
keyRanges = append(keyRanges, kr)
}
s := d.NewEventuallyFileOnlySnapshot(keyRanges)
efos[name] = s
return "ok"
case "get":
return runGetCmd(t, td, d)
case "iter":
opts := &IterOptions{
KeyTypes: IterKeyTypePointsAndRanges,
}
var reader Reader = d
for i := range td.CmdArgs {
switch td.CmdArgs[i].Key {
case "range-key-masking":
opts.RangeKeyMasking = RangeKeyMasking{
Suffix: []byte(td.CmdArgs[i].Vals[0]),
Filter: func() BlockPropertyFilterMask {
return sstable.NewTestKeysMaskingFilter()
},
}
case "lower":
if len(td.CmdArgs[i].Vals) != 1 {
return fmt.Sprintf(
"%s expects at most 1 value for lower", td.Cmd)
}
opts.LowerBound = []byte(td.CmdArgs[i].Vals[0])
case "upper":
if len(td.CmdArgs[i].Vals) != 1 {
return fmt.Sprintf(
"%s expects at most 1 value for upper", td.Cmd)
}
opts.UpperBound = []byte(td.CmdArgs[i].Vals[0])
case "snapshot":
reader = efos[td.CmdArgs[i].Vals[0]]
default:
return fmt.Sprintf("unexpected argument: %s", td.CmdArgs[i].Key)
}
}
iter, _ := reader.NewIter(opts)
return runIterCmd(td, iter, true)
case "lsm":
return runLSMCmd(td, d)
case "metrics":
// The asynchronous loading of table stats can change metrics, so
// wait for all the tables' stats to be loaded.
d.mu.Lock()
d.waitTableStats()
d.mu.Unlock()
return d.Metrics().StringForTests()
case "wait-pending-table-stats":
return runTableStatsCmd(td, d)
case "excise":
ve := &versionEdit{
DeletedFiles: map[deletedFileEntry]*fileMetadata{},
}
var exciseSpan KeyRange
if len(td.CmdArgs) != 2 {
panic("insufficient args for compact command")
}
exciseSpan.Start = []byte(td.CmdArgs[0].Key)
exciseSpan.End = []byte(td.CmdArgs[1].Key)
d.mu.Lock()
d.mu.versions.logLock()
d.mu.Unlock()
current := d.mu.versions.currentVersion()
current.IterAllLevelsAndSublevels(func(iter manifest.LevelIterator, l manifest.Layer) {
for m := iter.SeekGE(d.cmp, exciseSpan.Start); m != nil && d.cmp(m.Smallest.UserKey, exciseSpan.End) < 0; m = iter.Next() {
_, err := d.excise(context.Background(), exciseSpan.UserKeyBounds(), m, ve, l.Level())
if err != nil {
td.Fatalf(t, "error when excising %s: %s", m.FileNum, err.Error())
}
}
})
d.mu.Lock()
d.mu.versions.logUnlock()
d.mu.Unlock()
return fmt.Sprintf("would excise %d files, use ingest-and-excise to excise.\n%s", len(ve.DeletedFiles), ve.DebugString(base.DefaultFormatter))
case "confirm-backing":
// Confirms that the files have the same FileBacking.
fileNums := make(map[base.FileNum]struct{})
for i := range td.CmdArgs {
fNum, err := strconv.Atoi(td.CmdArgs[i].Key)
if err != nil {
panic("invalid file number")
}
fileNums[base.FileNum(fNum)] = struct{}{}
}
d.mu.Lock()
currVersion := d.mu.versions.currentVersion()
var ptr *manifest.FileBacking
for _, level := range currVersion.Levels {
lIter := level.Iter()
for f := lIter.First(); f != nil; f = lIter.Next() {
if _, ok := fileNums[f.FileNum]; ok {
if ptr == nil {
ptr = f.FileBacking
continue
}
if f.FileBacking != ptr {
d.mu.Unlock()
return "file backings are not the same"
}
}
}
}
d.mu.Unlock()
return "file backings are the same"
case "compact":
if len(td.CmdArgs) != 2 {
panic("insufficient args for compact command")
}
l := td.CmdArgs[0].Key
r := td.CmdArgs[1].Key
err := d.Compact([]byte(l), []byte(r), false)
if err != nil {
return err.Error()
}
return ""
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func testIngestSharedImpl(
t *testing.T, createOnShared remote.CreateOnSharedStrategy, fileName string,
) {
var d, d1, d2 *DB
var efos map[string]*EventuallyFileOnlySnapshot
defer func() {
for _, e := range efos {
require.NoError(t, e.Close())
}
if d1 != nil {
require.NoError(t, d1.Close())
}
if d2 != nil {
require.NoError(t, d2.Close())
}
}()
creatorIDCounter := uint64(1)
replicateCounter := 1
var opts1, opts2 *Options
reset := func(t *testing.T) {
for _, e := range efos {
require.NoError(t, e.Close())
}
if d1 != nil {
require.NoError(t, d1.Close())
}
if d2 != nil {
require.NoError(t, d2.Close())
}
efos = make(map[string]*EventuallyFileOnlySnapshot)
sstorage := remote.NewInMem()
mem1 := vfs.NewMem()
mem2 := vfs.NewMem()
require.NoError(t, mem1.MkdirAll("ext", 0755))
require.NoError(t, mem2.MkdirAll("ext", 0755))
opts1 = &Options{
Comparer: testkeys.Comparer,
FS: mem1,
LBaseMaxBytes: 1,
L0CompactionThreshold: 100,
L0StopWritesThreshold: 100,
DebugCheck: DebugCheckLevels,
FormatMajorVersion: FormatVirtualSSTables,
Logger: testLogger{t},
}
// lel.
lel := MakeLoggingEventListener(testLogger{t})
opts1.EventListener = &lel
opts1.Experimental.RemoteStorage = remote.MakeSimpleFactory(map[remote.Locator]remote.Storage{
"": sstorage,
})
opts1.Experimental.CreateOnShared = createOnShared
opts1.Experimental.CreateOnSharedLocator = ""
// Disable automatic compactions because otherwise we'll race with
// delete-only compactions triggered by ingesting range tombstones.
opts1.DisableAutomaticCompactions = true
opts2 = &Options{}
*opts2 = *opts1
opts2.Experimental.RemoteStorage = remote.MakeSimpleFactory(map[remote.Locator]remote.Storage{
"": sstorage,