forked from cockroachdb/pebble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compaction_iter_test.go
360 lines (342 loc) · 10.4 KB
/
compaction_iter_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
// 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"
"encoding/binary"
"fmt"
"io"
"slices"
"strconv"
"strings"
"testing"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/invalidating"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/rangekey"
"github.com/stretchr/testify/require"
)
func TestSnapshotIndex(t *testing.T) {
testCases := []struct {
snapshots []uint64
seq uint64
expectedIndex int
expectedSeqNum uint64
}{
{[]uint64{}, 1, 0, InternalKeySeqNumMax},
{[]uint64{1}, 0, 0, 1},
{[]uint64{1}, 1, 1, InternalKeySeqNumMax},
{[]uint64{1}, 2, 1, InternalKeySeqNumMax},
{[]uint64{1, 3}, 1, 1, 3},
{[]uint64{1, 3}, 2, 1, 3},
{[]uint64{1, 3}, 3, 2, InternalKeySeqNumMax},
{[]uint64{1, 3}, 4, 2, InternalKeySeqNumMax},
{[]uint64{1, 3, 3}, 2, 1, 3},
}
for _, c := range testCases {
t.Run("", func(t *testing.T) {
idx, seqNum := snapshotIndex(c.seq, c.snapshots)
if c.expectedIndex != idx {
t.Fatalf("expected %d, but got %d", c.expectedIndex, idx)
}
if c.expectedSeqNum != seqNum {
t.Fatalf("expected %d, but got %d", c.expectedSeqNum, seqNum)
}
})
}
}
type debugMerger struct {
buf []byte
}
func (m *debugMerger) MergeNewer(value []byte) error {
m.buf = append(m.buf, value...)
return nil
}
func (m *debugMerger) MergeOlder(value []byte) error {
buf := make([]byte, 0, len(m.buf)+len(value))
buf = append(buf, value...)
buf = append(buf, m.buf...)
m.buf = buf
return nil
}
func (m *debugMerger) Finish(includesBase bool) ([]byte, io.Closer, error) {
if includesBase {
m.buf = append(m.buf, []byte("[base]")...)
}
return m.buf, nil, nil
}
func TestCompactionIter(t *testing.T) {
var merge Merge
var kvs []base.InternalKV
var rangeKeys []keyspan.Span
var rangeDels []keyspan.Span
var snapshots []uint64
var elideTombstones bool
var allowZeroSeqnum bool
var rangeKeyInterleaving *keyspan.InterleavingIter
var rangeDelInterleaving *keyspan.InterleavingIter
// The input to the data-driven test is dependent on the format major
// version we are testing against.
fileFunc := func(formatVersion FormatMajorVersion) string {
if formatVersion < FormatDeleteSizedAndObsolete {
return "testdata/compaction_iter_set_with_del"
}
return "testdata/compaction_iter_delete_sized"
}
var ineffectualSingleDeleteKeys []string
var invariantViolationSingleDeleteKeys []string
resetSingleDelStats := func() {
ineffectualSingleDeleteKeys = ineffectualSingleDeleteKeys[:0]
invariantViolationSingleDeleteKeys = invariantViolationSingleDeleteKeys[:0]
}
newIter := func(formatVersion FormatMajorVersion) *compactionIter {
// To adhere to the existing assumption that range deletion blocks in
// SSTables are not released while iterating, and therefore not
// susceptible to use-after-free bugs, we skip the zeroing of
// RangeDelete keys.
fi := &fakeIter{kvs: kvs}
rangeDelInterleaving = &keyspan.InterleavingIter{}
rangeDelInterleaving.Init(
base.DefaultComparer,
fi,
keyspan.NewIter(base.DefaultComparer.Compare, rangeDels),
keyspan.InterleavingIterOpts{})
rangeKeyInterleaving = &keyspan.InterleavingIter{}
rangeKeyInterleaving.Init(
base.DefaultComparer,
rangeDelInterleaving,
keyspan.NewIter(base.DefaultComparer.Compare, rangeKeys),
keyspan.InterleavingIterOpts{})
iter := invalidating.NewIter(rangeKeyInterleaving, invalidating.IgnoreKinds(InternalKeyKindRangeDelete))
if merge == nil {
merge = func(key, value []byte) (base.ValueMerger, error) {
m := &debugMerger{}
m.buf = append(m.buf, value...)
return m, nil
}
}
resetSingleDelStats()
return newCompactionIter(
DefaultComparer.Compare,
DefaultComparer.Equal,
DefaultComparer.FormatKey,
merge,
iter,
snapshots,
&keyspan.Fragmenter{},
&keyspan.Fragmenter{},
allowZeroSeqnum,
func([]byte) bool {
return elideTombstones
},
func(_, _ []byte) bool {
return elideTombstones
},
func(userKey []byte) {
ineffectualSingleDeleteKeys = append(ineffectualSingleDeleteKeys, string(userKey))
},
func(userKey []byte) {
invariantViolationSingleDeleteKeys = append(invariantViolationSingleDeleteKeys, string(userKey))
},
formatVersion,
)
}
runTest := func(t *testing.T, formatVersion FormatMajorVersion) {
datadriven.RunTest(t, fileFunc(formatVersion), func(t *testing.T, d *datadriven.TestData) string {
switch d.Cmd {
case "define":
merge = nil
if len(d.CmdArgs) > 0 && d.CmdArgs[0].Key == "merger" &&
len(d.CmdArgs[0].Vals) > 0 && d.CmdArgs[0].Vals[0] == "deletable" {
merge = newDeletableSumValueMerger
}
kvs = kvs[:0]
rangeKeys = rangeKeys[:0]
rangeDels = rangeDels[:0]
rangeDelFragmenter := keyspan.Fragmenter{
Cmp: DefaultComparer.Compare,
Format: DefaultComparer.FormatKey,
Emit: func(s keyspan.Span) {
rangeDels = append(rangeDels, s)
},
}
for _, key := range strings.Split(d.Input, "\n") {
// If the line ends in a '}' assume it's a span.
if strings.HasSuffix(key, "}") {
s := keyspan.ParseSpan(strings.TrimSpace(key))
rangeKeys = append(rangeKeys, s)
continue
}
j := strings.Index(key, ":")
ik := base.ParseInternalKey(key[:j])
if rangekey.IsRangeKey(ik.Kind()) {
panic("range keys must be pre-fragmented and formatted as spans")
}
if ik.Kind() == base.InternalKeyKindRangeDelete {
rangeDelFragmenter.Add(keyspan.Span{
Start: ik.UserKey,
End: []byte(key[j+1:]),
Keys: []keyspan.Key{{Trailer: ik.Trailer}},
})
continue
}
var value []byte
if strings.HasPrefix(key[j+1:], "varint(") {
valueStr := strings.TrimSuffix(strings.TrimPrefix(key[j+1:], "varint("), ")")
v, err := strconv.ParseUint(valueStr, 10, 64)
require.NoError(t, err)
value = binary.AppendUvarint([]byte(nil), v)
} else {
value = []byte(key[j+1:])
}
kvs = append(kvs, base.MakeInternalKV(ik, value))
}
rangeDelFragmenter.Finish()
return ""
case "iter":
snapshots = snapshots[:0]
elideTombstones = false
allowZeroSeqnum = false
printSnapshotPinned := false
printMissizedDels := false
printForceObsolete := false
for _, arg := range d.CmdArgs {
switch arg.Key {
case "snapshots":
for _, val := range arg.Vals {
seqNum, err := strconv.Atoi(val)
if err != nil {
return err.Error()
}
snapshots = append(snapshots, uint64(seqNum))
}
case "elide-tombstones":
var err error
elideTombstones, err = strconv.ParseBool(arg.Vals[0])
if err != nil {
return err.Error()
}
case "allow-zero-seqnum":
var err error
allowZeroSeqnum, err = strconv.ParseBool(arg.Vals[0])
if err != nil {
return err.Error()
}
case "print-snapshot-pinned":
printSnapshotPinned = true
case "print-missized-dels":
printMissizedDels = true
case "print-force-obsolete":
printForceObsolete = true
default:
return fmt.Sprintf("%s: unknown arg: %s", d.Cmd, arg.Key)
}
}
slices.Sort(snapshots)
iter := newIter(formatVersion)
var b bytes.Buffer
for _, line := range strings.Split(d.Input, "\n") {
parts := strings.Fields(line)
if len(parts) == 0 {
continue
}
switch parts[0] {
case "first":
iter.First()
case "next":
iter.Next()
case "tombstones":
var key []byte
if len(parts) == 2 {
key = []byte(parts[1])
}
for _, v := range iter.Tombstones(key) {
for _, k := range v.Keys {
fmt.Fprintf(&b, "%s-%s#%d\n", v.Start, v.End, k.SeqNum())
}
}
fmt.Fprintf(&b, ".\n")
continue
case "range-keys":
var key []byte
if len(parts) == 2 {
key = []byte(parts[1])
}
for _, v := range iter.RangeKeys(key) {
fmt.Fprintf(&b, "%s\n", v)
}
fmt.Fprintf(&b, ".\n")
continue
default:
return fmt.Sprintf("unknown op: %s", parts[0])
}
if iter.Valid() {
snapshotPinned := ""
if printSnapshotPinned {
snapshotPinned = " (not pinned)"
if iter.snapshotPinned {
snapshotPinned = " (pinned)"
}
}
forceObsolete := ""
if printForceObsolete {
forceObsolete = " (not force obsolete)"
if iter.forceObsoleteDueToRangeDel {
forceObsolete = " (force obsolete)"
}
}
v := string(iter.Value())
if iter.Key().Kind() == base.InternalKeyKindDeleteSized && len(iter.Value()) > 0 {
vn, n := binary.Uvarint(iter.Value())
if n != len(iter.Value()) {
v = fmt.Sprintf("err: %0x value not a uvarint", iter.Value())
} else {
v = fmt.Sprintf("varint(%d)", vn)
}
}
fmt.Fprintf(&b, "%s:%s%s%s", iter.Key(), v, snapshotPinned, forceObsolete)
if iter.Key().Kind() == InternalKeyKindRangeDelete {
iter.rangeDelFrag.Add(*rangeDelInterleaving.Span())
fmt.Fprintf(&b, "; Span() = %s", *rangeDelInterleaving.Span())
}
if rangekey.IsRangeKey(iter.Key().Kind()) {
iter.rangeKeyFrag.Add(*rangeKeyInterleaving.Span())
}
fmt.Fprintln(&b)
} else if err := iter.Error(); err != nil {
fmt.Fprintf(&b, "err=%v\n", err)
} else {
fmt.Fprintf(&b, ".\n")
}
}
if printMissizedDels {
fmt.Fprintf(&b, "missized-dels=%d\n", iter.stats.countMissizedDels)
}
if len(ineffectualSingleDeleteKeys) > 0 {
fmt.Fprintf(&b, "ineffectual-single-deletes: %s\n",
strings.Join(ineffectualSingleDeleteKeys, ","))
}
if len(invariantViolationSingleDeleteKeys) > 0 {
fmt.Fprintf(&b, "invariant-violation-single-deletes: %s\n",
strings.Join(invariantViolationSingleDeleteKeys, ","))
}
return b.String()
default:
return fmt.Sprintf("unknown command: %s", d.Cmd)
}
})
}
// Rather than testing against all format version, we test against the
// significant boundaries.
formatVersions := []FormatMajorVersion{
FormatMinSupported,
internalFormatNewest,
}
for _, formatVersion := range formatVersions {
t.Run(fmt.Sprintf("version-%s", formatVersion), func(t *testing.T) {
runTest(t, formatVersion)
})
}
}