-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
mvcc_history_test.go
3132 lines (2867 loc) · 93.2 KB
/
mvcc_history_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 2019 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_test
import (
"bytes"
"context"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/lock"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/spanset"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/uncertainty"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/fs"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"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/metamorphic"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/redact"
"github.com/stretchr/testify/require"
)
var (
clearRangeUsingIter = metamorphic.ConstantWithTestBool(
"mvcc-histories-clear-range-using-iterator", false)
cmdDeleteRangeTombstoneKnownStats = metamorphic.ConstantWithTestBool(
"mvcc-histories-deleterange-tombstome-known-stats", false)
mvccHistoriesReader = metamorphic.ConstantWithTestChoice("mvcc-histories-reader",
"engine", "readonly", "batch", "snapshot", "efos").(string)
mvccHistoriesUseBatch = metamorphic.ConstantWithTestBool("mvcc-histories-use-batch", false)
mvccHistoriesPeekBounds = metamorphic.ConstantWithTestChoice("mvcc-histories-peek-bounds",
"none", "left", "right", "both").(string)
sstIterVerify = metamorphic.ConstantWithTestBool("mvcc-histories-sst-iter-verify", false)
metamorphicIteratorSeed = metamorphic.ConstantWithTestRange("mvcc-metamorphic-iterator-seed", 0, 0, 100000) // 0 = disabled
separateEngineBlocks = metamorphic.ConstantWithTestBool("mvcc-histories-separate-engine-blocks", false)
)
// TestMVCCHistories verifies that sequences of MVCC reads and writes
// perform properly.
//
// The input files use the following DSL:
//
// run [ok|trace|stats|error|log-ops]
//
// txn_begin t=<name> [ts=<int>[,<int>]] [globalUncertaintyLimit=<int>[,<int>]]
// txn_remove t=<name>
// txn_restart t=<name> [epoch=<int>]
// txn_update t=<name> t2=<name>
// txn_step t=<name> [n=<int>] [seq=<int>]
// txn_advance t=<name> ts=<int>[,<int>]
// txn_status t=<name> status=<txnstatus>
// txn_ignore_seqs t=<name> seqs=[<int>-<int>[,<int>-<int>...]]
//
// resolve_intent t=<name> k=<key> [status=<txnstatus>] [clockWhilePending=<int>[,<int>]] [targetBytes=<int>]
// resolve_intent_range t=<name> k=<key> end=<key> [status=<txnstatus>] [maxKeys=<int>] [targetBytes=<int>]
// check_intent k=<key> [none]
// add_unreplicated_lock t=<name> k=<key>
// check_for_acquire_lock t=<name> k=<key> str=<strength> [maxLockConflicts=<int>] [targetLockConflictBytes=<int>]
// acquire_lock t=<name> k=<key> str=<strength> [maxLockConflicts=<int>] [targetLockConflictBytes=<int>]
//
// cput [t=<name>] [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>]
// [targetLockConflictBytes=<int>] k=<key> v=<string> [raw] [cond=<string>]
// del [t=<name>] [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>]
// [targetLockConflictBytes=<int>] k=<key>
// del_range [t=<name>] [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>]
// [targetLockConflictBytes=<int>] k=<key> end=<key> [max=<max>] [returnKeys]
// del_range_ts [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [maxLockConflicts=<int>] [targetLockConflictBytes=<int>] k=<key> end=<key> [idempotent]
// [noCoveredStats]
// del_range_pred [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [maxLockConflicts=<int>] [targetLockConflictBytes=<int>] k=<key> end=<key>
// [startTime=<int>,max=<int>,maxBytes=<int>,rangeThreshold=<int>]
// increment [t=<name>] [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>]
// [targetLockConflictBytes=<int>] k=<key> [inc=<val>]
// initput [t=<name>] [ts=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>] k=<key> v=<string> [raw] [failOnTombstones]
// put [t=<name>] [ts=<int>[,<int>]] [localTs=<int>[,<int>]] [resolve [status=<txnstatus>]] [ambiguousReplay] [maxLockConflicts=<int>] k=<key> v=<string> [raw]
// put_rangekey ts=<int>[,<int>] [localTs=<int>[,<int>]] k=<key> end=<key>
// put_blind_inline k=<key> v=<string> [prev=<string>]
// get [t=<name>] [ts=<int>[,<int>]] [resolve [status=<txnstatus>]] k=<key> [inconsistent] [skipLocked] [tombstones] [failOnMoreRecent]
// [localUncertaintyLimit=<int>[,<int>]] [globalUncertaintyLimit=<int>[,<int>]] [maxKeys=<int>] [targetBytes=<int>] [allowEmpty]
// scan [t=<name>] [ts=<int>[,<int>]] [resolve [status=<txnstatus>]] k=<key> [end=<key>] [inconsistent] [skipLocked] [tombstones] [reverse] [failOnMoreRecent]
// [localUncertaintyLimit=<int>[,<int>]] [globalUncertaintyLimit=<int>[,<int>]] [max=<max>] [targetbytes=<target>] [wholeRows[=<int>]] [allowEmpty]
// export [k=<key>] [end=<key>] [ts=<int>[,<int>]] [kTs=<int>[,<int>]] [startTs=<int>[,<int>]] [maxLockConflicts=<int>] [targetLockConflictBytes=<int>]
// [allRevisions] [targetSize=<int>] [maxSize=<int>] [stopMidKey] [fingerprint]
//
// iter_new [k=<key>] [end=<key>] [prefix] [kind=key|keyAndIntents] [types=pointsOnly|pointsWithRanges|pointsAndRanges|rangesOnly] [maskBelow=<int>[,<int>]]
// [minTimestamp=<int>[,<int>]] [maxTimestamp=<int>[,<int>]]
// iter_new_incremental [k=<key>] [end=<key>] [startTs=<int>[,<int>]] [endTs=<int>[,<int>]] [types=pointsOnly|pointsWithRanges|pointsAndRanges|rangesOnly]
// [maskBelow=<int>[,<int>]] [intents=error|aggregate|emit]
// iter_seek_ge k=<key> [ts=<int>[,<int>]]
// iter_seek_lt k=<key> [ts=<int>[,<int>]]
// iter_next
// iter_next_ignoring_time
// iter_next_key_ignoring_time
// iter_next_key
// iter_prev
// iter_scan [reverse]
//
// merge [ts=<int>[,<int>]] k=<key> v=<string> [raw]
//
// clear k=<key> [ts=<int>[,<int>]]
// clear_range k=<key> end=<key>
// clear_rangekey k=<key> end=<key> ts=<int>[,<int>]
// clear_time_range k=<key> end=<key> ts=<int>[,<int>] targetTs=<int>[,<int>] [clearRangeThreshold=<int>] [maxBatchSize=<int>] [maxBatchByteSize=<int>]
//
// gc_clear_range k=<key> end=<key> startTs=<int>[,<int>] ts=<int>[,<int>]
// gc_points_clear_range k=<key> end=<key> startTs=<int>[,<int>] ts=<int>[,<int>]
// replace_point_tombstones_with_range_tombstones k=<key> [end=<key>]
//
// sst_put [ts=<int>[,<int>]] [localTs=<int>[,<int>]] k=<key> [v=<string>]
// sst_put_rangekey ts=<int>[,<int>] [localTS=<int>[,<int>]] k=<key> end=<key> [syntheticBit]
// sst_clear_range k=<key> end=<key>
// sst_clear_rangekey k=<key> end=<key> ts=<int>[,<int>]
// sst_finish
// sst_iter_new
//
// Where `<key>` can be a simple string, or a string
// prefixed by the following characters:
//
// - `=foo` means exactly key `foo`
// - `+foo` means `Key(foo).Next()`
// - `-foo` means `Key(foo).PrefixEnd()`
// - `%foo` means `append(LocalRangePrefix, "foo")`
// - `/foo/7` means SQL row with key foo, optional column family 7 (system tenant, table/index 1).
//
// Additionally, the pseudo-command `with` enables sharing
// a group of arguments between multiple commands, for example:
//
// with t=A
// txn_begin
// with k=a
// put v=b
// resolve_intent
//
// Really means:
//
// txn_begin t=A
// put v=b k=a t=A
// resolve_intent k=a t=A
func TestMVCCHistories(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// TODO(storage-team): this prevents us from easily finding bugs which
// incorrectly assume simple value encoding. We only find bugs where we are
// explicitly using the extended encoding by setting a localTs. One way to
// handle the different test output with extended value encoding would be to
// duplicate each test file for the two cases.
storage.DisableMetamorphicSimpleValueEncoding(t)
ctx := context.Background()
// intentInterleavingIter doesn't allow iterating from the local to the global
// keyspace, so we have to process these key spans separately.
spans := []roachpb.Span{
{Key: keys.MinKey, EndKey: roachpb.LocalMax},
{Key: keys.LocalMax, EndKey: roachpb.KeyMax},
}
// lockTableSpan returns the span of the lock table that corresponds to the
// given span.
lockTableSpan := func(s roachpb.Span) roachpb.Span {
k, _ := keys.LockTableSingleKey(s.Key, nil)
ek, _ := keys.LockTableSingleKey(s.EndKey, nil)
return roachpb.Span{Key: k, EndKey: ek}
}
// Timestamp for MVCC stats calculations, in nanoseconds.
const statsTS = 100e9
datadriven.Walk(t, datapathutils.TestDataPath(t, "mvcc_histories"), func(t *testing.T, path string) {
st := cluster.MakeTestingClusterSettings()
if strings.Contains(path, "_norace") {
skip.UnderRace(t)
}
if strings.Contains(path, "_disable_local_timestamps") {
storage.LocalTimestampsEnabled.Override(ctx, &st.SV, false)
}
disableSeparateEngineBlocks := strings.Contains(path, "_disable_separate_engine_blocks")
storageConfigOpts := []storage.ConfigOption{
storage.CacheSize(1 << 20 /* 1 MiB */),
storage.If(separateEngineBlocks && !disableSeparateEngineBlocks, storage.BlockSize(1)),
storage.DiskWriteStatsCollector(vfs.NewDiskWriteStatsCollector()),
}
// We start from a clean slate in every test file.
engine, err := storage.Open(ctx, storage.InMemory(), st, storageConfigOpts...)
require.NoError(t, err)
defer engine.Close()
reportDataEntries := func(buf *redact.StringBuilder) error {
var hasData bool
for _, span := range spans {
err = engine.MVCCIterate(context.Background(), span.Key, span.EndKey, storage.MVCCKeyAndIntentsIterKind, storage.IterKeyTypeRangesOnly,
fs.UnknownReadCategory,
func(_ storage.MVCCKeyValue, rangeKeys storage.MVCCRangeKeyStack) error {
hasData = true
buf.Printf("rangekey: %s/[", rangeKeys.Bounds)
for i, version := range rangeKeys.Versions {
val, err := storage.DecodeMVCCValue(version.Value)
require.NoError(t, err)
if i > 0 {
buf.Printf(" ")
}
buf.Printf("%s=%s", version.Timestamp, val)
}
buf.Printf("]\n")
return nil
})
if err != nil {
return err
}
err = engine.MVCCIterate(context.Background(), span.Key, span.EndKey, storage.MVCCKeyAndIntentsIterKind, storage.IterKeyTypePointsOnly,
fs.UnknownReadCategory,
func(r storage.MVCCKeyValue, _ storage.MVCCRangeKeyStack) error {
hasData = true
if r.Key.Timestamp.IsEmpty() {
// Meta is at timestamp zero.
meta := enginepb.MVCCMetadata{}
if err := protoutil.Unmarshal(r.Value, &meta); err != nil {
buf.Printf("meta: %v -> error decoding proto from %v: %v\n", r.Key, r.Value, err)
} else {
buf.Printf("meta: %v -> %+v\n", r.Key, &meta)
}
} else {
val, err := storage.DecodeMVCCValue(r.Value)
if err != nil {
buf.Printf("data: %v -> error decoding value %v: %v\n", r.Key, r.Value, err)
} else {
buf.Printf("data: %v -> %s\n", r.Key, val)
}
}
return nil
})
}
if !hasData {
buf.SafeString("<no data>\n")
}
return err
}
// reportSSTEntries outputs entries from a raw SSTable. It uses a raw
// SST iterator in order to accurately represent the raw SST data.
reportSSTEntries := func(buf *redact.StringBuilder, name string, sst []byte) error {
r, err := sstable.NewMemReader(sst, sstable.ReaderOptions{
Comparer: storage.EngineComparer,
})
if err != nil {
return err
}
buf.Printf(">> %s:\n", name)
// Dump point keys.
iter, err := r.NewIter(sstable.NoTransforms, nil, nil)
if err != nil {
return err
}
defer func() { _ = iter.Close() }()
for kv := iter.SeekGE(nil, 0); kv != nil; kv = iter.Next() {
if err := iter.Error(); err != nil {
return err
}
key, err := storage.DecodeMVCCKey(kv.K.UserKey)
if err != nil {
return err
}
v, _, err := kv.Value(nil)
if err != nil {
return err
}
value, err := storage.DecodeMVCCValue(v)
if err != nil {
return err
}
buf.Printf("%s: %s -> %s\n", strings.ToLower(kv.Kind().String()), key, value)
}
// Dump rangedels.
if rdIter, err := r.NewRawRangeDelIter(context.Background(), sstable.NoFragmentTransforms); err != nil {
return err
} else if rdIter != nil {
defer rdIter.Close()
s, err := rdIter.First()
for ; s != nil; s, err = rdIter.Next() {
start, err := storage.DecodeMVCCKey(s.Start)
if err != nil {
return err
}
end, err := storage.DecodeMVCCKey(s.End)
if err != nil {
return err
}
for _, k := range s.Keys {
buf.Printf("%s: %s\n", strings.ToLower(k.Kind().String()),
roachpb.Span{Key: start.Key, EndKey: end.Key})
}
}
if err != nil {
return err
}
}
// Dump range keys.
if rkIter, err := r.NewRawRangeKeyIter(context.Background(), sstable.NoFragmentTransforms); err != nil {
return err
} else if rkIter != nil {
defer rkIter.Close()
s, err := rkIter.First()
for ; s != nil; s, err = rkIter.Next() {
start, err := storage.DecodeMVCCKey(s.Start)
if err != nil {
return err
}
end, err := storage.DecodeMVCCKey(s.End)
if err != nil {
return err
}
for _, k := range s.Keys {
buf.Printf("%s: %s", strings.ToLower(k.Kind().String()),
roachpb.Span{Key: start.Key, EndKey: end.Key})
if k.Suffix != nil {
ts, err := storage.DecodeMVCCTimestampSuffix(k.Suffix)
if err != nil {
return err
}
buf.Printf("/%s", ts)
}
if k.Kind() == pebble.InternalKeyKindRangeKeySet {
value, err := storage.DecodeMVCCValue(k.Value)
if err != nil {
return err
}
buf.Printf(" -> %s", value)
}
buf.Printf("\n")
}
}
if err != nil {
return err
}
}
return nil
}
// reportLockTable outputs the contents of the lock table.
reportLockTable := func(e *evalCtx, buf *redact.StringBuilder) error {
// Replicated locks.
ltStart := keys.LocalRangeLockTablePrefix
ltEnd := keys.LocalRangeLockTablePrefix.PrefixEnd()
iter, err := engine.NewEngineIterator(context.Background(), storage.IterOptions{UpperBound: ltEnd})
if err != nil {
return err
}
defer iter.Close()
var meta enginepb.MVCCMetadata
for valid, err := iter.SeekEngineKeyGE(storage.EngineKey{Key: ltStart}); ; valid, err = iter.NextEngineKey() {
if err != nil {
return err
} else if !valid {
break
}
eKey, err := iter.EngineKey()
if err != nil {
return err
}
ltKey, err := eKey.ToLockTableKey()
if err != nil {
return errors.Wrapf(err, "decoding LockTable key: %v", eKey)
}
if ltKey.Strength == lock.Intent {
// Ignore intents, which are reported by reportDataEntries.
continue
}
// Unmarshal.
v, err := iter.UnsafeValue()
if err != nil {
return err
}
if err := protoutil.Unmarshal(v, &meta); err != nil {
return errors.Wrapf(err, "unmarshaling mvcc meta: %v", ltKey)
}
buf.Printf("lock (%s): %v/%s -> %+v\n",
lock.Replicated, ltKey.Key, ltKey.Strength, &meta)
}
// Unreplicated locks.
if len(e.unreplLocks) > 0 {
var ks []string
for k := range e.unreplLocks {
ks = append(ks, k)
}
sort.Strings(ks)
for _, k := range ks {
info := e.unreplLocks[k]
buf.Printf("lock (%s): %v/%s -> %+v\n",
lock.Unreplicated, k, info.str, info.txn)
}
}
return nil
}
e := newEvalCtx(ctx, engine)
defer func() {
require.NoError(t, engine.Compact())
m := engine.GetMetrics().Metrics
if m.Keys.MissizedTombstonesCount > 0 {
// A missized tombstone is a Pebble DELSIZED tombstone that encodes
// the wrong size of the value it deletes. This kind of tombstone is
// written when ClearOptions.ValueSizeKnown=true. If this assertion
// failed, something might be awry in the code clearing the key. Are
// we feeding the wrong value length to ValueSize?
t.Fatalf("expected to find 0 missized tombstones; found %d", m.Keys.MissizedTombstonesCount)
}
}()
defer e.close()
if strings.Contains(path, "_nometamorphiciter") {
e.noMetamorphicIter = true
}
datadriven.RunTest(t, path, func(t *testing.T, d *datadriven.TestData) string {
// We'll be overriding cmd/cmdargs below, because the
// datadriven reader does not know about sub-commands.
defer func(pos, cmd string, cmdArgs []datadriven.CmdArg) {
d.Pos = pos
d.Cmd = cmd
d.CmdArgs = cmdArgs
}(d.Pos, d.Cmd, d.CmdArgs)
// The various evalCtx helpers want access to the current test
// and testdata structs.
e.t = t
e.td = d
defer func() {
if e.iter != nil {
if r := recover(); r != nil {
e.iter.Close()
panic(r)
}
}
}()
switch d.Cmd {
case "skip":
if len(d.CmdArgs) == 0 {
skip.IgnoreLint(e.t, "skipped")
}
return d.Expected
case "run":
// Syntax: run [trace] [error]
// (other words - in particular "ok" - are accepted but ignored)
//
// "run" executes a script of zero or more operations from
// the commands library defined below.
// It stops upon the first error encountered, if any.
//
// Options:
// - trace: emit intermediate results after each operation.
// - stats: emit MVCC statistics for each operation and at the end.
// - log-ops: emit any MVCC Logical operations at the end.
// - error: expect an error to occur. The specific error type/ message
// to expect is spelled out in the expected output.
//
trace := e.hasArg("trace")
stats := e.hasArg("stats")
logOps := e.hasArg("log-ops")
expectError := e.hasArg("error")
// buf will accumulate the actual output, which the
// datadriven driver will use to compare to the expected
// output.
var buf redact.StringBuilder
e.results.buf = &buf
e.results.traceClearKey = trace
e.logOps = logOps
e.opLog = nil
// We reset the stats such that they accumulate for all commands
// in a single test.
e.ms = &enginepb.MVCCStats{}
// foundErr remembers which error was last encountered while
// executing the script under "run".
var foundErr error
// pos is the original <file>:<lineno> prefix computed by
// datadriven. It points to the top "run" command itself.
// We are editing d.Pos in-place below by extending `pos` upon
// each new line of the script.
pos := d.Pos
// dataChange indicates whether some command in the script
// has modified the stored data. When this becomes true, the
// current content of storage is printed in the results
// buffer at the end.
dataChange := false
// txnChange indicates whether some command has modified
// a transaction object. When set, the last modified txn
// object is reported in the result buffer at the end.
txnChange := false
// locksChange indicates whether some command has modified
// the lock table. When set, the lock table is reported in
// the result buffer at the end.
locksChange := false
reportResults := func(printTxn, printData, printLocks bool) {
if printTxn && e.results.txn != nil {
buf.Printf("txn: %v\n", e.results.txn)
}
if printData {
err := reportDataEntries(&buf)
if err != nil {
if foundErr == nil {
// Handle the error below.
foundErr = err
} else {
buf.Printf("error reading data: (%T:) %v\n", err, err)
}
}
for i, sst := range e.ssts {
err = reportSSTEntries(&buf, fmt.Sprintf("sst-%d", i), sst)
if err != nil {
if foundErr == nil {
// Handle the error below.
foundErr = err
} else {
buf.Printf("error reading SST data: (%T:) %v\n", err, err)
}
}
}
}
if printLocks {
err = reportLockTable(e, &buf)
if err != nil {
if foundErr == nil {
// Handle the error below.
foundErr = err
} else {
buf.Printf("error reading locks: (%T:) %v\n", err, err)
}
}
}
if logOps {
prettyPrintOp := func(op enginepb.MVCCLogicalOp) string {
switch t := op.GetValue().(type) {
case *enginepb.MVCCWriteValueOp:
return fmt.Sprintf("write_value: key=%s, ts=%s", roachpb.Key(t.Key), t.Timestamp)
case *enginepb.MVCCDeleteRangeOp:
return fmt.Sprintf("delete_range: startKey=%s endKey=%s ts=%s", roachpb.Key(t.StartKey), roachpb.Key(t.EndKey), t.Timestamp)
default:
return fmt.Sprintf("%T", t)
}
}
for _, op := range e.opLog {
buf.Printf("logical op: %s\n", prettyPrintOp(op))
}
}
}
// sharedCmdArgs is updated by "with" pseudo-commands,
// to pre-populate common arguments for the following
// indented commands.
var sharedCmdArgs []datadriven.CmdArg
// The lines of the script under "run".
lines := strings.Split(d.Input, "\n")
for i, line := range lines {
if short := strings.TrimSpace(line); short == "" || strings.HasPrefix(short, "#") {
// Comment or empty line. Do nothing.
continue
}
// Compute a line prefix, to clarify error message. We
// prefix a newline character because some text editor do
// not know how to jump to the location of an error if
// there are multiple file:line prefixes on the same line.
d.Pos = fmt.Sprintf("\n%s: (+%d)", pos, i+1)
// Trace the execution in testing.T, to clarify where we
// are in case an error occurs.
log.Infof(context.Background(), "TestMVCCHistories:\n\t%s: %s", d.Pos, line)
// Decompose the current script line.
var err error
d.Cmd, d.CmdArgs, err = datadriven.ParseLine(line)
if err != nil {
e.t.Fatalf("%s: %v", d.Pos, err)
}
// Expand "with" commands:
// with t=A
// txn_begin
// resolve_intent k=a
// is equivalent to:
// txn_begin t=A
// resolve_intent k=a t=A
isIndented := strings.TrimLeft(line, " \t") != line
if d.Cmd == "with" {
if !isIndented {
// Reset shared args.
sharedCmdArgs = d.CmdArgs
} else {
// Prefix shared args. We use prefix so that the
// innermost "with" can override/shadow the outermost
// "with".
sharedCmdArgs = append(d.CmdArgs, sharedCmdArgs...)
}
continue
} else if isIndented {
// line is indented. Inherit arguments.
if len(sharedCmdArgs) == 0 {
// sanity check.
e.Fatalf("indented command without prior 'with': %s", line)
}
// We prepend the args that are provided on the command
// itself so it's possible to override those provided
// via "with".
d.CmdArgs = append(d.CmdArgs, sharedCmdArgs...)
} else {
// line is not indented. Clear shared arguments.
sharedCmdArgs = nil
}
cmd := e.getCmd()
txnChangeForCmd := cmd.typ&typTxnUpdate != 0
dataChangeForCmd := cmd.typ&typDataUpdate != 0
locksChangeForCmd := cmd.typ&typLocksUpdate != 0
txnChange = txnChange || txnChangeForCmd
dataChange = dataChange || dataChangeForCmd
locksChange = locksChange || locksChangeForCmd
statsForCmd := stats && (dataChangeForCmd || locksChangeForCmd)
if trace || statsForCmd {
// If tracing is also requested by the datadriven input,
// we'll trace the statement in the actual results too.
buf.Printf(">> %s", d.Cmd)
for i := range d.CmdArgs {
buf.Printf(" %s", &d.CmdArgs[i])
}
_ = buf.WriteByte('\n')
}
// Record the engine and evaluated stats before the command, so
// that we can compare the deltas.
var msEngineBefore enginepb.MVCCStats
if stats {
for _, span := range spans {
ms, err := storage.ComputeStats(ctx, e.engine, span.Key, span.EndKey, statsTS)
require.NoError(t, err)
msEngineBefore.Add(ms)
lockSpan := lockTableSpan(span)
lockMs, err := storage.ComputeStats(
ctx, e.engine, lockSpan.Key, lockSpan.EndKey, statsTS)
require.NoError(t, err)
msEngineBefore.Add(lockMs)
}
}
msEvalBefore := *e.ms
// Run the command.
foundErr = cmd.fn(e)
if separateEngineBlocks && !disableSeparateEngineBlocks && dataChange {
require.NoError(t, e.engine.Flush())
}
if trace {
// If tracing is enabled, we report the intermediate results
// after each individual step in the script.
// This may modify foundErr too.
reportResults(txnChangeForCmd, dataChangeForCmd, dataChangeForCmd)
}
if statsForCmd {
// If stats are enabled, emit evaluated stats returned by the
// command, and compare them with the real computed stats diff.
var msEngineDiff enginepb.MVCCStats
for _, span := range spans {
ms, err := storage.ComputeStats(ctx, e.engine, span.Key, span.EndKey, statsTS)
require.NoError(t, err)
msEngineDiff.Add(ms)
lockSpan := lockTableSpan(span)
lockMs, err := storage.ComputeStats(
ctx, e.engine, lockSpan.Key, lockSpan.EndKey, statsTS)
require.NoError(t, err)
msEngineDiff.Add(lockMs)
}
msEngineDiff.Subtract(msEngineBefore)
msEvalDiff := *e.ms
msEvalDiff.Subtract(msEvalBefore)
msEvalDiff.AgeTo(msEngineDiff.LastUpdateNanos)
buf.Printf("stats: %s\n", formatStats(msEvalDiff, true))
if msEvalDiff != msEngineDiff {
e.t.Errorf("MVCC stats mismatch for %q at %s\nReturned: %s\nExpected: %s",
d.Cmd, d.Pos, formatStats(msEvalDiff, true), formatStats(msEngineDiff, true))
}
}
if foundErr != nil {
// An error occurred. Stop the script prematurely.
break
}
}
// End of script.
// Check for any deferred iterator errors.
if foundErr == nil {
foundErr = e.iterErr()
}
// Flush any unfinished SSTs.
if foundErr == nil {
foundErr = e.finishSST()
} else {
e.closeSST()
}
if !trace {
// If we were not tracing, no results were printed yet. Do it now.
if txnChange || dataChange || locksChange {
buf.SafeString(">> at end:\n")
}
reportResults(txnChange, dataChange, locksChange)
}
// Calculate and output final stats if requested and the data changed.
if stats && (dataChange || locksChange) {
var msFinal enginepb.MVCCStats
for _, span := range spans {
ms, err := storage.ComputeStats(ctx, e.engine, span.Key, span.EndKey, statsTS)
require.NoError(t, err)
msFinal.Add(ms)
lockSpan := lockTableSpan(span)
lockMs, err := storage.ComputeStats(
ctx, e.engine, lockSpan.Key, lockSpan.EndKey, statsTS)
require.NoError(t, err)
msFinal.Add(lockMs)
}
buf.Printf("stats: %s\n", formatStats(msFinal, false))
}
signalError := e.t.Errorf
if txnChange || dataChange || locksChange {
// We can't recover from an error and continue
// to proceed further tests, because the state
// may have changed from what the test may be expecting.
signalError = e.t.Fatalf
}
// Check for errors.
if foundErr == nil && expectError {
signalError("%s: expected error, got success", d.Pos)
return d.Expected
} else if foundErr != nil {
if expectError {
buf.Printf("error: (%T:) %v\n", foundErr, foundErr)
} else /* !expectError */ {
signalError("%s: expected success, found: (%T:) %v", d.Pos, foundErr, foundErr)
return d.Expected
}
}
// We're done. Report the actual results and errors to the
// datadriven executor.
return buf.String()
default:
e.t.Errorf("%s: unknown command: %s", d.Pos, d.Cmd)
return d.Expected
}
})
})
}
// getCmd retrieves the cmd entry for the current script line.
func (e *evalCtx) getCmd() cmd {
e.t.Helper()
c, ok := commands[e.td.Cmd]
if !ok {
e.Fatalf("unknown command: %s", e.td.Cmd)
}
return c
}
// cmd represents one supported script command.
type cmd struct {
typ cmdType
fn func(e *evalCtx) error
}
type cmdType int
const (
typReadOnly cmdType = 1 << iota
typTxnUpdate
typDataUpdate
typLocksUpdate
)
// commands is the list of all supported script commands.
var commands = map[string]cmd{
"txn_advance": {typTxnUpdate, cmdTxnAdvance},
"txn_begin": {typTxnUpdate, cmdTxnBegin},
"txn_ignore_seqs": {typTxnUpdate, cmdTxnIgnoreSeqs},
"txn_remove": {typTxnUpdate, cmdTxnRemove},
"txn_restart": {typTxnUpdate, cmdTxnRestart},
"txn_status": {typTxnUpdate, cmdTxnSetStatus},
"txn_step": {typTxnUpdate, cmdTxnStep},
"txn_update": {typTxnUpdate, cmdTxnUpdate},
"resolve_intent": {typDataUpdate | typLocksUpdate, cmdResolveIntent},
"resolve_intent_range": {typDataUpdate | typLocksUpdate, cmdResolveIntentRange},
"check_intent": {typReadOnly, cmdCheckIntent},
"add_unreplicated_lock": {typLocksUpdate, cmdAddUnreplicatedLock},
"check_for_acquire_lock": {typReadOnly, cmdCheckForAcquireLock},
"acquire_lock": {typLocksUpdate, cmdAcquireLock},
"verify_lock": {typReadOnly, cmdVerifyLock},
"clear": {typDataUpdate, cmdClear},
"clear_range": {typDataUpdate, cmdClearRange},
"clear_rangekey": {typDataUpdate, cmdClearRangeKey},
"clear_time_range": {typDataUpdate, cmdClearTimeRange},
"cput": {typDataUpdate, cmdCPut},
"del": {typDataUpdate, cmdDelete},
"del_range": {typDataUpdate, cmdDeleteRange},
"del_range_ts": {typDataUpdate, cmdDeleteRangeTombstone},
"del_range_pred": {typDataUpdate, cmdDeleteRangePredicate},
"export": {typReadOnly, cmdExport},
"get": {typReadOnly, cmdGet},
"gc_clear_range": {typDataUpdate, cmdGCClearRange},
"gc_points_clear_range": {typDataUpdate, cmdGCPointsClearRange},
"increment": {typDataUpdate, cmdIncrement},
"initput": {typDataUpdate, cmdInitPut},
"merge": {typDataUpdate, cmdMerge},
"put": {typDataUpdate, cmdPut},
"put_blind_inline": {typDataUpdate, cmdPutBlindInline},
"put_rangekey": {typDataUpdate, cmdPutRangeKey},
"scan": {typReadOnly, cmdScan},
"is_span_empty": {typReadOnly, cmdIsSpanEmpty},
"iter_new": {typReadOnly, cmdIterNew},
"iter_new_incremental": {typReadOnly, cmdIterNewIncremental}, // MVCCIncrementalIterator
"iter_new_read_as_of": {typReadOnly, cmdIterNewReadAsOf}, // readAsOfIterator
"iter_seek_ge": {typReadOnly, cmdIterSeekGE},
"iter_seek_lt": {typReadOnly, cmdIterSeekLT},
"iter_next": {typReadOnly, cmdIterNext},
"iter_next_ignoring_time": {typReadOnly, cmdIterNextIgnoringTime}, // MVCCIncrementalIterator
"iter_next_key_ignoring_time": {typReadOnly, cmdIterNextKeyIgnoringTime}, // MVCCIncrementalIterator
"iter_next_key": {typReadOnly, cmdIterNextKey},
"iter_prev": {typReadOnly, cmdIterPrev},
"iter_scan": {typReadOnly, cmdIterScan},
"sst_put": {typDataUpdate, cmdSSTPut},
"sst_put_rangekey": {typDataUpdate, cmdSSTPutRangeKey},
"sst_clear_range": {typDataUpdate, cmdSSTClearRange},
"sst_clear_rangekey": {typDataUpdate, cmdSSTClearRangeKey},
"sst_finish": {typDataUpdate, cmdSSTFinish},
"sst_reset": {typDataUpdate, cmdSSTReset},
"sst_iter_new": {typReadOnly, cmdSSTIterNew},
"replace_point_tombstones_with_range_tombstones": {typDataUpdate, cmdReplacePointTombstonesWithRangeTombstones},
}
func cmdTxnAdvance(e *evalCtx) error {
txn := e.getTxn(mandatory)
ts := e.getTs(txn)
if ts.Less(txn.ReadTimestamp) {
e.Fatalf("cannot advance txn to earlier (%s) than its ReadTimestamp (%s)",
ts, txn.ReadTimestamp)
}
txn.WriteTimestamp = ts
e.results.txn = txn
return nil
}
func cmdTxnBegin(e *evalCtx) error {
var txnName string
e.scanArg("t", &txnName)
ts := e.getTs(nil)
globalUncertaintyLimit := e.getTsWithName("globalUncertaintyLimit")
key := roachpb.KeyMin
if e.hasArg("k") {
key = e.getKey()
}
txn, err := e.newTxn(txnName, ts, globalUncertaintyLimit, key)
e.results.txn = txn
return err
}
func cmdTxnIgnoreSeqs(e *evalCtx) error {
txn := e.getTxn(mandatory)
seql := e.getList("seqs")
is := []enginepb.IgnoredSeqNumRange{}
for _, s := range seql {
parts := strings.Split(s, "-")
if len(parts) != 2 {
e.Fatalf("syntax error: expected 'a-b', got: '%s'", s)
}
a, err := strconv.ParseInt(parts[0], 10, 32)
if err != nil {
e.Fatalf("%v", err)
}
b, err := strconv.ParseInt(parts[1], 10, 32)
if err != nil {
e.Fatalf("%v", err)
}
is = append(is, enginepb.IgnoredSeqNumRange{Start: enginepb.TxnSeq(a), End: enginepb.TxnSeq(b)})
}
txn.IgnoredSeqNums = is
e.results.txn = txn
return nil
}
func cmdTxnRemove(e *evalCtx) error {
txn := e.getTxn(mandatory)
delete(e.txns, txn.Name)
e.results.txn = nil
return nil
}
func cmdTxnRestart(e *evalCtx) error {
txn := e.getTxn(mandatory)
ts := e.getTs(txn)
up := roachpb.NormalUserPriority
tp := enginepb.MinTxnPriority
txn.Restart(up, tp, ts)
if e.hasArg("epoch") {
var epoch int
e.scanArg("epoch", &epoch)
txn.Epoch = enginepb.TxnEpoch(epoch)
}
e.results.txn = txn
return nil
}
func cmdTxnSetStatus(e *evalCtx) error {
txn := e.getTxn(mandatory)
status := e.getTxnStatus()
txn.Status = status
e.results.txn = txn
return nil
}
func cmdTxnStep(e *evalCtx) error {
txn := e.getTxn(mandatory)
n := 1
if e.hasArg("seq") {
e.scanArg("seq", &n)
txn.Sequence = enginepb.TxnSeq(n)
} else {
if e.hasArg("n") {
e.scanArg("n", &n)
}
txn.Sequence += enginepb.TxnSeq(n)
}
e.results.txn = txn
return nil
}