-
Notifications
You must be signed in to change notification settings - Fork 468
/
iterator_histories_test.go
439 lines (427 loc) · 11.3 KB
/
iterator_histories_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
// Copyright 2022 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"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/testkeys"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/stretchr/testify/require"
)
// TODO(jackson): Add a range keys test with concurrency: the logic to cache
// fragmented spans is susceptible to races.
func TestIterHistories(t *testing.T) {
datadriven.Walk(t, "testdata/iter_histories", func(t *testing.T, path string) {
filename := filepath.Base(path)
switch {
case invariants.Enabled && strings.Contains(filename, "no_invariants"):
t.Skip("disabled when run with -tags invariants due to nondeterminism")
}
var d *DB
var refedCache bool
var buf bytes.Buffer
iters := map[string]*Iterator{}
batches := map[string]*Batch{}
newIter := func(name string, reader Reader, o *IterOptions) *Iterator {
it, _ := reader.NewIter(o)
iters[name] = it
return it
}
var opts *Options
parseOpts := func(td *datadriven.TestData) (*Options, error) {
opts = &Options{
FS: vfs.NewMem(),
Comparer: testkeys.Comparer,
FormatMajorVersion: FormatMinSupported,
BlockPropertyCollectors: []func() BlockPropertyCollector{
sstable.NewTestKeysBlockPropertyCollector,
},
Logger: testLogger{t},
}
opts.DisableAutomaticCompactions = true
opts.EnsureDefaults()
opts.WithFSDefaults()
originalCache := opts.Cache
if err := parseDBOptionsArgs(opts, td.CmdArgs); err != nil {
return nil, err
}
// If the test replaced the cache, we'll need to unref the
// new cache later.
refedCache = opts.Cache != originalCache
return opts, nil
}
cleanup := func() (err error) {
for key, batch := range batches {
err = firstError(err, batch.Close())
delete(batches, key)
}
for key, iter := range iters {
err = firstError(err, iter.Close())
delete(iters, key)
}
if d != nil {
// Close all open snapshots.
d.mu.Lock()
var ss []*Snapshot
l := &d.mu.snapshots
for i := l.root.next; i != &l.root; i = i.next {
ss = append(ss, i)
}
d.mu.Unlock()
for i := range ss {
err = firstError(err, ss[i].Close())
}
err = firstError(err, d.Close())
d = nil
}
if refedCache {
opts.Cache.Unref()
opts.Cache = nil
refedCache = false
}
return err
}
defer cleanup()
datadriven.RunTest(t, path, func(t *testing.T, td *datadriven.TestData) string {
buf.Reset()
switch td.Cmd {
case "define":
var err error
if err := cleanup(); err != nil {
return err.Error()
}
opts, err = parseOpts(td)
if err != nil {
return err.Error()
}
d, err = runDBDefineCmd(td, opts)
if err != nil {
return err.Error()
}
return runLSMCmd(td, d)
case "reopen":
var err error
if err := cleanup(); err != nil {
return err.Error()
}
originalCache := opts.Cache
if err := parseDBOptionsArgs(opts, td.CmdArgs); err != nil {
return err.Error()
}
// If the test replaced the cache, we'll need to unref the
// new cache later.
refedCache = originalCache != opts.Cache
d, err = Open("", opts)
require.NoError(t, err)
return ""
case "reset":
var err error
if err := cleanup(); err != nil {
return err.Error()
}
opts, err = parseOpts(td)
if err != nil {
return err.Error()
}
d, err = Open("", opts)
require.NoError(t, err)
return ""
case "populate":
b := d.NewBatch()
runPopulateCmd(t, td, b)
count := b.Count()
require.NoError(t, b.Commit(nil))
return fmt.Sprintf("wrote %d keys\n", count)
case "batch":
var name string
td.MaybeScanArgs(t, "name", &name)
commit := td.HasArg("commit")
b := d.NewIndexedBatch()
require.NoError(t, runBatchDefineCmd(td, b))
var err error
if commit {
func() {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
err = b.Commit(nil)
}()
} else if name != "" {
batches[name] = b
}
if err != nil {
return err.Error()
}
count := b.Count()
if commit {
return fmt.Sprintf("committed %d keys\n", count)
}
return fmt.Sprintf("wrote %d keys to batch %q\n", count, name)
case "compact":
if err := runCompactCmd(td, d); err != nil {
return err.Error()
}
return runLSMCmd(td, d)
case "flush":
err := d.Flush()
if err != nil {
return err.Error()
}
return ""
case "disable-flushes":
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
return ""
case "enable-flushes":
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
return ""
case "get":
var reader Reader = d
if arg, ok := td.Arg("reader"); ok {
if reader, ok = batches[arg.Vals[0]]; !ok {
return fmt.Sprintf("unknown reader %q", arg.Vals[0])
}
}
for _, l := range strings.Split(td.Input, "\n") {
v, closer, err := reader.Get([]byte(l))
if err != nil {
fmt.Fprintf(&buf, "%s: error: %s\n", l, err)
} else {
fmt.Fprintf(&buf, "%s: %s\n", l, v)
}
if err := closer.Close(); err != nil {
fmt.Fprintf(&buf, "close err: %s\n", err)
}
}
return buf.String()
case "build":
if err := runBuildCmd(td, d, d.opts.FS); err != nil {
return err.Error()
}
return ""
case "ingest-existing":
if err := runIngestCmd(td, d, d.opts.FS); err != nil {
return err.Error()
}
return ""
case "ingest":
if err := runBuildCmd(td, d, d.opts.FS); err != nil {
return err.Error()
}
if err := runIngestCmd(td, d, d.opts.FS); err != nil {
return err.Error()
}
return ""
case "layout":
var verbose bool
var filename string
td.ScanArgs(t, "filename", &filename)
td.MaybeScanArgs(t, "verbose", &verbose)
f, err := opts.FS.Open(filename)
if err != nil {
return err.Error()
}
readable, err := sstable.NewSimpleReadable(f)
if err != nil {
return err.Error()
}
r, err := sstable.NewReader(context.Background(), readable, opts.MakeReaderOptions())
if err != nil {
return err.Error()
}
defer r.Close()
l, err := r.Layout()
if err != nil {
return err.Error()
}
return l.Describe(verbose, r, nil)
case "lsm":
return runLSMCmd(td, d)
case "metrics":
d.mu.Lock()
d.waitTableStats()
d.mu.Unlock()
m := d.Metrics()
return fmt.Sprintf("Metrics.Keys.RangeKeySetsCount = %d\n", m.Keys.RangeKeySetsCount)
case "mutate":
var batchName string
td.ScanArgs(t, "batch", &batchName)
mut := newBatch(d)
if err := runBatchDefineCmd(td, mut); err != nil {
return err.Error()
}
if err := batches[batchName].Apply(mut, nil); err != nil {
return err.Error()
}
return ""
case "clone":
var from, to string
var cloneOpts CloneOptions
var iterOpts IterOptions
td.ScanArgs(t, "from", &from)
td.ScanArgs(t, "to", &to)
td.ScanArgs(t, "refresh-batch", &cloneOpts.RefreshBatchView)
fromIter := iters[from]
if foundAny, err := parseIterOptions(&iterOpts, &fromIter.opts, strings.Fields(td.Input)); err != nil {
return fmt.Sprintf("clone: %s", err.Error())
} else if foundAny {
cloneOpts.IterOptions = &iterOpts
}
var err error
iters[to], err = fromIter.Clone(cloneOpts)
if err != nil {
return err.Error()
}
return ""
case "commit":
name := pluckStringCmdArg(td, "batch")
b := batches[name]
defer b.Close()
count := b.Count()
require.NoError(t, d.Apply(b, nil))
delete(batches, name)
return fmt.Sprintf("committed %d keys\n", count)
case "combined-iter":
o := &IterOptions{KeyTypes: IterKeyTypePointsAndRanges}
var reader Reader = d
var name string
for _, arg := range td.CmdArgs {
switch arg.Key {
case "mask-suffix":
o.RangeKeyMasking.Suffix = []byte(arg.Vals[0])
case "mask-filter":
o.RangeKeyMasking.Filter = func() BlockPropertyFilterMask {
return sstable.NewTestKeysMaskingFilter()
}
case "lower":
o.LowerBound = []byte(arg.Vals[0])
case "upper":
o.UpperBound = []byte(arg.Vals[0])
case "name":
name = arg.Vals[0]
case "reader":
reader = batches[arg.Vals[0]]
if reader == nil {
return fmt.Sprintf("unknown reader %q", arg.Vals[0])
}
case "point-key-filter":
if len(arg.Vals) != 2 {
return fmt.Sprintf("blockprop-filter expects 2 arguments, received %d", len(arg.Vals))
}
min, err := strconv.ParseUint(arg.Vals[0], 10, 64)
if err != nil {
return err.Error()
}
max, err := strconv.ParseUint(arg.Vals[1], 10, 64)
if err != nil {
return err.Error()
}
o.PointKeyFilters = []sstable.BlockPropertyFilter{
sstable.NewTestKeysBlockPropertyFilter(min, max),
}
o.SkipPoint = func(k []byte) bool {
i := testkeys.Comparer.Split(k)
if i == len(k) {
return false
}
v, err := testkeys.ParseSuffix(k[i:])
if err != nil {
return false
}
return uint64(v) < min || uint64(v) >= max
}
case "snapshot":
s := base.ParseSeqNum(arg.Vals[0])
func() {
d.mu.Lock()
defer d.mu.Unlock()
l := &d.mu.snapshots
for i := l.root.next; i != &l.root; i = i.next {
if i.seqNum == s {
reader = i
break
}
}
}()
case "use-l6-filter":
o.UseL6Filters = true
}
}
var iter *Iterator
var err error
func() {
defer func() {
if r := recover(); r != nil {
switch v := r.(type) {
case string:
err = errors.New(v)
case error:
err = v
default:
panic(r)
}
}
}()
iter = newIter(name, reader, o)
}()
if err != nil {
return err.Error()
}
return runIterCmd(td, iter, name == "" /* close iter */)
case "rangekey-iter":
name := pluckStringCmdArg(td, "name")
iter := newIter(name, d, &IterOptions{KeyTypes: IterKeyTypeRangesOnly})
return runIterCmd(td, iter, name == "" /* close iter */)
case "scan-rangekeys":
iter := newIter(
pluckStringCmdArg(td, "name"),
d,
&IterOptions{KeyTypes: IterKeyTypeRangesOnly},
)
func() {
defer iter.Close()
for iter.First(); iter.Valid(); iter.Next() {
start, end := iter.RangeBounds()
fmt.Fprintf(&buf, "[%s, %s)\n", start, end)
writeRangeKeys(&buf, iter)
fmt.Fprintln(&buf)
}
}()
return buf.String()
case "iter":
var name string
td.ScanArgs(t, "iter", &name)
return runIterCmd(td, iters[name], false /* close iter */)
case "wait-table-stats":
d.mu.Lock()
d.waitTableStats()
d.mu.Unlock()
return ""
default:
return fmt.Sprintf("unknown command %q", td.Cmd)
}
})
})
}
func pluckStringCmdArg(td *datadriven.TestData, key string) string {
if arg, ok := td.Arg(key); ok {
return arg.Vals[0]
}
return ""
}