-
Notifications
You must be signed in to change notification settings - Fork 458
/
mem_table_test.go
576 lines (535 loc) · 14.8 KB
/
mem_table_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
// Copyright 2011 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"
"math/rand/v2"
"strconv"
"strings"
"testing"
"time"
"unicode"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/arenaskl"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/itertest"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
// get gets the value for the given key. It returns ErrNotFound if the DB does
// not contain the key.
func (m *memTable) get(key []byte) (value []byte, err error) {
it := m.skl.NewIter(nil, nil)
kv := it.SeekGE(key, base.SeekGEFlagsNone)
if kv == nil {
return nil, ErrNotFound
}
if !m.equal(key, kv.K.UserKey) {
return nil, ErrNotFound
}
switch kv.Kind() {
case InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
return nil, ErrNotFound
default:
return kv.InPlaceValue(), nil
}
}
// Set sets the value for the given key. It overwrites any previous value for
// that key; a DB is not a multi-map. NB: this might have unexpected
// interaction with prepare/apply. Caveat emptor!
func (m *memTable) set(key InternalKey, value []byte) error {
if key.Kind() == InternalKeyKindRangeDelete {
if err := m.rangeDelSkl.Add(key, value); err != nil {
return err
}
m.tombstones.invalidate(1)
return nil
}
if rangekey.IsRangeKey(key.Kind()) {
if err := m.rangeKeySkl.Add(key, value); err != nil {
return err
}
m.rangeKeys.invalidate(1)
return nil
}
return m.skl.Add(key, value)
}
// count returns the number of entries in a DB.
func (m *memTable) count() (n int) {
x := m.newIter(nil)
for kv := x.First(); kv != nil; kv = x.Next() {
n++
}
if x.Close() != nil {
return -1
}
return n
}
func ikey(s string) InternalKey {
return base.MakeInternalKey([]byte(s), 0, InternalKeyKindSet)
}
func TestMemTableBasic(t *testing.T) {
// Check the empty DB.
m := newMemTable(memTableOptions{})
if got, want := m.count(), 0; got != want {
t.Fatalf("0.count: got %v, want %v", got, want)
}
v, err := m.get([]byte("cherry"))
if string(v) != "" || err != ErrNotFound {
t.Fatalf("1.get: got (%q, %v), want (%q, %v)", v, err, "", ErrNotFound)
}
// Add some key/value pairs.
m.set(ikey("cherry"), []byte("red"))
m.set(ikey("peach"), []byte("yellow"))
m.set(ikey("grape"), []byte("red"))
m.set(ikey("grape"), []byte("green"))
m.set(ikey("plum"), []byte("purple"))
if got, want := m.count(), 4; got != want {
t.Fatalf("2.count: got %v, want %v", got, want)
}
// Get keys that are and aren't in the DB.
v, err = m.get([]byte("plum"))
if string(v) != "purple" || err != nil {
t.Fatalf("6.get: got (%q, %v), want (%q, %v)", v, err, "purple", error(nil))
}
v, err = m.get([]byte("lychee"))
if string(v) != "" || err != ErrNotFound {
t.Fatalf("7.get: got (%q, %v), want (%q, %v)", v, err, "", ErrNotFound)
}
// Check an iterator.
s, x := "", m.newIter(nil)
for kv := x.SeekGE([]byte("mango"), base.SeekGEFlagsNone); kv != nil; kv = x.Next() {
v, _, err := kv.Value(nil)
require.NoError(t, err)
s += fmt.Sprintf("%s/%s.", kv.K.UserKey, v)
}
if want := "peach/yellow.plum/purple."; s != want {
t.Fatalf("8.iter: got %q, want %q", s, want)
}
if err = x.Close(); err != nil {
t.Fatalf("9.close: %v", err)
}
// Check some more sets and deletes.
if err := m.set(ikey("apricot"), []byte("orange")); err != nil {
t.Fatalf("12.set: %v", err)
}
if got, want := m.count(), 5; got != want {
t.Fatalf("13.count: got %v, want %v", got, want)
}
}
func TestMemTableCount(t *testing.T) {
m := newMemTable(memTableOptions{})
for i := 0; i < 200; i++ {
if j := m.count(); j != i {
t.Fatalf("count: got %d, want %d", j, i)
}
m.set(InternalKey{UserKey: []byte{byte(i)}}, nil)
}
}
func TestMemTableEmpty(t *testing.T) {
m := newMemTable(memTableOptions{})
if !m.empty() {
t.Errorf("got !empty, want empty")
}
// Add one key/value pair with an empty key and empty value.
m.set(InternalKey{}, nil)
if m.empty() {
t.Errorf("got empty, want !empty")
}
}
func TestMemTable1000Entries(t *testing.T) {
// Initialize the DB.
const N = 1000
m0 := newMemTable(memTableOptions{})
for i := 0; i < N; i++ {
k := ikey(strconv.Itoa(i))
v := []byte(strings.Repeat("x", i))
m0.set(k, v)
}
// Check the DB count.
if got, want := m0.count(), 1000; got != want {
t.Fatalf("count: got %v, want %v", got, want)
}
// Check random-access lookup.
r := rand.New(rand.NewPCG(0, 0))
for i := 0; i < 3*N; i++ {
j := r.IntN(N)
k := []byte(strconv.Itoa(j))
v, err := m0.get(k)
require.NoError(t, err)
if len(v) != cap(v) {
t.Fatalf("get: j=%d, got len(v)=%d, cap(v)=%d", j, len(v), cap(v))
}
var c uint8
if len(v) != 0 {
c = v[0]
} else {
c = 'x'
}
if len(v) != j || c != 'x' {
t.Fatalf("get: j=%d, got len(v)=%d,c=%c, want %d,%c", j, len(v), c, j, 'x')
}
}
// Check that iterating through the middle of the DB looks OK.
// Keys are in lexicographic order, not numerical order.
// Multiples of 3 are not present.
wants := []string{
"499",
"5",
"50",
"500",
"501",
"502",
"503",
"504",
"505",
"506",
"507",
}
x := m0.newIter(nil)
kv := x.SeekGE([]byte(wants[0]), base.SeekGEFlagsNone)
for _, want := range wants {
if kv == nil {
t.Fatalf("iter: next failed, want=%q", want)
}
if got := string(kv.K.UserKey); got != want {
t.Fatalf("iter: got %q, want %q", got, want)
}
if k := kv.K.UserKey; len(k) != cap(k) {
t.Fatalf("iter: len(k)=%d, cap(k)=%d", len(k), cap(k))
}
v, _, err := kv.Value(nil)
require.NoError(t, err)
if len(v) != cap(v) {
t.Fatalf("iter: len(v)=%d, cap(v)=%d", len(v), cap(v))
}
x.Next()
}
if err := x.Close(); err != nil {
t.Fatalf("close: %v", err)
}
}
func TestMemTableIter(t *testing.T) {
var mem *memTable
for _, testdata := range []string{
"testdata/internal_iter_next", "testdata/internal_iter_bounds"} {
datadriven.RunTest(t, testdata, func(t *testing.T, d *datadriven.TestData) string {
switch d.Cmd {
case "define":
mem = newMemTable(memTableOptions{})
for _, key := range strings.Split(d.Input, "\n") {
j := strings.Index(key, ":")
if err := mem.set(base.ParseInternalKey(key[:j]), []byte(key[j+1:])); err != nil {
return err.Error()
}
}
return ""
case "iter":
var options IterOptions
for _, arg := range d.CmdArgs {
switch arg.Key {
case "lower":
if len(arg.Vals) != 1 {
return fmt.Sprintf(
"%s expects at most 1 value for lower", d.Cmd)
}
options.LowerBound = []byte(arg.Vals[0])
case "upper":
if len(arg.Vals) != 1 {
return fmt.Sprintf(
"%s expects at most 1 value for upper", d.Cmd)
}
options.UpperBound = []byte(arg.Vals[0])
default:
return fmt.Sprintf("unknown arg: %s", arg.Key)
}
}
iter := mem.newIter(&options)
defer iter.Close()
return itertest.RunInternalIterCmd(t, d, iter)
default:
return fmt.Sprintf("unknown command: %s", d.Cmd)
}
})
}
}
func TestMemTableDeleteRange(t *testing.T) {
var mem *memTable
var seqNum base.SeqNum
datadriven.RunTest(t, "testdata/delete_range", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "clear":
mem = nil
seqNum = 0
return ""
case "define":
b := newBatch(nil)
if err := runBatchDefineCmd(td, b); err != nil {
return err.Error()
}
if mem == nil {
mem = newMemTable(memTableOptions{})
}
if err := mem.apply(b, seqNum); err != nil {
return err.Error()
}
seqNum += base.SeqNum(b.Count())
return ""
case "scan":
var buf bytes.Buffer
if td.HasArg("range-del") {
iter := mem.newRangeDelIter(nil)
defer iter.Close()
scanKeyspanIterator(&buf, iter)
} else {
iter := mem.newIter(nil)
defer iter.Close()
scanInternalIter(&buf, iter)
}
return buf.String()
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestMemTableConcurrentDeleteRange(t *testing.T) {
// Concurrently write and read range tombstones. Workers add range
// tombstones, and then immediately retrieve them verifying that the
// tombstones they've added are all present.
m := newMemTable(memTableOptions{Options: &Options{MemTableSize: 64 << 20}})
const workers = 10
eg, _ := errgroup.WithContext(context.Background())
var seqNum base.AtomicSeqNum
seqNum.Store(1)
for i := 0; i < workers; i++ {
i := i
eg.Go(func() error {
start := ([]byte)(fmt.Sprintf("%03d", i))
end := ([]byte)(fmt.Sprintf("%03d", i+1))
for j := 0; j < 100; j++ {
b := newBatch(nil)
b.DeleteRange(start, end, nil)
n := seqNum.Add(1) - 1
require.NoError(t, m.apply(b, n))
b.Close()
var count int
it := m.newRangeDelIter(nil)
s, err := it.SeekGE(start)
for ; s != nil; s, err = it.Next() {
if m.cmp(s.Start, end) >= 0 {
break
}
count += len(s.Keys)
}
if err != nil {
return err
}
if j+1 != count {
return errors.Errorf("%d: expected %d tombstones, but found %d", i, j+1, count)
}
}
return nil
})
}
err := eg.Wait()
if err != nil {
t.Error(err)
}
}
func TestMemTableReserved(t *testing.T) {
m := newMemTable(memTableOptions{size: 5000})
// Increase to 2 references.
m.writerRef()
// The initial reservation accounts for the already allocated bytes from the
// arena.
require.Equal(t, m.reserved, m.skl.Arena().Size())
b := newBatch(nil)
b.Set([]byte("blueberry"), []byte("pie"), nil)
require.NotEqual(t, 0, int(b.memTableSize))
prevReserved := m.reserved
m.prepare(b)
require.Equal(t, int(m.reserved), int(b.memTableSize)+int(prevReserved))
}
func TestMemTable(t *testing.T) {
var m *memTable
var buf bytes.Buffer
batches := map[string]*Batch{}
summary := func() string {
return fmt.Sprintf("%d of %d bytes available",
m.availBytes(), m.totalBytes())
}
datadriven.RunTest(t, "testdata/mem_table", func(t *testing.T, td *datadriven.TestData) string {
buf.Reset()
switch td.Cmd {
case "new":
var o memTableOptions
td.MaybeScanArgs(t, "size", &o.size)
m = newMemTable(o)
return ""
case "prepare":
var name string
td.ScanArgs(t, "name", &name)
b := newBatch(nil)
if err := runBatchDefineCmd(td, b); err != nil {
return err.Error()
}
batches[name] = b
if err := m.prepare(b); err != nil {
return err.Error()
}
return summary()
case "apply":
var name string
var seqNum uint64
td.ScanArgs(t, "name", &name)
td.ScanArgs(t, "seq", &seqNum)
if err := m.apply(batches[name], base.SeqNum(seqNum)); err != nil {
return err.Error()
}
delete(batches, name)
return summary()
case "computePossibleOverlaps":
stopAfterFirst := td.HasArg("stop-after-first")
var keyRanges []bounded
for _, l := range strings.Split(td.Input, "\n") {
s := strings.FieldsFunc(l, func(r rune) bool { return unicode.IsSpace(r) || r == '-' })
keyRanges = append(keyRanges, KeyRange{Start: []byte(s[0]), End: []byte(s[1])})
}
m.computePossibleOverlaps(func(b bounded) shouldContinue {
fmt.Fprintf(&buf, "%s\n", b)
if stopAfterFirst {
return stopIteration
}
return continueIteration
}, keyRanges...)
return buf.String()
default:
return fmt.Sprintf("unrecognized command %q", td.Cmd)
}
})
}
func buildMemTable(b *testing.B) (*memTable, [][]byte) {
m := newMemTable(memTableOptions{})
var keys [][]byte
var ikey InternalKey
for i := 0; ; i++ {
key := []byte(fmt.Sprintf("%08d", i))
keys = append(keys, key)
ikey = base.MakeInternalKey(key, 0, InternalKeyKindSet)
if m.set(ikey, nil) == arenaskl.ErrArenaFull {
break
}
}
return m, keys
}
func BenchmarkMemTableIterSeekGE(b *testing.B) {
m, keys := buildMemTable(b)
iter := m.newIter(nil)
rng := rand.New(rand.NewPCG(0, uint64(time.Now().UnixNano())))
b.ResetTimer()
for i := 0; i < b.N; i++ {
iter.SeekGE(keys[rng.IntN(len(keys))], base.SeekGEFlagsNone)
}
}
func BenchmarkMemTableIterSeqSeekGEWithBounds(b *testing.B) {
m, keys := buildMemTable(b)
rng := rand.New(rand.NewPCG(0, uint64(17136275210000)))
// Set bounds to restrict iteration to the middle 50% of keys.
iter := m.newIter(&IterOptions{
LowerBound: keys[len(keys)/4],
UpperBound: keys[3*len(keys)/4],
})
b.ResetTimer()
for i := 0; i < b.N; i++ {
iter.SeekGE(keys[rng.IntN(len(keys))], base.SeekGEFlagsNone)
}
}
// BenchmarkMemTableIterSeekGESuccessiveWithBounds benchmarks a particular case
// where an upper bound excludes the majority of the memtable keys and the user
// seeks the iterator with successively increasing keys. This pattern is
// expected to be common in CockroachDB: eg, intent resolution with an upper
// bound at the end of the lock table span, or a MVCC iterator with an upper
// bound restricting constraining iteration to a single CockroachDB Range.
func BenchmarkMemTableIterSeekGESuccessiveWithBounds(b *testing.B) {
m, keys := buildMemTable(b)
iter := m.newIter(&IterOptions{
UpperBound: keys[1],
})
flags := base.SeekGEFlagsNone.EnableTrySeekUsingNext()
seekKeys := make([][]byte, 256)
for i := 1; i < len(seekKeys); i++ {
seekKeys[i] = append(append([]byte(nil), keys[0]...), byte(i-1))
}
b.ResetTimer()
iter.SeekGE(keys[0], base.SeekGEFlagsNone)
for i := 0; i < b.N-1; i++ {
iter.SeekGE(seekKeys[i%len(seekKeys)], flags)
}
}
func BenchmarkMemTableIterNext(b *testing.B) {
m, _ := buildMemTable(b)
iter := m.newIter(nil)
_ = iter.First()
b.ResetTimer()
for i := 0; i < b.N; i++ {
kv := iter.Next()
if kv == nil {
kv = iter.First()
}
_ = kv
}
}
func BenchmarkMemTableIterNextWithBounds(b *testing.B) {
m, keys := buildMemTable(b)
// Set bounds to restrict iteration to the middle 50% of keys.
opts := &IterOptions{
LowerBound: keys[len(keys)/4],
UpperBound: keys[3*len(keys)/4],
}
iter := m.newIter(opts)
_ = iter.SeekGE(opts.LowerBound, base.SeekGEFlagsNone)
b.ResetTimer()
for i := 0; i < b.N; i++ {
kv := iter.Next()
if kv == nil {
kv = iter.SeekGE(opts.LowerBound, base.SeekGEFlagsNone)
}
_ = kv
}
}
func BenchmarkMemTableIterPrev(b *testing.B) {
m, _ := buildMemTable(b)
iter := m.newIter(nil)
_ = iter.Last()
b.ResetTimer()
for i := 0; i < b.N; i++ {
kv := iter.Prev()
if kv == nil {
kv = iter.Last()
}
_ = kv
}
}
func BenchmarkMemTableIterPrevWithBounds(b *testing.B) {
m, keys := buildMemTable(b)
// Set bounds to restrict iteration to the middle 50% of keys.
opts := &IterOptions{
LowerBound: keys[len(keys)/4],
UpperBound: keys[3*len(keys)/4],
}
iter := m.newIter(opts)
_ = iter.SeekLT(opts.UpperBound, base.SeekLTFlagsNone)
b.ResetTimer()
for i := 0; i < b.N; i++ {
kv := iter.Prev()
if kv == nil {
kv = iter.SeekLT(opts.UpperBound, base.SeekLTFlagsNone)
}
_ = kv
}
}