-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathmvcc_test.go
5113 lines (4656 loc) · 165 KB
/
mvcc_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"
"fmt"
"math"
"math/rand"
"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/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/zerofields"
"github.com/cockroachdb/cockroach/pkg/util/caller"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"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/shuffle"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/kr/pretty"
"github.com/stretchr/testify/require"
)
// Constants for system-reserved keys in the KV map.
var (
localMax = keys.LocalMax
keyMax = roachpb.KeyMax
testKey1 = roachpb.Key("/db1")
testKey2 = roachpb.Key("/db2")
testKey3 = roachpb.Key("/db3")
testKey4 = roachpb.Key("/db4")
testKey5 = roachpb.Key("/db5")
testKey6 = roachpb.Key("/db6")
txn1ID = uuid.MakeV4()
txn2ID = uuid.MakeV4()
txn1TS = hlc.Timestamp{Logical: 1}
txn2TS = hlc.Timestamp{Logical: 2}
txn1 = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn1ID, Epoch: 1, WriteTimestamp: txn1TS, MinTimestamp: txn1TS}, ReadTimestamp: txn1TS}
txn1Commit = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn1ID, Epoch: 1, WriteTimestamp: txn1TS, MinTimestamp: txn1TS}, ReadTimestamp: txn1TS, Status: roachpb.COMMITTED}
txn1Abort = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn1ID, Epoch: 1, WriteTimestamp: txn1TS, MinTimestamp: txn1TS}, Status: roachpb.ABORTED}
txn1e2 = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn1ID, Epoch: 2, WriteTimestamp: txn1TS, MinTimestamp: txn1TS}, ReadTimestamp: txn1TS}
txn1e2Commit = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn1ID, Epoch: 2, WriteTimestamp: txn1TS, MinTimestamp: txn1TS}, ReadTimestamp: txn1TS, Status: roachpb.COMMITTED}
txn2 = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn2ID, WriteTimestamp: txn2TS, MinTimestamp: txn2TS}, ReadTimestamp: txn2TS}
txn2Commit = &roachpb.Transaction{TxnMeta: enginepb.TxnMeta{Key: roachpb.Key("a"), ID: txn2ID, WriteTimestamp: txn2TS, MinTimestamp: txn2TS}, ReadTimestamp: txn2TS, Status: roachpb.COMMITTED}
value1 = roachpb.MakeValueFromString("testValue1")
value2 = roachpb.MakeValueFromString("testValue2")
value3 = roachpb.MakeValueFromString("testValue3")
value4 = roachpb.MakeValueFromString("testValue4")
value5 = roachpb.MakeValueFromString("testValue5")
value6 = roachpb.MakeValueFromString("testValue6")
tsvalue1 = timeSeriesRowAsValue(testtime, 1000, []tsSample{
{1, 1, 5, 5, 5},
}...)
tsvalue2 = timeSeriesRowAsValue(testtime, 1000, []tsSample{
{1, 1, 15, 15, 15},
}...)
)
// createTestPebbleEngine returns a new in-memory Pebble storage engine.
func createTestPebbleEngine() Engine {
return NewDefaultInMemForTesting()
}
func createTestPebbleEngineWithSettings(settings *cluster.Settings) Engine {
return newPebbleInMem(context.Background(), roachpb.Attributes{}, 1<<20, settings)
}
// TODO(sumeer): the following is legacy from when we had multiple engine
// implementations. Some tests are switched over to only create Pebble, since
// the create method does not provide control over cluster.Settings. Switch
// the rest and remove this.
var mvccEngineImpls = []struct {
name string
create func() Engine
}{
{"pebble", createTestPebbleEngine},
}
// makeTxn creates a new transaction using the specified base
// txn and timestamp.
func makeTxn(baseTxn roachpb.Transaction, ts hlc.Timestamp) *roachpb.Transaction {
txn := baseTxn.Clone()
txn.ReadTimestamp = ts
txn.WriteTimestamp = ts
return txn
}
func mvccVersionKey(key roachpb.Key, ts hlc.Timestamp) MVCCKey {
return MVCCKey{Key: key, Timestamp: ts}
}
type mvccKeys []MVCCKey
func (n mvccKeys) Len() int { return len(n) }
func (n mvccKeys) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n mvccKeys) Less(i, j int) bool { return n[i].Less(n[j]) }
func TestMVCCStatsAddSubForward(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
goldMS := enginepb.MVCCStats{
ContainsEstimates: 1,
KeyBytes: 1,
KeyCount: 1,
ValBytes: 1,
ValCount: 1,
IntentBytes: 1,
IntentCount: 1,
SeparatedIntentCount: 1,
IntentAge: 1,
GCBytesAge: 1,
LiveBytes: 1,
LiveCount: 1,
SysBytes: 1,
SysCount: 1,
LastUpdateNanos: 1,
AbortSpanBytes: 1,
}
if err := zerofields.NoZeroField(&goldMS); err != nil {
t.Fatal(err) // prevent rot as fields are added
}
cmp := func(act, exp enginepb.MVCCStats) {
t.Helper()
f, l, _ := caller.Lookup(1)
if !reflect.DeepEqual(act, exp) {
t.Fatalf("%s:%d: wanted %+v back, got %+v", f, l, exp, act)
}
}
ms := goldMS
zeroWithLU := enginepb.MVCCStats{
ContainsEstimates: 0,
LastUpdateNanos: ms.LastUpdateNanos,
}
ms.Subtract(goldMS)
cmp(ms, zeroWithLU)
ms.Add(goldMS)
cmp(ms, goldMS)
// Double-add double-sub guards against mistaking `+=` for `=`.
ms = zeroWithLU
ms.Add(goldMS)
ms.Add(goldMS)
ms.Subtract(goldMS)
ms.Subtract(goldMS)
cmp(ms, zeroWithLU)
// Run some checks for Forward.
goldDelta := enginepb.MVCCStats{
KeyBytes: 42,
IntentCount: 11,
LastUpdateNanos: 1e9 - 1000,
}
delta := goldDelta
for i, ns := range []int64{1, 1e9 - 1001, 1e9 - 1000, 1e9 - 1, 1e9, 1e9 + 1, 2e9 - 1} {
oldDelta := delta
delta.AgeTo(ns)
if delta.LastUpdateNanos < ns {
t.Fatalf("%d: expected LastUpdateNanos < %d, got %d", i, ns, delta.LastUpdateNanos)
}
shouldAge := ns/1e9-oldDelta.LastUpdateNanos/1e9 > 0
didAge := delta.IntentAge != oldDelta.IntentAge &&
delta.GCBytesAge != oldDelta.GCBytesAge
if shouldAge != didAge {
t.Fatalf("%d: should age: %t, but had\n%+v\nand now\n%+v", i, shouldAge, oldDelta, delta)
}
}
expDelta := goldDelta
expDelta.LastUpdateNanos = 2e9 - 1
expDelta.GCBytesAge = 42
expDelta.IntentAge = 11
cmp(delta, expDelta)
delta.AgeTo(2e9)
expDelta.LastUpdateNanos = 2e9
expDelta.GCBytesAge += 42
expDelta.IntentAge += 11
cmp(delta, expDelta)
{
// Verify that AgeTo can go backwards in time.
// Works on a copy.
tmpDelta := delta
expDelta := expDelta
tmpDelta.AgeTo(2e9 - 1)
expDelta.LastUpdateNanos = 2e9 - 1
expDelta.GCBytesAge -= 42
expDelta.IntentAge -= 11
cmp(tmpDelta, expDelta)
}
delta.AgeTo(3e9 - 1)
delta.Forward(5) // should be noop
expDelta.LastUpdateNanos = 3e9 - 1
cmp(delta, expDelta)
// Check that Add calls Forward appropriately.
mss := []enginepb.MVCCStats{goldMS, goldMS}
mss[0].LastUpdateNanos = 2e9 - 1
mss[1].LastUpdateNanos = 10e9 + 1
expMS := goldMS
expMS.Add(goldMS)
expMS.LastUpdateNanos = 10e9 + 1
expMS.IntentAge += 9 // from aging 9 ticks from 2E9-1 to 10E9+1
expMS.GCBytesAge += 9 // ditto
for i := range mss[:1] {
ms := mss[(1+i)%2]
ms.Add(mss[i])
cmp(ms, expMS)
}
// Finally, check Forward with negative counts (can happen).
neg := zeroWithLU
neg.Subtract(goldMS)
exp := neg
neg.AgeTo(2e9)
exp.LastUpdateNanos = 2e9
exp.GCBytesAge = -3
exp.IntentAge = -3
cmp(neg, exp)
}
// Verify the sort ordering of successive keys with metadata and
// versioned values. In particular, the following sequence of keys /
// versions:
//
// a
// a<t=max>
// a<t=1>
// a<t=0>
// a\x00
// a\x00<t=max>
// a\x00<t=1>
// a\x00<t=0>
func TestMVCCKeys(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
aKey := roachpb.Key("a")
a0Key := roachpb.Key("a\x00")
keys := mvccKeys{
mvccKey(aKey),
mvccVersionKey(aKey, hlc.Timestamp{WallTime: math.MaxInt64}),
mvccVersionKey(aKey, hlc.Timestamp{WallTime: 1}),
mvccVersionKey(aKey, hlc.Timestamp{Logical: 1}),
mvccKey(a0Key),
mvccVersionKey(a0Key, hlc.Timestamp{WallTime: math.MaxInt64}),
mvccVersionKey(a0Key, hlc.Timestamp{WallTime: 1}),
mvccVersionKey(a0Key, hlc.Timestamp{Logical: 1}),
}
sortKeys := make(mvccKeys, len(keys))
copy(sortKeys, keys)
shuffle.Shuffle(sortKeys)
sort.Sort(sortKeys)
if !reflect.DeepEqual(sortKeys, keys) {
t.Errorf("expected keys to sort in order %s, but got %s", keys, sortKeys)
}
}
func TestMVCCGetNotExist(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
value, _, err := MVCCGet(context.Background(), engine, testKey1, hlc.Timestamp{Logical: 1},
MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value != nil {
t.Fatal("the value should be empty")
}
})
}
}
func TestMVCCGetNoMoreOldVersion(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
// Need to handle the case here where the scan takes us to the
// next key, which may not match the key we're looking for. In
// other words, if we're looking for a<T=2>, and we have the
// following keys:
//
// a: MVCCMetadata(a)
// a<T=3>
// b: MVCCMetadata(b)
// b<T=1>
//
// If we search for a<T=2>, the scan should not return "b".
engine := engineImpl.create()
defer engine.Close()
if err := MVCCPut(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 3}, value1, nil); err != nil {
t.Fatal(err)
}
if err := MVCCPut(ctx, engine, nil, testKey2, hlc.Timestamp{WallTime: 1}, value2, nil); err != nil {
t.Fatal(err)
}
value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 2}, MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value != nil {
t.Fatal("the value should be empty")
}
})
}
}
func TestMVCCGetAndDelete(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
if err := MVCCPut(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 1}, value1, nil); err != nil {
t.Fatal(err)
}
value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 2}, MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value == nil {
t.Fatal("the value should not be empty")
}
err = MVCCDelete(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 3}, nil)
if err != nil {
t.Fatal(err)
}
// Read the latest version which should be deleted.
value, _, err = MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 4}, MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value != nil {
t.Fatal("the value should be empty")
}
// Read the latest version with tombstone.
value, _, err = MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 4},
MVCCGetOptions{Tombstones: true})
if err != nil {
t.Fatal(err)
} else if value == nil || len(value.RawBytes) != 0 {
t.Fatalf("the value should be non-nil with empty RawBytes; got %+v", value)
}
// Read the old version which should still exist.
for _, logical := range []int32{0, math.MaxInt32} {
value, _, err = MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 2, Logical: logical},
MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value == nil {
t.Fatal("the value should not be empty")
}
}
})
}
}
// TestMVCCWriteWithOlderTimestampAfterDeletionOfNonexistentKey tests a write
// that comes after a delete on a nonexistent key, with the write holding a
// timestamp earlier than the delete timestamp. The delete must write a
// tombstone with its timestamp in order to push the write's timestamp.
func TestMVCCWriteWithOlderTimestampAfterDeletionOfNonexistentKey(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
if err := MVCCDelete(
context.Background(), engine, nil, testKey1, hlc.Timestamp{WallTime: 3}, nil,
); err != nil {
t.Fatal(err)
}
if err := MVCCPut(
context.Background(), engine, nil, testKey1, hlc.Timestamp{WallTime: 1}, value1, nil,
); !testutils.IsError(
err, "write at timestamp 0.000000001,0 too old; wrote at 0.000000003,1",
) {
t.Fatal(err)
}
value, _, err := MVCCGet(context.Background(), engine, testKey1, hlc.Timestamp{WallTime: 2},
MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
// The attempted write at ts(1,0) was performed at ts(3,1), so we should
// not see it at ts(2,0).
if value != nil {
t.Fatalf("value present at TS = %s", value.Timestamp)
}
// Read the latest version which will be the value written with the timestamp pushed.
value, _, err = MVCCGet(context.Background(), engine, testKey1, hlc.Timestamp{WallTime: 4},
MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if value == nil {
t.Fatal("value doesn't exist")
}
if !bytes.Equal(value.RawBytes, value1.RawBytes) {
t.Errorf("expected %q; got %q", value1.RawBytes, value.RawBytes)
}
if expTS := (hlc.Timestamp{WallTime: 3, Logical: 1}); value.Timestamp != expTS {
t.Fatalf("timestamp was not pushed: %s, expected %s", value.Timestamp, expTS)
}
})
}
}
func TestMVCCInlineWithTxn(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
// Put an inline value.
if err := MVCCPut(ctx, engine, nil, testKey1, hlc.Timestamp{}, value1, nil); err != nil {
t.Fatal(err)
}
// Now verify inline get.
value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{}, MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(value1, *value) {
t.Errorf("the inline value should be %v; got %v", value1, *value)
}
// Verify inline get with txn does still work (this will happen on a
// scan if the distributed sender is forced to wrap it in a txn).
if _, _, err = MVCCGet(ctx, engine, testKey1, hlc.Timestamp{}, MVCCGetOptions{
Txn: txn1,
}); err != nil {
t.Error(err)
}
// Verify inline put with txn is an error.
err = MVCCPut(ctx, engine, nil, testKey2, hlc.Timestamp{}, value2, txn2)
if !testutils.IsError(err, "writes not allowed within transactions") {
t.Errorf("unexpected error: %+v", err)
}
})
}
}
func TestMVCCDeleteMissingKey(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
if err := MVCCDelete(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 1}, nil); err != nil {
t.Fatal(err)
}
// Verify nothing is written to the engine.
if val, err := engine.MVCCGet(mvccKey(testKey1)); err != nil || val != nil {
t.Fatalf("expected no mvcc metadata after delete of a missing key; got %q: %+v", val, err)
}
})
}
}
func TestMVCCGetAndDeleteInTxn(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
txn := makeTxn(*txn1, hlc.Timestamp{WallTime: 1})
txn.Sequence++
if err := MVCCPut(ctx, engine, nil, testKey1, txn.ReadTimestamp, value1, txn); err != nil {
t.Fatal(err)
}
if value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 2}, MVCCGetOptions{
Txn: txn,
}); err != nil {
t.Fatal(err)
} else if value == nil {
t.Fatal("the value should not be empty")
}
txn.Sequence++
txn.WriteTimestamp = hlc.Timestamp{WallTime: 3}
if err := MVCCDelete(ctx, engine, nil, testKey1, txn.ReadTimestamp, txn); err != nil {
t.Fatal(err)
}
// Read the latest version which should be deleted.
if value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 4}, MVCCGetOptions{
Txn: txn,
}); err != nil {
t.Fatal(err)
} else if value != nil {
t.Fatal("the value should be empty")
}
// Read the latest version with tombstone.
if value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 4}, MVCCGetOptions{
Tombstones: true,
Txn: txn,
}); err != nil {
t.Fatal(err)
} else if value == nil || len(value.RawBytes) != 0 {
t.Fatalf("the value should be non-nil with empty RawBytes; got %+v", value)
}
// Read the old version which shouldn't exist, as within a
// transaction, we delete previous values.
if value, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 2}, MVCCGetOptions{}); err != nil {
t.Fatal(err)
} else if value != nil {
t.Fatalf("expected value nil, got: %s", value)
}
})
}
}
func TestMVCCGetWriteIntentError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
if err := MVCCPut(ctx, engine, nil, testKey1, txn1.ReadTimestamp, value1, txn1); err != nil {
t.Fatal(err)
}
if _, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 1}, MVCCGetOptions{}); err == nil {
t.Fatal("cannot read the value of a write intent without TxnID")
}
if _, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 1}, MVCCGetOptions{
Txn: txn2,
}); err == nil {
t.Fatal("cannot read the value of a write intent from a different TxnID")
}
})
}
}
func mkVal(s string, ts hlc.Timestamp) roachpb.Value {
v := roachpb.MakeValueFromString(s)
v.Timestamp = ts
return v
}
func TestMVCCScanWriteIntentError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
ts := []hlc.Timestamp{{Logical: 1}, {Logical: 2}, {Logical: 3}, {Logical: 4}, {Logical: 5}, {Logical: 6}}
txn1ts := makeTxn(*txn1, ts[2])
txn2ts := makeTxn(*txn2, ts[5])
fixtureKVs := []roachpb.KeyValue{
{Key: testKey1, Value: mkVal("testValue1 pre", ts[0])},
{Key: testKey4, Value: mkVal("testValue4 pre", ts[1])},
{Key: testKey1, Value: mkVal("testValue1", ts[2])},
{Key: testKey2, Value: mkVal("testValue2", ts[3])},
{Key: testKey3, Value: mkVal("testValue3", ts[4])},
{Key: testKey4, Value: mkVal("testValue4", ts[5])},
}
for i, kv := range fixtureKVs {
var txn *roachpb.Transaction
if i == 2 {
txn = txn1ts
} else if i == 5 {
txn = txn2ts
}
v := *protoutil.Clone(&kv.Value).(*roachpb.Value)
v.Timestamp = hlc.Timestamp{}
if err := MVCCPut(ctx, engine, nil, kv.Key, kv.Value.Timestamp, v, txn); err != nil {
t.Fatal(err)
}
}
scanCases := []struct {
consistent bool
txn *roachpb.Transaction
expIntents []roachpb.Intent
expValues []roachpb.KeyValue
}{
{
consistent: true,
txn: nil,
expIntents: []roachpb.Intent{
roachpb.MakeIntent(&txn1ts.TxnMeta, testKey1),
roachpb.MakeIntent(&txn2ts.TxnMeta, testKey4),
},
// would be []roachpb.KeyValue{fixtureKVs[3], fixtureKVs[4]} without WriteIntentError
expValues: nil,
},
{
consistent: true,
txn: txn1ts,
expIntents: []roachpb.Intent{
roachpb.MakeIntent(&txn2ts.TxnMeta, testKey4),
},
expValues: nil, // []roachpb.KeyValue{fixtureKVs[2], fixtureKVs[3], fixtureKVs[4]},
},
{
consistent: true,
txn: txn2ts,
expIntents: []roachpb.Intent{
roachpb.MakeIntent(&txn1ts.TxnMeta, testKey1),
},
expValues: nil, // []roachpb.KeyValue{fixtureKVs[3], fixtureKVs[4], fixtureKVs[5]},
},
{
consistent: false,
txn: nil,
expIntents: []roachpb.Intent{
roachpb.MakeIntent(&txn1ts.TxnMeta, testKey1),
roachpb.MakeIntent(&txn2ts.TxnMeta, testKey4),
},
expValues: []roachpb.KeyValue{fixtureKVs[0], fixtureKVs[3], fixtureKVs[4], fixtureKVs[1]},
},
}
for i, scan := range scanCases {
cStr := "inconsistent"
if scan.consistent {
cStr = "consistent"
}
res, err := MVCCScan(ctx, engine, testKey1, testKey4.Next(),
hlc.Timestamp{WallTime: 1}, MVCCScanOptions{Inconsistent: !scan.consistent, Txn: scan.txn})
var wiErr *roachpb.WriteIntentError
_ = errors.As(err, &wiErr)
if (err == nil) != (wiErr == nil) {
t.Errorf("%s(%d): unexpected error: %+v", cStr, i, err)
}
if wiErr == nil != !scan.consistent {
t.Errorf("%s(%d): expected write intent error; got %s", cStr, i, err)
continue
}
intents := res.Intents
kvs := res.KVs
if len(intents) > 0 != !scan.consistent {
t.Errorf("%s(%d): expected different intents slice; got %+v", cStr, i, intents)
continue
}
if scan.consistent {
intents = wiErr.Intents
}
if !reflect.DeepEqual(intents, scan.expIntents) {
t.Fatalf("%s(%d): expected intents:\n%+v;\n got\n%+v", cStr, i, scan.expIntents, intents)
}
if !reflect.DeepEqual(kvs, scan.expValues) {
t.Errorf("%s(%d): expected values %+v; got %+v", cStr, i, scan.expValues, kvs)
}
}
})
}
}
// TestMVCCGetInconsistent verifies the behavior of get with
// consistent set to false.
func TestMVCCGetInconsistent(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
// Put two values to key 1, the latest with a txn.
if err := MVCCPut(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 1}, value1, nil); err != nil {
t.Fatal(err)
}
txn1ts := makeTxn(*txn1, hlc.Timestamp{WallTime: 2})
if err := MVCCPut(ctx, engine, nil, testKey1, txn1ts.ReadTimestamp, value2, txn1ts); err != nil {
t.Fatal(err)
}
// A get with consistent=false should fail in a txn.
if _, _, err := MVCCGet(ctx, engine, testKey1, hlc.Timestamp{WallTime: 1}, MVCCGetOptions{
Inconsistent: true,
Txn: txn1,
}); err == nil {
t.Error("expected an error getting with consistent=false in txn")
}
// Inconsistent get will fetch value1 for any timestamp.
for _, ts := range []hlc.Timestamp{{WallTime: 1}, {WallTime: 2}} {
val, intent, err := MVCCGet(ctx, engine, testKey1, ts, MVCCGetOptions{Inconsistent: true})
if ts.Less(hlc.Timestamp{WallTime: 2}) {
if err != nil {
t.Fatal(err)
}
} else {
if intent == nil || !intent.Key.Equal(testKey1) {
t.Fatalf("expected %v, but got %v", testKey1, intent)
}
}
if !bytes.Equal(val.RawBytes, value1.RawBytes) {
t.Errorf("@%s expected %q; got %q", ts, value1.RawBytes, val.RawBytes)
}
}
// Write a single intent for key 2 and verify get returns empty.
if err := MVCCPut(ctx, engine, nil, testKey2, txn2.ReadTimestamp, value1, txn2); err != nil {
t.Fatal(err)
}
val, intent, err := MVCCGet(ctx, engine, testKey2, hlc.Timestamp{WallTime: 2},
MVCCGetOptions{Inconsistent: true})
if intent == nil || !intent.Key.Equal(testKey2) {
t.Fatal(err)
}
if val != nil {
t.Errorf("expected empty val; got %+v", val)
}
})
}
}
// TestMVCCGetProtoInconsistent verifies the behavior of MVCCGetProto with
// consistent set to false.
func TestMVCCGetProtoInconsistent(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
bytes1, err := protoutil.Marshal(&value1)
if err != nil {
t.Fatal(err)
}
bytes2, err := protoutil.Marshal(&value2)
if err != nil {
t.Fatal(err)
}
v1 := roachpb.MakeValueFromBytes(bytes1)
v2 := roachpb.MakeValueFromBytes(bytes2)
// Put two values to key 1, the latest with a txn.
if err := MVCCPut(ctx, engine, nil, testKey1, hlc.Timestamp{WallTime: 1}, v1, nil); err != nil {
t.Fatal(err)
}
txn1ts := makeTxn(*txn1, hlc.Timestamp{WallTime: 2})
if err := MVCCPut(ctx, engine, nil, testKey1, txn1ts.ReadTimestamp, v2, txn1ts); err != nil {
t.Fatal(err)
}
// An inconsistent get should fail in a txn.
if _, err := MVCCGetProto(ctx, engine, testKey1, hlc.Timestamp{WallTime: 1}, nil, MVCCGetOptions{
Inconsistent: true,
Txn: txn1,
}); err == nil {
t.Error("expected an error getting inconsistently in txn")
} else if errors.HasType(err, (*roachpb.WriteIntentError)(nil)) {
t.Error("expected non-WriteIntentError with inconsistent read in txn")
}
// Inconsistent get will fetch value1 for any timestamp.
for _, ts := range []hlc.Timestamp{{WallTime: 1}, {WallTime: 2}} {
val := roachpb.Value{}
found, err := MVCCGetProto(ctx, engine, testKey1, ts, &val, MVCCGetOptions{
Inconsistent: true,
})
if ts.Less(hlc.Timestamp{WallTime: 2}) {
if err != nil {
t.Fatal(err)
}
} else if err != nil {
t.Fatal(err)
}
if !found {
t.Errorf("expected to find result with inconsistent read")
}
valBytes, err := val.GetBytes()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(valBytes, []byte("testValue1")) {
t.Errorf("@%s expected %q; got %q", ts, []byte("value1"), valBytes)
}
}
{
// Write a single intent for key 2 and verify get returns empty.
if err := MVCCPut(ctx, engine, nil, testKey2, txn2.ReadTimestamp, v1, txn2); err != nil {
t.Fatal(err)
}
val := roachpb.Value{}
found, err := MVCCGetProto(ctx, engine, testKey2, hlc.Timestamp{WallTime: 2}, &val, MVCCGetOptions{
Inconsistent: true,
})
if err != nil {
t.Fatal(err)
}
if found {
t.Errorf("expected no result; got %+v", val)
}
}
{
// Write a malformed value (not an encoded MVCCKeyValue) and a
// write intent to key 3; the parse error is returned instead of the
// write intent.
if err := MVCCPut(ctx, engine, nil, testKey3, hlc.Timestamp{WallTime: 1}, value3, nil); err != nil {
t.Fatal(err)
}
if err := MVCCPut(ctx, engine, nil, testKey3, txn1ts.ReadTimestamp, v2, txn1ts); err != nil {
t.Fatal(err)
}
val := roachpb.Value{}
found, err := MVCCGetProto(ctx, engine, testKey3, hlc.Timestamp{WallTime: 1}, &val, MVCCGetOptions{
Inconsistent: true,
})
if err == nil {
t.Errorf("expected error reading malformed data")
} else if !strings.HasPrefix(err.Error(), "proto: ") {
t.Errorf("expected proto error, got %s", err)
}
if !found {
t.Errorf("expected to find result with malformed data")
}
}
})
}
}
// Regression test for #28205: MVCCGet and MVCCScan, FindSplitKey, and
// ComputeStats need to invalidate the cached iterator data.
func TestMVCCInvalidateIterator(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, which := range []string{"get", "scan", "findSplitKey", "computeStats"} {
t.Run(which, func(t *testing.T) {
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()
ctx := context.Background()
ts1 := hlc.Timestamp{WallTime: 1}
ts2 := hlc.Timestamp{WallTime: 2}
key := roachpb.Key("a")
if err := MVCCPut(ctx, engine, nil, key, ts1, value1, nil); err != nil {
t.Fatal(err)
}
var iterOptions IterOptions
switch which {
case "get":
iterOptions.Prefix = true
case "scan", "findSplitKey", "computeStats":
iterOptions.UpperBound = roachpb.KeyMax
}
// Use a batch which internally caches the iterator.
batch := engine.NewBatch()
defer batch.Close()
{
// Seek the iter to a valid position.
iter := batch.NewMVCCIterator(MVCCKeyAndIntentsIterKind, iterOptions)
iter.SeekGE(MakeMVCCMetadataKey(key))
iter.Close()
}
var err error
switch which {
case "get":
_, _, err = MVCCGet(ctx, batch, key, ts2, MVCCGetOptions{})
case "scan":
_, err = MVCCScan(ctx, batch, key, roachpb.KeyMax, ts2, MVCCScanOptions{})
case "findSplitKey":
_, err = MVCCFindSplitKey(ctx, batch, roachpb.RKeyMin, roachpb.RKeyMax, 64<<20)
case "computeStats":
iter := batch.NewMVCCIterator(MVCCKeyAndIntentsIterKind, iterOptions)
_, err = iter.ComputeStats(keys.LocalMax, roachpb.KeyMax, 0)
iter.Close()
}
if err != nil {
t.Fatal(err)
}
// Verify that the iter is invalid.
iter := batch.NewMVCCIterator(MVCCKeyAndIntentsIterKind, iterOptions)
defer iter.Close()
if ok, _ := iter.Valid(); ok {
t.Fatalf("iterator should not be valid")
}
})
}
})
}
}
func TestMVCCPutAfterBatchIterCreate(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, engineImpl := range mvccEngineImpls {
t.Run(engineImpl.name, func(t *testing.T) {
engine := engineImpl.create()
defer engine.Close()