forked from cockroachdb/pebble
/
generator.go
1470 lines (1320 loc) · 41.3 KB
/
generator.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 2019 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 metamorphic
import (
"bytes"
"fmt"
"sort"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/internal/randvar"
"github.com/cockroachdb/pebble/internal/testkeys"
"golang.org/x/exp/rand"
)
const maxValueSize = 20
type iterOpts struct {
lower []byte
upper []byte
keyTypes uint32 // pebble.IterKeyType
// maskSuffix may be set if keyTypes is IterKeyTypePointsAndRanges to
// configure IterOptions.RangeKeyMasking.Suffix.
maskSuffix []byte
// If filterMax is >0, this iterator will filter out any keys that have
// suffixes that don't fall within the range [filterMin,filterMax).
// Additionally, the iterator will be constructed with a block-property
// filter that filters out blocks accordingly. Not all OPTIONS hook up the
// corresponding block property collector, so block-filtering may still be
// effectively disabled in some runs. The iterator operations themselves
// however will always skip past any points that should be filtered to
// ensure determinism.
filterMin uint64
filterMax uint64
// see IterOptions.UseL6Filters.
useL6Filters bool
// NB: If adding or removing fields, ensure IsZero is in sync.
}
func (o iterOpts) IsZero() bool {
return o.lower == nil && o.upper == nil && o.keyTypes == 0 &&
o.maskSuffix == nil && o.filterMin == 0 && o.filterMax == 0 && !o.useL6Filters
}
type generator struct {
cfg config
rng *rand.Rand
init *initOp
ops []op
// keyManager tracks the state of keys a operation generation time.
keyManager *keyManager
// Unordered sets of object IDs for live objects. Used to randomly select on
// object when generating an operation. There are 4 concrete objects: the DB
// (of which there is exactly 1), batches, iterators, and snapshots.
//
// liveBatches contains the live indexed and write-only batches.
liveBatches objIDSlice
// liveIters contains the live iterators.
liveIters objIDSlice
itersLastOpts map[objID]iterOpts
// liveReaders contains the DB, and any live indexed batches and snapshots. The DB is always
// at index 0.
liveReaders objIDSlice
// liveSnapshots contains the live snapshots.
liveSnapshots objIDSlice
// liveWriters contains the DB, and any live batches. The DB is always at index 0.
liveWriters objIDSlice
// Maps used to find associated objects during generation. These maps are not
// needed during test execution.
//
// batchID -> batch iters: used to keep track of the open iterators on an
// indexed batch. The iter set value will also be indexed by the readers map.
batches map[objID]objIDSet
// iterID -> reader iters: used to keep track of all of the open
// iterators. The iter set value will also be indexed by either the batches
// or snapshots maps.
iters map[objID]objIDSet
// readerID -> reader iters: used to keep track of the open iterators on a
// reader. The iter set value will also be indexed by either the batches or
// snapshots maps. This map is the union of batches and snapshots maps.
readers map[objID]objIDSet
// snapshotID -> snapshot iters: used to keep track of the open iterators on
// a snapshot. The iter set value will also be indexed by the readers map.
snapshots map[objID]objIDSet
// snapshotID -> bounds of the snapshot: only populated for snapshots that
// are constrained by bounds.
snapshotBounds map[objID][]pebble.KeyRange
// iterSequenceNumber is the metaTimestamp at which the iter was created.
iterCreationTimestamp map[objID]int
// iterReaderID is a map from an iterID to a readerID.
iterReaderID map[objID]objID
}
func newGenerator(rng *rand.Rand, cfg config, km *keyManager) *generator {
g := &generator{
cfg: cfg,
rng: rng,
init: &initOp{},
keyManager: km,
liveReaders: objIDSlice{makeObjID(dbTag, 0)},
liveWriters: objIDSlice{makeObjID(dbTag, 0)},
batches: make(map[objID]objIDSet),
iters: make(map[objID]objIDSet),
readers: make(map[objID]objIDSet),
snapshots: make(map[objID]objIDSet),
snapshotBounds: make(map[objID][]pebble.KeyRange),
itersLastOpts: make(map[objID]iterOpts),
iterCreationTimestamp: make(map[objID]int),
iterReaderID: make(map[objID]objID),
}
// Note that the initOp fields are populated during generation.
g.ops = append(g.ops, g.init)
return g
}
func generate(rng *rand.Rand, count uint64, cfg config, km *keyManager) []op {
g := newGenerator(rng, cfg, km)
generators := []func(){
batchAbort: g.batchAbort,
batchCommit: g.batchCommit,
dbCheckpoint: g.dbCheckpoint,
dbCompact: g.dbCompact,
dbFlush: g.dbFlush,
dbRatchetFormatMajorVersion: g.dbRatchetFormatMajorVersion,
dbRestart: g.dbRestart,
iterClose: g.randIter(g.iterClose),
iterFirst: g.randIter(g.iterFirst),
iterLast: g.randIter(g.iterLast),
iterNext: g.randIter(g.iterNext),
iterNextWithLimit: g.randIter(g.iterNextWithLimit),
iterNextPrefix: g.randIter(g.iterNextPrefix),
iterPrev: g.randIter(g.iterPrev),
iterPrevWithLimit: g.randIter(g.iterPrevWithLimit),
iterSeekGE: g.randIter(g.iterSeekGE),
iterSeekGEWithLimit: g.randIter(g.iterSeekGEWithLimit),
iterSeekLT: g.randIter(g.iterSeekLT),
iterSeekLTWithLimit: g.randIter(g.iterSeekLTWithLimit),
iterSeekPrefixGE: g.randIter(g.iterSeekPrefixGE),
iterSetBounds: g.randIter(g.iterSetBounds),
iterSetOptions: g.randIter(g.iterSetOptions),
newBatch: g.newBatch,
newIndexedBatch: g.newIndexedBatch,
newIter: g.newIter,
newIterUsingClone: g.newIterUsingClone,
newSnapshot: g.newSnapshot,
readerGet: g.readerGet,
snapshotClose: g.snapshotClose,
writerApply: g.writerApply,
writerDelete: g.writerDelete,
writerDeleteRange: g.writerDeleteRange,
writerIngest: g.writerIngest,
writerMerge: g.writerMerge,
writerRangeKeyDelete: g.writerRangeKeyDelete,
writerRangeKeySet: g.writerRangeKeySet,
writerRangeKeyUnset: g.writerRangeKeyUnset,
writerSet: g.writerSet,
writerSingleDelete: g.writerSingleDelete,
}
// TPCC-style deck of cards randomization. Every time the end of the deck is
// reached, we shuffle the deck.
deck := randvar.NewDeck(g.rng, cfg.ops...)
for i := uint64(0); i < count; i++ {
generators[deck.Int()]()
}
g.dbClose()
return g.ops
}
func (g *generator) add(op op) {
g.ops = append(g.ops, op)
g.keyManager.update(op)
}
// randKeyToWrite returns a key for any write other than SingleDelete.
//
// TODO(peter): make the size and distribution of keys configurable. See
// keyDist and keySizeDist in config.go.
func (g *generator) randKeyToWrite(newKey float64) []byte {
return g.randKeyHelper(g.keyManager.eligibleWriteKeys(), newKey, nil)
}
// prefixKeyRange generates a [start, end) pair consisting of two prefix keys.
func (g *generator) prefixKeyRange() ([]byte, []byte) {
start := g.randPrefixToWrite(0.001)
end := g.randPrefixToWrite(0.001)
for g.cmp(start, end) == 0 {
end = g.randPrefixToWrite(0.05)
}
if g.cmp(start, end) > 0 {
start, end = end, start
}
return start, end
}
// randPrefixToWrite returns a prefix key (a key with no suffix) for a range key
// write operation.
func (g *generator) randPrefixToWrite(newPrefix float64) []byte {
prefixes := g.keyManager.prefixes()
if len(prefixes) > 0 && g.rng.Float64() > newPrefix {
// Use an existing prefix.
p := g.rng.Intn(len(prefixes))
return prefixes[p]
}
// Use a new prefix.
var prefix []byte
for {
prefix = g.randKeyHelperSuffix(nil, 4, 12, 0)
if !g.keyManager.prefixExists(prefix) {
if !g.keyManager.addNewKey(prefix) {
panic("key must not exist if prefix doesn't exist")
}
return prefix
}
}
}
// randSuffixToWrite generates a random suffix according to the configuration's suffix
// distribution. It takes a probability 0 ≤ p ≤ 1.0 indicating the probability
// with which the generator should increase the max suffix generated by the
// generator.
//
// randSuffixToWrite may return a nil suffix, with the probability the
// configuration's suffix distribution assigns to the zero suffix.
func (g *generator) randSuffixToWrite(incMaxProb float64) []byte {
if g.rng.Float64() < incMaxProb {
g.cfg.writeSuffixDist.IncMax(1)
}
return suffixFromInt(int64(g.cfg.writeSuffixDist.Uint64(g.rng)))
}
// randSuffixToRead generates a random suffix used during reads. The suffixes
// generated by this function are within the same range as suffixes generated by
// randSuffixToWrite, however randSuffixToRead pulls from a uniform
// distribution.
func (g *generator) randSuffixToRead() []byte {
// When reading, don't apply the recency skewing in order to better exercise
// a reading a mix of older and newer keys.
max := g.cfg.writeSuffixDist.Max()
return suffixFromInt(g.rng.Int63n(int64(max)))
}
func suffixFromInt(suffix int64) []byte {
// Treat the zero as no suffix to match the behavior during point key
// generation in randKeyHelper.
if suffix == 0 {
return nil
}
return testkeys.Suffix(suffix)
}
func (g *generator) randKeyToSingleDelete(id objID) []byte {
keys := g.keyManager.eligibleSingleDeleteKeys(id)
length := len(keys)
if length == 0 {
return nil
}
return keys[g.rng.Intn(length)]
}
// randKeyToRead returns a key for read operations.
func (g *generator) randKeyToRead(newKey float64) []byte {
return g.randKeyHelper(g.keyManager.eligibleReadKeys(), newKey, nil)
}
// randKeyToReadInRange returns a key for read operations within the provided
// key range. The bounds of the provided key range must span a prefix boundary.
func (g *generator) randKeyToReadInRange(newKey float64, kr pebble.KeyRange) []byte {
return g.randKeyHelper(g.keyManager.eligibleReadKeysInRange(kr), newKey, &kr)
}
func (g *generator) randKeyHelper(
keys [][]byte, newKey float64, newKeyBounds *pebble.KeyRange,
) []byte {
switch {
case len(keys) > 0 && g.rng.Float64() > newKey:
// Use an existing user key.
return keys[g.rng.Intn(len(keys))]
case len(keys) > 0 && g.rng.Float64() > g.cfg.newPrefix:
// Use an existing prefix but a new suffix, producing a new user key.
prefixes := g.keyManager.prefixes()
// If we're constrained to a key range, find which existing prefixes
// fall within that key range.
if newKeyBounds != nil {
s := sort.Search(len(prefixes), func(i int) bool {
return g.cmp(prefixes[i], newKeyBounds.Start) >= 0
})
e := sort.Search(len(prefixes), func(i int) bool {
return g.cmp(prefixes[i], newKeyBounds.End) >= 0
})
prefixes = prefixes[s:e]
}
if len(prefixes) > 0 {
for {
// Pick a prefix on each iteration in case most or all suffixes are
// already in use for any individual prefix.
p := g.rng.Intn(len(prefixes))
suffix := int64(g.cfg.writeSuffixDist.Uint64(g.rng))
var key []byte
if suffix > 0 {
key = resizeBuffer(key, len(prefixes[p]), testkeys.SuffixLen(suffix))
n := copy(key, prefixes[p])
testkeys.WriteSuffix(key[n:], suffix)
} else {
key = resizeBuffer(key, len(prefixes[p]), 0)
copy(key, prefixes[p])
}
if (newKeyBounds == nil || (g.cmp(key, newKeyBounds.Start) >= 0 && g.cmp(key, newKeyBounds.End) < 0)) &&
g.keyManager.addNewKey(key) {
return key
}
// If the generated key already existed, or the generated key
// fell outside the provided bounds, increase the suffix
// distribution and loop.
g.cfg.writeSuffixDist.IncMax(1)
}
}
// Otherwise fall through to generating a new prefix.
fallthrough
default:
// Use a new prefix, producing a new user key.
var key []byte
suffix := int64(g.cfg.writeSuffixDist.Uint64(g.rng))
// If we have bounds in which we need to generate the key, use
// testkeys.RandomSeparator to generate a key between the bounds.
if newKeyBounds != nil {
targetLength := 4 + g.rng.Intn(8)
key = testkeys.RandomSeparator(nil, g.prefix(newKeyBounds.Start), g.prefix(newKeyBounds.End),
suffix, targetLength, g.rng)
} else {
for {
key = g.randKeyHelperSuffix(nil, 4, 12, suffix)
if !g.keyManager.prefixExists(key[:testkeys.Comparer.Split(key)]) {
if !g.keyManager.addNewKey(key) {
panic("key must not exist if prefix doesn't exist")
}
break
}
}
}
return key
}
}
// randKeyHelperSuffix is a helper function for randKeyHelper, and should not be
// invoked directly.
func (g *generator) randKeyHelperSuffix(
dst []byte, minPrefixLen, maxPrefixLen int, suffix int64,
) []byte {
n := minPrefixLen
if maxPrefixLen > minPrefixLen {
n += g.rng.Intn(maxPrefixLen - minPrefixLen)
}
// In order to test a mix of suffixed and unsuffixed keys, omit the zero
// suffix.
if suffix == 0 {
dst = resizeBuffer(dst, n, 0)
g.fillRand(dst)
return dst
}
suffixLen := testkeys.SuffixLen(suffix)
dst = resizeBuffer(dst, n, suffixLen)
g.fillRand(dst[:n])
testkeys.WriteSuffix(dst[n:], suffix)
return dst
}
func resizeBuffer(buf []byte, prefixLen, suffixLen int) []byte {
if cap(buf) >= prefixLen+suffixLen {
return buf[:prefixLen+suffixLen]
}
return make([]byte, prefixLen+suffixLen)
}
// TODO(peter): make the value size configurable. See valueSizeDist in
// config.go.
func (g *generator) randValue(min, max int) []byte {
n := min
if max > min {
n += g.rng.Intn(max - min)
}
if n == 0 {
return nil
}
buf := make([]byte, n)
g.fillRand(buf)
return buf
}
func (g *generator) fillRand(buf []byte) {
// NB: The actual random values are not particularly important. We only use
// lowercase letters because that makes visual determination of ordering
// easier, rather than having to remember the lexicographic ordering of
// uppercase vs lowercase, or letters vs numbers vs punctuation.
const letters = "abcdefghijklmnopqrstuvwxyz"
const lettersLen = uint64(len(letters))
const lettersCharsPerRand = 12 // floor(log(math.MaxUint64)/log(lettersLen))
var r uint64
var q int
for i := 0; i < len(buf); i++ {
if q == 0 {
r = g.rng.Uint64()
q = lettersCharsPerRand
}
buf[i] = letters[r%lettersLen]
r = r / lettersLen
q--
}
}
func (g *generator) newBatch() {
batchID := makeObjID(batchTag, g.init.batchSlots)
g.init.batchSlots++
g.liveBatches = append(g.liveBatches, batchID)
g.liveWriters = append(g.liveWriters, batchID)
g.add(&newBatchOp{
batchID: batchID,
})
}
func (g *generator) newIndexedBatch() {
batchID := makeObjID(batchTag, g.init.batchSlots)
g.init.batchSlots++
g.liveBatches = append(g.liveBatches, batchID)
g.liveReaders = append(g.liveReaders, batchID)
g.liveWriters = append(g.liveWriters, batchID)
iters := make(objIDSet)
g.batches[batchID] = iters
g.readers[batchID] = iters
g.add(&newIndexedBatchOp{
batchID: batchID,
})
}
// removeFromBatchGenerator will not generate a closeOp for the target batch as
// not every batch that is removed from the generator should be closed. For
// example, running a closeOp before an ingestOp that contains the closed batch
// will cause an error.
func (g *generator) removeBatchFromGenerator(batchID objID) {
g.liveBatches.remove(batchID)
iters := g.batches[batchID]
delete(g.batches, batchID)
if iters != nil {
g.liveReaders.remove(batchID)
delete(g.readers, batchID)
}
g.liveWriters.remove(batchID)
for _, id := range iters.sorted() {
g.liveIters.remove(id)
delete(g.iters, id)
g.add(&closeOp{objID: id})
}
}
func (g *generator) batchAbort() {
if len(g.liveBatches) == 0 {
return
}
batchID := g.liveBatches.rand(g.rng)
g.removeBatchFromGenerator(batchID)
g.add(&closeOp{objID: batchID})
}
func (g *generator) batchCommit() {
if len(g.liveBatches) == 0 {
return
}
batchID := g.liveBatches.rand(g.rng)
g.removeBatchFromGenerator(batchID)
g.add(&batchCommitOp{
batchID: batchID,
})
g.add(&closeOp{objID: batchID})
}
func (g *generator) dbClose() {
// Close any live iterators and snapshots, so that we can close the DB
// cleanly.
for len(g.liveIters) > 0 {
g.randIter(g.iterClose)()
}
for len(g.liveSnapshots) > 0 {
g.snapshotClose()
}
for len(g.liveBatches) > 0 {
batchID := g.liveBatches[0]
g.removeBatchFromGenerator(batchID)
g.add(&closeOp{objID: batchID})
}
g.add(&closeOp{objID: makeObjID(dbTag, 0)})
}
func (g *generator) dbCheckpoint() {
// 1/2 of the time we don't restrict the checkpoint;
// 1/4 of the time we restrict to 1 span;
// 1/8 of the time we restrict to 2 spans; etc.
numSpans := 0
var spans []pebble.CheckpointSpan
for g.rng.Intn(2) == 0 {
numSpans++
}
if numSpans > 0 {
spans = make([]pebble.CheckpointSpan, numSpans)
}
for i := range spans {
start := g.randKeyToRead(0.01)
end := g.randKeyToRead(0.01)
if g.cmp(start, end) > 0 {
start, end = end, start
}
spans[i].Start = start
spans[i].End = end
}
g.add(&checkpointOp{
spans: spans,
})
}
func (g *generator) dbCompact() {
// Generate new key(s) with a 1% probability.
start := g.randKeyToRead(0.01)
end := g.randKeyToRead(0.01)
if g.cmp(start, end) > 0 {
start, end = end, start
}
g.add(&compactOp{
start: start,
end: end,
parallelize: g.rng.Float64() < 0.5,
})
}
func (g *generator) dbFlush() {
g.add(&flushOp{})
}
func (g *generator) dbRatchetFormatMajorVersion() {
// Ratchet to a random format major version between the minimum the
// metamorphic tests support and the newest. At runtime, the generated
// version may be behind the database's format major version, in which case
// RatchetFormatMajorVersion should deterministically error.
n := int(newestFormatMajorVersionToTest - minimumFormatMajorVersion)
vers := pebble.FormatMajorVersion(g.rng.Intn(n+1)) + minimumFormatMajorVersion
g.add(&dbRatchetFormatMajorVersionOp{vers: vers})
}
func (g *generator) dbRestart() {
// Close any live iterators and snapshots, so that we can close the DB
// cleanly.
for len(g.liveIters) > 0 {
g.randIter(g.iterClose)()
}
for len(g.liveSnapshots) > 0 {
g.snapshotClose()
}
// Close the batches.
for len(g.liveBatches) > 0 {
batchID := g.liveBatches[0]
g.removeBatchFromGenerator(batchID)
g.add(&closeOp{objID: batchID})
}
if len(g.liveReaders) != 1 || len(g.liveWriters) != 1 {
panic(fmt.Sprintf("unexpected counts: liveReaders %d, liveWriters: %d",
len(g.liveReaders), len(g.liveWriters)))
}
g.add(&dbRestartOp{})
}
// maybeSetSnapshotIterBounds must be called whenever creating a new iterator or
// modifying the bounds of an iterator. If the iterator is backed by a snapshot
// that only guarantees consistency within a limited set of key spans, then the
// iterator must set bounds within one of the snapshot's consistent keyspans. It
// returns true if the provided readerID is a bounded snapshot and bounds were
// set.
func (g *generator) maybeSetSnapshotIterBounds(readerID objID, opts *iterOpts) bool {
snapBounds, isBoundedSnapshot := g.snapshotBounds[readerID]
if !isBoundedSnapshot {
return false
}
// Pick a random keyrange within one of the snapshot's key ranges.
parentBounds := snapBounds[g.rng.Intn(len(snapBounds))]
// With 10% probability, use the parent start bound as-is.
if g.rng.Float64() <= 0.1 {
opts.lower = parentBounds.Start
} else {
opts.lower = testkeys.RandomSeparator(
nil, /* dst */
parentBounds.Start,
parentBounds.End,
0, /* suffix */
4+g.rng.Intn(8),
g.rng,
)
}
// With 10% probability, use the parent end bound as-is.
if g.rng.Float64() <= 0.1 {
opts.upper = parentBounds.End
} else {
opts.upper = testkeys.RandomSeparator(
nil, /* dst */
opts.lower,
parentBounds.End,
0, /* suffix */
4+g.rng.Intn(8),
g.rng,
)
}
return true
}
func (g *generator) newIter() {
iterID := makeObjID(iterTag, g.init.iterSlots)
g.init.iterSlots++
g.liveIters = append(g.liveIters, iterID)
readerID := g.liveReaders.rand(g.rng)
if iters := g.readers[readerID]; iters != nil {
iters[iterID] = struct{}{}
g.iters[iterID] = iters
//lint:ignore SA9003 - readability
} else {
// NB: the DB object does not track its open iterators because it never
// closes.
}
g.iterReaderID[iterID] = readerID
var opts iterOpts
if !g.maybeSetSnapshotIterBounds(readerID, &opts) {
// Generate lower/upper bounds with a 10% probability.
if g.rng.Float64() <= 0.1 {
// Generate a new key with a .1% probability.
opts.lower = g.randKeyToRead(0.001)
}
if g.rng.Float64() <= 0.1 {
// Generate a new key with a .1% probability.
opts.upper = g.randKeyToRead(0.001)
}
if g.cmp(opts.lower, opts.upper) > 0 {
opts.lower, opts.upper = opts.upper, opts.lower
}
}
opts.keyTypes, opts.maskSuffix = g.randKeyTypesAndMask()
// With 10% probability, enable automatic filtering of keys with suffixes
// not in the provided range. This filtering occurs both through
// block-property filtering and explicitly within the iterator operations to
// ensure determinism.
if g.rng.Float64() <= 0.1 {
max := g.cfg.writeSuffixDist.Max()
opts.filterMin, opts.filterMax = g.rng.Uint64n(max)+1, g.rng.Uint64n(max)+1
if opts.filterMin > opts.filterMax {
opts.filterMin, opts.filterMax = opts.filterMax, opts.filterMin
} else if opts.filterMin == opts.filterMax {
opts.filterMax = opts.filterMin + 1
}
}
// Enable L6 filters with a 10% probability.
if g.rng.Float64() <= 0.1 {
opts.useL6Filters = true
}
g.itersLastOpts[iterID] = opts
g.iterCreationTimestamp[iterID] = g.keyManager.nextMetaTimestamp()
g.iterReaderID[iterID] = readerID
g.add(&newIterOp{
readerID: readerID,
iterID: iterID,
iterOpts: opts,
})
}
func (g *generator) randKeyTypesAndMask() (keyTypes uint32, maskSuffix []byte) {
// Iterate over different key types.
p := g.rng.Float64()
switch {
case p < 0.2: // 20% probability
keyTypes = uint32(pebble.IterKeyTypePointsOnly)
case p < 0.8: // 60% probability
keyTypes = uint32(pebble.IterKeyTypePointsAndRanges)
// With 50% probability, enable masking.
if g.rng.Intn(2) == 1 {
maskSuffix = g.randSuffixToRead()
}
default: // 20% probability
keyTypes = uint32(pebble.IterKeyTypeRangesOnly)
}
return keyTypes, maskSuffix
}
func (g *generator) newIterUsingClone() {
if len(g.liveIters) == 0 {
return
}
existingIterID := g.liveIters.rand(g.rng)
iterID := makeObjID(iterTag, g.init.iterSlots)
g.init.iterSlots++
g.liveIters = append(g.liveIters, iterID)
if iters := g.iters[existingIterID]; iters != nil {
iters[iterID] = struct{}{}
g.iters[iterID] = iters
//lint:ignore SA9003 - readability
} else {
// NB: the DB object does not track its open iterators because it never
// closes.
}
readerID := g.iterReaderID[existingIterID]
g.iterReaderID[iterID] = readerID
var refreshBatch bool
if readerID.tag() == batchTag {
refreshBatch = g.rng.Intn(2) == 1
}
opts := g.itersLastOpts[existingIterID]
// With 50% probability, consider modifying the iterator options used by the
// clone.
if g.rng.Intn(2) == 1 {
g.maybeMutateOptions(readerID, &opts)
}
g.itersLastOpts[iterID] = opts
g.iterCreationTimestamp[iterID] = g.keyManager.nextMetaTimestamp()
g.iterReaderID[iterID] = g.iterReaderID[existingIterID]
g.add(&newIterUsingCloneOp{
existingIterID: existingIterID,
iterID: iterID,
refreshBatch: refreshBatch,
iterOpts: opts,
derivedReaderID: readerID,
})
}
func (g *generator) iterClose(iterID objID) {
g.liveIters.remove(iterID)
if readerIters, ok := g.iters[iterID]; ok {
delete(g.iters, iterID)
delete(readerIters, iterID)
//lint:ignore SA9003 - readability
} else {
// NB: the DB object does not track its open iterators because it never
// closes.
}
g.add(&closeOp{objID: iterID})
}
func (g *generator) iterSetBounds(iterID objID) {
iterLastOpts := g.itersLastOpts[iterID]
newOpts := iterLastOpts
// TODO(jackson): The logic to increase the probability of advancing bounds
// monotonically only applies if the snapshot is not bounded. Refactor to
// allow bounded snapshots to benefit too, when possible.
if !g.maybeSetSnapshotIterBounds(g.iterReaderID[iterID], &newOpts) {
var lower, upper []byte
genLower := g.rng.Float64() <= 0.9
genUpper := g.rng.Float64() <= 0.9
// When one of ensureLowerGE, ensureUpperLE is true, the new bounds
// don't overlap with the previous bounds.
var ensureLowerGE, ensureUpperLE bool
if genLower && iterLastOpts.upper != nil && g.rng.Float64() <= 0.9 {
ensureLowerGE = true
}
if (!ensureLowerGE || g.rng.Float64() < 0.5) && genUpper && iterLastOpts.lower != nil {
ensureUpperLE = true
ensureLowerGE = false
}
attempts := 0
for {
attempts++
if genLower {
// Generate a new key with a .1% probability.
lower = g.randKeyToRead(0.001)
}
if genUpper {
// Generate a new key with a .1% probability.
upper = g.randKeyToRead(0.001)
}
if g.cmp(lower, upper) > 0 {
lower, upper = upper, lower
}
if ensureLowerGE && g.cmp(iterLastOpts.upper, lower) > 0 {
if attempts < 25 {
continue
}
lower = iterLastOpts.upper
upper = lower
break
}
if ensureUpperLE && g.cmp(upper, iterLastOpts.lower) > 0 {
if attempts < 25 {
continue
}
upper = iterLastOpts.lower
lower = upper
break
}
break
}
newOpts.lower = lower
newOpts.upper = upper
}
g.itersLastOpts[iterID] = newOpts
g.add(&iterSetBoundsOp{
iterID: iterID,
lower: newOpts.lower,
upper: newOpts.upper,
})
// Additionally seek the iterator in a manner consistent with the bounds,
// and do some steps (Next/Prev). The seeking exercises typical
// CockroachDB behavior when using iterators and the steps are trying to
// stress the region near the bounds. Ideally, we should not do this as
// part of generating a single op, but this is easier than trying to
// control future op generation via generator state.
doSeekLT := newOpts.upper != nil && g.rng.Float64() < 0.5
doSeekGE := newOpts.lower != nil && g.rng.Float64() < 0.5
if doSeekLT && doSeekGE {
// Pick the seek.
if g.rng.Float64() < 0.5 {
doSeekGE = false
} else {
doSeekLT = false
}
}
if doSeekLT {
g.add(&iterSeekLTOp{
iterID: iterID,
key: newOpts.upper,
derivedReaderID: g.iterReaderID[iterID],
})
if g.rng.Float64() < 0.5 {
g.iterNext(iterID)
}
if g.rng.Float64() < 0.5 {
g.iterNext(iterID)
}
if g.rng.Float64() < 0.5 {
g.iterPrev(iterID)
}
} else if doSeekGE {
g.add(&iterSeekGEOp{
iterID: iterID,
key: newOpts.lower,
derivedReaderID: g.iterReaderID[iterID],
})
if g.rng.Float64() < 0.5 {
g.iterPrev(iterID)
}
if g.rng.Float64() < 0.5 {
g.iterPrev(iterID)
}
if g.rng.Float64() < 0.5 {
g.iterNext(iterID)
}
}
}
func (g *generator) iterSetOptions(iterID objID) {
opts := g.itersLastOpts[iterID]
g.maybeMutateOptions(g.iterReaderID[iterID], &opts)
g.itersLastOpts[iterID] = opts
g.add(&iterSetOptionsOp{
iterID: iterID,
iterOpts: opts,
derivedReaderID: g.iterReaderID[iterID],
})
// Additionally, perform a random absolute positioning operation. The
// SetOptions contract requires one before the next relative positioning
// operation. Ideally, we should not do this as part of generating a single
// op, but this is easier than trying to control future op generation via
// generator state.
g.pickOneUniform(
g.iterFirst,
g.iterLast,
g.iterSeekGE,
g.iterSeekGEWithLimit,
g.iterSeekPrefixGE,
g.iterSeekLT,
g.iterSeekLTWithLimit,
)(iterID)
}
func (g *generator) iterSeekGE(iterID objID) {
g.add(&iterSeekGEOp{
iterID: iterID,
key: g.randKeyToRead(0.001), // 0.1% new keys
derivedReaderID: g.iterReaderID[iterID],
})
}
func (g *generator) iterSeekGEWithLimit(iterID objID) {
// 0.1% new keys
key, limit := g.randKeyToRead(0.001), g.randKeyToRead(0.001)
if g.cmp(key, limit) > 0 {
key, limit = limit, key
}
g.add(&iterSeekGEOp{
iterID: iterID,
key: key,
limit: limit,
derivedReaderID: g.iterReaderID[iterID],
})
}
func (g *generator) randKeyToReadWithinBounds(lower, upper []byte, readerID objID) []*keyMeta {
var inRangeKeys []*keyMeta
for _, keyMeta := range g.keyManager.byObj[readerID] {
posKey := keyMeta.key
if g.cmp(posKey, lower) < 0 || g.cmp(posKey, upper) >= 0 {
continue
}
inRangeKeys = append(inRangeKeys, keyMeta)
}
return inRangeKeys
}
func (g *generator) iterSeekPrefixGE(iterID objID) {
lower := g.itersLastOpts[iterID].lower
upper := g.itersLastOpts[iterID].upper
iterCreationTimestamp := g.iterCreationTimestamp[iterID]
var key []byte
// We try to make sure that the SeekPrefixGE key is within the iter bounds,
// and that the iter can read the key. If the key was created on a batch
// which deleted the key, then the key will still be considered visible
// by the current logic. We're also not accounting for keys written to
// batches which haven't been presisted to the DB. But we're only picking
// keys in a best effort manner, and the logic is better than picking a
// random key.
if g.rng.Intn(10) >= 1 {
possibleKeys := make([][]byte, 0, 100)
inRangeKeys := g.randKeyToReadWithinBounds(lower, upper, dbObjID)
for _, keyMeta := range inRangeKeys {
posKey := keyMeta.key
var foundWriteWithoutDelete bool
for _, update := range keyMeta.updateOps {
if update.metaTimestamp > iterCreationTimestamp {
break
}
if update.deleted {
foundWriteWithoutDelete = false
} else {
foundWriteWithoutDelete = true
}
}
if foundWriteWithoutDelete {
possibleKeys = append(possibleKeys, posKey)
}
}
if len(possibleKeys) > 0 {
key = []byte(possibleKeys[g.rng.Int31n(int32(len(possibleKeys)))])
}
}
if key == nil {
// TODO(bananabrick): We should try and use keys within the bounds,
// even if we couldn't find any keys visible to the iterator. However,
// doing this in experiments didn't really increase the valid
// SeekPrefixGE calls by much.
key = g.randKeyToRead(0) // 0% new keys
}
g.add(&iterSeekPrefixGEOp{
iterID: iterID,
key: key,
derivedReaderID: g.iterReaderID[iterID],