-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
dist_sender_server_test.go
2585 lines (2443 loc) · 85.8 KB
/
dist_sender_server_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 2015 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 kv_test
import (
"bytes"
"context"
"fmt"
"regexp"
"sort"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
// NOTE: these tests are in package kv_test to avoid a circular
// dependency between the server and kv packages. These tests rely on
// starting a TestServer, which creates a "real" node and employs a
// distributed sender server-side.
func strToValue(s string) *roachpb.Value {
v := roachpb.MakeValueFromBytes([]byte(s))
return &v
}
func startNoSplitMergeServer(t *testing.T) (serverutils.TestServerInterface, *client.DB) {
s, _, db := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &storage.StoreTestingKnobs{
DisableSplitQueue: true,
DisableMergeQueue: true,
},
},
})
return s, db
}
// TestRangeLookupWithOpenTransaction verifies that range lookups are
// done in such a way (e.g. using inconsistent reads) that they
// proceed in the event that a write intent is extant at the meta
// index record being read.
func TestRangeLookupWithOpenTransaction(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
defer s.Stopper().Stop(context.TODO())
// Create an intent on the meta1 record by writing directly to the
// engine.
key := testutils.MakeKey(keys.Meta1Prefix, roachpb.KeyMax)
now := s.Clock().Now()
txn := roachpb.MakeTransaction("txn", roachpb.Key("foobar"), 0, now, 0)
if err := engine.MVCCPutProto(
context.Background(), s.(*server.TestServer).Engines()[0],
nil, key, now, &txn, &roachpb.RangeDescriptor{}); err != nil {
t.Fatal(err)
}
// Create a new DistSender and client.DB so that the Get below is guaranteed
// to not hit in the range descriptor cache forcing a RangeLookup operation.
ambient := log.AmbientContext{Tracer: s.ClusterSettings().Tracer}
ds := kv.NewDistSender(
kv.DistSenderConfig{
AmbientCtx: ambient,
Clock: s.Clock(),
RPCContext: s.RPCContext(),
NodeDialer: nodedialer.New(s.RPCContext(), gossip.AddressResolver(s.(*server.TestServer).Gossip())),
},
s.(*server.TestServer).Gossip(),
)
tsf := kv.NewTxnCoordSenderFactory(
kv.TxnCoordSenderFactoryConfig{
AmbientCtx: ambient,
Clock: s.Clock(),
Stopper: s.Stopper(),
},
ds,
)
db := client.NewDB(ambient, tsf, s.Clock())
// Now, with an intent pending, attempt (asynchronously) to read
// from an arbitrary key. This will cause the distributed sender to
// do a range lookup, which will encounter the intent. We're
// verifying here that the range lookup doesn't fail with a write
// intent error. If it did, it would go into a deadloop attempting
// to push the transaction, which in turn requires another range
// lookup, etc, ad nauseam.
if _, err := db.Get(context.TODO(), "a"); err != nil {
t.Fatal(err)
}
}
// setupMultipleRanges creates a database client to the supplied test
// server and splits the key range at the given keys. Returns the DB
// client.
func setupMultipleRanges(ctx context.Context, db *client.DB, splitAt ...string) error {
// Split the keyspace at the given keys.
for _, key := range splitAt {
if err := db.AdminSplit(ctx, key /* spanKey */, key /* splitKey */, hlc.MaxTimestamp /* expirationTime */); err != nil {
return err
}
}
return nil
}
var errInfo = testutils.MakeCaller(3, 2)
type checkResultsMode int
const (
// Strict means that the expected results must be passed exactly.
Strict checkResultsMode = iota
// AcceptPrefix means that a superset of the expected results may be passed.
// The actual results for each scan must be a prefix of the passed-in values.
AcceptPrefix
)
type checkOptions struct {
mode checkResultsMode
expCount int
}
// checks the keys returned from a Scan/ReverseScan.
//
// Args:
// expSatisfied: A set of indexes into spans representing the scans that
// have been completed and don't need a ResumeSpan. For these scans, having no
// results and also no resume span is acceptable by this function.
// resultsMode: Specifies how strict the result checking is supposed to be.
// expCount
// expCount: If resultsMode == AcceptPrefix, this is the total number of
// expected results. Ignored for resultsMode == Strict.
func checkSpanResults(
t *testing.T,
spans [][]string,
results []client.Result,
expResults [][]string,
expSatisfied map[int]struct{},
opt checkOptions,
) {
if len(expResults) != len(results) {
t.Fatalf("only got %d results, wanted %d", len(expResults), len(results))
}
// Ensure all the keys returned align properly with what is expected.
count := 0
for i, res := range results {
count += len(res.Rows)
if opt.mode == Strict {
if len(res.Rows) != len(expResults[i]) {
t.Fatalf("%s: scan %d (%s): expected %d rows, got %d (%s)",
errInfo(), i, spans[i], len(expResults[i]), len(res.Rows), res)
}
}
for j, kv := range res.Rows {
if key, expKey := string(kv.Key), expResults[i][j]; key != expKey {
t.Fatalf("%s: scan %d (%s) expected result %d to be %q; got %q",
errInfo(), i, spans[i], j, expKey, key)
}
}
}
if opt.mode == AcceptPrefix && count != opt.expCount {
// Check that the bound was respected.
t.Errorf("count = %d, expCount = %d", count, opt.expCount)
}
}
// checks ResumeSpan returned in a ScanResponse.
func checkResumeSpanScanResults(
t *testing.T,
spans [][]string,
results []client.Result,
expResults [][]string,
expSatisfied map[int]struct{},
opt checkOptions,
) {
for i, res := range results {
rowLen := len(res.Rows)
// Check that satisfied scans don't have resume spans.
if _, satisfied := expSatisfied[i]; satisfied {
if res.ResumeSpan != nil {
t.Fatalf("%s: satisfied scan %d (%s) has ResumeSpan: %v",
errInfo(), i, spans[i], res.ResumeSpan)
}
continue
}
if res.ResumeReason == roachpb.RESUME_UNKNOWN {
t.Fatalf("%s: scan %d (%s): no resume reason. resume span: %+v",
errInfo(), i, spans[i], res.ResumeSpan)
}
// The scan is not expected to be satisfied, so there must be a resume span.
// The resume span should be identical to the original request if no
// results have been produced, or should continue after the last result
// otherwise.
resumeKey := string(res.ResumeSpan.Key)
if res.ResumeReason != roachpb.RESUME_KEY_LIMIT {
t.Fatalf("%s: scan %d (%s): unexpected resume reason %s",
errInfo(), i, spans[i], res.ResumeReason)
}
if rowLen == 0 {
if resumeKey != spans[i][0] {
t.Fatalf("%s: scan %d: expected resume %s, got: %s",
errInfo(), i, spans[i][0], resumeKey)
}
} else {
lastRes := expResults[i][rowLen-1]
if resumeKey <= lastRes {
t.Fatalf("%s: scan %d: expected resume %s to be above last result %s",
errInfo(), i, resumeKey, lastRes)
}
}
// The EndKey must be untouched.
if key, expKey := string(res.ResumeSpan.EndKey), spans[i][1]; key != expKey {
t.Errorf("%s: expected resume endkey %d to be %q; got %q", errInfo(), i, expKey, key)
}
}
}
// check ResumeSpan returned in a ReverseScanResponse.
func checkResumeSpanReverseScanResults(
t *testing.T,
spans [][]string,
results []client.Result,
expResults [][]string,
expSatisfied map[int]struct{},
opt checkOptions,
) {
for i, res := range results {
rowLen := len(res.Rows)
// Check that satisfied scans don't have resume spans.
if _, satisfied := expSatisfied[i]; satisfied {
if res.ResumeSpan != nil {
t.Fatalf("%s: satisfied scan %d has ResumeSpan: %v", errInfo(), i, res.ResumeSpan)
}
continue
}
// The scan is not expected to be satisfied, so there must be a resume span.
// The resume span should be identical to the original request if no
// results have been produced, or should continue after the last result
// otherwise.
resumeKey := string(res.ResumeSpan.EndKey)
if res.ResumeReason != roachpb.RESUME_KEY_LIMIT {
t.Fatalf("%s: scan %d (%s): unexpected resume reason %s",
errInfo(), i, spans[i], res.ResumeReason)
}
if rowLen == 0 {
if resumeKey != spans[i][1] {
t.Fatalf("%s: scan %d (%s) expected resume %s, got: %s",
errInfo(), i, spans[i], spans[i][1], resumeKey)
}
} else {
lastRes := expResults[i][rowLen-1]
if resumeKey >= lastRes {
t.Fatalf("%s: scan %d: expected resume %s to be below last result %s",
errInfo(), i, resumeKey, lastRes)
}
}
// The Key must be untouched.
if key, expKey := string(res.ResumeSpan.Key), spans[i][0]; key != expKey {
t.Errorf("%s: expected resume key %d to be %q; got %q", errInfo(), i, expKey, key)
}
}
}
// check an entire scan result including the ResumeSpan.
func checkScanResults(
t *testing.T,
spans [][]string,
results []client.Result,
expResults [][]string,
expSatisfied map[int]struct{},
opt checkOptions,
) {
checkSpanResults(t, spans, results, expResults, expSatisfied, opt)
checkResumeSpanScanResults(t, spans, results, expResults, expSatisfied, opt)
}
// check an entire reverse scan result including the ResumeSpan.
func checkReverseScanResults(
t *testing.T,
spans [][]string,
results []client.Result,
expResults [][]string,
expSatisfied map[int]struct{},
opt checkOptions,
) {
checkSpanResults(t, spans, results, expResults, expSatisfied, opt)
checkResumeSpanReverseScanResults(t, spans, results, expResults, expSatisfied, opt)
}
// Tests multiple scans, forward and reverse, across many ranges with multiple
// bounds.
func TestMultiRangeBoundedBatchScan(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
defer s.Stopper().Stop(context.TODO())
ctx := context.TODO()
db := s.DB()
splits := []string{"a", "b", "c", "d", "e", "f"}
if err := setupMultipleRanges(ctx, db, splits...); err != nil {
t.Fatal(err)
}
keys := []string{"a1", "a2", "a3", "b1", "b2", "c1", "c2", "d1", "f1", "f2", "f3"}
for _, key := range keys {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
scans := [][]string{{"a", "c"}, {"b", "c2"}, {"c", "g"}, {"f1a", "f2a"}}
// These are the expected results if there is no bound.
expResults := [][]string{
{"a1", "a2", "a3", "b1", "b2"},
{"b1", "b2", "c1"},
{"c1", "c2", "d1", "f1", "f2", "f3"},
{"f2"},
}
var expResultsReverse [][]string
for _, res := range expResults {
var rres []string
for i := len(res) - 1; i >= 0; i-- {
rres = append(rres, res[i])
}
expResultsReverse = append(expResultsReverse, rres)
}
maxExpCount := 0
for _, res := range expResults {
maxExpCount += len(res)
}
// Compute the `bound` at which each scan is satisfied. We take advantage
// that, in this test, each scan is satisfied as soon as its last expected
// results is generated; in other words, the last result for each scan is in
// the same range as the scan's end key.
// This loopy code "simulates" the way the DistSender operates in the face of
// overlapping spans that cross ranges and have key limits: the batch run
// range by range and, within a range, scans are satisfied in the order in
// which they appear in the batch.
satisfiedBoundThreshold := make([]int, len(expResults))
satisfiedBoundThresholdReverse := make([]int, len(expResults))
remaining := make(map[int]int)
for i := range expResults {
remaining[i] = len(expResults[i])
}
const maxBound int = 20
var r int
splits = append([]string{""}, splits...)
splits = append(splits, "zzzzzz")
for s := 1; s < len(splits)-1; s++ {
firstK := sort.SearchStrings(keys, splits[s])
lastK := sort.SearchStrings(keys, splits[s+1]) - 1
for j, res := range expResults {
for _, expK := range res {
for k := firstK; k <= lastK; k++ {
if keys[k] == expK {
r++
remaining[j]--
if remaining[j] == 0 {
satisfiedBoundThreshold[j] = r
}
break
}
}
}
}
}
// Compute the thresholds for the reverse scans.
r = 0
for i := range expResults {
remaining[i] = len(expResults[i])
}
for s := len(splits) - 1; s > 0; s-- {
// The split contains keys [lastK..firstK].
firstK := sort.SearchStrings(keys, splits[s]) - 1
lastK := sort.SearchStrings(keys, splits[s-1])
for j, res := range expResultsReverse {
for expIdx := len(res) - 1; expIdx >= 0; expIdx-- {
expK := res[expIdx]
for k := firstK; k >= lastK; k-- {
if keys[k] == expK {
r++
remaining[j]--
if remaining[j] == 0 {
satisfiedBoundThresholdReverse[j] = r
}
break
}
}
}
}
}
for _, reverse := range []bool{false, true} {
for bound := 1; bound <= maxBound; bound++ {
t.Run(fmt.Sprintf("reverse=%t,bound=%d", reverse, bound), func(t *testing.T) {
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = int64(bound)
for _, span := range scans {
if !reverse {
b.Scan(span[0], span[1])
} else {
b.ReverseScan(span[0], span[1])
}
}
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
expCount := maxExpCount
if bound < maxExpCount {
expCount = bound
}
// Compute the satisfied scans.
expSatisfied := make(map[int]struct{})
for i := range b.Results {
var threshold int
if !reverse {
threshold = satisfiedBoundThreshold[i]
} else {
threshold = satisfiedBoundThresholdReverse[i]
}
if bound >= threshold {
expSatisfied[i] = struct{}{}
}
}
opt := checkOptions{mode: AcceptPrefix, expCount: expCount}
if !reverse {
checkScanResults(
t, scans, b.Results, expResults, expSatisfied, opt)
} else {
checkReverseScanResults(
t, scans, b.Results, expResultsReverse, expSatisfied, opt)
}
// Re-query using the resume spans that were returned; check that all
// spans are read properly.
if bound < maxExpCount {
newB := &client.Batch{}
for _, res := range b.Results {
if res.ResumeSpan != nil {
if !reverse {
newB.Scan(res.ResumeSpan.Key, res.ResumeSpan.EndKey)
} else {
newB.ReverseScan(res.ResumeSpan.Key, res.ResumeSpan.EndKey)
}
}
}
if err := db.Run(ctx, newB); err != nil {
t.Fatal(err)
}
// Add the results to the previous results.
j := 0
for i, res := range b.Results {
if res.ResumeSpan != nil {
b.Results[i].Rows = append(b.Results[i].Rows, newB.Results[j].Rows...)
b.Results[i].ResumeSpan = newB.Results[j].ResumeSpan
j++
}
}
for i := range b.Results {
expSatisfied[i] = struct{}{}
}
// Check that the scan results contain all the expected results.
opt = checkOptions{mode: Strict}
if !reverse {
checkScanResults(
t, scans, b.Results, expResults, expSatisfied, opt)
} else {
checkReverseScanResults(
t, scans, b.Results, expResultsReverse, expSatisfied, opt)
}
}
})
}
}
}
// TestMultiRangeBoundedBatchScanUnsortedOrder runs two non-overlapping
// scan requests out of order and shows how the batch response can
// contain two partial responses.
func TestMultiRangeBoundedBatchScanUnsortedOrder(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b", "c", "d", "e", "f"); err != nil {
t.Fatal(err)
}
for _, key := range []string{"a1", "a2", "a3", "b1", "b2", "b3", "b4", "b5", "c1", "c2", "d1", "f1", "f2", "f3"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
bound := 6
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = int64(bound)
// Two non-overlapping requests out of order.
spans := [][]string{{"b3", "c2"}, {"a", "b3"}}
for _, span := range spans {
b.Scan(span[0], span[1])
}
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
// See incomplete results for the two requests.
expResults := [][]string{
{"b3", "b4", "b5"},
{"a1", "a2", "a3"},
}
checkScanResults(t, spans, b.Results, expResults, nil /* satisfied */, checkOptions{mode: Strict})
}
// TestMultiRangeBoundedBatchScanSortedOverlapping runs two overlapping
// ordered (by start key) scan requests, and shows how the batch response can
// contain two partial responses.
func TestMultiRangeBoundedBatchScanSortedOverlapping(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b", "c", "d", "e", "f"); err != nil {
t.Fatal(err)
}
for _, key := range []string{"a1", "a2", "a3", "b1", "b2", "c1", "c2", "d1", "f1", "f2", "f3"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
bound := 6
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = int64(bound)
// Two ordered overlapping requests.
spans := [][]string{{"a", "d"}, {"b", "g"}}
for _, span := range spans {
b.Scan(span[0], span[1])
}
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
// See incomplete results for the two requests.
expResults := [][]string{
{"a1", "a2", "a3", "b1", "b2"},
{"b1"},
}
checkScanResults(t, spans, b.Results, expResults, nil /* satisfied */, checkOptions{mode: Strict})
}
// check ResumeSpan in the DelRange results.
func checkResumeSpanDelRangeResults(
t *testing.T, spans [][]string, results []client.Result, expResults [][]string, expCount int,
) {
for i, res := range results {
// Check ResumeSpan when request has been processed.
rowLen := len(res.Keys)
if rowLen > 0 {
// The key can be empty once the entire span has been deleted.
if rowLen == len(expResults[i]) {
if res.ResumeSpan == nil {
// Done.
continue
}
}
// The next start key is always greater than the last key seen.
if key, expKey := string(res.ResumeSpan.Key), expResults[i][rowLen-1]; key <= expKey {
t.Errorf("%s: expected resume key %d, %d to be %q; got %q", errInfo(), i, expCount, expKey, key)
}
} else {
// The request was not processed; the resume span key <= first seen key.
if key, expKey := string(res.ResumeSpan.Key), expResults[i][0]; key > expKey {
t.Errorf("%s: expected resume key %d, %d to be %q; got %q", errInfo(), i, expCount, expKey, key)
}
}
// The EndKey is untouched.
if key, expKey := string(res.ResumeSpan.EndKey), spans[i][1]; key != expKey {
t.Errorf("%s: expected resume endkey %d, %d to be %q; got %q", errInfo(), i, expCount, expKey, key)
}
}
}
// Tests a batch of bounded DelRange() requests.
func TestMultiRangeBoundedBatchDelRange(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b", "c", "d", "e", "f", "g", "h"); err != nil {
t.Fatal(err)
}
// These are the expected results if there is no bound.
expResults := [][]string{
{"a1", "a2", "a3", "b1", "b2"},
{"c1", "c2", "d1"},
{"g1", "g2"},
}
maxExpCount := 0
for _, res := range expResults {
maxExpCount += len(res)
}
for bound := 1; bound <= 20; bound++ {
// Initialize all keys.
for _, key := range []string{"a1", "a2", "a3", "b1", "b2", "c1", "c2", "d1", "f1", "f2", "f3", "g1", "g2", "h1"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = int64(bound)
spans := [][]string{{"a", "c"}, {"c", "f"}, {"g", "h"}}
for _, span := range spans {
b.DelRange(span[0], span[1], true /* returnKeys */)
}
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
if len(expResults) != len(b.Results) {
t.Fatalf("bound: %d, only got %d results, wanted %d", bound, len(expResults), len(b.Results))
}
expCount := maxExpCount
if bound < maxExpCount {
expCount = bound
}
rem := expCount
for i, res := range b.Results {
// Verify that the KeyValue slice contains the given keys.
rem -= len(res.Keys)
for j, key := range res.Keys {
if expKey := expResults[i][j]; string(key) != expKey {
t.Errorf("%s: expected scan key %d, %d to be %q; got %q", errInfo(), i, j, expKey, key)
}
}
}
if rem != 0 {
t.Errorf("expected %d keys, got %d", bound, expCount-rem)
}
checkResumeSpanDelRangeResults(t, spans, b.Results, expResults, expCount)
}
}
// Test that a bounded DelRange() request that gets terminated at a range
// boundary uses the range boundary as the start key in the response
// ResumeSpan.
func TestMultiRangeBoundedBatchDelRangeBoundary(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b"); err != nil {
t.Fatal(err)
}
// Check that a
for _, key := range []string{"a1", "a2", "a3", "b1", "b2"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = 3
b.DelRange("a", "c", true /* returnKeys */)
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
if len(b.Results) != 1 {
t.Fatalf("%d results returned", len(b.Results))
}
if string(b.Results[0].ResumeSpan.Key) != "b" || string(b.Results[0].ResumeSpan.EndKey) != "c" {
t.Fatalf("received ResumeSpan %+v", b.Results[0].ResumeSpan)
}
b = &client.Batch{}
b.Header.MaxSpanRequestKeys = 1
b.DelRange("b", "c", true /* returnKeys */)
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
if len(b.Results) != 1 {
t.Fatalf("%d results returned", len(b.Results))
}
if string(b.Results[0].ResumeSpan.Key) != "b2" || string(b.Results[0].ResumeSpan.EndKey) != "c" {
t.Fatalf("received ResumeSpan %+v", b.Results[0].ResumeSpan)
}
}
// Tests a batch of bounded DelRange() requests deleting key ranges that
// overlap.
func TestMultiRangeBoundedBatchDelRangeOverlappingKeys(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b", "c", "d", "e", "f"); err != nil {
t.Fatal(err)
}
expResults := [][]string{
{"a1", "a2", "a3", "b1", "b2"},
{"b3", "c1", "c2"},
{"d1", "f1", "f2"},
{"f3"},
}
maxExpCount := 0
for _, res := range expResults {
maxExpCount += len(res)
}
for bound := 1; bound <= 20; bound++ {
for _, key := range []string{"a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "d1", "f1", "f2", "f3"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = int64(bound)
spans := [][]string{{"a", "b3"}, {"b", "d"}, {"c", "f2a"}, {"f1a", "g"}}
for _, span := range spans {
b.DelRange(span[0], span[1], true /* returnKeys */)
}
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
if len(expResults) != len(b.Results) {
t.Fatalf("bound: %d, only got %d results, wanted %d", bound, len(expResults), len(b.Results))
}
expCount := maxExpCount
if bound < maxExpCount {
expCount = bound
}
rem := expCount
for i, res := range b.Results {
// Verify that the KeyValue slice contains the given keys.
rem -= len(res.Keys)
for j, key := range res.Keys {
if expKey := expResults[i][j]; string(key) != expKey {
t.Errorf("%s: expected scan key %d, %d to be %q; got %q", errInfo(), i, j, expKey, key)
}
}
}
if rem != 0 {
t.Errorf("expected %d keys, got %d", bound, expCount-rem)
}
checkResumeSpanDelRangeResults(t, spans, b.Results, expResults, expCount)
}
}
// TestMultiRangeEmptyAfterTruncate exercises a code path in which a
// multi-range request deals with a range without any active requests after
// truncation. In that case, the request is skipped.
func TestMultiRangeEmptyAfterTruncate(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "c", "d"); err != nil {
t.Fatal(err)
}
// Delete the keys within a transaction. The range [c,d) doesn't have
// any active requests.
if err := db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
b := txn.NewBatch()
b.DelRange("a", "b", false /* returnKeys */)
b.DelRange("e", "f", false /* returnKeys */)
return txn.CommitInBatch(ctx, b)
}); err != nil {
t.Fatalf("unexpected error on transactional DeleteRange: %s", err)
}
}
// TestMultiRequestBatchWithFwdAndReverseRequests are disallowed.
func TestMultiRequestBatchWithFwdAndReverseRequests(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "a", "b"); err != nil {
t.Fatal(err)
}
b := &client.Batch{}
b.Header.MaxSpanRequestKeys = 100
b.Scan("a", "b")
b.ReverseScan("a", "b")
if err := db.Run(ctx, b); !testutils.IsError(
err, "batch with limit contains both forward and reverse scans",
) {
t.Fatal(err)
}
}
// TestMultiRangeScanReverseScanDeleteResolve verifies that Scan, ReverseScan,
// DeleteRange and ResolveIntentRange work across ranges.
func TestMultiRangeScanReverseScanDeleteResolve(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "b"); err != nil {
t.Fatal(err)
}
// Write keys before, at, and after the split key.
for _, key := range []string{"a", "b", "c"} {
if err := db.Put(ctx, key, "value"); err != nil {
t.Fatal(err)
}
}
// Scan to retrieve the keys just written.
if rows, err := db.Scan(ctx, "a", "q", 0); err != nil {
t.Fatalf("unexpected error on Scan: %s", err)
} else if l := len(rows); l != 3 {
t.Errorf("expected 3 rows; got %d", l)
}
// Scan in reverse order to retrieve the keys just written.
if rows, err := db.ReverseScan(ctx, "a", "q", 0); err != nil {
t.Fatalf("unexpected error on ReverseScan: %s", err)
} else if l := len(rows); l != 3 {
t.Errorf("expected 3 rows; got %d", l)
}
// Delete the keys within a transaction. Implicitly, the intents are
// resolved via ResolveIntentRange upon completion.
if err := db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
b := txn.NewBatch()
b.DelRange("a", "d", false /* returnKeys */)
return txn.CommitInBatch(ctx, b)
}); err != nil {
t.Fatalf("unexpected error on transactional DeleteRange: %s", err)
}
// Scan consistently to make sure the intents are gone.
if rows, err := db.Scan(ctx, "a", "q", 0); err != nil {
t.Fatalf("unexpected error on Scan: %s", err)
} else if l := len(rows); l != 0 {
t.Errorf("expected 0 rows; got %d", l)
}
// ReverseScan consistently to make sure the intents are gone.
if rows, err := db.ReverseScan(ctx, "a", "q", 0); err != nil {
t.Fatalf("unexpected error on ReverseScan: %s", err)
} else if l := len(rows); l != 0 {
t.Errorf("expected 0 rows; got %d", l)
}
}
// TestMultiRangeScanReverseScanInconsistent verifies that a Scan/ReverseScan
// across ranges that doesn't require read consistency will set a timestamp
// using the clock local to the distributed sender.
func TestMultiRangeScanReverseScanInconsistent(t *testing.T) {
defer leaktest.AfterTest(t)()
for _, rc := range []roachpb.ReadConsistencyType{
roachpb.READ_UNCOMMITTED,
roachpb.INCONSISTENT,
} {
t.Run(rc.String(), func(t *testing.T) {
s, _ := startNoSplitMergeServer(t)
ctx := context.TODO()
defer s.Stopper().Stop(ctx)
db := s.DB()
if err := setupMultipleRanges(ctx, db, "b"); err != nil {
t.Fatal(err)
}
// Write keys "a" and "b", the latter of which is the first key in the
// second range.
keys := [2]string{"a", "b"}
ts := [2]hlc.Timestamp{}
for i, key := range keys {
b := &client.Batch{}
b.Put(key, "value")
if err := db.Run(ctx, b); err != nil {
t.Fatal(err)
}
ts[i] = s.Clock().Now()
log.Infof(ctx, "%d: %s %d", i, key, ts[i])
if i == 0 {
testutils.SucceedsSoon(t, func() error {
// Enforce that when we write the second key, it's written
// with a strictly higher timestamp. We're dropping logical
// ticks and the clock may just have been pushed into the
// future, so that's necessary. See #3122.
if ts[0].WallTime >= s.Clock().Now().WallTime {
return errors.New("time stands still")
}
return nil
})
}
}
// Do an inconsistent Scan/ReverseScan from a new DistSender and verify
// it does the read at its local clock and doesn't receive an
// OpRequiresTxnError. We set the local clock to the timestamp of
// just above the first key to verify it's used to read only key "a".
for i, request := range []roachpb.Request{
roachpb.NewScan(roachpb.Key("a"), roachpb.Key("c")),
roachpb.NewReverseScan(roachpb.Key("a"), roachpb.Key("c")),
} {
manual := hlc.NewManualClock(ts[0].WallTime + 1)
clock := hlc.NewClock(manual.UnixNano, time.Nanosecond)
ds := kv.NewDistSender(
kv.DistSenderConfig{
AmbientCtx: log.AmbientContext{Tracer: s.ClusterSettings().Tracer},
Clock: clock,
RPCContext: s.RPCContext(),
NodeDialer: nodedialer.New(s.RPCContext(), gossip.AddressResolver(s.(*server.TestServer).Gossip())),
},
s.(*server.TestServer).Gossip(),
)
reply, err := client.SendWrappedWith(context.Background(), ds, roachpb.Header{
ReadConsistency: rc,
}, request)
if err != nil {
t.Fatal(err)
}
var rows []roachpb.KeyValue
switch r := reply.(type) {
case *roachpb.ScanResponse:
rows = r.Rows
case *roachpb.ReverseScanResponse:
rows = r.Rows
default:
t.Fatalf("unexpected response %T: %v", reply, reply)
}
if l := len(rows); l != 1 {
t.Fatalf("%d: expected 1 row; got %d\n%v", i, l, rows)
}
if key := string(rows[0].Key); keys[0] != key {
t.Errorf("expected key %q; got %q", keys[0], key)
}
}
})
}
}
// TestParallelSender splits the keyspace 10 times and verifies that a
// scan across all and 10 puts to each range both use parallelizing
// dist sender.
func TestParallelSender(t *testing.T) {
defer leaktest.AfterTest(t)()