-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
operations.go
1626 lines (1503 loc) · 42.5 KB
/
operations.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 2020 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 metamorphic
import (
"context"
"fmt"
"math"
"path/filepath"
"sort"
"strconv"
"strings"
"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/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
)
// opReference represents one operation; an opGenerator reference as well as
// bound arguments.
type opReference struct {
generator *opGenerator
args []string
}
// opRun represents one operation run; a generated operation, and bound
// arguments.
type opRun struct {
name string
op mvccOp
// TODO(itsbilal): Instead of storing arguments separately and printing them,
// have mvccOp be able to print and parse its arguments itself. This would
// give us more freedom with printing of arguments and would easily correct
// for things like endKey and key being swapped if endKey < key. It would also
// let us avoid the opGenerator.generate() call completely when
// parsing/checking an already-generated output file.
args []string
// The following fields are only used in the "check mode", in parseFileAndRun.
lineNum uint64
expectedOutput string
}
// mvccOp represents an operation instance that can be run. It's generated by
// an instance of opGenerator.
type mvccOp interface {
// run runs the operation. An output string is returned.
run(ctx context.Context) string
}
// An opGenerator instance represents one type of an operation. The run and
// dependantOps commands should be stateless, with all state stored in the
// passed-in test runner or its operand generators.
type opGenerator struct {
// Name of the operation. Used in file output and parsing.
name string
// Function to call to generate the operation runner.
generate func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp
// Returns a list of operation runs that must happen before this operation.
// Note that openers for non-existent operands are handled separately and
// don't need to be handled here.
dependentOps func(m *metaTestRunner, args ...string) []opReference
// Operands this operation expects. Passed in the same order to run and
// dependentOps.
operands []operandType
// weight is used to denote frequency of this operation to the TPCC-style
// deck.
//
// Note that the generator tends to bias towards opener operations; since
// an opener can be generated outside of the deck shuffle, in resolveAndAddOp
// to create an instance of an operand that does not exist. To counter this
// bias, we try to keep the sum of opener operations to be less than half
// the sum of "closer" operations for an operand type, to prevent too many
// of that type of object from accumulating throughout the run.
weight int
// isOpener denotes whether this operation is an opener. Opener operations are
// special, in that the last operand specified is generated from a getNew()
// call to the matching operand generator, instead of the usual get().
isOpener bool
}
// Helper function to generate iterator_close opRuns for all iterators on a
// passed-in Batch.
func closeItersOnBatch(m *metaTestRunner, reader readWriterID) (results []opReference) {
// No need to close iters on non-batches (i.e. engines).
if reader == "engine" {
return
}
// Close all iterators for this batch first.
for _, iter := range m.iterGenerator.readerToIter[reader] {
results = append(results, opReference{
generator: m.nameToGenerator["iterator_close"],
args: []string{string(iter)},
})
}
return
}
// Helper function to run MVCCScan given a key range and a reader.
func generateMVCCScan(
ctx context.Context, m *metaTestRunner, reverse bool, inconsistent bool, args []string,
) *mvccScanOp {
key := m.keyGenerator.parse(args[0])
endKey := m.keyGenerator.parse(args[1])
if endKey.Less(key) {
key, endKey = endKey, key
}
var ts hlc.Timestamp
var txn txnID
if inconsistent {
ts = m.pastTSGenerator.parse(args[2])
} else {
txn = txnID(args[2])
}
maxKeys := int64(m.floatGenerator.parse(args[3]) * 32)
targetBytes := int64(m.floatGenerator.parse(args[4]) * (1 << 20))
allowEmpty := m.boolGenerator.parse(args[5])
return &mvccScanOp{
m: m,
key: key.Key,
endKey: endKey.Key,
ts: ts,
txn: txn,
inconsistent: inconsistent,
reverse: reverse,
maxKeys: maxKeys,
targetBytes: targetBytes,
allowEmpty: allowEmpty,
}
}
// Prints the key where an iterator is positioned, or valid = false if invalid.
func printIterState(iter storage.MVCCIterator) string {
if ok, err := iter.Valid(); !ok || err != nil {
if err != nil {
return fmt.Sprintf("valid = %v, err = %s", ok, err.Error())
}
return "valid = false"
}
return fmt.Sprintf("key = %s", iter.UnsafeKey().String())
}
func addKeyToLockSpans(txn *roachpb.Transaction, key roachpb.Key) {
// Update the txn's lock spans to account for this intent being written.
newLockSpans := make([]roachpb.Span, 0, len(txn.LockSpans)+1)
newLockSpans = append(newLockSpans, txn.LockSpans...)
newLockSpans = append(newLockSpans, roachpb.Span{
Key: key,
})
txn.LockSpans, _ = roachpb.MergeSpans(&newLockSpans)
}
type mvccGetOp struct {
m *metaTestRunner
reader readWriterID
key roachpb.Key
ts hlc.Timestamp
txn txnID
inconsistent bool
}
func (m mvccGetOp) run(ctx context.Context) string {
reader := m.m.getReadWriter(m.reader)
var txn *roachpb.Transaction
if !m.inconsistent {
txn = m.m.getTxn(m.txn)
m.ts = txn.ReadTimestamp
}
// TODO(itsbilal): Specify these bools as operands instead of having a
// separate operation for inconsistent cases. This increases visibility for
// anyone reading the output file.
res, err := storage.MVCCGet(ctx, reader, m.key, m.ts, storage.MVCCGetOptions{
Inconsistent: m.inconsistent,
Tombstones: true,
Txn: txn,
})
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return fmt.Sprintf("val = %v, intent = %v", res.Value, res.Intent)
}
type mvccPutOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
value roachpb.Value
txn txnID
}
func (m mvccPutOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
txn.Sequence++
writer := m.m.getReadWriter(m.writer)
_, err := storage.MVCCPut(ctx, writer, m.key, txn.ReadTimestamp, m.value, storage.MVCCWriteOptions{Txn: txn})
if err != nil {
if writeTooOldErr := (*kvpb.WriteTooOldError)(nil); errors.As(err, &writeTooOldErr) {
txn.WriteTimestamp.Forward(writeTooOldErr.ActualTimestamp)
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
}
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
return "ok"
}
type mvccCPutOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
value roachpb.Value
expVal []byte
txn txnID
}
func (m mvccCPutOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
writer := m.m.getReadWriter(m.writer)
txn.Sequence++
_, err := storage.MVCCConditionalPut(ctx, writer, m.key,
txn.ReadTimestamp, m.value, m.expVal, true, storage.MVCCWriteOptions{Txn: txn})
if err != nil {
if writeTooOldErr := (*kvpb.WriteTooOldError)(nil); errors.As(err, &writeTooOldErr) {
txn.WriteTimestamp.Forward(writeTooOldErr.ActualTimestamp)
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
}
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
return "ok"
}
type mvccInitPutOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
value roachpb.Value
txn txnID
}
func (m mvccInitPutOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
writer := m.m.getReadWriter(m.writer)
txn.Sequence++
_, err := storage.MVCCInitPut(ctx, writer, m.key, txn.ReadTimestamp, m.value, false, storage.MVCCWriteOptions{Txn: txn})
if err != nil {
if writeTooOldErr := (*kvpb.WriteTooOldError)(nil); errors.As(err, &writeTooOldErr) {
txn.WriteTimestamp.Forward(writeTooOldErr.ActualTimestamp)
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
}
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
return "ok"
}
type mvccCheckForAcquireLockOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
txn txnID
strength lock.Strength
}
func (m mvccCheckForAcquireLockOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
txn.Sequence++
writer := m.m.getReadWriter(m.writer)
err := storage.MVCCCheckForAcquireLock(ctx, writer, txn, m.strength, m.key, 64)
if err != nil {
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
return "ok"
}
type mvccAcquireLockOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
txn txnID
strength lock.Strength
}
func (m mvccAcquireLockOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
txn.Sequence++
writer := m.m.getReadWriter(m.writer)
err := storage.MVCCAcquireLock(ctx, writer, txn, m.strength, m.key, nil, 64)
if err != nil {
if writeTooOldErr := (*kvpb.WriteTooOldError)(nil); errors.As(err, &writeTooOldErr) {
txn.WriteTimestamp.Forward(writeTooOldErr.ActualTimestamp)
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
}
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
return "ok"
}
type mvccDeleteRangeOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
endKey roachpb.Key
txn txnID
}
func (m mvccDeleteRangeOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
writer := m.m.getReadWriter(m.writer)
if m.key.Compare(m.endKey) >= 0 {
// Empty range. No-op.
return "no-op due to no non-conflicting key range"
}
txn.Sequence++
keys, _, _, _, err := storage.MVCCDeleteRange(ctx, writer, m.key, m.endKey,
0, txn.WriteTimestamp, storage.MVCCWriteOptions{Txn: txn}, true)
if err != nil {
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
for _, key := range keys {
addKeyToLockSpans(txn, key)
}
var builder strings.Builder
fmt.Fprintf(&builder, "truncated range to delete = %s - %s, deleted keys = ", m.key, m.endKey)
for i, key := range keys {
fmt.Fprintf(&builder, "%s", key)
if i < len(keys)-1 {
fmt.Fprintf(&builder, ", ")
}
}
return builder.String()
}
type mvccDeleteRangeUsingRangeTombstoneOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
endKey roachpb.Key
ts hlc.Timestamp
}
func (m mvccDeleteRangeUsingRangeTombstoneOp) run(ctx context.Context) string {
writer := m.m.getReadWriter(m.writer)
if m.key.Compare(m.endKey) >= 0 {
// Empty range. No-op.
return "no-op due to no non-conflicting key range"
}
err := storage.MVCCDeleteRangeUsingTombstone(ctx, writer, nil, m.key, m.endKey, m.ts,
hlc.ClockTimestamp{}, m.key, m.endKey, false /* idempotent */, math.MaxInt64, /* maxLockConflicts */
nil /* msCovered */)
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return fmt.Sprintf("deleted range = %s - %s", m.key, m.endKey)
}
type mvccClearTimeRangeOp struct {
m *metaTestRunner
key roachpb.Key
endKey roachpb.Key
startTime hlc.Timestamp
endTime hlc.Timestamp
}
func (m mvccClearTimeRangeOp) run(ctx context.Context) string {
if m.key.Compare(m.endKey) >= 0 {
// Empty range. No-op.
return "no-op due to no non-conflicting key range"
}
span, err := storage.MVCCClearTimeRange(ctx, m.m.engine, &enginepb.MVCCStats{}, m.key, m.endKey,
m.startTime, m.endTime, nil, nil, math.MaxInt64, math.MaxInt64, math.MaxInt64)
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return fmt.Sprintf("ok, deleted span = %s - %s, resumeSpan = %v", m.key, m.endKey, span)
}
type mvccDeleteOp struct {
m *metaTestRunner
writer readWriterID
key roachpb.Key
txn txnID
}
func (m mvccDeleteOp) run(ctx context.Context) string {
txn := m.m.getTxn(m.txn)
writer := m.m.getReadWriter(m.writer)
txn.Sequence++
_, _, err := storage.MVCCDelete(ctx, writer, m.key, txn.ReadTimestamp, storage.MVCCWriteOptions{Txn: txn})
if err != nil {
if writeTooOldErr := (*kvpb.WriteTooOldError)(nil); errors.As(err, &writeTooOldErr) {
txn.WriteTimestamp.Forward(writeTooOldErr.ActualTimestamp)
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
}
return fmt.Sprintf("error: %s", err)
}
// Update the txn's lock spans to account for this intent being written.
addKeyToLockSpans(txn, m.key)
return "ok"
}
type mvccFindSplitKeyOp struct {
m *metaTestRunner
key roachpb.RKey
endKey roachpb.RKey
splitSize int64
}
func (m mvccFindSplitKeyOp) run(ctx context.Context) string {
splitKey, err := storage.MVCCFindSplitKey(ctx, m.m.engine, m.key, m.endKey, m.splitSize)
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return fmt.Sprintf("ok, splitSize = %d, splitKey = %v", m.splitSize, splitKey)
}
type mvccScanOp struct {
m *metaTestRunner
key roachpb.Key
endKey roachpb.Key
ts hlc.Timestamp
txn txnID
inconsistent bool
reverse bool
maxKeys int64
targetBytes int64
allowEmpty bool
}
func (m mvccScanOp) run(ctx context.Context) string {
var txn *roachpb.Transaction
if !m.inconsistent {
txn = m.m.getTxn(m.txn)
m.ts = txn.ReadTimestamp
}
// While MVCCScanning on a batch works in Pebble, it does not in rocksdb.
// This is due to batch iterators not supporting SeekForPrev. For now, use
// m.engine instead of a readWriterGenerator-generated engine.Reader, otherwise
// we will try MVCCScanning on batches and produce diffs between runs on
// different engines that don't point to an actual issue.
result, err := storage.MVCCScan(ctx, m.m.engine, m.key, m.endKey, m.ts, storage.MVCCScanOptions{
Inconsistent: m.inconsistent,
Tombstones: true,
Reverse: m.reverse,
Txn: txn,
MaxKeys: m.maxKeys,
TargetBytes: m.targetBytes,
AllowEmpty: m.allowEmpty,
})
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return fmt.Sprintf("kvs = %v, intents = %v, resumeSpan = %v, numBytes = %d, numKeys = %d",
result.KVs, result.Intents, result.ResumeSpan, result.NumBytes, result.NumKeys)
}
type txnOpenOp struct {
m *metaTestRunner
id txnID
ts hlc.Timestamp
}
func (t txnOpenOp) run(ctx context.Context) string {
var id uint64
if _, err := fmt.Sscanf(string(t.id), "t%d", &id); err != nil {
panic(err)
}
txn := &roachpb.Transaction{
TxnMeta: enginepb.TxnMeta{
ID: uuid.FromUint128(uint128.FromInts(0, id)),
Key: roachpb.KeyMin,
WriteTimestamp: t.ts,
Sequence: 0,
},
Name: string(t.id),
ReadTimestamp: t.ts,
Status: roachpb.PENDING,
}
t.m.setTxn(t.id, txn)
return txn.Name
}
type txnCommitOp struct {
m *metaTestRunner
id txnID
}
func (t txnCommitOp) run(ctx context.Context) string {
txn := t.m.getTxn(t.id)
txn.Status = roachpb.COMMITTED
txn.Sequence++
for _, span := range txn.LockSpans {
intent := roachpb.MakeLockUpdate(txn, span)
intent.Status = roachpb.COMMITTED
_, _, _, _, err := storage.MVCCResolveWriteIntent(context.TODO(), t.m.engine, nil, intent, storage.MVCCResolveWriteIntentOptions{})
if err != nil {
panic(err)
}
}
delete(t.m.openTxns, t.id)
delete(t.m.openSavepoints, t.id)
return "ok"
}
type txnAbortOp struct {
m *metaTestRunner
id txnID
}
func (t txnAbortOp) run(ctx context.Context) string {
txn := t.m.getTxn(t.id)
txn.Status = roachpb.ABORTED
for _, span := range txn.LockSpans {
intent := roachpb.MakeLockUpdate(txn, span)
intent.Status = roachpb.ABORTED
_, _, _, _, err := storage.MVCCResolveWriteIntent(context.TODO(), t.m.engine, nil, intent, storage.MVCCResolveWriteIntentOptions{})
if err != nil {
panic(err)
}
}
delete(t.m.openTxns, t.id)
delete(t.m.openSavepoints, t.id)
return "ok"
}
type txnCreateSavepointOp struct {
m *metaTestRunner
id txnID
// The index of the savepoint (in m.openSavepoints[id]) being created.
// As savepoints are only appended to the end, this must equal
// len(m.openSavepoints[t.id]) at time of running.
savepoint int
}
func (t txnCreateSavepointOp) run(ctx context.Context) string {
txn := t.m.getTxn(t.id)
txn.Sequence++
// Append txn.Sequence.
if len(t.m.openSavepoints[t.id]) == t.savepoint {
t.m.openSavepoints[t.id] = append(t.m.openSavepoints[t.id], txn.Sequence)
} else {
panic(fmt.Sprintf("mismatching savepoint index: %d != %d", len(t.m.openSavepoints[t.id]), t.savepoint))
}
return fmt.Sprintf("savepoint %d", t.savepoint)
}
type txnRollbackSavepointOp struct {
m *metaTestRunner
id txnID
// The index of the savepoint (in m.openSavepoints[id]) being rolled back to.
// Txn sequences are generated and stored at runtime in that slice.
savepoint int
}
func (t txnRollbackSavepointOp) run(ctx context.Context) string {
txn := t.m.getTxn(t.id)
txn.Sequence++
savepoints := t.m.openSavepoints[t.id]
if len(savepoints) == 0 || t.savepoint > len(savepoints) {
panic(fmt.Sprintf("got a higher savepoint idx %d than allowed for txn %s", t.savepoint, t.id))
}
ignoredSeqNumRange := enginepb.IgnoredSeqNumRange{
Start: savepoints[t.savepoint],
End: txn.Sequence,
}
txn.AddIgnoredSeqNumRange(ignoredSeqNumRange)
return "ok"
}
type batchOpenOp struct {
m *metaTestRunner
id readWriterID
}
func (b batchOpenOp) run(ctx context.Context) string {
batch := b.m.engine.NewBatch()
b.m.setReadWriter(b.id, batch)
return string(b.id)
}
type batchCommitOp struct {
m *metaTestRunner
id readWriterID
}
func (b batchCommitOp) run(ctx context.Context) string {
if b.id == "engine" {
return "noop"
}
batch := b.m.getReadWriter(b.id).(storage.Batch)
if err := batch.Commit(true); err != nil {
return err.Error()
}
batch.Close()
delete(b.m.openBatches, b.id)
return "ok"
}
type iterOpenOp struct {
m *metaTestRunner
rw readWriterID
key roachpb.Key
endKey roachpb.Key
id iteratorID
}
func (i iterOpenOp) run(ctx context.Context) string {
rw := i.m.getReadWriter(i.rw)
iter, err := rw.NewMVCCIterator(ctx, storage.MVCCKeyIterKind, storage.IterOptions{
Prefix: false,
LowerBound: i.key,
UpperBound: i.endKey.Next(),
})
if err != nil {
return err.Error()
}
i.m.setIterInfo(i.id, iteratorInfo{
id: i.id,
lowerBound: i.key,
iter: iter,
isBatchIter: i.rw != "engine",
})
if _, ok := rw.(storage.Batch); ok {
// When Next()-ing on a newly initialized batch iter without a key,
// pebble's iterator stays invalid while RocksDB's finds the key after
// the first key. This is a known difference. For now seek the iterator
// to standardize behavior for this test.
iter.SeekGE(storage.MakeMVCCMetadataKey(i.key))
}
return string(i.id)
}
type iterCloseOp struct {
m *metaTestRunner
id iteratorID
}
func (i iterCloseOp) run(ctx context.Context) string {
iterInfo := i.m.getIterInfo(i.id)
iterInfo.iter.Close()
delete(i.m.openIters, i.id)
return "ok"
}
type iterSeekOp struct {
m *metaTestRunner
iter iteratorID
key storage.MVCCKey
seekLT bool
}
func (i iterSeekOp) run(ctx context.Context) string {
iterInfo := i.m.getIterInfo(i.iter)
iter := iterInfo.iter
if iterInfo.isBatchIter {
if i.seekLT {
return "noop due to missing seekLT support in rocksdb batch iterators"
}
// RocksDB batch iterators do not account åfor lower bounds consistently:
// https://github.com/cockroachdb/cockroach/issues/44512
// In the meantime, ensure the SeekGE key >= lower bound.
lowerBound := iterInfo.lowerBound
if i.key.Key.Compare(lowerBound) < 0 {
i.key.Key = lowerBound
}
}
if i.seekLT {
iter.SeekLT(i.key)
} else {
iter.SeekGE(i.key)
}
return printIterState(iter)
}
type iterNextOp struct {
m *metaTestRunner
iter iteratorID
nextKey bool
}
func (i iterNextOp) run(ctx context.Context) string {
iter := i.m.getIterInfo(i.iter).iter
// The rocksdb iterator does not treat kindly to a Next() if it is already
// invalid. Don't run next if that is the case.
if ok, err := iter.Valid(); !ok || err != nil {
if err != nil {
return fmt.Sprintf("valid = %v, err = %s", ok, err.Error())
}
return "valid = false"
}
if i.nextKey {
iter.NextKey()
} else {
iter.Next()
}
return printIterState(iter)
}
type iterPrevOp struct {
m *metaTestRunner
iter iteratorID
}
func (i iterPrevOp) run(ctx context.Context) string {
iterInfo := i.m.getIterInfo(i.iter)
iter := iterInfo.iter
if iterInfo.isBatchIter {
return "noop due to missing Prev support in rocksdb batch iterators"
}
// The rocksdb iterator does not treat kindly to a Prev() if it is already
// invalid. Don't run prev if that is the case.
if ok, err := iter.Valid(); !ok || err != nil {
if err != nil {
return fmt.Sprintf("valid = %v, err = %s", ok, err.Error())
}
return "valid = false"
}
iter.Prev()
return printIterState(iter)
}
type clearRangeOp struct {
m *metaTestRunner
key roachpb.Key
endKey roachpb.Key
}
func (c clearRangeOp) run(ctx context.Context) string {
// ClearRange calls in Cockroach usually happen with boundaries demarcated
// using unversioned keys, so mimic the same behavior here.
if c.key.Compare(c.endKey) >= 0 {
// Empty range. No-op.
return "no-op due to no non-conflicting key range"
}
err := c.m.engine.ClearMVCCRange(c.key, c.endKey, true, true)
if err != nil {
return fmt.Sprintf("error: %s", err.Error())
}
return fmt.Sprintf("deleted range = %s - %s", c.key, c.endKey)
}
type compactOp struct {
m *metaTestRunner
key roachpb.Key
endKey roachpb.Key
}
func (c compactOp) run(ctx context.Context) string {
err := c.m.engine.CompactRange(c.key, c.endKey)
if err != nil {
return fmt.Sprintf("error: %s", err.Error())
}
return "ok"
}
type ingestOp struct {
m *metaTestRunner
keys []storage.MVCCKey
}
func (i ingestOp) run(ctx context.Context) string {
sstPath := filepath.Join(i.m.path, "ingest.sst")
f, err := i.m.engineFS.Create(sstPath)
if err != nil {
return fmt.Sprintf("error = %s", err.Error())
}
sstWriter := storage.MakeIngestionSSTWriter(ctx, i.m.st, objstorageprovider.NewFileWritable(f))
for _, key := range i.keys {
_ = sstWriter.Put(key, []byte("ingested"))
}
if err := sstWriter.Finish(); err != nil {
return fmt.Sprintf("error = %s", err.Error())
}
sstWriter.Close()
if err := i.m.engine.IngestLocalFiles(ctx, []string{sstPath}); err != nil {
return fmt.Sprintf("error = %s", err.Error())
}
return "ok"
}
type restartOp struct {
m *metaTestRunner
}
func (r restartOp) run(ctx context.Context) string {
if !r.m.restarts {
r.m.printComment("no-op due to restarts being disabled")
return "ok"
}
oldEngine, newEngine := r.m.restart()
r.m.printComment(fmt.Sprintf("restarting: %s -> %s", oldEngine.name, newEngine.name))
r.m.printComment(fmt.Sprintf("new options: %s", newEngine.opts.String()))
return "ok"
}
// List of operation generators, where each operation is defined as one instance of opGenerator.
//
// TODO(itsbilal): Add more missing MVCC operations, such as:
// - MVCCBlindPut
// - MVCCMerge
// - MVCCIncrement
// - and any others that would be important to test.
var opGenerators = []opGenerator{
{
name: "mvcc_inconsistent_get",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
reader := readWriterID(args[0])
key := m.keyGenerator.parse(args[1])
ts := m.pastTSGenerator.parse(args[2])
return &mvccGetOp{
m: m,
reader: reader,
key: key.Key,
ts: ts,
inconsistent: true,
}
},
operands: []operandType{
operandReadWriter,
operandMVCCKey,
operandPastTS,
},
weight: 100,
},
{
name: "mvcc_get",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
reader := readWriterID(args[0])
key := m.keyGenerator.parse(args[1])
txn := txnID(args[2])
return &mvccGetOp{
m: m,
reader: reader,
key: key.Key,
txn: txn,
}
},
operands: []operandType{
operandReadWriter,
operandMVCCKey,
operandTransaction,
},
weight: 100,
},
{
name: "mvcc_put",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
writer := readWriterID(args[0])
txn := txnID(args[1])
key := m.txnKeyGenerator.parse(args[2])
value := roachpb.MakeValueFromBytes(m.valueGenerator.parse(args[3]))
// Track this write in the txn generator. This ensures the batch will be
// committed before the transaction is committed
m.txnGenerator.trackTransactionalWrite(writer, txn, key.Key, nil)
return &mvccPutOp{
m: m,
writer: writer,
key: key.Key,
value: value,
txn: txn,
}
},
operands: []operandType{
operandReadWriter,
operandTransaction,
operandUnusedMVCCKey,
operandValue,
},
weight: 500,
},
{
name: "mvcc_conditional_put",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
writer := readWriterID(args[0])
txn := txnID(args[1])
key := m.txnKeyGenerator.parse(args[2])
value := roachpb.MakeValueFromBytes(m.valueGenerator.parse(args[3]))
expVal := m.valueGenerator.parse(args[4])
// Track this write in the txn generator. This ensures the batch will be
// committed before the transaction is committed
m.txnGenerator.trackTransactionalWrite(writer, txn, key.Key, nil)
return &mvccCPutOp{
m: m,
writer: writer,
key: key.Key,
value: value,
expVal: expVal,
txn: txn,
}
},
operands: []operandType{
operandReadWriter,
operandTransaction,
operandUnusedMVCCKey,
operandValue,
operandValue,
},
weight: 50,
},
{
name: "mvcc_init_put",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
writer := readWriterID(args[0])
txn := txnID(args[1])
key := m.txnKeyGenerator.parse(args[2])
value := roachpb.MakeValueFromBytes(m.valueGenerator.parse(args[3]))
// Track this write in the txn generator. This ensures the batch will be
// committed before the transaction is committed
m.txnGenerator.trackTransactionalWrite(writer, txn, key.Key, nil)
return &mvccInitPutOp{
m: m,
writer: writer,
key: key.Key,
value: value,
txn: txn,
}
},
operands: []operandType{
operandReadWriter,
operandTransaction,
operandUnusedMVCCKey,
operandValue,
},
weight: 50,
},
{
name: "mvcc_acquire_lock",
generate: func(ctx context.Context, m *metaTestRunner, args ...string) mvccOp {
writer := readWriterID(args[0])
txn := txnID(args[1])
key := m.txnKeyGenerator.parse(args[2])
strength := lock.Shared
if m.floatGenerator.parse(args[3]) < 0.5 {
strength = lock.Exclusive