-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathbench_test.go
2140 lines (1955 loc) · 66.5 KB
/
bench_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"
"os"
"path/filepath"
"sort"
"testing"
"time"
"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/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/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/sstable"
"github.com/stretchr/testify/require"
)
// Note: most benchmarks in this package have an engine-specific Benchmark
// function (see bench_rocksdb_test.go and bench_pebble_test.go). The newer
// Benchmarks with a unified implementation are here at the top of this file
// with the business logic for the implementation of the other tests following.
func BenchmarkMVCCGarbageCollect(b *testing.B) {
skip.UnderShort(b)
defer log.Scope(b).Close(b)
// NB: To debug #16068, test only 128-128-15000-6.
keySizes := []int{128}
valSizes := []int{128}
numKeys := []int{1, 1024}
versionConfigs := []struct {
total int
rangeTombstoneKeys []int
toDelete []int
}{
{
total: 2,
rangeTombstoneKeys: []int{0, 1, 2},
toDelete: []int{1},
},
{
total: 1024,
rangeTombstoneKeys: []int{0, 1, 100},
toDelete: []int{1, 16, 32, 512, 1015, 1023},
},
}
updateStats := []bool{false, true}
engineMakers := []struct {
name string
create engineMaker
}{
{"pebble", setupPebbleInMemPebbleForLatestRelease},
}
ctx := context.Background()
for _, engineImpl := range engineMakers {
b.Run(engineImpl.name, func(b *testing.B) {
for _, keySize := range keySizes {
b.Run(fmt.Sprintf("keySize=%d", keySize), func(b *testing.B) {
for _, valSize := range valSizes {
b.Run(fmt.Sprintf("valSize=%d", valSize), func(b *testing.B) {
for _, numKeys := range numKeys {
b.Run(fmt.Sprintf("numKeys=%d", numKeys), func(b *testing.B) {
for _, versions := range versionConfigs {
b.Run(fmt.Sprintf("numVersions=%d", versions.total), func(b *testing.B) {
for _, toDelete := range versions.toDelete {
b.Run(fmt.Sprintf("deleteVersions=%d", toDelete), func(b *testing.B) {
for _, rangeTombstones := range versions.rangeTombstoneKeys {
b.Run(fmt.Sprintf("numRangeTs=%d", rangeTombstones), func(b *testing.B) {
for _, stats := range updateStats {
b.Run(fmt.Sprintf("updateStats=%t", stats), func(b *testing.B) {
runMVCCGarbageCollect(ctx, b, engineImpl.create,
benchGarbageCollectOptions{
mvccBenchData: mvccBenchData{
numKeys: numKeys,
numVersions: versions.total,
valueBytes: valSize,
numRangeKeys: rangeTombstones,
},
keyBytes: keySize,
deleteVersions: toDelete,
updateStats: stats,
})
})
}
})
}
})
}
})
}
})
}
})
}
})
}
})
}
}
func BenchmarkMVCCExportToSST(b *testing.B) {
skip.UnderShort(b)
defer log.Scope(b).Close(b)
// To run and compare on range keys:
//
// go test ./pkg/storage -run - -count 5 -bench BenchmarkMVCCExportToSST -timeout 500m 2>&1 | tee bench.txt
// for flavor in numRangeKeys=0 numRangeKeys=1 numRangeKeys=100; do grep -E "${flavor}[^0-9]+" bench.txt | sed -E "s/${flavor}+/X/" > $flavor.txt; done
// benchstat numRangeKeys\={0,1}.txt
// benchstat numRangeKeys\={0,100}.txt
numKeys := []int{64, 512, 1024, 8192, 65536}
numRevisions := []int{1, 10, 100}
numRangeKeys := []int{0, 1, 100}
exportAllRevisions := []bool{false, true}
for _, numKey := range numKeys {
b.Run(fmt.Sprintf("numKeys=%d", numKey), func(b *testing.B) {
for _, numRevision := range numRevisions {
b.Run(fmt.Sprintf("numRevisions=%d", numRevision), func(b *testing.B) {
for _, numRangeKey := range numRangeKeys {
b.Run(fmt.Sprintf("numRangeKeys=%d", numRangeKey), func(b *testing.B) {
for _, perc := range []int{100, 50, 10} {
if numRevision == 1 && perc != 100 {
continue // no point in incremental exports with 1 revision
}
b.Run(fmt.Sprintf("perc=%d%%", perc), func(b *testing.B) {
for _, exportAllRevisionsVal := range exportAllRevisions {
b.Run(fmt.Sprintf("exportAllRevisions=%t", exportAllRevisionsVal), func(b *testing.B) {
opts := mvccExportToSSTOpts{
numKeys: numKey,
numRevisions: numRevision,
numRangeKeys: numRangeKey,
exportAllRevisions: exportAllRevisionsVal,
percentage: perc,
}
runMVCCExportToSST(b, opts)
})
}
})
}
})
}
})
}
})
}
// Doubling the test variants because of this one parameter feels pretty
// excessive (this benchmark is already very long), so handle it specially
// and hard code the other parameters. To run and compare:
//
// dev bench pkg/storage --filter BenchmarkMVCCExportToSST/useElasticCPUHandle --count 10 --timeout 20m -v --stream-output --ignore-cache 2>&1 | tee bench.txt
// for flavor in useElasticCPUHandle=true useElasticCPUHandle=false; do grep -E "${flavor}[^0-9]+" bench.txt | sed -E "s/${flavor}+/X/" > $flavor.txt; done
// benchstat useElasticCPUHandle\={false,true}.txt
//
// Results (08/29/2022):
//
// goos: linux
// goarch: amd64
// cpu: Intel(R) Xeon(R) CPU @ 2.20GHz
// ...
// $ benchstat useElasticCPUHandle\={false,true}.txt
// name old time/op new time/op delta
// MVCCExportToSST/X/numKeys=65536/numRevisions=100/exportAllRevisions=true-24 2.54s ± 2% 2.53s ± 2% ~ (p=0.549 n=10+9)
//
withElasticCPUHandle := []bool{false, true}
for _, useElasticCPUHandle := range withElasticCPUHandle {
numKey := numKeys[len(numKeys)-1]
numRevision := numRevisions[len(numRevisions)-1]
numRangeKey := numRangeKeys[len(numRangeKeys)-1]
exportAllRevisionVal := exportAllRevisions[len(exportAllRevisions)-1]
b.Run(fmt.Sprintf("useElasticCPUHandle=%t/numKeys=%d/numRevisions=%d/exportAllRevisions=%t",
useElasticCPUHandle, numKey, numRevision, exportAllRevisionVal,
), func(b *testing.B) {
opts := mvccExportToSSTOpts{
numKeys: numKey,
numRevisions: numRevision,
numRangeKeys: numRangeKey,
exportAllRevisions: exportAllRevisionVal,
useElasticCPUHandle: useElasticCPUHandle,
}
runMVCCExportToSST(b, opts)
})
}
}
const numIntentKeys = 1000
// setupKeysWithIntent writes keys using transactions to eng. The number of
// different keys is equal to numIntentKeys and each key has numVersions
// versions written to it. The number of versions that are resolved is either
// numVersions-1 or numVersions, which is controlled by the resolveAll
// parameter (when true, numVersions are resolved). The latest version for a
// key is generated using one of possibly two transactions. One of these is
// what is returned in the LockUpdate so that the caller can resolve intents
// for it (if any). This distinguished transaction writes the latest version
// with a stride equal to lockUpdateTxnHasLatestVersionStride. A stride of k
// means it writes every k-th latest version. Strides longer than 1 are for
// use in tests with ranged intent resolution for this distinguished
// transaction, where some of the intents encountered should not be resolved.
// The latest intents written by the non-distinguished transaction may also be
// resolved, if resolveIntentForLatestVersionWhenNonLockUpdateTxn is true.
// This causes ranged intent resolution to not encounter intents owned by
// other transactions, but may have to skip through keys that have no intents
// at all. numFlushedVersions is a parameter that controls how many versions
// are flushed out from the memtable to sstables -- when less is flushed out,
// and we are using separated intents, the SingleDeletes, Sets corresponding
// to resolved intents still exist in the memtable, and can result in more
// work during intent resolution. In a production setting numFlushedVersions
// should be close to all the versions.
func setupKeysWithIntent(
b testing.TB,
eng Engine,
numVersions int,
numFlushedVersions int,
resolveAll bool,
lockUpdateTxnHasLatestVersionStride int,
resolveIntentForLatestVersionWhenNonLockUpdateTxn bool,
) roachpb.LockUpdate {
txnIDCount := 2 * numVersions
adjustTxnID := func(txnID int) int {
// Assign txn IDs in a deterministic way that will mimic the end result of
// random assignment -- the live intent is centered between dead intents,
// when we have separated intents.
if txnID%2 == 0 {
txnID = txnIDCount - txnID
}
return txnID
}
txnIDWithLatestVersion := adjustTxnID(numVersions)
otherTxnWithLatestVersion := txnIDCount + 2
otherTxnUUID := uuid.FromUint128(uint128.FromInts(0, uint64(otherTxnWithLatestVersion)))
var rvLockUpdate roachpb.LockUpdate
for i := 1; i <= numVersions; i++ {
// Assign txn IDs in a deterministic way that will mimic the end result of
// random assignment -- the live intent is centered between dead intents,
// when we have separated intents.
txnID := adjustTxnID(i)
txnUUID := uuid.FromUint128(uint128.FromInts(0, uint64(txnID)))
ts := hlc.Timestamp{WallTime: int64(i)}
txn := roachpb.Transaction{
TxnMeta: enginepb.TxnMeta{
ID: txnUUID,
Key: []byte("foo"),
WriteTimestamp: ts,
MinTimestamp: ts,
},
Status: roachpb.PENDING,
ReadTimestamp: ts,
GlobalUncertaintyLimit: ts,
}
lockUpdate := roachpb.LockUpdate{
Txn: txn.TxnMeta,
Status: roachpb.COMMITTED,
}
var otherTxn roachpb.Transaction
var otherLockUpdate roachpb.LockUpdate
if txnID == txnIDWithLatestVersion {
rvLockUpdate = lockUpdate
if lockUpdateTxnHasLatestVersionStride != 1 {
otherTxn = roachpb.Transaction{
TxnMeta: enginepb.TxnMeta{
ID: otherTxnUUID,
Key: []byte("foo"),
WriteTimestamp: ts,
MinTimestamp: ts,
},
Status: roachpb.PENDING,
ReadTimestamp: ts,
GlobalUncertaintyLimit: ts,
}
otherLockUpdate = roachpb.LockUpdate{
Txn: otherTxn.TxnMeta,
Status: roachpb.COMMITTED,
}
}
}
value := roachpb.MakeValueFromString("value")
batch := eng.NewBatch()
for j := 0; j < numIntentKeys; j++ {
putTxn := &txn
if txnID == txnIDWithLatestVersion && j%lockUpdateTxnHasLatestVersionStride != 0 {
putTxn = &otherTxn
}
key := makeKey(nil, j)
_, err := MVCCPut(context.Background(), batch, key, ts, value, MVCCWriteOptions{Txn: putTxn})
require.NoError(b, err)
}
require.NoError(b, batch.Commit(true))
batch.Close()
if i < numVersions || resolveAll || resolveIntentForLatestVersionWhenNonLockUpdateTxn {
batch := eng.NewBatch()
for j := 0; j < numIntentKeys; j++ {
key := makeKey(nil, j)
lu := lockUpdate
latestVersionNonLockUpdateTxn := false
if txnID == txnIDWithLatestVersion && j%lockUpdateTxnHasLatestVersionStride != 0 {
lu = otherLockUpdate
latestVersionNonLockUpdateTxn = true
}
lu.Key = key
if i == numVersions && !resolveAll && !latestVersionNonLockUpdateTxn {
// Only here because of
// resolveIntentForLatestVersionWhenNonLockUpdateTxn, and this key
// is not one that should be resolved.
continue
}
found, _, _, _, err := MVCCResolveWriteIntent(context.Background(), batch, nil, lu, MVCCResolveWriteIntentOptions{})
require.Equal(b, true, found)
require.NoError(b, err)
}
require.NoError(b, batch.Commit(true))
batch.Close()
}
if i == numFlushedVersions {
require.NoError(b, eng.Flush())
}
}
return rvLockUpdate
}
// BenchmarkIntentScan compares separated and interleaved intents, when
// reading the intent and latest version for a range of keys.
func BenchmarkIntentScan(b *testing.B) {
skip.UnderShort(b, "setting up unflushed data takes too long")
defer log.Scope(b).Close(b)
for _, numVersions := range []int{10, 100, 200, 400} {
b.Run(fmt.Sprintf("versions=%d", numVersions), func(b *testing.B) {
for _, percentFlushed := range []int{0, 50, 80, 90, 100} {
b.Run(fmt.Sprintf("percent-flushed=%d", percentFlushed), func(b *testing.B) {
eng := setupMVCCInMemPebbleWithSeparatedIntents(b)
numFlushedVersions := (percentFlushed * numVersions) / 100
setupKeysWithIntent(b, eng, numVersions, numFlushedVersions, false, /* resolveAll */
1, false /* resolveIntentForLatestVersionWhenNotLockUpdate */)
lower := makeKey(nil, 0)
iter, err := eng.NewMVCCIterator(context.Background(), MVCCKeyAndIntentsIterKind, IterOptions{
LowerBound: lower,
UpperBound: makeKey(nil, numIntentKeys),
})
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
valid, err := iter.Valid()
if err != nil {
b.Fatal(err)
}
if !valid {
iter.SeekGE(MVCCKey{Key: lower})
} else {
// Read intent.
k := iter.UnsafeKey()
if k.IsValue() {
b.Fatalf("expected intent %s", k.String())
}
// Read latest version.
//
// This Next dominates the cost of the benchmark when
// percent-flushed is < 100, since the pebble.Iterator has
// to iterate over all the Deletes/SingleDeletes/Sets
// corresponding to resolved intents.
iter.Next()
valid, err = iter.Valid()
if !valid || err != nil {
b.Fatalf("valid: %t, err: %s", valid, err)
}
k = iter.UnsafeKey()
if !k.IsValue() {
b.Fatalf("expected value")
}
// Skip to next key. This dominates the cost of the benchmark,
// when percent-flushed=100.
iter.NextKey()
}
}
})
}
})
}
}
// BenchmarkScanAllIntentsResolved compares separated and interleaved intents,
// when reading the latest version for a range of keys, when all the intents
// have been resolved.
func BenchmarkScanAllIntentsResolved(b *testing.B) {
skip.UnderShort(b, "setting up unflushed data takes too long")
defer log.Scope(b).Close(b)
for _, numVersions := range []int{200} {
b.Run(fmt.Sprintf("versions=%d", numVersions), func(b *testing.B) {
for _, percentFlushed := range []int{0, 50, 90, 100} {
b.Run(fmt.Sprintf("percent-flushed=%d", percentFlushed), func(b *testing.B) {
eng := setupMVCCInMemPebbleWithSeparatedIntents(b)
numFlushedVersions := (percentFlushed * numVersions) / 100
setupKeysWithIntent(b, eng, numVersions, numFlushedVersions, true, /* resolveAll */
1, false /* resolveIntentForLatestVersionWhenNotLockUpdate */)
lower := makeKey(nil, 0)
var iter MVCCIterator
var buf []byte
b.ResetTimer()
for i := 0; i < b.N; i++ {
var valid bool
var err error
if iter != nil {
valid, err = iter.Valid()
}
if err != nil {
b.Fatal(err)
}
if !valid {
// Create a new MVCCIterator. Simply seeking to the earlier
// key is not representative of a real workload where
// iterator reuse always seeks to a later key (because of
// the sorting in a BatchRequest). Seeking to an earlier key
// allows for an optimization in lock table iteration when
// not using the *WithLimit() operations on the underlying
// pebble.Iterator, where the SeekGE can be turned into a
// noop since the original SeekGE is what was remembered
// (and this seek is to the same position as the original
// seek). This optimization won't fire in this manner in
// practice, so we don't want it to happen in this Benchmark
// either.
b.StopTimer()
iter, err = eng.NewMVCCIterator(context.Background(), MVCCKeyAndIntentsIterKind, IterOptions{
LowerBound: lower,
UpperBound: makeKey(nil, numIntentKeys),
})
if err != nil {
b.Fatal(err)
}
b.StartTimer()
iter.SeekGE(MVCCKey{Key: lower})
} else {
// Read latest version.
k := iter.UnsafeKey()
if !k.IsValue() {
b.Fatalf("expected value %s", k.String())
}
// Skip to next key.
buf = append(buf[:0], k.Key...)
buf = encoding.BytesNext(buf)
iter.SeekGE(MVCCKey{Key: buf})
}
}
})
}
})
}
}
// BenchmarkScanOneAllIntentsResolved compares separated and interleaved
// intents, when reading the latest version for a range of keys, when all the
// intents have been resolved. Unlike the previous benchmark, each scan reads
// one key.
func BenchmarkScanOneAllIntentsResolved(b *testing.B) {
skip.UnderShort(b, "setting up unflushed data takes too long")
defer log.Scope(b).Close(b)
for _, numVersions := range []int{200} {
b.Run(fmt.Sprintf("versions=%d", numVersions), func(b *testing.B) {
for _, percentFlushed := range []int{0, 50, 90, 100} {
b.Run(fmt.Sprintf("percent-flushed=%d", percentFlushed), func(b *testing.B) {
eng := setupMVCCInMemPebbleWithSeparatedIntents(b)
numFlushedVersions := (percentFlushed * numVersions) / 100
setupKeysWithIntent(b, eng, numVersions, numFlushedVersions, true, /* resolveAll */
1, false /* resolveIntentForLatestVersionWhenNotLockUpdate */)
lower := makeKey(nil, 0)
upper := makeKey(nil, numIntentKeys)
buf := append([]byte(nil), lower...)
b.ResetTimer()
for i := 0; i < b.N; i++ {
iter, err := eng.NewMVCCIterator(context.Background(), MVCCKeyAndIntentsIterKind, IterOptions{
LowerBound: buf,
UpperBound: upper,
})
if err != nil {
b.Fatal(err)
}
iter.SeekGE(MVCCKey{Key: buf})
valid, err := iter.Valid()
if err != nil {
b.Fatal(err)
}
if !valid {
buf = append(buf[:0], lower...)
} else {
// Read latest version.
k := iter.UnsafeKey()
if !k.IsValue() {
b.Fatalf("expected value %s", k.String())
}
// Skip to next key.
buf = append(buf[:0], k.Key...)
buf = encoding.BytesNext(buf)
iter.Close()
}
}
})
}
})
}
}
// BenchmarkIntentResolution compares separated and interleaved intents, when
// doing intent resolution for individual intents.
func BenchmarkIntentResolution(b *testing.B) {
skip.UnderShort(b, "setting up unflushed data takes too long")
defer log.Scope(b).Close(b)
for _, numVersions := range []int{10, 100, 200, 400} {
b.Run(fmt.Sprintf("versions=%d", numVersions), func(b *testing.B) {
for _, percentFlushed := range []int{0, 50, 80, 90, 100} {
b.Run(fmt.Sprintf("percent-flushed=%d", percentFlushed), func(b *testing.B) {
eng := setupMVCCInMemPebbleWithSeparatedIntents(b)
numFlushedVersions := (percentFlushed * numVersions) / 100
lockUpdate := setupKeysWithIntent(b, eng, numVersions, numFlushedVersions,
false /* resolveAll */, 1,
false /* resolveIntentForLatestVersionWhenNotLockUpdate */)
keys := make([]roachpb.Key, numIntentKeys)
for i := range keys {
keys[i] = makeKey(nil, i)
}
batch := eng.NewBatch()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if i > 0 && i%numIntentKeys == 0 {
// Wrapped around.
b.StopTimer()
batch.Close()
batch = eng.NewBatch()
b.StartTimer()
}
lockUpdate.Key = keys[i%numIntentKeys]
found, _, _, _, err := MVCCResolveWriteIntent(context.Background(), batch, nil, lockUpdate, MVCCResolveWriteIntentOptions{})
if !found || err != nil {
b.Fatalf("intent not found or err %s", err)
}
}
})
}
})
}
}
// BenchmarkIntentRangeResolution benchmarks ranged intent resolution with
// various counts of mvcc versions and sparseness of intents.
func BenchmarkIntentRangeResolution(b *testing.B) {
skip.UnderShort(b, "setting up unflushed data takes too long")
defer log.Scope(b).Close(b)
for _, numVersions := range []int{10, 100, 400} {
b.Run(fmt.Sprintf("versions=%d", numVersions), func(b *testing.B) {
for _, sparseness := range []int{1, 100, 1000} {
b.Run(fmt.Sprintf("sparseness=%d", sparseness), func(b *testing.B) {
otherTxnUnresolvedIntentsCases := []bool{false, true}
if sparseness == 1 {
// Every intent is owned by the main txn.
otherTxnUnresolvedIntentsCases = []bool{false}
}
for _, haveOtherTxnUnresolvedIntents := range otherTxnUnresolvedIntentsCases {
b.Run(fmt.Sprintf("other-txn-intents=%t", haveOtherTxnUnresolvedIntents), func(b *testing.B) {
for _, percentFlushed := range []int{0, 50, 100} {
b.Run(fmt.Sprintf("percent-flushed=%d", percentFlushed), func(b *testing.B) {
eng := setupMVCCInMemPebbleWithSeparatedIntents(b)
numFlushedVersions := (percentFlushed * numVersions) / 100
lockUpdate := setupKeysWithIntent(b, eng, numVersions, numFlushedVersions,
false /* resolveAll */, sparseness, !haveOtherTxnUnresolvedIntents)
keys := make([]roachpb.Key, numIntentKeys+1)
for i := range keys {
keys[i] = makeKey(nil, i)
}
batch := eng.NewBatch()
numKeysPerRange := 100
numRanges := numIntentKeys / numKeysPerRange
var resolvedCount int64
expectedResolvedCount := int64(numIntentKeys / sparseness)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if i > 0 && i%numRanges == 0 {
// Wrapped around.
b.StopTimer()
if resolvedCount != expectedResolvedCount {
b.Fatalf("expected to resolve %d, actual %d",
expectedResolvedCount, resolvedCount)
}
resolvedCount = 0
batch.Close()
batch = eng.NewBatch()
b.StartTimer()
}
rangeNum := i % numRanges
lockUpdate.Key = keys[rangeNum*numKeysPerRange]
lockUpdate.EndKey = keys[(rangeNum+1)*numKeysPerRange]
resolved, _, span, _, _, err := MVCCResolveWriteIntentRange(
context.Background(), batch, nil, lockUpdate,
MVCCResolveWriteIntentRangeOptions{MaxKeys: 1000})
if err != nil {
b.Fatal(err)
}
resolvedCount += resolved
if span != nil {
b.Fatal("unexpected resume span")
}
}
})
}
})
}
})
}
})
}
}
const overhead = 48 // Per key/value overhead (empirically determined)
type engineMaker func(testing.TB, string) Engine
// loadTestData writes numKeys keys in numBatches separate batches. Keys are
// written in order. Every key in a given batch has the same MVCC timestamp;
// batch timestamps start at batchTimeSpan and increase in intervals of
// batchTimeSpan.
//
// Importantly, writing keys in order convinces RocksDB to output one SST per
// batch, where each SST contains keys of only one timestamp. E.g., writing A,B
// at t0 and C at t1 will create two SSTs: one for A,B that only contains keys
// at t0, and one for C that only contains keys at t1. Conversely, writing A, C
// at t0 and B at t1 would create just one SST that contained A,B,C (due to an
// immediate compaction).
//
// The creation of the database is time consuming, so the caller can choose
// whether to use a temporary or permanent location.
func loadTestData(dir string, numKeys, numBatches, batchTimeSpan, valueBytes int) (Engine, error) {
ctx := context.Background()
exists := true
if _, err := os.Stat(dir); oserror.IsNotExist(err) {
exists = false
}
eng, err := Open(
context.Background(),
Filesystem(dir),
cluster.MakeTestingClusterSettings())
if err != nil {
return nil, err
}
if exists {
testutils.ReadAllFiles(filepath.Join(dir, "*"))
return eng, nil
}
log.Infof(context.Background(), "creating test data: %s", dir)
// Generate the same data every time.
rng := rand.New(rand.NewSource(1449168817))
keys := make([]roachpb.Key, numKeys)
for i := 0; i < numKeys; i++ {
keys[i] = roachpb.Key(encoding.EncodeUvarintAscending([]byte("key-"), uint64(i)))
}
sstTimestamps := make([]int64, numBatches)
for i := 0; i < len(sstTimestamps); i++ {
sstTimestamps[i] = int64((i + 1) * batchTimeSpan)
}
var batch Batch
var minWallTime int64
batchSize := len(keys) / numBatches
for i, key := range keys {
if (i % batchSize) == 0 {
if i > 0 {
log.Infof(ctx, "committing (%d/~%d)", i/batchSize, numBatches)
if err := batch.Commit(false /* sync */); err != nil {
return nil, err
}
batch.Close()
if err := eng.Flush(); err != nil {
return nil, err
}
}
batch = eng.NewBatch()
minWallTime = sstTimestamps[i/batchSize]
}
timestamp := hlc.Timestamp{WallTime: minWallTime + rng.Int63n(int64(batchTimeSpan))}
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueBytes))
value.InitChecksum(key)
if _, err := MVCCPut(ctx, batch, key, timestamp, value, MVCCWriteOptions{}); err != nil {
return nil, err
}
}
if err := batch.Commit(false /* sync */); err != nil {
return nil, err
}
batch.Close()
if err := eng.Flush(); err != nil {
return nil, err
}
return eng, nil
}
type benchScanOptions struct {
mvccBenchData
numRows int
reverse bool
wholeRows bool
tombstones bool
}
// runMVCCScan first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCScans in increments of numRows
// keys over all of the data in the Engine instance, restarting at
// the beginning of the keyspace, as many times as necessary.
func runMVCCScan(ctx context.Context, b *testing.B, opts benchScanOptions) {
// Use the same number of keys for all of the mvcc scan
// benchmarks. Using a different number of keys per test gives
// preferential treatment to tests with fewer keys. Note that the
// datasets all fit in cache and the cache is pre-warmed.
if opts.numKeys != 0 {
b.Fatal("test error: cannot call runMVCCScan with non-zero numKeys")
}
opts.numKeys = 100000
if opts.wholeRows && opts.numColumnFamilies == 0 {
b.Fatal("test error: wholeRows requires numColumnFamilies > 0")
}
eng := getInitialStateEngine(ctx, b, opts.mvccBenchData, false /* inMemory */)
defer eng.Close()
{
// Pull all of the sstables into the RocksDB cache in order to make the
// timings more stable. Otherwise, the first run will be penalized pulling
// data into the cache while later runs will not.
if _, err := ComputeStats(ctx, eng, keys.LocalMax, roachpb.KeyMax, 0); err != nil {
b.Fatalf("stats failed: %s", err)
}
}
var startKey, endKey roachpb.Key
startKeyBuf := append(make([]byte, 0, 1024), []byte("key-")...)
endKeyBuf := append(make([]byte, 0, 1024), []byte("key-")...)
b.SetBytes(int64(opts.numRows * opts.valueBytes))
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Choose a random key to start scan.
if opts.numColumnFamilies == 0 {
keyIdx := rand.Int31n(int32(opts.numKeys - opts.numRows))
startKey = roachpb.Key(encoding.EncodeUvarintAscending(startKeyBuf[:4], uint64(keyIdx)))
endKey = roachpb.Key(encoding.EncodeUvarintAscending(endKeyBuf[:4], uint64(keyIdx+int32(opts.numRows)-1))).Next()
} else {
startID := rand.Int63n(int64((opts.numKeys - opts.numRows) / opts.numColumnFamilies))
endID := startID + int64(opts.numRows/opts.numColumnFamilies) + 1
startKey = makeBenchRowKey(b, startKeyBuf[:0], int(startID), 0)
endKey = makeBenchRowKey(b, endKeyBuf[:0], int(endID), 0)
}
walltime := int64(5 * (rand.Int31n(int32(opts.numVersions)) + 1))
if opts.garbage {
walltime = hlc.MaxTimestamp.WallTime
}
ts := hlc.Timestamp{WallTime: walltime}
var wholeRowsOfSize int32
if opts.wholeRows {
wholeRowsOfSize = int32(opts.numColumnFamilies)
}
res, err := MVCCScan(ctx, eng, startKey, endKey, ts, MVCCScanOptions{
MaxKeys: int64(opts.numRows),
WholeRowsOfSize: wholeRowsOfSize,
AllowEmpty: wholeRowsOfSize != 0,
Reverse: opts.reverse,
Tombstones: opts.tombstones,
})
if err != nil {
b.Fatalf("failed scan: %+v", err)
}
expectKVs := opts.numRows
if opts.wholeRows {
expectKVs -= opts.numRows % opts.numColumnFamilies
}
if !opts.garbage && len(res.KVs) != expectKVs {
b.Fatalf("failed to scan: %d != %d", len(res.KVs), expectKVs)
}
if opts.garbage && !opts.tombstones && len(res.KVs) != 0 {
b.Fatalf("failed to scan garbage: found %d keys", len(res.KVs))
}
}
b.StopTimer()
}
// runMVCCGet first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCGets.
func runMVCCGet(ctx context.Context, b *testing.B, opts mvccBenchData, useBatch bool) {
// Use the same number of keys for all of the mvcc scan
// benchmarks. Using a different number of keys per test gives
// preferential treatment to tests with fewer keys. Note that the
// datasets all fit in cache and the cache is pre-warmed.
if opts.numKeys != 0 {
b.Fatal("test error: cannot call runMVCCGet with non-zero numKeys")
}
opts.numKeys = 100000
eng := getInitialStateEngine(ctx, b, opts, false /* inMemory */)
defer eng.Close()
r := Reader(eng)
if useBatch {
batch := eng.NewBatch()
defer batch.Close()
r = batch
}
b.SetBytes(int64(opts.valueBytes))
b.ResetTimer()
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
for i := 0; i < b.N; i++ {
// Choose a random key to retrieve.
keyIdx := rand.Int31n(int32(opts.numKeys))
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx)))
walltime := int64(5 * (rand.Int31n(int32(opts.numVersions)) + 1))
ts := hlc.Timestamp{WallTime: walltime}
if valRes, err := MVCCGet(ctx, r, key, ts, MVCCGetOptions{}); err != nil {
b.Fatalf("failed get: %+v", err)
} else if valRes.Value == nil {
b.Fatalf("failed get (key not found): %d@%d", keyIdx, walltime)
} else if valueBytes, err := valRes.Value.GetBytes(); err != nil {
b.Fatal(err)
} else if len(valueBytes) != opts.valueBytes {
b.Fatalf("unexpected value size: %d", len(valueBytes))
}
}
b.StopTimer()
}
func runMVCCPut(
ctx context.Context, b *testing.B, emk engineMaker, valueSize, versions int, useBatch bool,
) {
rng, _ := randutil.NewTestRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng := emk(b, fmt.Sprintf("put_%d", valueSize))
defer eng.Close()
rw := ReadWriter(eng)
if useBatch {
batch := eng.NewBatch()
defer batch.Close()
rw = batch
}
b.SetBytes(int64(valueSize))
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < versions; j++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := hlc.Timestamp{WallTime: timeutil.Now().UnixNano()}
if _, err := MVCCPut(ctx, rw, key, ts, value, MVCCWriteOptions{}); err != nil {
b.Fatalf("failed put: %+v", err)
}
}
}
b.StopTimer()
}
func runMVCCBlindPut(ctx context.Context, b *testing.B, emk engineMaker, valueSize int) {
rng, _ := randutil.NewTestRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng := emk(b, fmt.Sprintf("put_%d", valueSize))
defer eng.Close()
b.SetBytes(int64(valueSize))
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := hlc.Timestamp{WallTime: timeutil.Now().UnixNano()}
if _, err := MVCCBlindPut(ctx, eng, key, ts, value, MVCCWriteOptions{}); err != nil {
b.Fatalf("failed put: %+v", err)
}
}
b.StopTimer()
}
func runMVCCConditionalPut(
ctx context.Context, b *testing.B, emk engineMaker, valueSize int, createFirst bool,
) {
rng, _ := randutil.NewTestRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng := emk(b, fmt.Sprintf("cput_%d", valueSize))
defer eng.Close()
b.SetBytes(int64(valueSize))
var expected []byte
if createFirst {
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := hlc.Timestamp{WallTime: timeutil.Now().UnixNano()}
if _, err := MVCCPut(ctx, eng, key, ts, value, MVCCWriteOptions{}); err != nil {
b.Fatalf("failed put: %+v", err)
}
}
expected = value.TagAndDataBytes()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := hlc.Timestamp{WallTime: timeutil.Now().UnixNano()}
if _, err := MVCCConditionalPut(ctx, eng, key, ts, value, expected, CPutFailIfMissing, MVCCWriteOptions{}); err != nil {
b.Fatalf("failed put: %+v", err)
}
}
b.StopTimer()
}
func runMVCCBlindConditionalPut(ctx context.Context, b *testing.B, emk engineMaker, valueSize int) {
rng, _ := randutil.NewTestRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng := emk(b, fmt.Sprintf("cput_%d", valueSize))
defer eng.Close()
b.SetBytes(int64(valueSize))
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(i)))
ts := hlc.Timestamp{WallTime: timeutil.Now().UnixNano()}
if _, err := MVCCBlindConditionalPut(
ctx, eng, key, ts, value, nil, CPutFailIfMissing, MVCCWriteOptions{},
); err != nil {
b.Fatalf("failed put: %+v", err)
}
}
b.StopTimer()
}
func runMVCCInitPut(ctx context.Context, b *testing.B, emk engineMaker, valueSize int) {
rng, _ := randutil.NewTestRand()
value := roachpb.MakeValueFromBytes(randutil.RandBytes(rng, valueSize))
keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
eng := emk(b, fmt.Sprintf("iput_%d", valueSize))
defer eng.Close()