-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_split_test.go
3635 lines (3295 loc) · 126 KB
/
client_split_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 kvserver_test
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"sort"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/abortspan"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/stateloader"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/ts"
"github.com/cockroachdb/cockroach/pkg/ts/tspb"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft/v3/raftpb"
)
// adminSplitArgs creates an AdminSplitRequest for the provided split key.
func adminSplitArgs(splitKey roachpb.Key) *roachpb.AdminSplitRequest {
return &roachpb.AdminSplitRequest{
RequestHeader: roachpb.RequestHeader{
Key: splitKey,
},
SplitKey: splitKey,
}
}
// TestStoreRangeSplitAtIllegalKeys verifies a range cannot be split
// at illegal keys.
func TestStoreRangeSplitAtIllegalKeys(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
defer s.Stopper().Stop(ctx)
for _, key := range []roachpb.Key{
keys.Meta1Prefix,
testutils.MakeKey(keys.Meta1Prefix, []byte("a")),
testutils.MakeKey(keys.Meta1Prefix, roachpb.RKeyMax),
keys.Meta2KeyMax,
testutils.MakeKey(keys.Meta2KeyMax, []byte("a")),
keys.SystemSQLCodec.TablePrefix(10 /* system descriptor ID */),
} {
args := adminSplitArgs(key)
_, pErr := kv.SendWrapped(context.Background(), s.DB().NonTransactionalSender(), args)
if !testutils.IsPError(pErr, "cannot split") {
t.Errorf("%q: unexpected split error %s", key, pErr)
}
}
}
// Verify that on a split, only the non-expired abort span records are copied
// into the right hand side of the split.
func TestStoreSplitAbortSpan(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
left, middle, right := roachpb.Key("a"), roachpb.Key("b"), roachpb.Key("c")
txn := func(key roachpb.Key, ts hlc.Timestamp) *roachpb.Transaction {
txn := roachpb.MakeTransaction("test", key, 0, ts, 0, int32(s.SQLInstanceID()))
return &txn
}
var expAll []roachpb.AbortSpanEntry
populateAbortSpan := func(key roachpb.Key, ts hlc.Timestamp) *roachpb.ResolveIntentRequest {
pushee := txn(key, ts)
// First write an intent on the key...
incArgs := incrementArgs(key, 1)
_, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{Txn: pushee}, incArgs)
if pErr != nil {
t.Fatalf("while sending +%v: %s", incArgs, pErr)
}
// Then resolve the intent and poison. Without the intent write, the
// intent resolution would be a no-op and wouldn't leave an AbortSpan
// entry.
expAll = append(expAll, roachpb.AbortSpanEntry{
Key: key,
Timestamp: ts,
})
return &roachpb.ResolveIntentRequest{
RequestHeader: roachpb.RequestHeader{
Key: key,
},
IntentTxn: pushee.TxnMeta,
Status: roachpb.ABORTED,
Poison: true,
}
}
key := func(k roachpb.Key, i int) roachpb.Key {
var r []byte
r = append(r, k...)
r = append(r, []byte(strconv.Itoa(i))...)
return r
}
thresh := kvserverbase.TxnCleanupThreshold.Nanoseconds()
// Make sure this test doesn't run out of padding time if we significantly
// reduce TxnCleanupThreshold in the future for whatever reason.
require.Greater(t, thresh, int64(time.Minute))
// Pick a non-gcable and gcable timestamp, respectively.
// Use the current time for some non-expired abort span records.
// Note that the cleanup threshold is so large that while this test runs,
// these records won't expire.
tsFresh := hlc.Timestamp{WallTime: s.Clock().Now().WallTime}
tsStale := hlc.Timestamp{WallTime: s.Clock().Now().WallTime - thresh - 1}
args := []roachpb.Request{
populateAbortSpan(key(left, 1), tsFresh),
populateAbortSpan(key(left, 2), tsStale),
populateAbortSpan(key(middle, 1), tsFresh),
populateAbortSpan(key(middle, 2), tsStale),
populateAbortSpan(key(right, 1), tsFresh),
populateAbortSpan(key(right, 2), tsStale),
adminSplitArgs(middle),
}
// Nothing gets removed from the LHS during the split. This could
// be done but has to be done carefully to avoid large Raft proposals,
// and the stats computation needs to be checked carefully.
expL := []roachpb.AbortSpanEntry{
{Key: key(left, 1), Timestamp: tsFresh},
{Key: key(left, 2), Timestamp: tsStale},
{Key: key(middle, 1), Timestamp: tsFresh},
{Key: key(middle, 2), Timestamp: tsStale},
{Key: key(right, 1), Timestamp: tsFresh},
{Key: key(right, 2), Timestamp: tsStale},
}
// But we don't blindly copy everything over to the RHS. Only entries with
// recent timestamp are duplicated. This is important because otherwise the
// Raft command size can blow up and splits fail.
expR := []roachpb.AbortSpanEntry{
{Key: key(left, 1), Timestamp: tsFresh},
{Key: key(middle, 1), Timestamp: tsFresh},
{Key: key(right, 1), Timestamp: tsFresh},
}
for _, arg := range args {
_, pErr := kv.SendWrapped(ctx, store.TestSender(), arg)
if pErr != nil {
t.Fatalf("while sending +%v: %s", arg, pErr)
}
}
collect := func(as *abortspan.AbortSpan) []roachpb.AbortSpanEntry {
var results []roachpb.AbortSpanEntry
if err := as.Iterate(ctx, store.Engine(), func(_ roachpb.Key, entry roachpb.AbortSpanEntry) error {
entry.Priority = 0 // don't care about that
results = append(results, entry)
return nil
}); err != nil {
t.Fatal(err)
}
sort.Slice(results, func(i, j int) bool {
c := bytes.Compare(results[i].Key, results[j].Key)
if c == 0 {
return results[i].Timestamp.Less(results[j].Timestamp)
}
return c < 0
})
return results
}
l := collect(store.LookupReplica(keys.MustAddr(left)).AbortSpan())
r := collect(store.LookupReplica(keys.MustAddr(right)).AbortSpan())
if !reflect.DeepEqual(expL, l) {
t.Fatalf("left hand side: expected %+v, got %+v", expL, l)
}
if !reflect.DeepEqual(expR, r) {
t.Fatalf("right hand side: expected %+v, got %+v", expR, r)
}
}
// TestStoreRangeSplitAtTablePrefix verifies a range can be split at
// UserTableDataMin and still gossip the SystemConfig properly.
func TestStoreRangeSplitAtTablePrefix(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.WithIssue(t, 59091, "flaky test")
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
key := bootstrap.TestingUserTableDataMin()
args := adminSplitArgs(key)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), args); pErr != nil {
t.Fatalf("%q: split unexpected error: %s", key, pErr)
}
var desc descpb.Descriptor
descBytes, err := protoutil.Marshal(&desc)
if err != nil {
t.Fatal(err)
}
// Update SystemConfig to trigger gossip.
if err := store.DB().Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
if err := txn.SetSystemConfigTrigger(true /* forSystemTenant */); err != nil {
return err
}
// We don't care about the values, just the keys.
k := catalogkeys.MakeDescMetadataKey(keys.SystemSQLCodec, descpb.ID(bootstrap.TestingUserDescID(0)))
return txn.Put(ctx, k, &desc)
}); err != nil {
t.Fatal(err)
}
successChan := make(chan struct{}, 1)
store.Gossip().RegisterCallback(gossip.KeySystemConfig, func(_ string, content roachpb.Value) {
contentBytes, err := content.GetBytes()
if err != nil {
t.Fatal(err)
}
if bytes.Contains(contentBytes, descBytes) {
select {
case successChan <- struct{}{}:
default:
}
}
})
select {
case <-time.After(time.Second):
t.Errorf("expected a schema gossip containing %q, but did not see one", descBytes)
case <-successChan:
}
}
// TestStoreRangeSplitInsideRow verifies an attempt to split a range inside of
// a table row will cause a split at a boundary between rows.
func TestStoreRangeSplitInsideRow(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
// Manually create some the column keys corresponding to the table:
//
// CREATE TABLE t (id STRING PRIMARY KEY, col1 INT, col2 INT)
tableKey := roachpb.RKey(keys.SystemSQLCodec.TablePrefix(bootstrap.TestingUserDescID(0)))
rowKey := roachpb.Key(encoding.EncodeVarintAscending(append([]byte(nil), tableKey...), 1))
rowKey = encoding.EncodeStringAscending(encoding.EncodeVarintAscending(rowKey, 1), "a")
col1Key, err := keys.EnsureSafeSplitKey(keys.MakeFamilyKey(append([]byte(nil), rowKey...), 1))
if err != nil {
t.Fatal(err)
}
col2Key, err := keys.EnsureSafeSplitKey(keys.MakeFamilyKey(append([]byte(nil), rowKey...), 2))
if err != nil {
t.Fatal(err)
}
// We don't care about the value, so just store any old thing.
if err := store.DB().Put(ctx, col1Key, "column 1"); err != nil {
t.Fatal(err)
}
if err := store.DB().Put(ctx, col2Key, "column 2"); err != nil {
t.Fatal(err)
}
// Split between col1Key and col2Key by splitting before col2Key.
args := adminSplitArgs(col2Key)
_, pErr := kv.SendWrapped(ctx, store.TestSender(), args)
if pErr != nil {
t.Fatalf("%s: split unexpected error: %s", col1Key, pErr)
}
repl1 := store.LookupReplica(roachpb.RKey(col1Key))
repl2 := store.LookupReplica(roachpb.RKey(col2Key))
// Verify the two columns are still on the same range.
if !reflect.DeepEqual(repl1, repl2) {
t.Fatalf("%s: ranges differ: %+v vs %+v", col1Key, repl1, repl2)
}
// Verify we split on a row key.
if startKey := repl1.Desc().StartKey; !startKey.Equal(rowKey) {
t.Fatalf("%s: expected split on %s, but found %s", col1Key, rowKey, startKey)
}
// Verify the previous range was split on a row key.
repl3 := store.LookupReplica(tableKey)
if endKey := repl3.Desc().EndKey; !endKey.Equal(rowKey) {
t.Fatalf("%s: expected split on %s, but found %s", col1Key, rowKey, endKey)
}
}
// TestStoreRangeSplitIntents executes a split of a range and verifies
// that all intents are cleared and the transaction record cleaned up.
func TestStoreRangeSplitIntents(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
// First, write some values left and right of the proposed split key.
pArgs := putArgs([]byte("c"), []byte("foo"))
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), pArgs); pErr != nil {
t.Fatal(pErr)
}
pArgs = putArgs([]byte("x"), []byte("bar"))
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), pArgs); pErr != nil {
t.Fatal(pErr)
}
// Split the range.
splitKey := roachpb.Key("m")
args := adminSplitArgs(splitKey)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), args); pErr != nil {
t.Fatal(pErr)
}
// Verify no intents remains on range descriptor keys.
splitKeyAddr, err := keys.Addr(splitKey)
if err != nil {
t.Fatal(err)
}
for _, key := range []roachpb.Key{keys.RangeDescriptorKey(roachpb.RKeyMin), keys.RangeDescriptorKey(splitKeyAddr)} {
if _, _, err := storage.MVCCGet(
ctx, store.Engine(), key, store.Clock().Now(), storage.MVCCGetOptions{},
); err != nil {
t.Errorf("failed to read consistent range descriptor for key %s: %+v", key, err)
}
}
txnPrefix := func(key roachpb.Key) roachpb.Key {
rk, err := keys.Addr(key)
if err != nil {
t.Fatal(err)
}
return keys.MakeRangeKey(rk, keys.LocalTransactionSuffix, nil)
}
// Verify the transaction record is gone.
start := storage.MakeMVCCMetadataKey(keys.MakeRangeKeyPrefix(roachpb.RKeyMin))
end := storage.MakeMVCCMetadataKey(keys.MakeRangeKeyPrefix(roachpb.RKeyMax))
iter := store.Engine().NewMVCCIterator(storage.MVCCKeyAndIntentsIterKind, storage.IterOptions{UpperBound: end.Key})
defer iter.Close()
for iter.SeekGE(start); ; iter.Next() {
if ok, err := iter.Valid(); err != nil {
t.Fatal(err)
} else if !ok {
break
}
if bytes.HasPrefix([]byte(iter.Key().Key), txnPrefix(roachpb.KeyMin)) ||
bytes.HasPrefix([]byte(iter.Key().Key), txnPrefix(splitKey)) {
t.Errorf("unexpected system key: %s; txn record should have been cleaned up", iter.Key())
}
}
}
// TestStoreRangeSplitAtRangeBounds verifies that attempting to
// split a range at its start key is a no-op and does not actually
// perform a split (would create zero-length range!). This sort
// of thing might happen in the wild if two split requests arrived for
// same key. The first one succeeds and second would try to split
// at the start of the newly split range.
func TestStoreRangeSplitAtRangeBounds(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
// Split range 1 at an arbitrary key.
key := roachpb.Key("a")
rngID := store.LookupReplica(roachpb.RKey(key)).RangeID
h := roachpb.Header{RangeID: rngID}
args := adminSplitArgs(key)
if _, pErr := kv.SendWrappedWith(ctx, store, h, args); pErr != nil {
t.Fatal(pErr)
}
replCount := store.ReplicaCount()
// An AdminSplit request sent to the end of the old range should be re-routed
// to the start of the new range, succeeding but without creating any new ranges.
if _, pErr := kv.SendWrappedWith(ctx, store, h, args); pErr != nil {
t.Fatal(pErr)
}
postEndSplitReplCount := store.ReplicaCount()
if replCount != postEndSplitReplCount {
t.Fatalf("splitting at the end of a range should not create a new range; before second split "+
"found %d ranges, after second split found %d ranges", replCount, postEndSplitReplCount)
}
// An AdminSplit request sent to the start of the new range
// should succeed but no new ranges should be created.
newRng := store.LookupReplica(roachpb.RKey(key))
h.RangeID = newRng.RangeID
if _, pErr := kv.SendWrappedWith(ctx, store, h, args); pErr != nil {
t.Fatal(pErr)
}
postStartSplitReplCount := store.ReplicaCount()
if postEndSplitReplCount != postStartSplitReplCount {
t.Fatalf("splitting at the start boundary should not create a new range; before third split "+
"found %d ranges, after fourth split found %d ranges", postEndSplitReplCount, postEndSplitReplCount)
}
}
// TestStoreRangeSplitIdempotency executes a split of a range and
// verifies that the resulting ranges respond to the right key ranges
// and that their stats have been properly accounted for and requests
// can't be replayed.
func TestStoreRangeSplitIdempotency(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
splitKey := roachpb.Key("m")
content := roachpb.Key("asdvb")
// First, write some values left and right of the proposed split key.
pArgs := putArgs([]byte("c"), content)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), pArgs); pErr != nil {
t.Fatal(pErr)
}
pArgs = putArgs([]byte("x"), content)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), pArgs); pErr != nil {
t.Fatal(pErr)
}
// Increments are a good way of testing idempotency. Up here, we
// address them to the original range, then later to the one that
// contains the key.
txn := roachpb.MakeTransaction("test", []byte("c"), 10, store.Clock().Now(), 0, int32(s.SQLInstanceID()))
lIncArgs := incrementArgs([]byte("apoptosis"), 100)
lTxn := txn
lTxn.Sequence++
lIncArgs.Sequence = lTxn.Sequence
if _, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
Txn: &lTxn,
}, lIncArgs); pErr != nil {
t.Fatal(pErr)
}
rIncArgs := incrementArgs([]byte("wobble"), 10)
rTxn := txn
rTxn.Sequence++
rIncArgs.Sequence = rTxn.Sequence
if _, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
Txn: &rTxn,
}, rIncArgs); pErr != nil {
t.Fatal(pErr)
}
originalRepl := store.LookupReplica(roachpb.RKey(splitKey))
require.NotNil(t, originalRepl)
// Get the original stats for key and value bytes.
ms, err := stateloader.Make(originalRepl.RangeID).LoadMVCCStats(ctx, store.Engine())
if err != nil {
t.Fatal(err)
}
keyBytes, valBytes := ms.KeyBytes, ms.ValBytes
// Split the range.
args := adminSplitArgs(splitKey)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), args); pErr != nil {
t.Fatal(pErr)
}
// Verify no intents remains on range descriptor keys.
splitKeyAddr, err := keys.Addr(splitKey)
if err != nil {
t.Fatal(err)
}
for _, key := range []roachpb.Key{keys.RangeDescriptorKey(roachpb.RKeyMin), keys.RangeDescriptorKey(splitKeyAddr)} {
if _, _, err := storage.MVCCGet(
context.Background(), store.Engine(), key, store.Clock().Now(), storage.MVCCGetOptions{},
); err != nil {
t.Fatal(err)
}
}
rngDesc := originalRepl.Desc()
newRng := store.LookupReplica([]byte("m"))
newRngDesc := newRng.Desc()
if !bytes.Equal(newRngDesc.StartKey, splitKey) || !bytes.Equal(splitKey, rngDesc.EndKey) {
t.Errorf("ranges mismatched, wanted %q=%q=%q", newRngDesc.StartKey, splitKey, rngDesc.EndKey)
}
// Try to get values from both left and right of where the split happened.
gArgs := getArgs([]byte("c"))
if reply, pErr := kv.SendWrapped(ctx, store.TestSender(), gArgs); pErr != nil {
t.Fatal(pErr)
} else if replyBytes, pErr := reply.(*roachpb.GetResponse).Value.GetBytes(); pErr != nil {
t.Fatal(pErr)
} else if !bytes.Equal(replyBytes, content) {
t.Fatalf("actual value %q did not match expected value %q", replyBytes, content)
}
gArgs = getArgs([]byte("x"))
if reply, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
RangeID: newRng.RangeID,
}, gArgs); pErr != nil {
t.Fatal(pErr)
} else if replyBytes, err := reply.(*roachpb.GetResponse).Value.GetBytes(); err != nil {
t.Fatal(err)
} else if !bytes.Equal(replyBytes, content) {
t.Fatalf("actual value %q did not match expected value %q", replyBytes, content)
}
// Send out an increment request copied from above (same txn/sequence)
// which remains in the old range.
_, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
Txn: &lTxn,
}, lIncArgs)
if pErr != nil {
t.Fatal(pErr)
}
// Send out the same increment copied from above (same txn/sequence), but
// now to the newly created range (which should hold that key).
_, pErr = kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
RangeID: newRng.RangeID,
Txn: &rTxn,
}, rIncArgs)
if pErr != nil {
t.Fatal(pErr)
}
// Compare stats of split ranges to ensure they are non zero and
// exceed the original range when summed.
left, err := stateloader.Make(originalRepl.RangeID).LoadMVCCStats(ctx, store.Engine())
if err != nil {
t.Fatal(err)
}
lKeyBytes, lValBytes := left.KeyBytes, left.ValBytes
right, err := stateloader.Make(newRng.RangeID).LoadMVCCStats(ctx, store.Engine())
if err != nil {
t.Fatal(err)
}
rKeyBytes, rValBytes := right.KeyBytes, right.ValBytes
if lKeyBytes == 0 || rKeyBytes == 0 {
t.Errorf("expected non-zero key bytes; got %d, %d", lKeyBytes, rKeyBytes)
}
if lValBytes == 0 || rValBytes == 0 {
t.Errorf("expected non-zero val bytes; got %d, %d", lValBytes, rValBytes)
}
if lKeyBytes+rKeyBytes != keyBytes {
t.Errorf("left + right key bytes don't match; %d + %d <= %d", lKeyBytes, rKeyBytes, keyBytes)
}
if lValBytes+rValBytes != valBytes {
t.Errorf("left + right val bytes don't match; %d + %d <= %d", lValBytes, rValBytes, valBytes)
}
}
// TestStoreRangeSplitStats starts by splitting the system keys from user-space
// keys and verifying that the user space side of the split (which is empty),
// has all zeros for stats. It then writes random data to the user space side,
// splits it halfway and verifies the two splits have stats exactly equaling
// the pre-split.
func TestStoreRangeSplitStats(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
DisableSplitQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
start := s.Clock().Now()
// Split the range after the last table data key.
keyPrefix := keys.SystemSQLCodec.TablePrefix(bootstrap.TestingUserDescID(0))
args := adminSplitArgs(keyPrefix)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), args); pErr != nil {
t.Fatal(pErr)
}
// Verify empty range has empty stats.
repl := store.LookupReplica(roachpb.RKey(keyPrefix))
// NOTE that this value is expected to change over time, depending on what
// we store in the sys-local keyspace. Update it accordingly for this test.
empty := enginepb.MVCCStats{LastUpdateNanos: start.WallTime}
if err := verifyRangeStats(store.Engine(), repl.RangeID, empty); err != nil {
t.Fatal(err)
}
// Write random data.
midKey := kvserver.WriteRandomDataToRange(t, store, repl.RangeID, keyPrefix)
// Get the range stats now that we have data.
snap := store.Engine().NewSnapshot()
defer snap.Close()
ms, err := stateloader.Make(repl.RangeID).LoadMVCCStats(ctx, snap)
if err != nil {
t.Fatal(err)
}
if err := verifyRecomputedStats(snap, repl.Desc(), ms, start.WallTime); err != nil {
t.Fatalf("failed to verify range's stats before split: %+v", err)
}
if inMemMS := repl.GetMVCCStats(); inMemMS != ms {
t.Fatalf("in-memory and on-disk diverged:\n%+v\n!=\n%+v", inMemMS, ms)
}
// Split the range at approximate halfway point.
args = adminSplitArgs(midKey)
if _, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
RangeID: repl.RangeID,
}, args); pErr != nil {
t.Fatal(pErr)
}
snap = store.Engine().NewSnapshot()
defer snap.Close()
msLeft, err := stateloader.Make(repl.RangeID).LoadMVCCStats(ctx, snap)
if err != nil {
t.Fatal(err)
}
replRight := store.LookupReplica(midKey)
msRight, err := stateloader.Make(replRight.RangeID).LoadMVCCStats(ctx, snap)
if err != nil {
t.Fatal(err)
}
// The stats should be exactly equal when added.
expMS := enginepb.MVCCStats{
LiveBytes: msLeft.LiveBytes + msRight.LiveBytes,
KeyBytes: msLeft.KeyBytes + msRight.KeyBytes,
ValBytes: msLeft.ValBytes + msRight.ValBytes,
IntentBytes: msLeft.IntentBytes + msRight.IntentBytes,
LiveCount: msLeft.LiveCount + msRight.LiveCount,
KeyCount: msLeft.KeyCount + msRight.KeyCount,
ValCount: msLeft.ValCount + msRight.ValCount,
IntentCount: msLeft.IntentCount + msRight.IntentCount,
}
ms.SysBytes, ms.SysCount, ms.AbortSpanBytes = 0, 0, 0
ms.LastUpdateNanos = 0
if expMS != ms {
t.Errorf("expected left plus right ranges to equal original, but\n %+v\n+\n %+v\n!=\n %+v", msLeft, msRight, ms)
}
// Stats should both have the new timestamp.
if lTs := msLeft.LastUpdateNanos; lTs < start.WallTime {
t.Errorf("expected left range stats to have new timestamp, want %d, got %d", start.WallTime, lTs)
}
if rTs := msRight.LastUpdateNanos; rTs < start.WallTime {
t.Errorf("expected right range stats to have new timestamp, want %d, got %d", start.WallTime, rTs)
}
// Stats should agree with recomputation.
if err := verifyRecomputedStats(snap, repl.Desc(), msLeft, s.Clock().PhysicalNow()); err != nil {
t.Fatalf("failed to verify left range's stats after split: %+v", err)
}
if err := verifyRecomputedStats(snap, replRight.Desc(), msRight, s.Clock().PhysicalNow()); err != nil {
t.Fatalf("failed to verify right range's stats after split: %+v", err)
}
}
// RaftMessageHandlerInterceptor wraps a storage.RaftMessageHandler. It
// delegates all methods to the underlying storage.RaftMessageHandler, except
// that HandleSnapshot calls receiveSnapshotFilter with the snapshot request
// header before delegating to the underlying HandleSnapshot method.
type RaftMessageHandlerInterceptor struct {
kvserver.RaftMessageHandler
handleSnapshotFilter func(header *kvserverpb.SnapshotRequest_Header)
}
func (mh RaftMessageHandlerInterceptor) HandleSnapshot(
ctx context.Context,
header *kvserverpb.SnapshotRequest_Header,
respStream kvserver.SnapshotResponseStream,
) error {
mh.handleSnapshotFilter(header)
return mh.RaftMessageHandler.HandleSnapshot(ctx, header, respStream)
}
// TestStoreEmptyRangeSnapshotSize tests that the snapshot request header for a
// range that contains no user data (an "empty" range) has RangeSize == 0. This
// is arguably a bug, because system data like the range descriptor and raft log
// should also count towards the size of the snapshot. Currently, though, this
// property conveniently allows us to optimize the rebalancing of empty ranges
// by throttling snapshots of empty ranges separately from non-empty snapshots.
//
// If you change the accounting of RangeSize such that this test breaks, please
// preserve the optimization by introducing an alternative means of identifying
// snapshot requests for empty or near-empty ranges, and then adjust this test
// accordingly.
func TestStoreEmptyRangeSnapshotSize(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 2,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
// Split the range after the last table data key to get a range that contains
// no user data.
splitKey := keys.SystemSQLCodec.TablePrefix(bootstrap.TestingUserDescID(0))
splitArgs := adminSplitArgs(splitKey)
if _, err := kv.SendWrapped(ctx, tc.Servers[0].DistSender(), splitArgs); err != nil {
t.Fatal(err)
}
// Wrap store 1's message handler to intercept and record all incoming
// snapshot request headers.
messageRecorder := struct {
syncutil.Mutex
headers []*kvserverpb.SnapshotRequest_Header
}{}
messageHandler := RaftMessageHandlerInterceptor{
RaftMessageHandler: tc.GetFirstStoreFromServer(t, 1),
handleSnapshotFilter: func(header *kvserverpb.SnapshotRequest_Header) {
// Each snapshot request is handled in a new goroutine, so we need
// synchronization.
messageRecorder.Lock()
defer messageRecorder.Unlock()
messageRecorder.headers = append(messageRecorder.headers, header)
},
}
tc.Servers[1].RaftTransport().Listen(tc.GetFirstStoreFromServer(t, 1).StoreID(), messageHandler)
// Replicate the newly-split range to trigger a snapshot request from store 0
// to store 1.
desc := tc.AddVotersOrFatal(t, splitKey, tc.Target(1))
// Verify that we saw at least one snapshot request,
messageRecorder.Lock()
defer messageRecorder.Unlock()
if a := len(messageRecorder.headers); a < 1 {
t.Fatalf("expected at least one snapshot header, but got %d", a)
}
for i, header := range messageRecorder.headers {
if e, a := header.State.Desc.RangeID, desc.RangeID; e != a {
t.Errorf("%d: expected RangeID to be %d, but got %d", i, e, a)
}
if header.RangeSize != 0 {
t.Errorf("%d: expected RangeSize to be 0, but got %d", i, header.RangeSize)
}
}
}
// TestStoreRangeSplitStatsWithMerges starts by splitting the system keys from
// user-space keys and verifying that the user space side of the split (which is empty),
// has all zeros for stats. It then issues a number of Merge requests to the user
// space side, simulating TimeSeries data. Finally, the test splits the user space
// side halfway and verifies the stats on either side of the split are equal to a
// recomputation.
//
// Note that unlike TestStoreRangeSplitStats, we do not check if the two halves of the
// split's stats are equal to the pre-split stats when added, because this will not be
// true of ranges populated with Merge requests. The reason for this is that Merge
// requests' impact on MVCCStats are only estimated. See updateStatsOnMerge.
func TestStoreRangeSplitStatsWithMerges(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableSplitQueue: true,
DisableMergeQueue: true,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
start := s.Clock().Now()
// Split the range after the last table data key.
keyPrefix := keys.SystemSQLCodec.TablePrefix(bootstrap.TestingUserDescID(0))
args := adminSplitArgs(keyPrefix)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), args); pErr != nil {
t.Fatal(pErr)
}
// Verify empty range has empty stats.
repl := store.LookupReplica(roachpb.RKey(keyPrefix))
// NOTE that this value is expected to change over time, depending on what
// we store in the sys-local keyspace. Update it accordingly for this test.
empty := enginepb.MVCCStats{LastUpdateNanos: start.WallTime}
if err := verifyRangeStats(store.Engine(), repl.RangeID, empty); err != nil {
t.Fatal(err)
}
// Write random TimeSeries data.
midKey := writeRandomTimeSeriesDataToRange(t, store, repl.RangeID, keyPrefix)
// Split the range at approximate halfway point.
args = adminSplitArgs(midKey)
if _, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{
RangeID: repl.RangeID,
}, args); pErr != nil {
t.Fatal(pErr)
}
snap := store.Engine().NewSnapshot()
defer snap.Close()
msLeft, err := stateloader.Make(repl.RangeID).LoadMVCCStats(ctx, snap)
if err != nil {
t.Fatal(err)
}
replRight := store.LookupReplica(midKey)
msRight, err := stateloader.Make(replRight.RangeID).LoadMVCCStats(ctx, snap)
if err != nil {
t.Fatal(err)
}
// Stats should both have the new timestamp.
if lTs := msLeft.LastUpdateNanos; lTs < start.WallTime {
t.Errorf("expected left range stats to have new timestamp, want %d, got %d", start.WallTime, lTs)
}
if rTs := msRight.LastUpdateNanos; rTs < start.WallTime {
t.Errorf("expected right range stats to have new timestamp, want %d, got %d", start.WallTime, rTs)
}
// Stats should agree with recomputation.
if err := verifyRecomputedStats(snap, repl.Desc(), msLeft, s.Clock().PhysicalNow()); err != nil {
t.Fatalf("failed to verify left range's stats after split: %+v", err)
}
if err := verifyRecomputedStats(snap, replRight.Desc(), msRight, s.Clock().PhysicalNow()); err != nil {
t.Fatalf("failed to verify right range's stats after split: %+v", err)
}
}
// fillRange writes keys with the given prefix and associated values
// until bytes bytes have been written or the given range has split.
func fillRange(
t *testing.T,
store *kvserver.Store,
rangeID roachpb.RangeID,
prefix roachpb.Key,
bytes int64,
singleKey bool,
) {
src := rand.New(rand.NewSource(0))
var key []byte
for {
ms, err := stateloader.Make(rangeID).LoadMVCCStats(context.Background(), store.Engine())
if err != nil {
t.Fatal(err)
}
keyBytes, valBytes := ms.KeyBytes, ms.ValBytes
if keyBytes+valBytes >= bytes {
return
}
if key == nil || !singleKey {
key = append(append([]byte(nil), prefix...), randutil.RandBytes(src, 100)...)
key = keys.MakeFamilyKey(key, src.Uint32())
}
val := randutil.RandBytes(src, int(src.Int31n(1<<8)))
pArgs := putArgs(key, val)
_, pErr := kv.SendWrappedWith(context.Background(), store, roachpb.Header{
RangeID: rangeID,
}, pArgs)
// When the split occurs in the background, our writes may start failing.