forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_test.go
1449 lines (1373 loc) · 39 KB
/
data_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"
crand "crypto/rand"
"fmt"
"io"
"math"
"math/rand"
"strconv"
"strings"
"testing"
"time"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/humanize"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/private"
"github.com/cockroachdb/pebble/internal/rangedel"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/cockroachdb/pebble/internal/testkeys"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/objstorage/remote"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/stretchr/testify/require"
)
type iterCmdOpts struct {
verboseKey bool
stats *base.InternalIteratorStats
}
type iterCmdOpt func(*iterCmdOpts)
func iterCmdVerboseKey(opts *iterCmdOpts) { opts.verboseKey = true }
func iterCmdStats(stats *base.InternalIteratorStats) iterCmdOpt {
return func(opts *iterCmdOpts) {
opts.stats = stats
}
}
func runGetCmd(t testing.TB, td *datadriven.TestData, d *DB) string {
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
td.MaybeScanArgs(t, "seq", &snap.seqNum)
var buf bytes.Buffer
for _, data := range strings.Split(td.Input, "\n") {
v, closer, err := snap.Get([]byte(data))
if err != nil {
fmt.Fprintf(&buf, "%s: %s\n", data, err)
} else {
fmt.Fprintf(&buf, "%s:%s\n", data, v)
closer.Close()
}
}
return buf.String()
}
func runIterCmd(d *datadriven.TestData, iter *Iterator, closeIter bool) string {
if closeIter {
defer func() {
if iter != nil {
iter.Close()
}
}()
}
var b bytes.Buffer
for _, line := range strings.Split(d.Input, "\n") {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
printValidityState := false
var valid bool
var validityState IterValidityState
switch parts[0] {
case "seek-ge":
if len(parts) != 2 {
return "seek-ge <key>\n"
}
valid = iter.SeekGE([]byte(parts[1]))
case "seek-prefix-ge":
if len(parts) != 2 {
return "seek-prefix-ge <key>\n"
}
valid = iter.SeekPrefixGE([]byte(parts[1]))
case "seek-lt":
if len(parts) != 2 {
return "seek-lt <key>\n"
}
valid = iter.SeekLT([]byte(parts[1]))
case "seek-ge-limit":
if len(parts) != 3 {
return "seek-ge-limit <key> <limit>\n"
}
validityState = iter.SeekGEWithLimit(
[]byte(parts[1]), []byte(parts[2]))
printValidityState = true
case "seek-lt-limit":
if len(parts) != 3 {
return "seek-lt-limit <key> <limit>\n"
}
validityState = iter.SeekLTWithLimit(
[]byte(parts[1]), []byte(parts[2]))
printValidityState = true
case "inspect":
if len(parts) != 2 {
return "inspect <field>\n"
}
field := parts[1]
switch field {
case "lastPositioningOp":
op := "?"
switch iter.lastPositioningOp {
case unknownLastPositionOp:
op = "unknown"
case seekPrefixGELastPositioningOp:
op = "seekprefixge"
case seekGELastPositioningOp:
op = "seekge"
case seekLTLastPositioningOp:
op = "seeklt"
case invalidatedLastPositionOp:
op = "invalidate"
}
fmt.Fprintf(&b, "%s=%q\n", field, op)
default:
return fmt.Sprintf("unrecognized inspect field %q\n", field)
}
continue
case "next-limit":
if len(parts) != 2 {
return "next-limit <limit>\n"
}
validityState = iter.NextWithLimit([]byte(parts[1]))
printValidityState = true
case "prev-limit":
if len(parts) != 2 {
return "prev-limit <limit>\n"
}
validityState = iter.PrevWithLimit([]byte(parts[1]))
printValidityState = true
case "first":
valid = iter.First()
case "last":
valid = iter.Last()
case "next":
valid = iter.Next()
case "next-prefix":
valid = iter.NextPrefix()
case "prev":
valid = iter.Prev()
case "set-bounds":
if len(parts) <= 1 || len(parts) > 3 {
return "set-bounds lower=<lower> upper=<upper>\n"
}
var lower []byte
var upper []byte
for _, part := range parts[1:] {
arg := strings.Split(part, "=")
switch arg[0] {
case "lower":
lower = []byte(arg[1])
case "upper":
upper = []byte(arg[1])
default:
return fmt.Sprintf("set-bounds: unknown arg: %s", arg)
}
}
iter.SetBounds(lower, upper)
valid = iter.Valid()
case "set-options":
opts := iter.opts
if _, err := parseIterOptions(&opts, &iter.opts, parts[1:]); err != nil {
return fmt.Sprintf("set-options: %s", err.Error())
}
iter.SetOptions(&opts)
valid = iter.Valid()
case "stats":
stats := iter.Stats()
// The timing is non-deterministic, so set to 0.
stats.InternalStats.BlockReadDuration = 0
fmt.Fprintf(&b, "stats: %s\n", stats.String())
continue
case "clone":
var opts CloneOptions
if len(parts) > 1 {
var iterOpts IterOptions
if foundAny, err := parseIterOptions(&iterOpts, &iter.opts, parts[1:]); err != nil {
return fmt.Sprintf("clone: %s", err.Error())
} else if foundAny {
opts.IterOptions = &iterOpts
}
for _, part := range parts[1:] {
if arg := strings.Split(part, "="); len(arg) == 2 && arg[0] == "refresh-batch" {
var err error
opts.RefreshBatchView, err = strconv.ParseBool(arg[1])
if err != nil {
return fmt.Sprintf("clone: refresh-batch: %s", err.Error())
}
}
}
}
clonedIter, err := iter.Clone(opts)
if err != nil {
fmt.Fprintf(&b, "error in clone, skipping rest of input: err=%v\n", err)
return b.String()
}
if err = iter.Close(); err != nil {
fmt.Fprintf(&b, "err=%v\n", err)
}
iter = clonedIter
case "is-using-combined":
if iter.opts.KeyTypes != IterKeyTypePointsAndRanges {
fmt.Fprintln(&b, "not configured for combined iteration")
} else if iter.lazyCombinedIter.combinedIterState.initialized {
fmt.Fprintln(&b, "using combined (non-lazy) iterator")
} else {
fmt.Fprintln(&b, "using lazy iterator")
}
continue
default:
return fmt.Sprintf("unknown op: %s", parts[0])
}
valid = valid || validityState == IterValid
if valid != iter.Valid() {
fmt.Fprintf(&b, "mismatched valid states: %t vs %t\n", valid, iter.Valid())
}
hasPoint, hasRange := iter.HasPointAndRange()
hasEither := hasPoint || hasRange
if hasEither != valid {
fmt.Fprintf(&b, "mismatched valid/HasPointAndRange states: valid=%t HasPointAndRange=(%t,%t)\n", valid, hasPoint, hasRange)
}
if valid {
validityState = IterValid
}
printIterState(&b, iter, validityState, printValidityState)
}
return b.String()
}
func parseIterOptions(
opts *IterOptions, ref *IterOptions, parts []string,
) (foundAny bool, err error) {
const usageString = "[lower=<lower>] [upper=<upper>] [key-types=point|range|both] [mask-suffix=<suffix>] [mask-filter=<bool>] [only-durable=<bool>] [table-filter=reuse|none] [point-filters=reuse|none]\n"
for _, part := range parts {
arg := strings.SplitN(part, "=", 2)
if len(arg) != 2 {
return false, errors.Newf(usageString)
}
switch arg[0] {
case "point-filters":
switch arg[1] {
case "reuse":
opts.PointKeyFilters = ref.PointKeyFilters
case "none":
opts.PointKeyFilters = nil
default:
return false, errors.Newf("unknown arg point-filter=%q:\n%s", arg[1], usageString)
}
case "lower":
opts.LowerBound = []byte(arg[1])
case "upper":
opts.UpperBound = []byte(arg[1])
case "key-types":
switch arg[1] {
case "point":
opts.KeyTypes = IterKeyTypePointsOnly
case "range":
opts.KeyTypes = IterKeyTypeRangesOnly
case "both":
opts.KeyTypes = IterKeyTypePointsAndRanges
default:
return false, errors.Newf("unknown key-type %q:\n%s", arg[1], usageString)
}
case "mask-suffix":
opts.RangeKeyMasking.Suffix = []byte(arg[1])
case "mask-filter":
opts.RangeKeyMasking.Filter = func() BlockPropertyFilterMask {
return sstable.NewTestKeysMaskingFilter()
}
case "table-filter":
switch arg[1] {
case "reuse":
opts.TableFilter = ref.TableFilter
case "none":
opts.TableFilter = nil
default:
return false, errors.Newf("unknown arg table-filter=%q:\n%s", arg[1], usageString)
}
case "only-durable":
var err error
opts.OnlyReadGuaranteedDurable, err = strconv.ParseBool(arg[1])
if err != nil {
return false, errors.Newf("cannot parse only-durable=%q: %s", arg[1], err)
}
default:
continue
}
foundAny = true
}
return foundAny, nil
}
func printIterState(
b io.Writer, iter *Iterator, validity IterValidityState, printValidityState bool,
) {
var validityStateStr string
if printValidityState {
switch validity {
case IterExhausted:
validityStateStr = " exhausted"
case IterValid:
validityStateStr = " valid"
case IterAtLimit:
validityStateStr = " at-limit"
}
}
if err := iter.Error(); err != nil {
fmt.Fprintf(b, "err=%v\n", err)
} else if validity == IterValid {
switch {
case iter.opts.pointKeys():
hasPoint, hasRange := iter.HasPointAndRange()
fmt.Fprintf(b, "%s:%s (", iter.Key(), validityStateStr)
if hasPoint {
fmt.Fprintf(b, "%s, ", iter.Value())
} else {
fmt.Fprint(b, "., ")
}
if hasRange {
start, end := iter.RangeBounds()
fmt.Fprintf(b, "[%s-%s)", formatASCIIKey(start), formatASCIIKey(end))
writeRangeKeys(b, iter)
} else {
fmt.Fprint(b, ".")
}
if iter.RangeKeyChanged() {
fmt.Fprint(b, " UPDATED")
}
fmt.Fprint(b, ")")
default:
if iter.Valid() {
hasPoint, hasRange := iter.HasPointAndRange()
if hasPoint || !hasRange {
panic(fmt.Sprintf("pebble: unexpected HasPointAndRange (%t, %t)", hasPoint, hasRange))
}
start, end := iter.RangeBounds()
fmt.Fprintf(b, "%s [%s-%s)", iter.Key(), formatASCIIKey(start), formatASCIIKey(end))
writeRangeKeys(b, iter)
} else {
fmt.Fprint(b, ".")
}
if iter.RangeKeyChanged() {
fmt.Fprint(b, " UPDATED")
}
}
fmt.Fprintln(b)
} else {
fmt.Fprintf(b, ".%s\n", validityStateStr)
}
}
func formatASCIIKey(b []byte) string {
if bytes.IndexFunc(b, func(r rune) bool { return r < 'A' || r > 'z' }) != -1 {
// This key is not just ASCII letters. Quote it.
return fmt.Sprintf("%q", b)
}
return string(b)
}
func writeRangeKeys(b io.Writer, iter *Iterator) {
rangeKeys := iter.RangeKeys()
for j := 0; j < len(rangeKeys); j++ {
if j > 0 {
fmt.Fprint(b, ",")
}
fmt.Fprintf(b, " %s=%s", rangeKeys[j].Suffix, rangeKeys[j].Value)
}
}
func runInternalIterCmd(
t *testing.T, d *datadriven.TestData, iter internalIterator, opts ...iterCmdOpt,
) string {
var o iterCmdOpts
for _, opt := range opts {
opt(&o)
}
getKV := func(key *InternalKey, val LazyValue) (*InternalKey, []byte) {
v, _, err := val.Value(nil)
require.NoError(t, err)
return key, v
}
var b bytes.Buffer
var prefix []byte
for _, line := range strings.Split(d.Input, "\n") {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
var key *InternalKey
var value []byte
switch parts[0] {
case "seek-ge":
if len(parts) < 2 || len(parts) > 3 {
return "seek-ge <key> [<try-seek-using-next>]\n"
}
prefix = nil
var flags base.SeekGEFlags
if len(parts) == 3 {
if trySeekUsingNext, err := strconv.ParseBool(parts[2]); err != nil {
return err.Error()
} else if trySeekUsingNext {
flags = flags.EnableTrySeekUsingNext()
}
}
key, value = getKV(iter.SeekGE([]byte(strings.TrimSpace(parts[1])), flags))
case "seek-prefix-ge":
if len(parts) != 2 && len(parts) != 3 {
return "seek-prefix-ge <key> [<try-seek-using-next>]\n"
}
prefix = []byte(strings.TrimSpace(parts[1]))
var flags base.SeekGEFlags
if len(parts) == 3 {
if trySeekUsingNext, err := strconv.ParseBool(parts[2]); err != nil {
return err.Error()
} else if trySeekUsingNext {
flags = flags.EnableTrySeekUsingNext()
}
}
key, value = getKV(iter.SeekPrefixGE(prefix, prefix /* key */, flags))
case "seek-lt":
if len(parts) != 2 {
return "seek-lt <key>\n"
}
prefix = nil
key, value = getKV(iter.SeekLT([]byte(strings.TrimSpace(parts[1])), base.SeekLTFlagsNone))
case "first":
prefix = nil
key, value = getKV(iter.First())
case "last":
prefix = nil
key, value = getKV(iter.Last())
case "next":
key, value = getKV(iter.Next())
case "prev":
key, value = getKV(iter.Prev())
case "set-bounds":
if len(parts) <= 1 || len(parts) > 3 {
return "set-bounds lower=<lower> upper=<upper>\n"
}
var lower []byte
var upper []byte
for _, part := range parts[1:] {
arg := strings.Split(strings.TrimSpace(part), "=")
switch arg[0] {
case "lower":
lower = []byte(arg[1])
case "upper":
upper = []byte(arg[1])
default:
return fmt.Sprintf("set-bounds: unknown arg: %s", arg)
}
}
iter.SetBounds(lower, upper)
continue
case "stats":
if o.stats != nil {
// The timing is non-deterministic, so set to 0.
o.stats.BlockReadDuration = 0
fmt.Fprintf(&b, "%+v\n", *o.stats)
}
continue
case "reset-stats":
if o.stats != nil {
*o.stats = base.InternalIteratorStats{}
}
continue
default:
return fmt.Sprintf("unknown op: %s", parts[0])
}
if key != nil {
if o.verboseKey {
fmt.Fprintf(&b, "%s:%s\n", key, value)
} else {
fmt.Fprintf(&b, "%s:%s\n", key.UserKey, value)
}
} else if err := iter.Error(); err != nil {
fmt.Fprintf(&b, "err=%v\n", err)
} else {
fmt.Fprintf(&b, ".\n")
}
}
return b.String()
}
func runBatchDefineCmd(d *datadriven.TestData, b *Batch) error {
for _, line := range strings.Split(d.Input, "\n") {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
if parts[1] == `<nil>` {
parts[1] = ""
}
var err error
switch parts[0] {
case "set":
if len(parts) != 3 {
return errors.Errorf("%s expects 2 arguments", parts[0])
}
err = b.Set([]byte(parts[1]), []byte(parts[2]), nil)
case "del":
if len(parts) != 2 {
return errors.Errorf("%s expects 1 argument", parts[0])
}
err = b.Delete([]byte(parts[1]), nil)
case "del-sized":
if len(parts) != 3 {
return errors.Errorf("%s expects 1 argument", parts[0])
}
var valSize uint64
valSize, err = strconv.ParseUint(parts[2], 10, 32)
if err != nil {
return err
}
err = b.DeleteSized([]byte(parts[1]), uint32(valSize), nil)
case "singledel":
if len(parts) != 2 {
return errors.Errorf("%s expects 1 argument", parts[0])
}
err = b.SingleDelete([]byte(parts[1]), nil)
case "del-range":
if len(parts) != 3 {
return errors.Errorf("%s expects 2 arguments", parts[0])
}
err = b.DeleteRange([]byte(parts[1]), []byte(parts[2]), nil)
case "merge":
if len(parts) != 3 {
return errors.Errorf("%s expects 2 arguments", parts[0])
}
err = b.Merge([]byte(parts[1]), []byte(parts[2]), nil)
case "range-key-set":
if len(parts) != 5 {
return errors.Errorf("%s expects 4 arguments", parts[0])
}
err = b.RangeKeySet(
[]byte(parts[1]),
[]byte(parts[2]),
[]byte(parts[3]),
[]byte(parts[4]),
nil)
case "range-key-unset":
if len(parts) != 4 {
return errors.Errorf("%s expects 3 arguments", parts[0])
}
err = b.RangeKeyUnset(
[]byte(parts[1]),
[]byte(parts[2]),
[]byte(parts[3]),
nil)
case "range-key-del":
if len(parts) != 3 {
return errors.Errorf("%s expects 2 arguments", parts[0])
}
err = b.RangeKeyDelete(
[]byte(parts[1]),
[]byte(parts[2]),
nil)
default:
return errors.Errorf("unknown op: %s", parts[0])
}
if err != nil {
return err
}
}
return nil
}
func runBuildRemoteCmd(td *datadriven.TestData, d *DB, storage remote.Storage) error {
b := d.NewIndexedBatch()
if err := runBatchDefineCmd(td, b); err != nil {
return err
}
if len(td.CmdArgs) < 1 {
return errors.New("build <path>: argument missing")
}
path := td.CmdArgs[0].String()
// Override table format, if provided.
tableFormat := d.opts.FormatMajorVersion.MaxTableFormat()
for _, cmdArg := range td.CmdArgs[1:] {
switch cmdArg.Key {
case "format":
switch cmdArg.Vals[0] {
case "leveldb":
tableFormat = sstable.TableFormatLevelDB
case "rocksdbv2":
tableFormat = sstable.TableFormatRocksDBv2
case "pebblev1":
tableFormat = sstable.TableFormatPebblev1
case "pebblev2":
tableFormat = sstable.TableFormatPebblev2
case "pebblev3":
tableFormat = sstable.TableFormatPebblev3
case "pebblev4":
tableFormat = sstable.TableFormatPebblev4
default:
return errors.Errorf("unknown format string %s", cmdArg.Vals[0])
}
}
}
writeOpts := d.opts.MakeWriterOptions(0 /* level */, tableFormat)
f, err := storage.CreateObject(path)
if err != nil {
return err
}
w := sstable.NewWriter(objstorageprovider.NewRemoteWritable(f), writeOpts)
iter := b.newInternalIter(nil)
for key, val := iter.First(); key != nil; key, val = iter.Next() {
tmp := *key
tmp.SetSeqNum(0)
if err := w.Add(tmp, val.InPlaceValue()); err != nil {
return err
}
}
if err := iter.Close(); err != nil {
return err
}
if rdi := b.newRangeDelIter(nil, math.MaxUint64); rdi != nil {
for s := rdi.First(); s != nil; s = rdi.Next() {
err := rangedel.Encode(s, func(k base.InternalKey, v []byte) error {
k.SetSeqNum(0)
return w.Add(k, v)
})
if err != nil {
return err
}
}
}
if rki := b.newRangeKeyIter(nil, math.MaxUint64); rki != nil {
for s := rki.First(); s != nil; s = rki.Next() {
for _, k := range s.Keys {
var err error
switch k.Kind() {
case base.InternalKeyKindRangeKeySet:
err = w.RangeKeySet(s.Start, s.End, k.Suffix, k.Value)
case base.InternalKeyKindRangeKeyUnset:
err = w.RangeKeyUnset(s.Start, s.End, k.Suffix)
case base.InternalKeyKindRangeKeyDelete:
err = w.RangeKeyDelete(s.Start, s.End)
default:
panic("not a range key")
}
if err != nil {
return err
}
}
}
}
return w.Close()
}
func runBuildCmd(td *datadriven.TestData, d *DB, fs vfs.FS) error {
b := d.NewIndexedBatch()
if err := runBatchDefineCmd(td, b); err != nil {
return err
}
if len(td.CmdArgs) < 1 {
return errors.New("build <path>: argument missing")
}
path := td.CmdArgs[0].String()
// Override table format, if provided.
tableFormat := d.opts.FormatMajorVersion.MaxTableFormat()
for _, cmdArg := range td.CmdArgs[1:] {
switch cmdArg.Key {
case "format":
switch cmdArg.Vals[0] {
case "leveldb":
tableFormat = sstable.TableFormatLevelDB
case "rocksdbv2":
tableFormat = sstable.TableFormatRocksDBv2
case "pebblev1":
tableFormat = sstable.TableFormatPebblev1
case "pebblev2":
tableFormat = sstable.TableFormatPebblev2
case "pebblev3":
tableFormat = sstable.TableFormatPebblev3
case "pebblev4":
tableFormat = sstable.TableFormatPebblev4
default:
return errors.Errorf("unknown format string %s", cmdArg.Vals[0])
}
}
}
writeOpts := d.opts.MakeWriterOptions(0 /* level */, tableFormat)
f, err := fs.Create(path)
if err != nil {
return err
}
w := sstable.NewWriter(objstorageprovider.NewFileWritable(f), writeOpts)
iter := b.newInternalIter(nil)
for key, val := iter.First(); key != nil; key, val = iter.Next() {
tmp := *key
tmp.SetSeqNum(0)
if err := w.Add(tmp, val.InPlaceValue()); err != nil {
return err
}
}
if err := iter.Close(); err != nil {
return err
}
if rdi := b.newRangeDelIter(nil, math.MaxUint64); rdi != nil {
for s := rdi.First(); s != nil; s = rdi.Next() {
err := rangedel.Encode(s, func(k base.InternalKey, v []byte) error {
k.SetSeqNum(0)
return w.Add(k, v)
})
if err != nil {
return err
}
}
}
if rki := b.newRangeKeyIter(nil, math.MaxUint64); rki != nil {
for s := rki.First(); s != nil; s = rki.Next() {
for _, k := range s.Keys {
var err error
switch k.Kind() {
case base.InternalKeyKindRangeKeySet:
err = w.RangeKeySet(s.Start, s.End, k.Suffix, k.Value)
case base.InternalKeyKindRangeKeyUnset:
err = w.RangeKeyUnset(s.Start, s.End, k.Suffix)
case base.InternalKeyKindRangeKeyDelete:
err = w.RangeKeyDelete(s.Start, s.End)
default:
panic("not a range key")
}
if err != nil {
return err
}
}
}
}
return w.Close()
}
func runCompactCmd(td *datadriven.TestData, d *DB) error {
if len(td.CmdArgs) > 4 {
return errors.Errorf("%s expects at most four arguments", td.Cmd)
}
parts := strings.Split(td.CmdArgs[0].Key, "-")
if len(parts) != 2 {
return errors.Errorf("expected <begin>-<end>: %s", td.Input)
}
parallelize := td.HasArg("parallel")
if len(td.CmdArgs) >= 2 && strings.HasPrefix(td.CmdArgs[1].Key, "L") {
levelString := td.CmdArgs[1].String()
iStart := base.MakeInternalKey([]byte(parts[0]), InternalKeySeqNumMax, InternalKeyKindMax)
iEnd := base.MakeInternalKey([]byte(parts[1]), 0, 0)
if levelString[0] != 'L' {
return errors.Errorf("expected L<n>: %s", levelString)
}
level, err := strconv.Atoi(levelString[1:])
if err != nil {
return err
}
return d.manualCompact(iStart.UserKey, iEnd.UserKey, level, parallelize)
}
return d.Compact([]byte(parts[0]), []byte(parts[1]), parallelize)
}
// runDBDefineCmd prepares a database state, returning the opened
// database with the initialized state.
//
// The command accepts input describing memtables and sstables to
// construct. Each new table is indicated by a line containing the
// level of the next table to build (eg, "L6"), or "mem" to build
// a memtable. Each subsequent line contains a new key-value pair.
//
// Point keys and range deletions should be encoded as the
// InternalKey's string representation, as understood by
// ParseInternalKey, followed a colon and the corresponding value.
//
// b.SET.50:foo
// c.DEL.20
//
// Range keys may be encoded by prefixing the line with `rangekey:`,
// followed by the keyspan.Span string representation, as understood
// by keyspan.ParseSpan.
//
// rangekey:b-d:{(#5,RANGEKEYSET,@2,foo)}
//
// # Mechanics
//
// runDBDefineCmd works by simulating a flush for every file written.
// Keys are written to a memtable. When a file is complete, the table
// is flushed to physical files through manually invoking runCompaction.
// The resulting version edit is then manipulated to write the files
// to the indicated level.
//
// Because of it's low-level manipulation, runDBDefineCmd does allow the
// creation of invalid database states. If opts.DebugCheck is set, the
// level checker should detect the invalid state.
func runDBDefineCmd(td *datadriven.TestData, opts *Options) (*DB, error) {
opts = opts.EnsureDefaults()
opts.FS = vfs.NewMem()
var snapshots []uint64
var levelMaxBytes map[int]int64
for _, arg := range td.CmdArgs {
switch arg.Key {
case "target-file-sizes":
opts.Levels = make([]LevelOptions, len(arg.Vals))
for i := range arg.Vals {
size, err := strconv.ParseInt(arg.Vals[i], 10, 64)
if err != nil {
return nil, err
}
opts.Levels[i].TargetFileSize = size
}
case "snapshots":
snapshots = make([]uint64, len(arg.Vals))
for i := range arg.Vals {
seqNum, err := strconv.ParseUint(arg.Vals[i], 10, 64)
if err != nil {
return nil, err
}
snapshots[i] = seqNum
if i > 0 && snapshots[i] < snapshots[i-1] {
return nil, errors.New("Snapshots must be in ascending order")
}
}
case "lbase-max-bytes":
lbaseMaxBytes, err := strconv.ParseInt(arg.Vals[0], 10, 64)
if err != nil {
return nil, err
}
opts.LBaseMaxBytes = lbaseMaxBytes
case "level-max-bytes":
levelMaxBytes = map[int]int64{}
for i := range arg.Vals {
j := strings.Index(arg.Vals[i], ":")
levelStr := strings.TrimSpace(arg.Vals[i][:j])
level, err := strconv.Atoi(levelStr[1:])
if err != nil {
return nil, err
}
size, err := strconv.ParseInt(strings.TrimSpace(arg.Vals[i][j+1:]), 10, 64)
if err != nil {
return nil, err
}
levelMaxBytes[level] = size
}
case "auto-compactions":
switch arg.Vals[0] {
case "off":
opts.DisableAutomaticCompactions = true
case "on":
opts.DisableAutomaticCompactions = false
default:
return nil, errors.Errorf("Unrecognized %q %q arg value: %q", td.Cmd, arg.Key, arg.Vals[0])
}
case "enable-table-stats":
enable, err := strconv.ParseBool(arg.Vals[0])
if err != nil {
return nil, errors.Errorf("%s: could not parse %q as bool: %s", td.Cmd, arg.Vals[0], err)
}
opts.private.disableTableStats = !enable
case "block-size":
size, err := strconv.Atoi(arg.Vals[0])
if err != nil {
return nil, err
}
for _, levelOpts := range opts.Levels {
levelOpts.BlockSize = size
}
case "format-major-version":
fmv, err := strconv.Atoi(arg.Vals[0])
if err != nil {
return nil, err
}
opts.FormatMajorVersion = FormatMajorVersion(fmv)
case "disable-multi-level":
opts.Experimental.MultiLevelCompactionHeuristic = NoMultiLevel{}
}
}
// This is placed after the argument parsing above, because the arguments
// to define should be parsed even if td.Input is empty.
if td.Input == "" {
// Empty LSM.
d, err := Open("", opts)
if err != nil {
return nil, err
}
d.mu.Lock()
for i := range snapshots {
s := &Snapshot{db: d}
s.seqNum = snapshots[i]
d.mu.snapshots.pushBack(s)
}
for l, maxBytes := range levelMaxBytes {
d.mu.versions.picker.(*compactionPickerByScore).levelMaxBytes[l] = maxBytes
}
d.mu.Unlock()
return d, nil
}
d, err := Open("", opts)
if err != nil {
return nil, err
}
d.mu.Lock()
d.mu.versions.dynamicBaseLevel = false
for i := range snapshots {
s := &Snapshot{db: d}
s.seqNum = snapshots[i]
d.mu.snapshots.pushBack(s)
}
defer d.mu.Unlock()
var mem *memTable
var start, end *base.InternalKey
ve := &versionEdit{}
level := -1
maybeFlush := func() error {
if level < 0 {
return nil
}
toFlush := flushableList{{
flushable: mem,
flushed: make(chan struct{}),
}}
c := newFlush(d.opts, d.mu.versions.currentVersion(),
d.mu.versions.picker.getBaseLevel(), toFlush, time.Now())
c.disableSpanElision = true
// NB: define allows the test to exactly specify which keys go
// into which sstables. If the test has a small target file
// size to test grandparent limits, etc, the maxOutputFileSize
// can cause splitting /within/ the bounds specified to the
// test. Ignore the target size here, and split only according
// to the user-defined boundaries.
c.maxOutputFileSize = math.MaxUint64
newVE, _, _, err := d.runCompaction(0, c)
if err != nil {
return err
}
largestSeqNum := d.mu.versions.logSeqNum.Load()
for _, f := range newVE.NewFiles {
if start != nil {
f.Meta.SmallestPointKey = *start
f.Meta.Smallest = *start
}
if end != nil {
f.Meta.LargestPointKey = *end
f.Meta.Largest = *end
}
if largestSeqNum <= f.Meta.LargestSeqNum {
largestSeqNum = f.Meta.LargestSeqNum + 1
}
ve.NewFiles = append(ve.NewFiles, newFileEntry{
Level: level,
Meta: f.Meta,
})
}
// The committed keys were never written to the WAL, so neither
// the logSeqNum nor the commit pipeline's visibleSeqNum have
// been ratcheted. Manually ratchet them to the largest sequence
// number committed to ensure iterators opened from the database
// correctly observe the committed keys.