-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
engine_test.go
2609 lines (2372 loc) · 78.2 KB
/
engine_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 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package storage
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"math"
"math/rand"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/fs"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/pebble"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)
func ensureRangeEqual(
t *testing.T, sortedKeys []string, keyMap map[string][]byte, keyvals []MVCCKeyValue,
) {
t.Helper()
if len(keyvals) != len(sortedKeys) {
t.Errorf("length mismatch. expected %s, got %s", sortedKeys, keyvals)
}
for i, kv := range keyvals {
if sortedKeys[i] != string(kv.Key.Key) {
t.Errorf("key mismatch at index %d: expected %q, got %q", i, sortedKeys[i], kv.Key)
}
if !bytes.Equal(keyMap[sortedKeys[i]], kv.Value) {
t.Errorf("value mismatch at index %d: expected %q, got %q", i, keyMap[sortedKeys[i]], kv.Value)
}
}
}
// TestEngineBatchCommit writes a batch containing 10K rows (all the
// same key) and concurrently attempts to read the value in a tight
// loop. The test verifies that either there is no value for the key
// or it contains the final value, but never a value in between.
func TestEngineBatchCommit(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
numWrites := 10000
key := mvccKey("a")
finalVal := []byte(strconv.Itoa(numWrites - 1))
e := NewDefaultInMemForTesting()
defer e.Close()
// Start a concurrent read operation in a busy loop.
readsBegun := make(chan struct{})
readsDone := make(chan error)
writesDone := make(chan struct{})
go func() {
readsDone <- func() error {
readsBegunAlias := readsBegun
for {
select {
case <-writesDone:
return nil
default:
val, err := mvccGetRawWithError(t, e, key)
if err != nil {
return err
}
if val != nil && !bytes.Equal(val, finalVal) {
return errors.Errorf("key value should be empty or %q; got %q", string(finalVal), string(val))
}
if readsBegunAlias != nil {
close(readsBegunAlias)
readsBegunAlias = nil
}
}
}
}()
}()
// Wait until we've succeeded with first read.
<-readsBegun
// Create key/values and put them in a batch to engine.
batch := e.NewBatch()
defer batch.Close()
for i := 0; i < numWrites; i++ {
if err := batch.PutUnversioned(key.Key, []byte(strconv.Itoa(i))); err != nil {
t.Fatal(err)
}
}
if err := batch.Commit(false /* sync */); err != nil {
t.Fatal(err)
}
close(writesDone)
if err := <-readsDone; err != nil {
t.Fatal(err)
}
}
func TestEngineBatchStaleCachedIterator(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Prevent regression of a bug which caused spurious MVCC errors due to an
// invalid optimization which let an iterator return key-value pairs which
// had since been deleted from the underlying engine.
// Discovered in #6878.
eng := NewDefaultInMemForTesting()
defer eng.Close()
// Focused failure mode: highlights the actual bug.
{
batch := eng.NewBatch()
defer batch.Close()
iter := batch.NewMVCCIterator(MVCCKeyAndIntentsIterKind, IterOptions{UpperBound: roachpb.KeyMax})
key := MVCCKey{Key: roachpb.Key("b")}
if err := batch.PutUnversioned(key.Key, []byte("foo")); err != nil {
t.Fatal(err)
}
iter.SeekGE(key)
if err := batch.ClearUnversioned(key.Key); err != nil {
t.Fatal(err)
}
// MVCCIterator should not reuse its cached result.
iter.SeekGE(key)
if ok, err := iter.Valid(); err != nil {
t.Fatal(err)
} else if ok {
v, _ := iter.UnsafeValue()
t.Fatalf("iterator unexpectedly valid: %v -> %v", iter.UnsafeKey(), v)
}
iter.Close()
}
// Higher-level failure mode. Mostly for documentation.
{
batch := eng.NewBatch()
defer batch.Close()
key := roachpb.Key("z")
// Put a value so that the deletion below finds a value to seek
// to.
if err := MVCCPut(context.Background(), batch, key, hlc.Timestamp{}, roachpb.MakeValueFromString("x"), MVCCWriteOptions{}); err != nil {
t.Fatal(err)
}
// Seek the iterator to `key` and clear the value (but without
// telling the iterator about that).
if _, err := MVCCDelete(context.Background(), batch, key, hlc.Timestamp{}, MVCCWriteOptions{}); err != nil {
t.Fatal(err)
}
// Trigger a seek on the cached iterator by seeking to the (now
// absent) key.
// The underlying iterator will already be in the right position
// due to a seek in MVCCDelete (followed by a Clear, which does not
// invalidate the iterator's cache), and if it reports its cached
// result back, we'll see the (newly deleted) value (due to the
// failure mode above).
if valRes, err := MVCCGet(context.Background(), batch, key,
hlc.Timestamp{}, MVCCGetOptions{}); err != nil {
t.Fatal(err)
} else if valRes.Value != nil {
t.Fatalf("expected no value, got %+v", valRes.Value)
}
}
}
func TestEngineBatch(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
numShuffles := 100
key := mvccKey("a")
// Those are randomized below.
type data struct {
key MVCCKey
value []byte
merge bool
}
batch := []data{
{key, appender("~ockroachDB"), false},
{key, appender("C~ckroachDB"), false},
{key, appender("Co~kroachDB"), false},
{key, appender("Coc~roachDB"), false},
{key, appender("Cock~oachDB"), false},
{key, appender("Cockr~achDB"), false},
{key, appender("Cockro~chDB"), false},
{key, appender("Cockroa~hDB"), false},
{key, appender("Cockroac~DB"), false},
{key, appender("Cockroach~B"), false},
{key, appender("CockroachD~"), false},
{key, nil, false},
{key, appender("C"), true},
{key, appender(" o"), true},
{key, appender(" c"), true},
{key, appender(" k"), true},
{key, appender("r"), true},
{key, appender(" o"), true},
{key, appender(" a"), true},
{key, appender(" c"), true},
{key, appender("h"), true},
{key, appender(" D"), true},
{key, appender(" B"), true},
}
apply := func(rw ReadWriter, d data) error {
if d.value == nil {
return rw.ClearUnversioned(d.key.Key)
} else if d.merge {
return rw.Merge(d.key, d.value)
}
return rw.PutUnversioned(d.key.Key, d.value)
}
get := func(rw ReadWriter, key MVCCKey) []byte {
b := mvccGetRaw(t, rw, key)
var m enginepb.MVCCMetadata
if err := protoutil.Unmarshal(b, &m); err != nil {
t.Fatal(err)
}
if !m.IsInline() {
return nil
}
valueBytes, err := MakeValue(m).GetBytes()
if err != nil {
t.Fatal(err)
}
return valueBytes
}
for i := 0; i < numShuffles; i++ {
// In each run, create an array of shuffled operations.
shuffledIndices := rand.Perm(len(batch))
currentBatch := make([]data, len(batch))
for k := range currentBatch {
currentBatch[k] = batch[shuffledIndices[k]]
}
// Reset the key
if err := engine.ClearUnversioned(key.Key); err != nil {
t.Fatal(err)
}
// Run it once with individual operations and remember the result.
for i, op := range currentBatch {
if err := apply(engine, op); err != nil {
t.Errorf("%d: op %v: %+v", i, op, err)
continue
}
}
expectedValue := get(engine, key)
// Run the whole thing as a batch and compare.
b := engine.NewBatch()
defer b.Close()
if err := b.ClearUnversioned(key.Key); err != nil {
t.Fatal(err)
}
for _, op := range currentBatch {
if err := apply(b, op); err != nil {
t.Fatal(err)
}
}
// Try getting the value from the batch.
actualValue := get(b, key)
if !bytes.Equal(actualValue, expectedValue) {
t.Errorf("%d: expected %s, but got %s", i, expectedValue, actualValue)
}
// Try using an iterator to get the value from the batch.
iter := b.NewMVCCIterator(MVCCKeyAndIntentsIterKind, IterOptions{UpperBound: roachpb.KeyMax})
iter.SeekGE(key)
if ok, err := iter.Valid(); !ok {
if currentBatch[len(currentBatch)-1].value != nil {
t.Errorf("%d: batch seek invalid, err=%v", i, err)
}
} else if !iter.UnsafeKey().Equal(key) {
t.Errorf("%d: batch seek expected key %s, but got %s", i, key, iter.UnsafeKey())
} else {
var m enginepb.MVCCMetadata
if err := iter.ValueProto(&m); err != nil {
t.Fatal(err)
}
valueBytes, err := MakeValue(m).GetBytes()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(valueBytes, expectedValue) {
t.Errorf("%d: expected %s, but got %s", i, expectedValue, valueBytes)
}
}
iter.Close()
// Commit the batch and try getting the value from the engine.
if err := b.Commit(false /* sync */); err != nil {
t.Errorf("%d: %+v", i, err)
continue
}
actualValue = get(engine, key)
if !bytes.Equal(actualValue, expectedValue) {
t.Errorf("%d: expected %s, but got %s", i, expectedValue, actualValue)
}
}
}
func TestEnginePutGetDelete(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
// Test for correct handling of empty keys, which should produce errors.
for i, err := range []error{
engine.PutUnversioned(mvccKey("").Key, []byte("")),
engine.PutUnversioned(NilKey.Key, []byte("")),
engine.ClearUnversioned(NilKey.Key),
engine.ClearUnversioned(NilKey.Key),
engine.ClearUnversioned(mvccKey("").Key),
} {
if err == nil {
t.Fatalf("%d: illegal handling of empty key", i)
}
}
// Test for allowed keys, which should go through.
testCases := []struct {
key MVCCKey
value []byte
}{
{mvccKey("dog"), []byte("woof")},
{mvccKey("cat"), []byte("meow")},
{mvccKey("emptyval"), nil},
{mvccKey("emptyval2"), []byte("")},
{mvccKey("server"), []byte("42")},
}
for _, c := range testCases {
val := mvccGetRaw(t, engine, c.key)
if len(val) != 0 {
t.Errorf("expected key %q value.Bytes to be nil: got %+v", c.key, val)
}
if err := engine.PutUnversioned(c.key.Key, c.value); err != nil {
t.Errorf("put: expected no error, but got %s", err)
}
val = mvccGetRaw(t, engine, c.key)
if !bytes.Equal(val, c.value) {
t.Errorf("expected key value %s to be %+v: got %+v", c.key, c.value, val)
}
if err := engine.ClearUnversioned(c.key.Key); err != nil {
t.Errorf("delete: expected no error, but got %s", err)
}
val = mvccGetRaw(t, engine, c.key)
if len(val) != 0 {
t.Errorf("expected key %s value.Bytes to be nil: got %+v", c.key, val)
}
}
}
func addMergeTimestamp(t *testing.T, data []byte, ts int64) []byte {
var v enginepb.MVCCMetadata
if err := protoutil.Unmarshal(data, &v); err != nil {
t.Fatal(err)
}
v.MergeTimestamp = &hlc.LegacyTimestamp{WallTime: ts}
return mustMarshal(&v)
}
var testtime = int64(-446061360000000000)
type tsSample struct {
offset int32
count uint32
sum float64
max float64
min float64
}
// timeSeriesRow generates a simple InternalTimeSeriesData object which starts
// at the given timestamp and has samples of the given duration. The time series
// is written using the older sample-row data format. The object is stored in an
// MVCCMetadata object and marshaled to bytes.
func timeSeriesRow(start int64, duration int64, samples ...tsSample) []byte {
tsv := timeSeriesRowAsValue(start, duration, samples...)
return mustMarshal(&enginepb.MVCCMetadataSubsetForMergeSerialization{RawBytes: tsv.RawBytes})
}
func timeSeriesRowAsValue(start int64, duration int64, samples ...tsSample) roachpb.Value {
ts := &roachpb.InternalTimeSeriesData{
StartTimestampNanos: start,
SampleDurationNanos: duration,
}
for _, sample := range samples {
newSample := roachpb.InternalTimeSeriesSample{
Offset: sample.offset,
Count: sample.count,
Sum: sample.sum,
}
if sample.count > 1 {
newSample.Max = proto.Float64(sample.max)
newSample.Min = proto.Float64(sample.min)
}
ts.Samples = append(ts.Samples, newSample)
}
var v roachpb.Value
if err := v.SetProto(ts); err != nil {
panic(err)
}
return v
}
// TestEngineMerge tests that the passing through of engine merge operations
// to the goMerge function works as expected. The semantics are tested more
// exhaustively in the merge tests themselves.
func TestEngineMerge(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
testcases := []struct {
testKey MVCCKey
merges [][]byte
expected []byte
}{
{
// Test case with RawBytes only.
mvccKey("haste not in life"),
[][]byte{
appender("x"),
appender("y"),
appender("z"),
},
appender("xyz"),
},
{
// Test case with RawBytes and MergeTimestamp.
mvccKey("timeseriesmerged"),
[][]byte{
addMergeTimestamp(t, timeSeriesRow(testtime, 1000, []tsSample{
{1, 1, 5, 5, 5},
}...), 27),
timeSeriesRow(testtime, 1000, []tsSample{
{2, 1, 5, 5, 5},
{1, 2, 10, 7, 3},
}...),
addMergeTimestamp(t, timeSeriesRow(testtime, 1000, []tsSample{
{10, 1, 5, 5, 5},
}...), 53),
timeSeriesRow(testtime, 1000, []tsSample{
{5, 1, 5, 5, 5},
{3, 1, 5, 5, 5},
}...),
},
addMergeTimestamp(t, timeSeriesRow(testtime, 1000, []tsSample{
{1, 2, 10, 7, 3},
{2, 1, 5, 5, 5},
{3, 1, 5, 5, 5},
{5, 1, 5, 5, 5},
{10, 1, 5, 5, 5},
}...), 27),
},
}
engineBytes := make([][]byte, len(testcases))
for tcIndex, tc := range testcases {
for i, update := range tc.merges {
if err := engine.Merge(tc.testKey, update); err != nil {
t.Fatalf("%d: %+v", i, err)
}
}
result := mvccGetRaw(t, engine, tc.testKey)
engineBytes[tcIndex] = result
var resultV, expectedV enginepb.MVCCMetadata
if err := protoutil.Unmarshal(result, &resultV); err != nil {
t.Fatal(err)
}
if err := protoutil.Unmarshal(tc.expected, &expectedV); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(resultV, expectedV) {
t.Errorf("unexpected append-merge result: %v != %v", resultV, expectedV)
}
}
}
func TestEngineMustExist(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
tempDir, dirCleanupFn := testutils.TempDir(t)
defer dirCleanupFn()
_, err := Open(context.Background(), Filesystem(tempDir), cluster.MakeClusterSettings(), MustExist)
if err == nil {
t.Fatal("expected error related to missing directory")
}
if !strings.Contains(fmt.Sprint(err), "does not exist") {
t.Fatal(err)
}
}
func TestEngineTimeBound(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
minTimestamp := hlc.Timestamp{WallTime: 3, Logical: 0}
maxTimestamp := hlc.Timestamp{WallTime: 7, Logical: 0}
times := []hlc.Timestamp{
{WallTime: 5, Logical: 0},
minTimestamp,
maxTimestamp,
{WallTime: 5, Logical: 0},
}
for i, time := range times {
s := fmt.Sprintf("%02d", i)
key := MVCCKey{Key: roachpb.Key(s), Timestamp: time}
value := MVCCValue{Value: roachpb.MakeValueFromString(s)}
require.NoError(t, engine.PutMVCC(key, value))
}
require.NoError(t, engine.Flush())
batch := engine.NewBatch()
defer batch.Close()
testCases := map[string]struct {
iter MVCCIterator
keys int
}{
"right not touching": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: maxTimestamp.WallNext(),
MaxTimestampHint: maxTimestamp.WallNext().WallNext(),
UpperBound: roachpb.KeyMax,
}),
keys: 0,
},
"left not touching": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: minTimestamp.WallPrev().WallPrev(),
MaxTimestampHint: minTimestamp.WallPrev(),
UpperBound: roachpb.KeyMax,
}),
keys: 0,
},
"right touching": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: maxTimestamp,
MaxTimestampHint: maxTimestamp,
UpperBound: roachpb.KeyMax,
}),
keys: len(times),
},
"right touching ignores logical": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: maxTimestamp.Next(),
MaxTimestampHint: maxTimestamp.Next().Next(),
UpperBound: roachpb.KeyMax,
}),
keys: len(times),
},
"left touching": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: minTimestamp,
MaxTimestampHint: minTimestamp,
UpperBound: roachpb.KeyMax,
}),
keys: len(times),
},
"left touching upperbound": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: minTimestamp,
MaxTimestampHint: minTimestamp,
UpperBound: []byte("02"),
}),
keys: 2,
},
"between": {
iter: batch.NewMVCCIterator(MVCCKeyIterKind, IterOptions{
MinTimestampHint: minTimestamp.Next(),
MaxTimestampHint: minTimestamp.Next(),
UpperBound: roachpb.KeyMax,
}),
keys: len(times),
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
tbi := tc.iter
defer tbi.Close()
var count int
for tbi.SeekGE(NilKey); ; tbi.Next() {
ok, err := tbi.Valid()
require.NoError(t, err)
if !ok {
break
}
count++
}
require.Equal(t, tc.keys, count)
})
}
// Make a regular iterator. Before #21721, this would accidentally pick up the
// time bounded iterator instead.
iter := batch.NewMVCCIterator(MVCCKeyAndIntentsIterKind, IterOptions{UpperBound: roachpb.KeyMax})
defer iter.Close()
var count int
for iter.SeekGE(MVCCKey{Key: keys.LocalMax}); ; iter.Next() {
ok, err := iter.Valid()
require.NoError(t, err)
if !ok {
break
}
count++
}
// Make sure the iterator sees the writes (i.e. it's not the time bounded iterator).
require.Equal(t, len(times), count)
}
func TestFlushNumSSTables(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
batch := engine.NewBatch()
for i := 0; i < 10000; i++ {
key := make([]byte, 4)
binary.BigEndian.PutUint32(key, uint32(i))
err := batch.PutUnversioned(key, []byte("foobar"))
if err != nil {
t.Fatal(err)
}
}
err := batch.Commit(true)
if err != nil {
t.Fatal(err)
}
batch.Close()
err = engine.Flush()
if err != nil {
t.Fatal(err)
}
m := engine.GetMetrics()
if m.NumSSTables() == 0 {
t.Fatal("expected non-zero sstables, got 0")
}
}
func TestEngineScan1(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
testCases := []struct {
key MVCCKey
value []byte
}{
{mvccKey("dog"), []byte("woof")},
{mvccKey("cat"), []byte("meow")},
{mvccKey("server"), []byte("42")},
{mvccKey("french"), []byte("Allô?")},
{mvccKey("german"), []byte("hallo")},
{mvccKey("chinese"), []byte("你好")},
}
keyMap := map[string][]byte{}
for _, c := range testCases {
if err := engine.PutUnversioned(c.key.Key, c.value); err != nil {
t.Errorf("could not put key %q: %+v", c.key, err)
}
keyMap[string(c.key.Key)] = c.value
}
sortedKeys := make([]string, len(testCases))
for i, t := range testCases {
sortedKeys[i] = string(t.key.Key)
}
sort.Strings(sortedKeys)
keyvals, err := Scan(engine, roachpb.Key("chinese"), roachpb.Key("german"), 0)
if err != nil {
t.Fatalf("could not run scan: %+v", err)
}
ensureRangeEqual(t, sortedKeys[1:4], keyMap, keyvals)
// Check an end of range which does not equal an existing key.
keyvals, err = Scan(engine, roachpb.Key("chinese"), roachpb.Key("german1"), 0)
if err != nil {
t.Fatalf("could not run scan: %+v", err)
}
ensureRangeEqual(t, sortedKeys[1:5], keyMap, keyvals)
keyvals, err = Scan(engine, roachpb.Key("chinese"), roachpb.Key("german"), 2)
if err != nil {
t.Fatalf("could not run scan: %+v", err)
}
ensureRangeEqual(t, sortedKeys[1:3], keyMap, keyvals)
// Should return all key/value pairs in lexicographic order. Note that
// LocalMax is the lowest possible global key.
startKeys := []roachpb.Key{roachpb.Key("cat"), keys.LocalMax}
for _, startKey := range startKeys {
keyvals, err = Scan(engine, startKey, roachpb.KeyMax, 0)
if err != nil {
t.Fatalf("could not run scan: %+v", err)
}
ensureRangeEqual(t, sortedKeys, keyMap, keyvals)
}
// Test iterator stats.
ro := engine.NewReadOnly(StandardDurability)
iter := ro.NewMVCCIterator(MVCCKeyIterKind,
IterOptions{LowerBound: roachpb.Key("cat"), UpperBound: roachpb.Key("server")})
iter.SeekGE(MVCCKey{Key: roachpb.Key("cat")})
for {
valid, err := iter.Valid()
require.NoError(t, err)
if !valid {
break
}
iter.Next()
}
stats := iter.Stats().Stats
// Setting non-deterministic InternalStats to empty.
stats.InternalStats = pebble.InternalIteratorStats{}
require.Equal(t, "(interface (dir, seek, step): (fwd, 1, 5), (rev, 0, 0)), "+
"(internal (dir, seek, step): (fwd, 1, 5), (rev, 0, 0))", stats.String())
iter.Close()
iter = ro.NewMVCCIterator(MVCCKeyIterKind,
IterOptions{LowerBound: roachpb.Key("cat"), UpperBound: roachpb.Key("server")})
// pebble.Iterator is reused, but stats are reset.
stats = iter.Stats().Stats
// Setting non-deterministic InternalStats to empty.
stats.InternalStats = pebble.InternalIteratorStats{}
require.Equal(t, "(interface (dir, seek, step): (fwd, 0, 0), (rev, 0, 0)), "+
"(internal (dir, seek, step): (fwd, 0, 0), (rev, 0, 0))", stats.String())
iter.SeekGE(MVCCKey{Key: roachpb.Key("french")})
iter.SeekLT(MVCCKey{Key: roachpb.Key("server")})
stats = iter.Stats().Stats
// Setting non-deterministic InternalStats to empty.
stats.InternalStats = pebble.InternalIteratorStats{}
require.Equal(t, "(interface (dir, seek, step): (fwd, 1, 0), (rev, 1, 0)), "+
"(internal (dir, seek, step): (fwd, 1, 0), (rev, 1, 1))", stats.String())
iter.Close()
ro.Close()
}
func verifyScan(start, end roachpb.Key, max int64, expKeys []MVCCKey, engine Engine, t *testing.T) {
kvs, err := Scan(engine, start, end, max)
if err != nil {
t.Errorf("scan %q-%q: expected no error, but got %s", start, end, err)
}
if len(kvs) != len(expKeys) {
t.Errorf("scan %q-%q: expected scanned keys mismatch %d != %d: %v",
start, end, len(kvs), len(expKeys), kvs)
}
for i, kv := range kvs {
if !kv.Key.Equal(expKeys[i]) {
t.Errorf("scan %q-%q: expected keys equal %q != %q", start, end, kv.Key, expKeys[i])
}
}
}
func TestEngineScan2(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// TODO(Tobias): Merge this with TestEngineScan1 and remove
// either verifyScan or the other helper function.
engine := NewDefaultInMemForTesting()
defer engine.Close()
keys := []MVCCKey{
mvccKey("a"),
mvccKey("aa"),
mvccKey("aaa"),
mvccKey("ab"),
mvccKey("abc"),
mvccKey(roachpb.RKeyMax),
}
insertKeys(keys, engine, t)
// Scan all keys (non-inclusive of final key).
verifyScan(localMax, roachpb.KeyMax, 10, keys[:5], engine, t)
verifyScan(roachpb.Key("a"), roachpb.KeyMax, 10, keys[:5], engine, t)
// Scan sub range.
verifyScan(roachpb.Key("aab"), roachpb.Key("abcc"), 10, keys[3:5], engine, t)
verifyScan(roachpb.Key("aa0"), roachpb.Key("abcc"), 10, keys[2:5], engine, t)
// Scan with max values.
verifyScan(localMax, roachpb.KeyMax, 3, keys[:3], engine, t)
verifyScan(roachpb.Key("a0"), roachpb.KeyMax, 3, keys[1:4], engine, t)
// Scan with max value 0 gets all values.
verifyScan(localMax, roachpb.KeyMax, 0, keys[:5], engine, t)
}
func TestSnapshot(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
key := mvccKey("a")
val1 := []byte("1")
if err := engine.PutUnversioned(key.Key, val1); err != nil {
t.Fatal(err)
}
val := mvccGetRaw(t, engine, key)
if !bytes.Equal(val, val1) {
t.Fatalf("the value %s in get result does not match the value %s in request",
val, val1)
}
snap := engine.NewSnapshot()
defer snap.Close()
val2 := []byte("2")
if err := engine.PutUnversioned(key.Key, val2); err != nil {
t.Fatal(err)
}
val = mvccGetRaw(t, engine, key)
valSnapshot := mvccGetRaw(t, snap, key)
if !bytes.Equal(val, val2) {
t.Fatalf("the value %s in get result does not match the value %s in request",
val, val2)
}
if !bytes.Equal(valSnapshot, val1) {
t.Fatalf("the value %s in get result does not match the value %s in request",
valSnapshot, val1)
}
keyvals, _ := Scan(engine, key.Key, roachpb.KeyMax, 0)
keyvalsSnapshot, error := Scan(snap, key.Key, roachpb.KeyMax, 0)
if error != nil {
t.Fatalf("error : %s", error)
}
if len(keyvals) != 1 || !bytes.Equal(keyvals[0].Value, val2) {
t.Fatalf("the value %s in get result does not match the value %s in request",
keyvals[0].Value, val2)
}
if len(keyvalsSnapshot) != 1 || !bytes.Equal(keyvalsSnapshot[0].Value, val1) {
t.Fatalf("the value %s in get result does not match the value %s in request",
keyvalsSnapshot[0].Value, val1)
}
}
// TestSnapshotMethods verifies that snapshots allow only read-only
// engine operations.
func TestSnapshotMethods(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
engine := NewDefaultInMemForTesting()
defer engine.Close()
keys := []MVCCKey{mvccKey("a"), mvccKey("b")}
vals := [][]byte{[]byte("1"), []byte("2")}
for i := range keys {
if err := engine.PutUnversioned(keys[i].Key, vals[i]); err != nil {
t.Fatal(err)
}
val := mvccGetRaw(t, engine, keys[i])
if !bytes.Equal(vals[i], val) {
t.Fatalf("expected %s, but found %s", vals[i], val)
}
}
snap := engine.NewSnapshot()
defer snap.Close()
// Verify Get.
for i := range keys {
valSnapshot := mvccGetRaw(t, snap, keys[i])
if !bytes.Equal(vals[i], valSnapshot) {
t.Fatalf("the value %s in get result does not match the value %s in snapshot",
vals[i], valSnapshot)
}
}
// Verify Scan.
keyvals, _ := Scan(engine, localMax, roachpb.KeyMax, 0)
keyvalsSnapshot, err := Scan(snap, localMax, roachpb.KeyMax, 0)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(keyvals, keyvalsSnapshot) {
t.Fatalf("the key/values %v in scan result does not match the value %s in snapshot",
keyvals, keyvalsSnapshot)
}
// Verify MVCCIterate.
index := 0
if err := snap.MVCCIterate(localMax, roachpb.KeyMax, MVCCKeyAndIntentsIterKind, IterKeyTypePointsOnly,
func(kv MVCCKeyValue, _ MVCCRangeKeyStack) error {
if !kv.Key.Equal(keys[index]) || !bytes.Equal(kv.Value, vals[index]) {
t.Errorf("%d: key/value not equal between expected and snapshot: %s/%s, %s/%s",
index, keys[index], vals[index], kv.Key, kv.Value)
}
index++
return nil
}); err != nil {
t.Fatal(err)
}
// Write a new key to engine.
newKey := mvccKey("c")
newVal := []byte("3")
if err := engine.PutUnversioned(newKey.Key, newVal); err != nil {
t.Fatal(err)
}
// Verify NewMVCCIterator still iterates over original snapshot.
iter := snap.NewMVCCIterator(MVCCKeyAndIntentsIterKind, IterOptions{UpperBound: roachpb.KeyMax})
iter.SeekGE(newKey)
if ok, err := iter.Valid(); err != nil {
t.Fatal(err)
} else if ok {
t.Error("expected invalid iterator when seeking to element which shouldn't be visible to snapshot")
}
iter.Close()
}
func insertKeys(keys []MVCCKey, engine Engine, t *testing.T) {
insertKeysAndValues(keys, nil, engine, t)
}
func insertKeysAndValues(keys []MVCCKey, values [][]byte, engine Engine, t *testing.T) {
// Add keys to store in random order (make sure they sort!).
order := rand.Perm(len(keys))
for _, idx := range order {
var val []byte
if idx < len(values) {
val = values[idx]
} else {
val = []byte("value")
}
if err := engine.PutUnversioned(keys[idx].Key, val); err != nil {
t.Errorf("put: expected no error, but got %s", err)
}
}
}
func TestCreateCheckpoint(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
dir, cleanup := testutils.TempDir(t)
defer cleanup()