forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator_test.go
2911 lines (2673 loc) · 79.5 KB
/
iterator_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 2013 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"
"flag"
"fmt"
"io"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/bytealloc"
"github.com/cockroachdb/pebble/internal/invalidating"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/manifest"
"github.com/cockroachdb/pebble/internal/testkeys"
"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"
)
var testKeyValuePairs = []string{
"10:10",
"11:11",
"12:12",
"13:13",
"14:14",
"15:15",
"16:16",
"17:17",
"18:18",
"19:19",
}
type fakeIter struct {
lower []byte
upper []byte
keys []InternalKey
vals [][]byte
index int
valid bool
closeErr error
}
// fakeIter implements the base.InternalIterator interface.
var _ base.InternalIterator = (*fakeIter)(nil)
func fakeIkey(s string) InternalKey {
j := strings.Index(s, ":")
seqNum, err := strconv.Atoi(s[j+1:])
if err != nil {
panic(err)
}
return base.MakeInternalKey([]byte(s[:j]), uint64(seqNum), InternalKeyKindSet)
}
func newFakeIterator(closeErr error, keys ...string) *fakeIter {
ikeys := make([]InternalKey, len(keys))
for i, k := range keys {
ikeys[i] = fakeIkey(k)
}
return &fakeIter{
keys: ikeys,
index: 0,
valid: len(ikeys) > 0,
closeErr: closeErr,
}
}
func (f *fakeIter) String() string {
return "fake"
}
func (f *fakeIter) SeekGE(key []byte, flags base.SeekGEFlags) (*InternalKey, base.LazyValue) {
f.valid = false
for f.index = 0; f.index < len(f.keys); f.index++ {
if DefaultComparer.Compare(key, f.key().UserKey) <= 0 {
if f.upper != nil && DefaultComparer.Compare(f.upper, f.key().UserKey) <= 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
}
return nil, base.LazyValue{}
}
func (f *fakeIter) SeekPrefixGE(
prefix, key []byte, flags base.SeekGEFlags,
) (*base.InternalKey, base.LazyValue) {
return f.SeekGE(key, flags)
}
func (f *fakeIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {
f.valid = false
for f.index = len(f.keys) - 1; f.index >= 0; f.index-- {
if DefaultComparer.Compare(key, f.key().UserKey) > 0 {
if f.lower != nil && DefaultComparer.Compare(f.lower, f.key().UserKey) > 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
}
return nil, base.LazyValue{}
}
func (f *fakeIter) First() (*InternalKey, base.LazyValue) {
f.valid = false
f.index = -1
if key, _ := f.Next(); key == nil {
return nil, base.LazyValue{}
}
if f.upper != nil && DefaultComparer.Compare(f.upper, f.key().UserKey) <= 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
func (f *fakeIter) Last() (*InternalKey, base.LazyValue) {
f.valid = false
f.index = len(f.keys)
if key, _ := f.Prev(); key == nil {
return nil, base.LazyValue{}
}
if f.lower != nil && DefaultComparer.Compare(f.lower, f.key().UserKey) > 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
func (f *fakeIter) Next() (*InternalKey, base.LazyValue) {
f.valid = false
if f.index == len(f.keys) {
return nil, base.LazyValue{}
}
f.index++
if f.index == len(f.keys) {
return nil, base.LazyValue{}
}
if f.upper != nil && DefaultComparer.Compare(f.upper, f.key().UserKey) <= 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
func (f *fakeIter) Prev() (*InternalKey, base.LazyValue) {
f.valid = false
if f.index < 0 {
return nil, base.LazyValue{}
}
f.index--
if f.index < 0 {
return nil, base.LazyValue{}
}
if f.lower != nil && DefaultComparer.Compare(f.lower, f.key().UserKey) > 0 {
return nil, base.LazyValue{}
}
f.valid = true
return f.Key(), f.Value()
}
func (f *fakeIter) NextPrefix(succKey []byte) (*InternalKey, base.LazyValue) {
return f.SeekGE(succKey, base.SeekGEFlagsNone)
}
// key returns the current Key the iterator is positioned at regardless of the
// value of f.valid.
func (f *fakeIter) key() *InternalKey {
return &f.keys[f.index]
}
func (f *fakeIter) Key() *InternalKey {
if f.valid {
return &f.keys[f.index]
}
// It is invalid to call Key() when Valid() returns false. Rather than
// returning nil here which would technically be more correct, return a
// non-nil key which is the behavior of some InternalIterator
// implementations. This provides better testing of users of
// InternalIterators.
if f.index < 0 {
return &f.keys[0]
}
return &f.keys[len(f.keys)-1]
}
func (f *fakeIter) Value() base.LazyValue {
if f.index >= 0 && f.index < len(f.vals) {
return base.MakeInPlaceValue(f.vals[f.index])
}
return base.LazyValue{}
}
func (f *fakeIter) Valid() bool {
return f.index >= 0 && f.index < len(f.keys) && f.valid
}
func (f *fakeIter) Error() error {
return f.closeErr
}
func (f *fakeIter) Close() error {
return f.closeErr
}
func (f *fakeIter) SetBounds(lower, upper []byte) {
f.lower = lower
f.upper = upper
}
// testIterator tests creating a combined iterator from a number of sub-
// iterators. newFunc is a constructor function. splitFunc returns a random
// split of the testKeyValuePairs slice such that walking a combined iterator
// over those splits should recover the original key/value pairs in order.
func testIterator(
t *testing.T,
newFunc func(...internalIterator) internalIterator,
splitFunc func(r *rand.Rand) [][]string,
) {
// Test pre-determined sub-iterators. The sub-iterators are designed
// so that the combined key/value pair order is the same whether the
// combined iterator is concatenating or merging.
testCases := []struct {
desc string
iters []internalIterator
want string
}{
{
"one sub-iterator",
[]internalIterator{
newFakeIterator(nil, "e:1", "w:2"),
},
"<e:1><w:2>.",
},
{
"two sub-iterators",
[]internalIterator{
newFakeIterator(nil, "a0:0"),
newFakeIterator(nil, "b1:1", "b2:2"),
},
"<a0:0><b1:1><b2:2>.",
},
{
"empty sub-iterators",
[]internalIterator{
newFakeIterator(nil),
newFakeIterator(nil),
newFakeIterator(nil),
},
".",
},
{
"sub-iterator errors",
[]internalIterator{
newFakeIterator(nil, "a0:0", "a1:1"),
newFakeIterator(errors.New("the sky is falling"), "b2:2", "b3:3", "b4:4"),
newFakeIterator(errors.New("run for your lives"), "c5:5", "c6:6"),
},
"<a0:0><a1:1><b2:2><b3:3><b4:4>err=the sky is falling",
},
}
for _, tc := range testCases {
var b bytes.Buffer
iter := invalidating.NewIter(newFunc(tc.iters...))
for key, _ := iter.First(); key != nil; key, _ = iter.Next() {
fmt.Fprintf(&b, "<%s:%d>", key.UserKey, key.SeqNum())
}
if err := iter.Close(); err != nil {
fmt.Fprintf(&b, "err=%v", err)
} else {
b.WriteByte('.')
}
if got := b.String(); got != tc.want {
t.Errorf("%s:\ngot %q\nwant %q", tc.desc, got, tc.want)
}
}
// Test randomly generated sub-iterators.
r := rand.New(rand.NewSource(0))
for i, nBad := 0, 0; i < 1000; i++ {
bad := false
splits := splitFunc(r)
iters := make([]internalIterator, len(splits))
for i, split := range splits {
iters[i] = newFakeIterator(nil, split...)
}
iter := newInternalIterAdapter(invalidating.NewIter(newFunc(iters...)))
iter.First()
j := 0
for ; iter.Valid() && j < len(testKeyValuePairs); j++ {
got := fmt.Sprintf("%s:%d", iter.Key().UserKey, iter.Key().SeqNum())
want := testKeyValuePairs[j]
if got != want {
bad = true
t.Errorf("random splits: i=%d, j=%d: got %q, want %q", i, j, got, want)
}
iter.Next()
}
if iter.Valid() {
bad = true
t.Errorf("random splits: i=%d, j=%d: iter was not exhausted", i, j)
}
if j != len(testKeyValuePairs) {
bad = true
t.Errorf("random splits: i=%d, j=%d: want j=%d", i, j, len(testKeyValuePairs))
return
}
if err := iter.Close(); err != nil {
bad = true
t.Errorf("random splits: i=%d, j=%d: %v", i, j, err)
}
if bad {
nBad++
if nBad == 10 {
t.Fatal("random splits: too many errors; stopping")
}
}
}
}
// deletableSumValueMerger computes the sum of its arguments,
// but transforms a zero sum into a non-existent entry.
type deletableSumValueMerger struct {
sum int64
}
func newDeletableSumValueMerger(key, value []byte) (ValueMerger, error) {
m := &deletableSumValueMerger{}
return m, m.MergeNewer(value)
}
func (m *deletableSumValueMerger) parseAndCalculate(value []byte) error {
v, err := strconv.ParseInt(string(value), 10, 64)
if err == nil {
m.sum += v
}
return err
}
func (m *deletableSumValueMerger) MergeNewer(value []byte) error {
return m.parseAndCalculate(value)
}
func (m *deletableSumValueMerger) MergeOlder(value []byte) error {
return m.parseAndCalculate(value)
}
func (m *deletableSumValueMerger) Finish(includesBase bool) ([]byte, io.Closer, error) {
if m.sum == 0 {
return nil, nil, nil
}
return []byte(strconv.FormatInt(m.sum, 10)), nil, nil
}
func (m *deletableSumValueMerger) DeletableFinish(
includesBase bool,
) ([]byte, bool, io.Closer, error) {
value, closer, err := m.Finish(includesBase)
return value, len(value) == 0, closer, err
}
func TestIterator(t *testing.T) {
var merge Merge
var keys []InternalKey
var vals [][]byte
newIter := func(seqNum uint64, opts IterOptions) *Iterator {
if merge == nil {
merge = DefaultMerger.Merge
}
wrappedMerge := func(key, value []byte) (ValueMerger, error) {
if len(key) == 0 {
t.Fatalf("an empty key is passed into Merge")
}
return merge(key, value)
}
it := &Iterator{
opts: opts,
comparer: *testkeys.Comparer,
merge: wrappedMerge,
}
// NB: Use a mergingIter to filter entries newer than seqNum.
iter := newMergingIter(nil /* logger */, &it.stats.InternalStats, it.cmp, it.split, &fakeIter{
lower: opts.GetLowerBound(),
upper: opts.GetUpperBound(),
keys: keys,
vals: vals,
})
iter.snapshot = seqNum
// NB: This Iterator cannot be cloned since it is not constructed
// with a readState. It suffices for this test.
it.iter = invalidating.NewIter(iter)
return it
}
datadriven.RunTest(t, "testdata/iterator", func(t *testing.T, d *datadriven.TestData) string {
switch d.Cmd {
case "define":
merge = nil
if arg, ok := d.Arg("merger"); ok && len(arg.Vals[0]) > 0 && arg.Vals[0] == "deletable" {
merge = newDeletableSumValueMerger
}
keys = keys[:0]
vals = vals[:0]
for _, key := range strings.Split(d.Input, "\n") {
j := strings.Index(key, ":")
keys = append(keys, base.ParseInternalKey(key[:j]))
vals = append(vals, []byte(key[j+1:]))
}
return ""
case "iter":
var seqNum uint64
var opts IterOptions
d.MaybeScanArgs(t, "seq", &seqNum)
var lower, upper string
if d.MaybeScanArgs(t, "lower", &lower) {
opts.LowerBound = []byte(lower)
}
if d.MaybeScanArgs(t, "upper", &upper) {
opts.UpperBound = []byte(upper)
}
iter := newIter(seqNum, opts)
iterOutput := runIterCmd(d, iter, true)
stats := iter.Stats()
return fmt.Sprintf("%sstats: %s\n", iterOutput, stats.String())
default:
return fmt.Sprintf("unknown command: %s", d.Cmd)
}
})
}
type minSeqNumPropertyCollector struct {
minSeqNum uint64
}
func (c *minSeqNumPropertyCollector) Add(key InternalKey, value []byte) error {
if c.minSeqNum == 0 || c.minSeqNum > key.SeqNum() {
c.minSeqNum = key.SeqNum()
}
return nil
}
func (c *minSeqNumPropertyCollector) Finish(userProps map[string]string) error {
userProps["test.min-seq-num"] = fmt.Sprint(c.minSeqNum)
return nil
}
func (c *minSeqNumPropertyCollector) Name() string {
return "minSeqNumPropertyCollector"
}
func TestReadSampling(t *testing.T) {
var d *DB
defer func() {
if d != nil {
require.NoError(t, d.Close())
}
}()
var iter *Iterator
defer func() {
if iter != nil {
require.NoError(t, iter.Close())
}
}()
datadriven.RunTest(t, "testdata/iterator_read_sampling", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "define":
if iter != nil {
if err := iter.Close(); err != nil {
return err.Error()
}
}
if d != nil {
if err := d.Close(); err != nil {
return err.Error()
}
}
opts := &Options{}
opts.TablePropertyCollectors = append(opts.TablePropertyCollectors,
func() TablePropertyCollector {
return &minSeqNumPropertyCollector{}
})
var err error
if d, err = runDBDefineCmd(td, opts); err != nil {
return err.Error()
}
d.mu.Lock()
// Disable the "dynamic base level" code for this test.
// d.mu.versions.picker.forceBaseLevel1()
s := d.mu.versions.currentVersion().String()
d.mu.Unlock()
return s
case "set":
if d == nil {
return fmt.Sprintf("%s: db is not defined", td.Cmd)
}
var allowedSeeks int64
td.ScanArgs(t, "allowed-seeks", &allowedSeeks)
d.mu.Lock()
for _, l := range d.mu.versions.currentVersion().Levels {
l.Slice().Each(func(f *fileMetadata) {
f.AllowedSeeks.Store(allowedSeeks)
})
}
d.mu.Unlock()
return ""
case "show":
if d == nil {
return fmt.Sprintf("%s: db is not defined", td.Cmd)
}
var fileNum int64
for _, arg := range td.CmdArgs {
if len(arg.Vals) != 2 {
return fmt.Sprintf("%s: %s=<value>", td.Cmd, arg.Key)
}
switch arg.Key {
case "allowed-seeks":
var err error
fileNum, err = strconv.ParseInt(arg.Vals[0], 10, 64)
if err != nil {
return err.Error()
}
}
}
var foundAllowedSeeks int64 = -1
d.mu.Lock()
for _, l := range d.mu.versions.currentVersion().Levels {
l.Slice().Each(func(f *fileMetadata) {
if f.FileNum == base.FileNum(fileNum) {
actualAllowedSeeks := f.AllowedSeeks.Load()
foundAllowedSeeks = actualAllowedSeeks
}
})
}
d.mu.Unlock()
if foundAllowedSeeks == -1 {
return fmt.Sprintf("invalid file num: %d", fileNum)
}
return fmt.Sprintf("%d", foundAllowedSeeks)
case "iter":
if iter == nil || iter.iter == nil {
// TODO(peter): runDBDefineCmd doesn't properly update the visible
// sequence number. So we have to use a snapshot with a very large
// sequence number, otherwise the DB appears empty.
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
iter, _ = snap.NewIter(nil)
iter.readSampling.forceReadSampling = true
}
return runIterCmd(td, iter, false)
case "read-compactions":
if d == nil {
return fmt.Sprintf("%s: db is not defined", td.Cmd)
}
d.mu.Lock()
var sb strings.Builder
if d.mu.compact.readCompactions.size == 0 {
sb.WriteString("(none)")
}
for i := 0; i < d.mu.compact.readCompactions.size; i++ {
rc := d.mu.compact.readCompactions.at(i)
sb.WriteString(fmt.Sprintf("(level: %d, start: %s, end: %s)\n", rc.level, string(rc.start), string(rc.end)))
}
d.mu.Unlock()
return sb.String()
case "iter-read-compactions":
if iter == nil {
return fmt.Sprintf("%s: iter is not defined", td.Cmd)
}
var sb strings.Builder
if iter.readSampling.pendingCompactions.size == 0 {
sb.WriteString("(none)")
}
for i := 0; i < iter.readSampling.pendingCompactions.size; i++ {
rc := iter.readSampling.pendingCompactions.at(i)
sb.WriteString(fmt.Sprintf("(level: %d, start: %s, end: %s)\n", rc.level, string(rc.start), string(rc.end)))
}
return sb.String()
case "close-iter":
if iter != nil {
if err := iter.Close(); err != nil {
return err.Error()
}
}
return ""
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestIteratorTableFilter(t *testing.T) {
var d *DB
defer func() {
if d != nil {
require.NoError(t, d.Close())
}
}()
datadriven.RunTest(t, "testdata/iterator_table_filter", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "define":
if d != nil {
if err := d.Close(); err != nil {
return err.Error()
}
}
opts := &Options{}
opts.TablePropertyCollectors = append(opts.TablePropertyCollectors,
func() TablePropertyCollector {
return &minSeqNumPropertyCollector{}
})
var err error
if d, err = runDBDefineCmd(td, opts); err != nil {
return err.Error()
}
d.mu.Lock()
// Disable the "dynamic base level" code for this test.
d.mu.versions.picker.forceBaseLevel1()
s := d.mu.versions.currentVersion().String()
d.mu.Unlock()
return s
case "iter":
// We're using an iterator table filter to approximate what is done by
// snapshots.
iterOpts := &IterOptions{}
var filterSeqNum uint64
if td.MaybeScanArgs(t, "filter", &filterSeqNum) {
iterOpts.TableFilter = func(userProps map[string]string) bool {
minSeqNum, err := strconv.ParseUint(userProps["test.min-seq-num"], 10, 64)
if err != nil {
return true
}
return minSeqNum < filterSeqNum
}
}
// TODO(peter): runDBDefineCmd doesn't properly update the visible
// sequence number. So we have to use a snapshot with a very large
// sequence number, otherwise the DB appears empty.
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
iter, _ := snap.NewIter(iterOpts)
return runIterCmd(td, iter, true)
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestIteratorNextPrev(t *testing.T) {
var mem vfs.FS
var d *DB
defer func() {
require.NoError(t, d.Close())
}()
reset := func() {
if d != nil {
require.NoError(t, d.Close())
}
mem = vfs.NewMem()
require.NoError(t, mem.MkdirAll("ext", 0755))
opts := &Options{FS: mem}
// Automatic compactions may compact away tombstones from L6, making
// some testcases non-deterministic.
opts.DisableAutomaticCompactions = true
var err error
d, err = Open("", opts)
require.NoError(t, err)
}
reset()
datadriven.RunTest(t, "testdata/iterator_next_prev", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "reset":
reset()
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()
}
return runLSMCmd(td, d)
case "iter":
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
td.MaybeScanArgs(t, "seq", &snap.seqNum)
iter, _ := snap.NewIter(nil)
return runIterCmd(td, iter, true)
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestIteratorStats(t *testing.T) {
var mem vfs.FS
var d *DB
defer func() {
require.NoError(t, d.Close())
}()
reset := func() {
if d != nil {
require.NoError(t, d.Close())
}
mem = vfs.NewMem()
require.NoError(t, mem.MkdirAll("ext", 0755))
opts := &Options{Comparer: testkeys.Comparer, FS: mem, FormatMajorVersion: internalFormatNewest}
// Automatic compactions may make some testcases non-deterministic.
opts.DisableAutomaticCompactions = true
var err error
d, err = Open("", opts)
require.NoError(t, err)
}
reset()
datadriven.RunTest(t, "testdata/iterator_stats", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "reset":
reset()
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()
}
return runLSMCmd(td, d)
case "iter":
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
td.MaybeScanArgs(t, "seq", &snap.seqNum)
iter, _ := snap.NewIter(nil)
return runIterCmd(td, iter, true)
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
type iterSeekOptWrapper struct {
internalIterator
seekGEUsingNext, seekPrefixGEUsingNext *int
}
func (i *iterSeekOptWrapper) SeekGE(
key []byte, flags base.SeekGEFlags,
) (*InternalKey, base.LazyValue) {
if flags.TrySeekUsingNext() {
*i.seekGEUsingNext++
}
return i.internalIterator.SeekGE(key, flags)
}
func (i *iterSeekOptWrapper) SeekPrefixGE(
prefix, key []byte, flags base.SeekGEFlags,
) (*InternalKey, base.LazyValue) {
if flags.TrySeekUsingNext() {
*i.seekPrefixGEUsingNext++
}
return i.internalIterator.SeekPrefixGE(prefix, key, flags)
}
func TestIteratorSeekOpt(t *testing.T) {
var d *DB
defer func() {
require.NoError(t, d.Close())
}()
var iter *Iterator
defer func() {
if iter != nil {
require.NoError(t, iter.Close())
}
}()
var seekGEUsingNext, seekPrefixGEUsingNext int
datadriven.RunTest(t, "testdata/iterator_seek_opt", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "define":
if iter != nil {
if err := iter.Close(); err != nil {
return err.Error()
}
}
if d != nil {
if err := d.Close(); err != nil {
return err.Error()
}
}
seekGEUsingNext = 0
seekPrefixGEUsingNext = 0
opts := &Options{}
opts.TablePropertyCollectors = append(opts.TablePropertyCollectors,
func() TablePropertyCollector {
return &minSeqNumPropertyCollector{}
})
var err error
if d, err = runDBDefineCmd(td, opts); err != nil {
return err.Error()
}
d.mu.Lock()
s := d.mu.versions.currentVersion().String()
d.mu.Unlock()
oldNewIters := d.newIters
d.newIters = func(
ctx context.Context, file *manifest.FileMetadata, opts *IterOptions,
internalOpts internalIterOpts) (internalIterator, keyspan.FragmentIterator, error) {
iter, rangeIter, err := oldNewIters(ctx, file, opts, internalOpts)
iterWrapped := &iterSeekOptWrapper{
internalIterator: iter,
seekGEUsingNext: &seekGEUsingNext,
seekPrefixGEUsingNext: &seekPrefixGEUsingNext,
}
return iterWrapped, rangeIter, err
}
return s
case "iter":
if iter == nil || iter.iter == nil {
// TODO(peter): runDBDefineCmd doesn't properly update the visible
// sequence number. So we have to use a snapshot with a very large
// sequence number, otherwise the DB appears empty.
snap := Snapshot{
db: d,
seqNum: InternalKeySeqNumMax,
}
iter, _ = snap.NewIter(nil)
iter.readSampling.forceReadSampling = true
iter.comparer.Split = func(a []byte) int { return len(a) }
iter.forceEnableSeekOpt = true
iter.merging.forceEnableSeekOpt = true
}
iterOutput := runIterCmd(td, iter, false)
stats := iter.Stats()
// InternalStats are non-deterministic since they depend on how data is
// distributed across memtables and sstables in the DB.
stats.InternalStats = InternalIteratorStats{}
var builder strings.Builder
fmt.Fprintf(&builder, "%sstats: %s\n", iterOutput, stats.String())
fmt.Fprintf(&builder, "SeekGEs with trySeekUsingNext: %d\n", seekGEUsingNext)
fmt.Fprintf(&builder, "SeekPrefixGEs with trySeekUsingNext: %d\n", seekPrefixGEUsingNext)
return builder.String()
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
type errorSeekIter struct {
internalIterator
// Fields controlling error injection for seeks.
injectSeekErrorCounts []int
seekCount int
err error
}
func (i *errorSeekIter) SeekGE(key []byte, flags base.SeekGEFlags) (*InternalKey, base.LazyValue) {
if i.tryInjectError() {
return nil, base.LazyValue{}
}
i.err = nil
i.seekCount++
return i.internalIterator.SeekGE(key, flags)
}
func (i *errorSeekIter) SeekPrefixGE(
prefix, key []byte, flags base.SeekGEFlags,
) (*InternalKey, base.LazyValue) {
if i.tryInjectError() {
return nil, base.LazyValue{}
}
i.err = nil
i.seekCount++
return i.internalIterator.SeekPrefixGE(prefix, key, flags)
}
func (i *errorSeekIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {
if i.tryInjectError() {
return nil, base.LazyValue{}
}
i.err = nil
i.seekCount++
return i.internalIterator.SeekLT(key, flags)
}
func (i *errorSeekIter) tryInjectError() bool {
if len(i.injectSeekErrorCounts) > 0 && i.injectSeekErrorCounts[0] == i.seekCount {
i.seekCount++
i.err = errors.Errorf("injecting error")
i.injectSeekErrorCounts = i.injectSeekErrorCounts[1:]
return true
}
return false
}
func (i *errorSeekIter) First() (*InternalKey, base.LazyValue) {
i.err = nil
return i.internalIterator.First()
}
func (i *errorSeekIter) Last() (*InternalKey, base.LazyValue) {
i.err = nil
return i.internalIterator.Last()
}
func (i *errorSeekIter) Next() (*InternalKey, base.LazyValue) {
if i.err != nil {
return nil, base.LazyValue{}
}
return i.internalIterator.Next()
}
func (i *errorSeekIter) Prev() (*InternalKey, base.LazyValue) {
if i.err != nil {
return nil, base.LazyValue{}
}
return i.internalIterator.Prev()
}
func (i *errorSeekIter) Error() error {
if i.err != nil {