-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathfollowerreads_test.go
1272 lines (1200 loc) · 43.4 KB
/
followerreads_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package kvfollowerreadsccl
import (
"context"
gosql "database/sql"
"fmt"
"math"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/lock"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan/replicaoracle"
"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/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util"
"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/stop"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
const (
expectedFollowerReadOffset time.Duration = -4200 * time.Millisecond
)
func TestEvalFollowerReadOffset(t *testing.T) {
defer leaktest.AfterTest(t)()
disableEnterprise := utilccl.TestingEnableEnterprise()
defer disableEnterprise()
st := cluster.MakeTestingClusterSettings()
if offset, err := evalFollowerReadOffset(uuid.MakeV4(), st); err != nil {
t.Fatal(err)
} else if offset != expectedFollowerReadOffset {
t.Fatalf("expected %v, got %v", expectedFollowerReadOffset, offset)
}
disableEnterprise()
_, err := evalFollowerReadOffset(uuid.MakeV4(), st)
if !testutils.IsError(err, "requires an enterprise license") {
t.Fatalf("failed to get error when evaluating follower read offset without " +
"an enterprise license")
}
}
func TestZeroDurationDisablesFollowerReadOffset(t *testing.T) {
defer leaktest.AfterTest(t)()
defer utilccl.TestingEnableEnterprise()()
ctx := context.Background()
st := cluster.MakeTestingClusterSettings()
closedts.TargetDuration.Override(ctx, &st.SV, 0)
if offset, err := evalFollowerReadOffset(uuid.MakeV4(), st); err != nil {
t.Fatal(err)
} else if offset != math.MinInt64 {
t.Fatalf("expected %v, got %v", math.MinInt64, offset)
}
}
func TestCanSendToFollower(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.UnderDeadlock(t, "test is flaky under deadlock+stress")
ctx := context.Background()
clock := hlc.NewClockWithSystemTimeSource(base.DefaultMaxClockOffset, base.DefaultMaxClockOffset)
stale := clock.Now().Add(2*expectedFollowerReadOffset.Nanoseconds(), 0)
current := clock.Now()
future := clock.Now().Add(2*clock.MaxOffset().Nanoseconds(), 0)
txn := func(ts hlc.Timestamp) *roachpb.Transaction {
txn := roachpb.MakeTransaction("txn", nil, 0, 0, ts, 0, 1, 0)
return &txn
}
withWriteTimestamp := func(txn *roachpb.Transaction, ts hlc.Timestamp) *roachpb.Transaction {
txn.WriteTimestamp = ts
return txn
}
withUncertaintyLimit := func(txn *roachpb.Transaction, ts hlc.Timestamp) *roachpb.Transaction {
txn.GlobalUncertaintyLimit = ts
return txn
}
batch := func(txn *roachpb.Transaction, reqs ...kvpb.Request) *kvpb.BatchRequest {
ba := &kvpb.BatchRequest{}
ba.Txn = txn
for _, req := range reqs {
ba.Add(req)
}
return ba
}
withBatchTimestamp := func(ba *kvpb.BatchRequest, ts hlc.Timestamp) *kvpb.BatchRequest {
ba.Timestamp = ts
return ba
}
withServerSideBatchTimestamp := func(ba *kvpb.BatchRequest, ts hlc.Timestamp) *kvpb.BatchRequest {
ba = withBatchTimestamp(ba, ts)
ba.TimestampFromServerClock = (*hlc.ClockTimestamp)(&ts)
return ba
}
testCases := []struct {
name string
ba *kvpb.BatchRequest
ctPolicy roachpb.RangeClosedTimestampPolicy
disabledEnterprise bool
disabledFollowerReads bool
zeroTargetDuration bool
exp bool
}{
{
name: "non-txn batch, without ts",
ba: batch(nil, &kvpb.GetRequest{}),
exp: false,
},
{
name: "stale non-txn batch",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
exp: true,
},
{
name: "stale non-txn export batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), stale),
exp: true,
},
{
name: "stale non-txn multiple exports batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}, &kvpb.ExportRequest{}), stale),
exp: true,
},
{
name: "stale non-txn mixed export-scan batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}, &kvpb.ScanRequest{}), stale),
exp: true,
},
{
name: "current-time non-txn batch",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), current),
exp: false,
},
{
name: "current-time non-txn export batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), current),
exp: false,
},
{
name: "current-time non-txn multiple exports batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}, &kvpb.ExportRequest{}), current),
exp: false,
},
{
name: "future non-txn batch",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), future),
exp: false,
},
{
name: "future non-txn export batch",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), future),
exp: false,
},
{
name: "stale non-txn batch, server-side ts",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
exp: false,
},
{
name: "current-time non-txn batch, server-side ts",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), current),
exp: false,
},
{
name: "future non-txn batch, server-side ts",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), future),
exp: false,
},
{
name: "stale read",
ba: batch(txn(stale), &kvpb.GetRequest{}),
exp: true,
},
{
name: "stale locking read",
ba: batch(txn(stale), &kvpb.GetRequest{KeyLockingStrength: lock.Exclusive}),
exp: false,
},
{
name: "stale scan",
ba: batch(txn(stale), &kvpb.ScanRequest{}),
exp: true,
},
{
name: "stale reverse scan",
ba: batch(txn(stale), &kvpb.ReverseScanRequest{}),
exp: true,
},
{
name: "stale refresh",
ba: batch(txn(stale), &kvpb.RefreshRequest{}),
exp: true,
},
{
name: "stale refresh range",
ba: batch(txn(stale), &kvpb.RefreshRangeRequest{}),
exp: true,
},
{
name: "stale write",
ba: batch(txn(stale), &kvpb.PutRequest{}),
exp: false,
},
{
name: "stale heartbeat txn",
ba: batch(txn(stale), &kvpb.HeartbeatTxnRequest{}),
exp: false,
},
{
name: "stale end txn",
ba: batch(txn(stale), &kvpb.EndTxnRequest{}),
exp: false,
},
{
name: "stale non-txn request",
ba: batch(txn(stale), &kvpb.QueryTxnRequest{}),
exp: false,
},
{
name: "stale read with current-time writes",
ba: batch(withWriteTimestamp(txn(stale), current), &kvpb.GetRequest{}),
exp: false,
},
{
name: "stale read with current-time uncertainty limit",
ba: batch(withUncertaintyLimit(txn(stale), current), &kvpb.GetRequest{}),
exp: false,
},
{
name: "stale read when zero target_duration",
ba: batch(txn(stale), &kvpb.GetRequest{}),
zeroTargetDuration: true,
exp: false,
},
{
name: "current-time read",
ba: batch(txn(current), &kvpb.GetRequest{}),
exp: false,
},
{
name: "future read",
ba: batch(txn(future), &kvpb.GetRequest{}),
exp: false,
},
{
name: "non-txn batch, without ts, global reads policy",
ba: batch(nil, &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale non-txn batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale non-txn export batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), stale),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time non-txn batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), current),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time non-txn export batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), current),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "future non-txn batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), future),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "future non-txn export batch, global reads policy",
ba: withBatchTimestamp(batch(nil, &kvpb.ExportRequest{}), future),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale non-txn batch, server-side ts, global reads policy",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "current-time non-txn batch, server-side ts, global reads policy",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), current),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "future non-txn batch, server-side ts, global reads policy",
ba: withServerSideBatchTimestamp(batch(nil, &kvpb.GetRequest{}), future),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale read, global reads policy",
ba: batch(txn(stale), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale locking read, global reads policy",
ba: batch(txn(stale), &kvpb.GetRequest{KeyLockingStrength: lock.Exclusive}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale scan, global reads policy",
ba: batch(txn(stale), &kvpb.ScanRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale reverse scan, global reads policy",
ba: batch(txn(stale), &kvpb.ReverseScanRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale refresh, global reads policy",
ba: batch(txn(stale), &kvpb.RefreshRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale refresh range, global reads policy",
ba: batch(txn(stale), &kvpb.RefreshRangeRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale write, global reads policy",
ba: batch(txn(stale), &kvpb.PutRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale heartbeat txn, global reads policy",
ba: batch(txn(stale), &kvpb.HeartbeatTxnRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale end txn, global reads policy",
ba: batch(txn(stale), &kvpb.EndTxnRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale non-txn request, global reads policy",
ba: batch(txn(stale), &kvpb.QueryTxnRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "stale read with current-time writes, global reads policy",
ba: batch(withWriteTimestamp(txn(stale), current), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "stale read with current-time uncertainty limit, global reads policy",
ba: batch(withUncertaintyLimit(txn(stale), current), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time read, global reads policy",
ba: batch(txn(current), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time scan, global reads policy",
ba: batch(txn(current), &kvpb.ScanRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time reverse scan, global reads policy",
ba: batch(txn(current), &kvpb.ReverseScanRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time refresh, global reads policy",
ba: batch(txn(current), &kvpb.RefreshRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time refresh range, global reads policy",
ba: batch(txn(current), &kvpb.RefreshRangeRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: true,
},
{
name: "current-time read with future writes, global reads policy",
ba: batch(withWriteTimestamp(txn(current), future), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "current-time read with future uncertainty limit, global reads policy",
ba: batch(withUncertaintyLimit(txn(current), future), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "future read, global reads policy",
ba: batch(txn(future), &kvpb.GetRequest{}),
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: false,
},
{
name: "non-enterprise",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
disabledEnterprise: true,
exp: false,
},
{
name: "follower reads disabled",
ba: withBatchTimestamp(batch(nil, &kvpb.GetRequest{}), stale),
disabledFollowerReads: true,
exp: false,
},
}
for _, c := range testCases {
t.Run(c.name, func(t *testing.T) {
if !c.disabledEnterprise {
defer utilccl.TestingEnableEnterprise()()
}
st := cluster.MakeTestingClusterSettings()
kvserver.FollowerReadsEnabled.Override(ctx, &st.SV, !c.disabledFollowerReads)
if c.zeroTargetDuration {
closedts.TargetDuration.Override(ctx, &st.SV, 0)
}
can := canSendToFollower(uuid.MakeV4(), st, clock, c.ctPolicy, c.ba)
require.Equal(t, c.exp, can)
})
}
}
// mockNodeStore implements the kvcoord.NodeDescStore interface.
type mockNodeStore []roachpb.NodeDescriptor
func (s mockNodeStore) GetNodeDescriptor(id roachpb.NodeID) (*roachpb.NodeDescriptor, error) {
for i := range s {
desc := &s[i]
if desc.NodeID == id {
return desc, nil
}
}
return nil, kvpb.NewNodeDescNotFoundError(id)
}
func (s mockNodeStore) GetNodeDescriptorCount() int {
return len(s)
}
func (s mockNodeStore) GetStoreDescriptor(id roachpb.StoreID) (*roachpb.StoreDescriptor, error) {
return nil, kvpb.NewStoreDescNotFoundError(id)
}
// TestOracle tests the Oracle exposed by this package.
func TestOracle(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
clock := hlc.NewClockWithSystemTimeSource(base.DefaultMaxClockOffset, base.DefaultMaxClockOffset)
stale := clock.Now().Add(2*expectedFollowerReadOffset.Nanoseconds(), 0)
current := clock.Now()
future := clock.Now().Add(2*clock.MaxOffset().Nanoseconds(), 0)
c := kv.NewDB(log.MakeTestingAmbientCtxWithNewTracer(), kv.MockTxnSenderFactory{}, clock, stopper)
staleTxn := kv.NewTxn(ctx, c, 0)
require.NoError(t, staleTxn.SetFixedTimestamp(ctx, stale))
currentTxn := kv.NewTxn(ctx, c, 0)
require.NoError(t, currentTxn.SetFixedTimestamp(ctx, current))
futureTxn := kv.NewTxn(ctx, c, 0)
require.NoError(t, futureTxn.SetFixedTimestamp(ctx, future))
nodes := mockNodeStore{
{NodeID: 1, Address: util.MakeUnresolvedAddr("tcp", "1")},
{NodeID: 2, Address: util.MakeUnresolvedAddr("tcp", "2")},
{NodeID: 3, Address: util.MakeUnresolvedAddr("tcp", "3")},
}
replicas := []roachpb.ReplicaDescriptor{
{NodeID: 1, StoreID: 1},
{NodeID: 2, StoreID: 2},
{NodeID: 3, StoreID: 3},
}
desc := &roachpb.RangeDescriptor{
InternalReplicas: replicas,
}
closestFollower := replicas[1]
leaseholder := replicas[2]
rpcContext := rpc.NewInsecureTestingContext(ctx, clock, stopper)
setLatency := func(id roachpb.NodeID, latency time.Duration) {
// All test cases have to have at least 11 measurement values in order for
// the exponentially-weighted moving average to work properly. See the
// comment on the WARMUP_SAMPLES const in the ewma package for details.
for i := 0; i < 11; i++ {
rpcContext.RemoteClocks.UpdateOffset(ctx, id, rpc.RemoteOffset{}, latency)
}
}
setLatency(1, 100*time.Millisecond)
setLatency(2, 2*time.Millisecond)
setLatency(3, 80*time.Millisecond)
testCases := []struct {
name string
txn *kv.Txn
lh *roachpb.ReplicaDescriptor
ctPolicy roachpb.RangeClosedTimestampPolicy
disabledEnterprise bool
disabledFollowerReads bool
exp roachpb.ReplicaDescriptor
}{
{
name: "non-txn, known leaseholder",
txn: nil,
lh: &leaseholder,
exp: leaseholder,
},
{
name: "non-txn, unknown leaseholder",
txn: nil,
exp: closestFollower,
},
{
name: "stale txn, known leaseholder",
txn: staleTxn,
lh: &leaseholder,
exp: closestFollower,
},
{
name: "stale txn, unknown leaseholder",
txn: staleTxn,
exp: closestFollower,
},
{
name: "current txn, known leaseholder",
txn: currentTxn,
lh: &leaseholder,
exp: leaseholder,
},
{
name: "current txn, unknown leaseholder",
txn: currentTxn,
exp: closestFollower,
},
{
name: "future txn, known leaseholder",
txn: futureTxn,
lh: &leaseholder,
exp: leaseholder,
},
{
name: "future txn, unknown leaseholder",
txn: futureTxn,
exp: closestFollower,
},
{
name: "stale txn, known leaseholder, global reads policy",
txn: staleTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
lh: &leaseholder,
exp: closestFollower,
},
{
name: "stale txn, unknown leaseholder, global reads policy",
txn: staleTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: closestFollower,
},
{
name: "current txn, known leaseholder, global reads policy",
txn: currentTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
lh: &leaseholder,
exp: closestFollower,
},
{
name: "current txn, unknown leaseholder, global reads policy",
txn: currentTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: closestFollower,
},
{
name: "future txn, known leaseholder, global reads policy",
txn: futureTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
lh: &leaseholder,
exp: leaseholder,
},
{
name: "future txn, unknown leaseholder, global reads policy",
txn: futureTxn,
ctPolicy: roachpb.LEAD_FOR_GLOBAL_READS,
exp: closestFollower,
},
{
name: "stale txn, non-enterprise",
txn: staleTxn,
lh: &leaseholder,
disabledEnterprise: true,
exp: leaseholder,
},
{
name: "stale txn, follower reads disabled",
txn: staleTxn,
lh: &leaseholder,
disabledFollowerReads: true,
exp: leaseholder,
},
}
for _, c := range testCases {
t.Run(c.name, func(t *testing.T) {
if !c.disabledEnterprise {
defer utilccl.TestingEnableEnterprise()()
}
st := cluster.MakeTestingClusterSettings()
kvserver.FollowerReadsEnabled.Override(ctx, &st.SV, !c.disabledFollowerReads)
o := replicaoracle.NewOracle(followerReadOraclePolicy, replicaoracle.Config{
NodeDescs: nodes,
Settings: st,
RPCContext: rpcContext,
Clock: clock,
HealthFunc: func(roachpb.NodeID) bool { return true },
})
res, _, err := o.ChoosePreferredReplica(ctx, c.txn, desc, c.lh, c.ctPolicy, replicaoracle.QueryState{})
require.NoError(t, err)
require.Equal(t, c.exp, res)
})
}
}
// Test that follower reads recover from a situation where a gateway node has
// the right leaseholder cached, but stale followers. This is an integration
// test checking that the cache on the gateway gets updated by the first request
// encountering this situation, and then follower reads work.
func TestFollowerReadsWithStaleDescriptor(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// The test uses follower_read_timestamp().
defer utilccl.TestingEnableEnterprise()()
var historicalQuery atomic.Value
historicalQuery.Store(`SELECT * FROM test AS OF SYSTEM TIME follower_read_timestamp() WHERE k=2`)
recCh := make(chan tracingpb.Recording, 1)
tc := testcluster.StartTestCluster(t, 4,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TODOTestTenantDisabled,
UseDatabase: "t",
},
// n4 pretends to have low latency to n2 and n3, so that it tries to use
// them for follower reads.
// Also, we're going to collect a trace of the test's final query.
ServerArgsPerNode: map[int]base.TestServerArgs{
3: {
UseDatabase: "t",
Knobs: base.TestingKnobs{
KVClient: &kvcoord.ClientTestingKnobs{
// Inhibit the checking of connection health done by the
// GRPCTransport. This test wants to control what replica (which
// follower) a request is sent to and, depending on timing, the
// connection from n4 to the respective follower might not be
// heartbeated by the time the test wants to use it. Without this
// knob, that would cause the transport to reorder replicas.
DontConsiderConnHealth: true,
LatencyFunc: func(id roachpb.NodeID) (time.Duration, bool) {
if (id == 2) || (id == 3) {
return time.Millisecond, true
}
return 100 * time.Millisecond, true
},
},
SQLExecutor: &sql.ExecutorTestingKnobs{
WithStatementTrace: func(trace tracingpb.Recording, stmt string) {
if stmt == historicalQuery.Load().(string) {
recCh <- trace
}
},
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
n1 := sqlutils.MakeSQLRunner(tc.Conns[0])
n1.Exec(t, `CREATE DATABASE t`)
n1.Exec(t, `CREATE TABLE test (k INT PRIMARY KEY)`)
n1.Exec(t, `ALTER TABLE test EXPERIMENTAL_RELOCATE VOTERS VALUES (ARRAY[1,2], 1)`)
// Speed up closing of timestamps, in order to sleep less below before we can
// use follower_read_timestamp(). follower_read_timestamp() uses the sum of
// the following settings.
n1.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.target_duration = '0.1s'`)
n1.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.side_transport_interval = '0.1s'`)
n1.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.propagation_slack = '0.1s'`)
// Sleep so that we can perform follower reads. The read timestamp needs to be
// above the timestamp when the table was created.
log.Infof(ctx, "test sleeping for the follower read timestamps to pass the table creation timestamp...")
time.Sleep(300 * time.Millisecond)
log.Infof(ctx, "test sleeping... done")
// Run a query on n4 to populate its cache.
n4 := sqlutils.MakeSQLRunner(tc.Conns[3])
n4.Exec(t, "SELECT * from test WHERE k=1")
// Check that the cache was indeed populated.
var tableID uint32
n1.QueryRow(t, `SELECT id from system.namespace WHERE name='test'`).Scan(&tableID)
tablePrefix := keys.MustAddr(keys.SystemSQLCodec.TablePrefix(tableID))
n4Cache := tc.Server(3).DistSenderI().(*kvcoord.DistSender).RangeDescriptorCache()
entry := n4Cache.GetCached(ctx, tablePrefix, false /* inverted */)
require.NotNil(t, entry)
require.False(t, entry.Lease().Empty())
require.Equal(t, roachpb.StoreID(1), entry.Lease().Replica.StoreID)
require.Equal(t, []roachpb.ReplicaDescriptor{
{NodeID: 1, StoreID: 1, ReplicaID: 1},
{NodeID: 2, StoreID: 2, ReplicaID: 2},
}, entry.Desc().Replicas().Descriptors())
// Remove the follower and add a new non-voter to n3. n2 will no longer have a
// replica.
n1.Exec(t, `ALTER TABLE test EXPERIMENTAL_RELOCATE VOTERS VALUES (ARRAY[1], 1)`)
n1.Exec(t, `ALTER TABLE test EXPERIMENTAL_RELOCATE NONVOTERS VALUES (ARRAY[3], 1)`)
// Execute the query again and assert the cache is updated. This query will
// not be executed as a follower read since it attempts to use n2 which
// doesn't have a replica any more and then it tries n1 which returns an
// updated descriptor.
n4.Exec(t, historicalQuery.Load().(string))
// As a sanity check, verify that this was not a follower read.
rec := <-recCh
require.False(t, kv.OnlyFollowerReads(rec), "query was served through follower reads: %s", rec)
// Check that the cache was properly updated.
entry = n4Cache.GetCached(ctx, tablePrefix, false /* inverted */)
require.NotNil(t, entry)
require.False(t, entry.Lease().Empty())
require.Equal(t, roachpb.StoreID(1), entry.Lease().Replica.StoreID)
require.Equal(t, []roachpb.ReplicaDescriptor{
{NodeID: 1, StoreID: 1, ReplicaID: 1},
{NodeID: 3, StoreID: 3, ReplicaID: 3, Type: roachpb.NON_VOTER},
}, entry.Desc().Replicas().Descriptors())
// Make a note of the follower reads metric on n3. We'll check that it was
// incremented.
var followerReadsCountBefore int64
err := tc.Servers[2].GetStores().(*kvserver.Stores).VisitStores(func(s *kvserver.Store) error {
followerReadsCountBefore = s.Metrics().FollowerReadsCount.Count()
return nil
})
require.NoError(t, err)
// Run a historical query and assert that it's served from the follower (n3).
// n4 should attempt to route to n3 because we pretend n3 has a lower latency
// (see testing knob).
n4.Exec(t, historicalQuery.Load().(string))
rec = <-recCh
// Look at the trace and check that we've served a follower read.
require.True(t, kv.OnlyFollowerReads(rec), "query was not served through follower reads: %s", rec)
// Check that the follower read metric was incremented.
var followerReadsCountAfter int64
err = tc.Servers[2].GetStores().(*kvserver.Stores).VisitStores(func(s *kvserver.Store) error {
followerReadsCountAfter = s.Metrics().FollowerReadsCount.Count()
return nil
})
require.NoError(t, err)
require.Greater(t, followerReadsCountAfter, followerReadsCountBefore)
// Now verify that follower reads aren't mistakenly counted as "misplanned
// ranges" (#61313).
// First, run a query on n3 to populate its cache.
n3 := sqlutils.MakeSQLRunner(tc.Conns[2])
n3.Exec(t, "SELECT * from test WHERE k=1")
n3Cache := tc.Server(2).DistSenderI().(*kvcoord.DistSender).RangeDescriptorCache()
entry = n3Cache.GetCached(ctx, tablePrefix, false /* inverted */)
require.NotNil(t, entry)
require.False(t, entry.Lease().Empty())
require.Equal(t, roachpb.StoreID(1), entry.Lease().Replica.StoreID)
require.Equal(t, []roachpb.ReplicaDescriptor{
{NodeID: 1, StoreID: 1, ReplicaID: 1},
{NodeID: 3, StoreID: 3, ReplicaID: 3, Type: roachpb.NON_VOTER},
}, entry.Desc().Replicas().Descriptors())
// Enable DistSQL so that we have a distributed plan with a single flow on
// n3 (local plans ignore the misplanned ranges).
n4.Exec(t, "SET distsql=on")
// Run a historical query and assert that it's served from the follower (n3).
// n4 should choose n3 to plan the TableReader on because we pretend n3 has
// a lower latency (see testing knob).
// Note that this query is such that the physical planning needs to fetch
// the ReplicaInfo twice for the same range. This allows us to verify that
// the cached - in the spanResolverIterator - information is correctly
// preserved.
historicalQuery.Store(`SELECT * FROM [SELECT * FROM test WHERE k=2 UNION ALL SELECT * FROM test WHERE k=3] AS OF SYSTEM TIME follower_read_timestamp()`)
n4.Exec(t, historicalQuery.Load().(string))
rec = <-recCh
// Sanity check that the plan was distributed.
require.True(t, strings.Contains(rec.String(), "creating DistSQL plan with isLocal=false"))
// Look at the trace and check that we've served a follower read.
require.True(t, kv.OnlyFollowerReads(rec), "query was not served through follower reads: %s", rec)
// Verify that we didn't produce the "misplanned ranges" metadata that would
// purge the non-stale entries from the range cache on n4.
require.False(t, strings.Contains(rec.String(), "clearing entries overlapping"))
// Also confirm that we didn't even check for the "misplanned ranges"
// metadata on n3.
require.False(t, strings.Contains(rec.String(), "checking range cache to see if range info updates should be communicated to the gateway"))
}
// TestSecondaryTenantFollowerReadsRouting ensures that secondary tenants route
// their requests to the nearest replica. The test exercises three
// configurations:
// - shared-process multi-tenancy
// - separate-process multi-tenancy, with accurate latency information between
// nodes available
// - separate-process multi-tenancy, with accurate latency information between
// nodes unavailable which requires the fallback to estimates using node
// localities.
//
// For the shared-process multi-tenancy we set up a single region cluster so
// that locality information didn't come into play when choosing the replica. We
// use n2 as the gateway for the query and expect that its replica will serve
// the follower read.
//
// For the separate-process multi-tenancy we set up a three region cluster where
// n2 and n4 are in the same region, and we use n4 as the gateway and expect
// that n2 serves the follower read.
func TestSecondaryTenantFollowerReadsRouting(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
defer utilccl.TestingEnableEnterprise()()
skip.UnderStressRace(t, "times out")
for _, testCase := range []struct {
name string
sharedProcess bool
validLatencyFunc bool
}{
{name: "shared-process", sharedProcess: true},
{name: "latency-based", sharedProcess: false, validLatencyFunc: true},
{name: "locality-based", sharedProcess: false, validLatencyFunc: false},
} {
t.Run(testCase.name, func(t *testing.T) {
const numNodes = 4
gatewayNode := 3
if testCase.sharedProcess {
gatewayNode = 1
}
serverArgs := make(map[int]base.TestServerArgs)
localities := make(map[int]roachpb.Locality)
for i := 0; i < numNodes; i++ {
regionName := fmt.Sprintf("region_%d", i)
if i == gatewayNode {
// Make it such that n4 and n2 are in the same region.
// Below, we'll expect a follower read from n4 to be served
// by n2 because they're in the same locality (when
// validLatencyFunc is false).
regionName = fmt.Sprintf("region_%d", 1)
}
if testCase.sharedProcess {
// In shared-process config we want all nodes to be in the
// same region so that other considerations (like latency
// function and locality matching don't come into play).
regionName = "test_region"
}
locality := roachpb.Locality{
Tiers: []roachpb.Tier{{Key: "region", Value: regionName}},
}
localities[i] = locality
serverArgs[i] = base.TestServerArgs{
Locality: localities[i],
}
}
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
ServerArgs: base.TestServerArgs{
DefaultTestTenant: base.TestControlsTenantsExplicitly,
},
})
ctx := context.Background()
defer tc.Stopper().Stop(ctx)
// Speed up closing of timestamps in order to sleep less below
// before we can use follower_read_timestamp(). Note that we need to
// override the setting for the tenant as well, because the builtin
// is run in the tenant's sql pod.
systemSQL := sqlutils.MakeSQLRunner(tc.Conns[0])
systemSQL.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.target_duration = '0.1s'`)
systemSQL.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.side_transport_interval = '0.1s'`)
systemSQL.Exec(t, `SET CLUSTER SETTING kv.closed_timestamp.propagation_slack = '0.1s'`)
// We're making assertions on traces collected by the tenant using
// log lines in KV so we must ensure they're not redacted.
systemSQL.Exec(t, `SET CLUSTER SETTING trace.redact_at_virtual_cluster_boundary.enabled = 'false'`)
historicalQuery := `SELECT * FROM t.test AS OF SYSTEM TIME follower_read_timestamp() WHERE k=2`
recCh := make(chan tracingpb.Recording, 1)
var tenants [numNodes]serverutils.ApplicationLayerInterface
dbs := make([]*gosql.DB, numNodes)
// In shared-process multi-tenancy we must initialize the tenant
// server on the gateway first in order to guarantee that the knobs
// are used (otherwise we have a race between the tenant server
// being started by the server controller and us explicitly starting
// the shared-process tenant server).
initOrder := []int{gatewayNode}
for i := 0; i < numNodes; i++ {
if i != gatewayNode {
initOrder = append(initOrder, i)
}
}
for _, i := range initOrder {
knobs := base.TestingKnobs{}
if i == gatewayNode {
knobs = base.TestingKnobs{
KVClient: &kvcoord.ClientTestingKnobs{
DontConsiderConnHealth: true,
// For the validLatencyFunc=true version of the
// test, the client pretends to have a low latency
// connection to n2. As a result, we expect n2 to be
// used for follower reads originating from n4.
//
// For the variant where no latency information is
// available, we expect n2 to serve follower reads
// as well, but because it is in the same locality
// as the client.
//
// Note that this latency func doesn't matter in the
// shared-process config.
LatencyFunc: func(id roachpb.NodeID) (time.Duration, bool) {
if !testCase.validLatencyFunc {