-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
flow_control_integration_test.go
5799 lines (5134 loc) · 218 KB
/
flow_control_integration_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 2023 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package kvserver_test
import (
"context"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvflowcontrol"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvflowcontrol/kvflowinspectpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvflowcontrol/rac2"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/fs"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/echotest"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/admission/admissionpb"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/errors"
"github.com/dustin/go-humanize"
"github.com/olekukonko/tablewriter"
"github.com/stretchr/testify/require"
)
// Tests in this file use the echotest library, printing out progressive state
// in files under testdata/flow_control_integration/*. Every
// TestFlowControlFileName maps to testdata/flow_control_integration/file_name
// -- running TestFlowControl* will match everything. It's instructive to run
// these tests with the following vmodule, as of 04/23:
//
// --vmodule='replica_raft=1,kvflowcontroller=2,replica_proposal_buf=1,
// raft_transport=2,kvflowdispatch=1,kvadmission=1,
// kvflowhandle=1,work_queue=1,replica_flow_control=1,
// tracker=1,client_raft_helpers_test=1'
//
// TODO(irfansharif): Add end-to-end tests for the following:
// - [ ] Node with full RaftTransport receive queue (I8).
// - [ ] Node with full RaftTransport send queue, with proposals dropped (I8).
// - [ ] Raft commands getting reproposed, either due to timeouts or not having
// the right MLAI. See TestReplicaRefreshPendingCommandsTicks,
// TestLogGrowthWhenRefreshingPendingCommands. I7.
// - [ ] Raft proposals getting dropped/abandoned. See
// (*Replica).cleanupFailedProposalLocked and its uses.
// TestFlowControlBasic runs a basic end-to-end test of the kvflowcontrol
// machinery, replicating + admitting a single 1MiB regular write.
func TestFlowControlBasic(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testutils.RunTrueAndFalse(t, "always-enqueue", func(t *testing.T, alwaysEnqueue bool) {
ctx := context.Background()
const numNodes = 3
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
},
},
AdmissionControl: &admission.TestingKnobs{
DisableWorkQueueFastPath: alwaysEnqueue,
},
},
},
})
defer tc.Stopper().Stop(ctx)
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1, 2)...)
desc, err := tc.LookupRange(k)
require.NoError(t, err)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("basic") // this test behaves identically with or without the fast path
h.enableVerboseRaftMsgLoggingForRange(desc.RangeID)
h.waitForConnectedStreams(ctx, desc.RangeID, 3, 0 /* serverIdx */)
h.comment(`-- Flow token metrics, before issuing the regular 1MiB replicated write.`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- (Issuing + admitting a regular 1MiB, triply replicated write...)`)
h.log("sending put request")
h.put(ctx, k, 1<<20 /* 1MiB */, admissionpb.NormalPri)
h.log("sent put request")
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */)
h.comment(`
-- Stream counts as seen by n1 post-write. We should see three {regular,elastic}
-- streams given there are three nodes and we're using a replication factor of
-- three.
`)
h.query(n1, `
SELECT name, value
FROM crdb_internal.node_metrics
WHERE name LIKE '%kvadmission.flow_controller%stream%'
ORDER BY name ASC;
`)
h.comment(`-- Another view of the stream count, using /inspectz-backed vtables.`)
h.query(n1, `
SELECT range_id, count(*) AS streams
FROM crdb_internal.kv_flow_control_handles
GROUP BY (range_id)
ORDER BY streams DESC;
`, "range_id", "stream_count")
h.comment(`
-- Flow token metrics from n1 after issuing the regular 1MiB replicated write,
-- and it being admitted on n1, n2 and n3. We should see 3*1MiB = 3MiB of
-- {regular,elastic} tokens deducted and returned, and {8*3=24MiB,16*3=48MiB} of
-- {regular,elastic} tokens available. Everything should be accounted for.
`)
h.query(n1, v1FlowTokensQueryStr)
// When run using -v the vmodule described at the top of this file, this
// test demonstrates end-to-end flow control machinery in the happy
// path.
//
// 1. The request gets admitted for flow tokens for each of the three
// replication streams (one per replica).
//
// [T1,n1] admitted request (pri=normal-pri stream=t1/s1 tokens=+16 MiB wait-duration=18.834µs mode=apply_to_all)
// [T1,n1] admitted request (pri=normal-pri stream=t1/s2 tokens=+16 MiB wait-duration=1.042µs mode=apply_to_all)
// [T1,n1] admitted request (pri=normal-pri stream=t1/s3 tokens=+16 MiB wait-duration=834ns mode=apply_to_all)
//
// 2. We encode the raft metadata as part of the raft command. At the
// proposer, we track 1 MiB of flow token deductions for each stream,
// using the log position the proposal is to end up in.
//
// [T1,n1,s1,r64/1:/{Table/Max-Max}] encoded raft admission meta: pri=normal-pri create-time=1685129503765352000 proposer=n1
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] bound index/log terms for proposal entry: 6/20 EntryNormal <omitted>
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 279 tracking +1.0 MiB flow control tokens for pri=normal-pri stream=t1/s1 pos=log-position=6/20
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 280 adjusted flow tokens (pri=normal-pri stream=t1/s1 delta=-1.0 MiB): regular=+15 MiB elastic=+7.0 MiB
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 281 tracking +1.0 MiB flow control tokens for pri=normal-pri stream=t1/s2 pos=log-position=6/20
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 282 adjusted flow tokens (pri=normal-pri stream=t1/s2 delta=-1.0 MiB): regular=+15 MiB elastic=+7.0 MiB
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 283 tracking +1.0 MiB flow control tokens for pri=normal-pri stream=t1/s3 pos=log-position=6/20
// [T1,n1,s1,r64/1:/{Table/Max-Max}] 284 adjusted flow tokens (pri=normal-pri stream=t1/s3 delta=-1.0 MiB): regular=+15 MiB elastic=+7.0 MiB
//
// 3. We decode the raft metadata below-raft on each of the replicas.
// The local replica does it first, either enqueues it in below-raft
// work queues or just fast path if tokens are available, informs itself
// of entries being admitted, and releases the corresponding flow
// tokens.
//
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] decoded raft admission meta below-raft: pri=normal-pri create-time=1685129503765352000 proposer=n1 receiver=[n1,s1] tenant=t1 tokens≈+1.0 MiB sideloaded=false raft-entry=6/20
// Fast-path:
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] fast-path: admitting t1 pri=normal-pri r64 origin=n1 log-position=6/20 ingested=false
// Async-path:
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] async-path: len(waiting-work)=1: enqueued t1 pri=normal-pri r64 origin=n1 log-position=6/20 ingested=false
// [T1,n1] async-path: len(waiting-work)=0 dequeued t1 pri=normal-pri r64 origin=n1 log-position=6/20 ingested=false
// [T1,n1] dispatching admitted-entries (r64 s1 pri=normal-pri up-to-log-position=6/20) to n1
// [T1,n1] released +1.0 MiB flow control tokens for 1 out of 1 tracked deductions for pri=normal-pri stream=t1/s1, up to log-position=6/20; 0 tracked deduction(s) remain
// [T1,n1] adjusted flow tokens (pri=normal-pri stream=t1/s1 delta=+1.0 MiB): regular=+16 MiB elastic=+8.0 MiB
//
//
// 4. We propagate MsgApps with encoded raft metadata to the follower
// replicas on n2 and n3. Each of them similarly decode, virtually
// enqueue/use the fast path, admit, and inform the origin node (n1)
// of admission. Below we just show the fast path.
//
// [T1,n2] [raft] r64 Raft message 1->2 MsgApp Term:6 Log:6/19 Commit:19 Entries:[6/20 EntryNormal <omitted>]
// [T1,n3] [raft] r64 Raft message 1->3 MsgApp Term:6 Log:6/19 Commit:19 Entries:[6/20 EntryNormal <omitted>]
//
// [T1,n2,s2,r64/2:/{Table/Max-Max},raft] decoded raft admission meta below-raft: pri=normal-pri create-time=1685129503765352000 proposer=n1 receiver=[n2,s2] tenant=t1 tokens≈+1.0 MiB sideloaded=false raft-entry=6/20
// [T1,n3,s3,r64/3:/{Table/Max-Max},raft] decoded raft admission meta below-raft: pri=normal-pri create-time=1685129503765352000 proposer=n1 receiver=[n3,s3] tenant=t1 tokens≈+1.0 MiB sideloaded=false raft-entry=6/20
// [T1,n2,s2,r64/2:/{Table/Max-Max},raft] 294 fast-path: admitting t1 pri=normal-pri r64 origin=n1 log-position=6/20 ingested=false
// [T1,n3,s3,r64/3:/{Table/Max-Max},raft] 298 fast-path: admitting t1 pri=normal-pri r64 origin=n1 log-position=6/20 ingested=false
// [T1,n2] dispatching admitted-entries (r64 s2 pri=normal-pri up-to-log-position=6/20) to n1
// [T1,n3] dispatching admitted-entries (r64 s3 pri=normal-pri up-to-log-position=6/20) to n1
//
// 5. On MsgAppResps (or really any raft messages bound for n1), we
// piggyback these token dispatches. n1, on hearing about them,
// returns relevant tokens back to the stream.
//
// [T1,n2] informing n1 of below-raft admitted-entries (r64 s2 pri=normal-pri up-to-log-position=6/20): 1 out of 1 dispatches
// [T1,n1] [raft] r64 Raft message 2->1 MsgAppResp Term:6 Log:0/20
// [T1,n1] released +1.0 MiB flow control tokens for 1 out of 1 tracked deductions for pri=normal-pri stream=t1/s2, up to log-position=6/20; 0 tracked deduction(s) remain
// [T1,n1] adjusted flow tokens (pri=normal-pri stream=t1/s2 delta=+1.0 MiB): regular=+16 MiB elastic=+8.0 MiB
// [T1,n3] informing n1 of below-raft admitted-entries (r64 s3 pri=normal-pri up-to-log-position=6/20): 1 out of 1 dispatches
// [T1,n1] [raft] r64 Raft message 3->1 MsgAppResp Term:6 Log:0/20
// [T1,n1] released +1.0 MiB flow control tokens for 1 out of 1 tracked deductions for pri=normal-pri stream=t1/s3, up to log-position=6/20; 0 tracked deduction(s) remain
// [T1,n1] adjusted flow tokens (pri=normal-pri stream=t1/s3 delta=+1.0 MiB): regular=+16 MiB elastic=+8.0 MiB
})
}
// TestFlowControlRangeSplitMerge walks through what happens to flow tokens when
// a range splits/merges.
func TestFlowControlRangeSplitMerge(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
const numNodes = 3
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1, 2)...)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("split_merge")
desc, err := tc.LookupRange(k)
require.NoError(t, err)
h.waitForConnectedStreams(ctx, desc.RangeID, 3, 0 /* serverIdx */)
h.log("sending put request to pre-split range")
h.put(ctx, k, 1<<20 /* 1MiB */, admissionpb.NormalPri)
h.log("sent put request to pre-split range")
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */)
h.comment(`
-- Flow token metrics from n1 after issuing + admitting the regular 1MiB 3x
-- replicated write to the pre-split range. There should be 3MiB of
-- {regular,elastic} tokens {deducted,returned}.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- (Splitting range.)`)
left, right := tc.SplitRangeOrFatal(t, k.Next())
h.waitForConnectedStreams(ctx, right.RangeID, 3, 0 /* serverIdx */)
// [T1,n1,s1,r63/1:/{Table/62-Max},*kvpb.AdminSplitRequest] initiating a split of this range at key /Table/Max [r64] (manual)
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] connected to stream: t1/s1
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] connected to stream: t1/s2
// [T1,n1,s1,r64/1:/{Table/Max-Max},raft] connected to stream: t1/s3
h.log("sending 2MiB put request to post-split LHS")
h.put(ctx, k, 2<<20 /* 2MiB */, admissionpb.NormalPri)
h.log("sent 2MiB put request to post-split LHS")
h.log("sending 3MiB put request to post-split RHS")
h.put(ctx, roachpb.Key(right.StartKey), 3<<20 /* 3MiB */, admissionpb.NormalPri)
h.log("sent 3MiB put request to post-split RHS")
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */)
h.comment(`
-- Flow token metrics from n1 after further issuing 2MiB and 3MiB writes to
-- post-split LHS and RHS ranges respectively. We should see 15MiB extra tokens
-- {deducted,returned}, which comes from (2MiB+3MiB)*3=15MiB. So we stand at
-- 3MiB+15MiB=18MiB now.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- Observe the newly split off replica, with its own three streams.`)
h.query(n1, `
SELECT range_id, count(*) AS streams
FROM crdb_internal.kv_flow_control_handles
GROUP BY (range_id)
ORDER BY streams DESC;
`, "range_id", "stream_count")
h.comment(`-- (Merging ranges.)`)
merged := tc.MergeRangesOrFatal(t, left.StartKey.AsRawKey())
// [T1,n1,s1,r64/1:{/Table/Max-\xfa\x00},*kvpb.AdminMergeRequest] initiating a merge of r65:{\xfa\x00-/Max} [(n1,s1):1, (n2,s2):2, (n3,s3):3, next=4, gen=6, sticky=9223372036.854775807,2147483647] into this range (manual)
// [T1,n1,s1,r64/1:{/Table/Max-\xfa\x00},raft] 380 removing replica r65/1
// [T1,n2,s2,r64/2:{/Table/Max-\xfa\x00},raft] 385 removing replica r65/2
// [T1,n3,s3,r64/3:{/Table/Max-\xfa\x00},raft] 384 removing replica r65/3
// [T1,n1,s1,r65/1:{\xfa\x00-/Max},raft] disconnected stream: t1/s1
// [T1,n1,s1,r65/1:{\xfa\x00-/Max},raft] disconnected stream: t1/s2
// [T1,n1,s1,r65/1:{\xfa\x00-/Max},raft] disconnected stream: t1/s3
h.log("sending 4MiB put request to post-merge range")
h.put(ctx, roachpb.Key(merged.StartKey), 4<<20 /* 4MiB */, admissionpb.NormalPri)
h.log("sent 4MiB put request to post-merged range")
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */)
h.comment(`
-- Flow token metrics from n1 after issuing 4MiB of regular replicated writes to
-- the post-merged range. We should see 12MiB extra tokens {deducted,returned},
-- which comes from 4MiB*3=12MiB. So we stand at 18MiB+12MiB=30MiB now.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- Observe only the merged replica with its own three streams.`)
h.query(n1, `
SELECT range_id, count(*) AS streams
FROM crdb_internal.kv_flow_control_handles
GROUP BY (range_id)
ORDER BY streams DESC;
`, "range_id", "stream_count")
}
// TestFlowControlBlockedAdmission tests token tracking behavior by explicitly
// blocking below-raft admission.
func TestFlowControlBlockedAdmission(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
const numNodes = 3
var disableWorkQueueGranting atomic.Bool
disableWorkQueueGranting.Store(true)
st := cluster.MakeTestingClusterSettings()
kvflowcontrol.Enabled.Override(ctx, &st.SV, true)
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Settings: st,
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
},
},
AdmissionControl: &admission.TestingKnobs{
DisableWorkQueueFastPath: true,
DisableWorkQueueGranting: func() bool {
return disableWorkQueueGranting.Load()
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1, 2)...)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
n2 := sqlutils.MakeSQLRunner(tc.ServerConn(1))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("blocked_admission")
desc, err := tc.LookupRange(k)
require.NoError(t, err)
h.waitForConnectedStreams(ctx, desc.RangeID, 3, 0 /* serverIdx */)
h.comment(`-- (Issuing regular 1MiB, 3x replicated write that's not admitted.)`)
h.log("sending put requests")
for i := 0; i < 5; i++ {
h.put(ctx, k, 1<<20 /* 1MiB */, admissionpb.NormalPri)
}
h.log("sent put requests")
h.comment(`
-- Flow token metrics from n1 after issuing 5 regular 1MiB 3x replicated writes
-- that are yet to get admitted. We see 5*1MiB*3=15MiB deductions of
-- {regular,elastic} tokens with no corresponding returns.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- Observe the total tracked tokens per-stream on n1.`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
h.comment(`-- Observe the individual tracked tokens per-stream on the scratch range.`)
h.query(n1, `
SELECT range_id, store_id, priority, crdb_internal.humanize_bytes(tokens::INT8)
FROM crdb_internal.kv_flow_token_deductions
`, "range_id", "store_id", "priority", "tokens")
h.comment(`-- (Allow below-raft admission to proceed.)`)
disableWorkQueueGranting.Store(false)
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */) // wait for admission
h.comment(`-- Observe flow token dispatch metrics from n1.`)
h.query(n1, `
SELECT name, value
FROM crdb_internal.node_metrics
WHERE name LIKE '%kvadmission.flow_token_dispatch.local_regular%'
ORDER BY name ASC;
`)
h.comment(`-- Observe flow token dispatch metrics from n2.`)
h.query(n2, `
SELECT name, value
FROM crdb_internal.node_metrics
WHERE name LIKE '%kvadmission.flow_token_dispatch.remote_regular%'
ORDER BY name ASC;
`)
h.comment(`
-- Flow token metrics from n1 after work gets admitted. We see 15MiB returns of
-- {regular,elastic} tokens, and the available capacities going back to what
-- they were.
`)
h.query(n1, v1FlowTokensQueryStr)
}
// TestFlowControlAdmissionPostSplitMerge walks through what happens with flow
// tokens when a range after undergoes splits/merges. It does this by blocking
// and later unblocking below-raft admission, verifying:
// - tokens for the RHS are released at the post-merge subsuming leaseholder,
// - admission for the RHS post-merge does not cause a double return of tokens,
// - admission for the LHS can happen post-merge,
// - admission for the LHS and RHS can happen post-split.
func TestFlowControlAdmissionPostSplitMerge(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
const numNodes = 3
var disableWorkQueueGranting atomic.Bool
disableWorkQueueGranting.Store(true)
st := cluster.MakeTestingClusterSettings()
kvflowcontrol.Enabled.Override(ctx, &st.SV, true)
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Settings: st,
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
},
},
AdmissionControl: &admission.TestingKnobs{
DisableWorkQueueFastPath: true,
DisableWorkQueueGranting: func() bool {
return disableWorkQueueGranting.Load()
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1, 2)...)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("admission_post_split_merge")
desc, err := tc.LookupRange(k)
require.NoError(t, err)
h.waitForConnectedStreams(ctx, desc.RangeID, 3, 0 /* serverIdx */)
h.log("sending put request to pre-split range")
h.put(ctx, k, 1<<20 /* 1MiB */, admissionpb.NormalPri)
h.put(ctx, k.Next(), 1<<20 /* 1MiB */, admissionpb.NormalPri)
h.log("sent put request to pre-split range")
h.comment(`
-- Flow token metrics from n1 after issuing a regular 2*1MiB 3x replicated write
-- that are yet to get admitted. We see 2*3*1MiB=6MiB deductions of
-- {regular,elastic} tokens with no corresponding returns. The 2*1MiB writes
-- happened on what is soon going to be the LHS and RHS of a range being split.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- (Splitting range.)`)
left, right := tc.SplitRangeOrFatal(t, k.Next())
h.waitForConnectedStreams(ctx, right.RangeID, 3, 0 /* serverIdx */)
h.log("sending 2MiB put request to post-split LHS")
h.put(ctx, k, 2<<20 /* 2MiB */, admissionpb.NormalPri)
h.log("sent 2MiB put request to post-split LHS")
h.log("sending 3MiB put request to post-split RHS")
h.put(ctx, roachpb.Key(right.StartKey), 3<<20 /* 3MiB */, admissionpb.NormalPri)
h.log("sent 3MiB put request to post-split RHS")
h.comment(`
-- Flow token metrics from n1 after further issuing 2MiB and 3MiB writes to
-- post-split LHS and RHS ranges respectively. We should see 15MiB extra tokens
-- deducted which comes from (2MiB+3MiB)*3=15MiB. So we stand at
-- 6MiB+15MiB=21MiB now.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- Observe the newly split off replica, with its own three streams.`)
h.query(n1, `
SELECT range_id, count(*) AS streams
FROM crdb_internal.kv_flow_control_handles
GROUP BY (range_id)
ORDER BY streams DESC;
`, "range_id", "stream_count")
h.comment(`-- (Merging ranges.)`)
merged := tc.MergeRangesOrFatal(t, left.StartKey.AsRawKey())
h.log("sending 4MiB put request to post-merge range")
h.put(ctx, roachpb.Key(merged.StartKey), 4<<20 /* 4MiB */, admissionpb.NormalPri)
h.log("sent 4MiB put request to post-merged range")
h.comment(`
-- Flow token metrics from n1 after issuing 4MiB of regular replicated writes to
-- the post-merged range. We should see 12MiB extra tokens deducted which comes
-- from 4MiB*3=12MiB. So we stand at 21MiB+12MiB=33MiB tokens deducted now. The
-- RHS of the range is gone now, and the previously 3*3MiB=9MiB of tokens
-- deducted for it are released at the subsuming LHS leaseholder.
`)
h.query(n1, `
SELECT name, crdb_internal.humanize_bytes(value::INT8)
FROM crdb_internal.node_metrics
WHERE name LIKE '%kvadmission%regular_tokens%'
ORDER BY name ASC;
`)
h.comment(`-- Observe only the merged replica with its own three streams.`)
h.query(n1, `
SELECT range_id, count(*) AS streams
FROM crdb_internal.kv_flow_control_handles
GROUP BY (range_id)
ORDER BY streams DESC;
`, "range_id", "stream_count")
h.comment(`-- (Allow below-raft admission to proceed.)`)
disableWorkQueueGranting.Store(false)
h.waitForAllTokensReturned(ctx, 3, 0 /* serverIdx */) // wait for admission
h.comment(`
-- Flow token metrics from n1 after work gets admitted. We see all outstanding
-- {regular,elastic} tokens returned, including those from:
-- - the LHS before the merge, and
-- - the LHS and RHS before the original split.
`)
h.query(n1, v1FlowTokensQueryStr)
}
// TestFlowControlCrashedNode tests flow token behavior in the presence of
// crashed nodes.
func TestFlowControlCrashedNode(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
const numNodes = 2
var maintainStreamsForBrokenRaftTransport atomic.Bool
st := cluster.MakeTestingClusterSettings()
// See I13 from kvflowcontrol/doc.go. We disable the raft-transport-break
// mechanism below, and for quiesced ranges, that can effectively disable
// the last-updated mechanism since quiesced ranges aren't being ticked, and
// we only check the last-updated state when ticked. So we disable range
// quiescence.
kvserver.ExpirationLeasesOnly.Override(ctx, &st.SV, true)
kvflowcontrol.Enabled.Override(ctx, &st.SV, true)
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Settings: st,
RaftConfig: base.RaftConfig{
// Suppress timeout-based elections. This test doesn't want to
// deal with leadership changing hands.
RaftElectionTimeoutTicks: 1000000,
// Reduce the RangeLeaseDuration to speeds up failure detection
// below.
RangeLeaseDuration: time.Second,
},
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
V1: kvflowcontrol.TestingKnobsV1{
MaintainStreamsForBrokenRaftTransport: func() bool {
return maintainStreamsForBrokenRaftTransport.Load()
},
},
},
},
AdmissionControl: &admission.TestingKnobs{
DisableWorkQueueFastPath: true,
DisableWorkQueueGranting: func() bool {
return true
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1)...)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("crashed_node")
desc, err := tc.LookupRange(k)
require.NoError(t, err)
tc.TransferRangeLeaseOrFatal(t, desc, tc.Target(0))
h.waitForConnectedStreams(ctx, desc.RangeID, 2, 0 /* serverIdx */)
h.comment(`-- (Issuing regular 5x1MiB, 2x replicated writes that are not admitted.)`)
h.log("sending put requests")
for i := 0; i < 5; i++ {
h.put(ctx, k, 1<<20 /* 1MiB */, admissionpb.NormalPri)
}
h.log("sent put requests")
h.comment(`
-- Flow token metrics from n1 after issuing 5 regular 1MiB 2x replicated writes
-- that are yet to get admitted. We see 5*1MiB*2=10MiB deductions of
-- {regular,elastic} tokens with no corresponding returns.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`-- Observe the per-stream tracked tokens on n1, before n2 is crashed.`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
// In this test we want to see how we integrate with nodes crashing -- we
// want to make sure that we return all held tokens when nodes crash.
// There's a secondary mechanism that would release flow tokens in such
// cases -- we also release tokens when the RaftTransport breaks. We don't
// want that to kick in here, so we disable it first. See
// TestFlowControlRaftTransportBreak where that mechanism is tested instead.
maintainStreamsForBrokenRaftTransport.Store(true)
h.comment(`-- (Crashing n2 but disabling the raft-transport-break token return mechanism.)`)
tc.StopServer(1)
h.waitForConnectedStreams(ctx, desc.RangeID, 1, 0 /* serverIdx */)
h.comment(`
-- Observe the per-stream tracked tokens on n1, after n2 crashed. We're no
-- longer tracking the 5MiB held by n2.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
h.comment(`
-- Flow token metrics from n1 after n2 crashed. Observe that we've returned the
-- 5MiB previously held by n2.
`)
h.query(n1, v1FlowTokensQueryStr)
}
// TestFlowControlRaftSnapshot tests flow token behavior when one replica needs
// to be caught up via raft snapshot.
func TestFlowControlRaftSnapshot(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numServers int = 5
stickyServerArgs := make(map[int]base.TestServerArgs)
var maintainStreamsForBehindFollowers atomic.Bool
var maintainStreamsForInactiveFollowers atomic.Bool
var maintainStreamsForBrokenRaftTransport atomic.Bool
var disableWorkQueueGranting atomic.Bool
disableWorkQueueGranting.Store(true)
ctx := context.Background()
st := cluster.MakeTestingClusterSettings()
kvflowcontrol.Enabled.Override(ctx, &st.SV, true)
kvflowcontrol.Mode.Override(ctx, &st.SV, kvflowcontrol.ApplyToAll)
for i := 0; i < numServers; i++ {
stickyServerArgs[i] = base.TestServerArgs{
Settings: st,
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyVFSID: strconv.FormatInt(int64(i), 10),
},
},
RaftConfig: base.RaftConfig{
// Suppress timeout-based elections. This test doesn't want to
// deal with leadership changing hands.
RaftElectionTimeoutTicks: 1000000,
},
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyVFSRegistry: fs.NewStickyRegistry(),
},
Store: &kvserver.StoreTestingKnobs{
FlowControlTestingKnobs: &kvflowcontrol.TestingKnobs{
UseOnlyForScratchRanges: true,
OverrideV2EnabledWhenLeaderLevel: func() kvflowcontrol.V2EnabledWhenLeaderLevel {
return kvflowcontrol.V2NotEnabledWhenLeader
},
OverrideTokenDeduction: func(_ kvflowcontrol.Tokens) kvflowcontrol.Tokens {
// This test makes use of (small) increment
// requests, but wants to see large token
// deductions/returns.
return kvflowcontrol.Tokens(1 << 20 /* 1MiB */)
},
V1: kvflowcontrol.TestingKnobsV1{
MaintainStreamsForBehindFollowers: func() bool {
return maintainStreamsForBehindFollowers.Load()
},
MaintainStreamsForInactiveFollowers: func() bool {
return maintainStreamsForInactiveFollowers.Load()
},
MaintainStreamsForBrokenRaftTransport: func() bool {
return maintainStreamsForBrokenRaftTransport.Load()
},
},
},
},
AdmissionControl: &admission.TestingKnobs{
DisableWorkQueueFastPath: true,
DisableWorkQueueGranting: func() bool {
return disableWorkQueueGranting.Load()
},
},
RaftTransport: &kvserver.RaftTransportTestingKnobs{
OverrideIdleTimeout: func() time.Duration {
// Effectively disable token returns due to underlying
// raft transport streams disconnecting due to
// inactivity.
return time.Hour
},
},
},
}
}
tc := testcluster.StartTestCluster(t, numServers,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: stickyServerArgs,
})
defer tc.Stopper().Stop(ctx)
n1 := sqlutils.MakeSQLRunner(tc.ServerConn(0))
n4 := sqlutils.MakeSQLRunner(tc.ServerConn(3))
h := newFlowControlTestHelperV1(t, tc)
h.init(kvflowcontrol.ApplyToAll)
defer h.close("raft_snapshot")
store := tc.GetFirstStoreFromServer(t, 0)
incA := int64(5)
incB := int64(7)
incAB := incA + incB
k := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, k, tc.Targets(1, 2)...)
tc.AddVotersOrFatal(t, k, tc.Targets(3, 4)...)
repl := store.LookupReplica(roachpb.RKey(k))
require.NotNil(t, repl)
h.waitForConnectedStreams(ctx, repl.RangeID, 5, 0 /* serverIdx */)
// Set up a key to replicate across the cluster. We're going to modify this
// key and truncate the raft logs from that command after killing one of the
// nodes to check that it gets the new value after it comes up.
incArgs := incrementArgs(k, incA)
if _, err := kv.SendWrappedWithAdmission(ctx, tc.Server(0).DB().NonTransactionalSender(), kvpb.Header{}, kvpb.AdmissionHeader{
Priority: int32(admissionpb.HighPri),
Source: kvpb.AdmissionHeader_FROM_SQL,
}, incArgs); err != nil {
t.Fatal(err)
}
h.comment(`
-- Flow token metrics from n1 after issuing 1 regular 1MiB 5x replicated write
-- that's not admitted. Since this test is ignoring crashed nodes for token
-- deduction purposes, we see a deduction of 5MiB {regular,elastic} tokens.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`
-- Observe the total tracked tokens per-stream on n1. 1MiB is tracked for n1-n5.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
tc.WaitForValues(t, k, []int64{incA, incA, incA, incA, incA})
h.comment(`
-- (Killing n2 and n3, but preventing their tokens from being returned +
-- artificially allowing tokens to get deducted.)`)
// In this test we want to see how we integrate with raft progress state
// when nodes are down long enough to warrant snapshots (post
// log-truncation). We want to do this without responding to the node
// actually being down, which is tested separately in
// TestFlowControlCrashedNode and TestFlowControlRaftTransportBreak.
maintainStreamsForInactiveFollowers.Store(true)
maintainStreamsForBrokenRaftTransport.Store(true)
// Depending on when the raft group gets ticked, we might notice than
// replicas on n2 and n3 are behind a bit too soon. Disable it first, and
// re-enable it right when this test wants to react to raft progress state.
maintainStreamsForBehindFollowers.Store(true)
// Now kill stores 1 + 2, increment the key on the other stores and
// truncate their logs to make sure that when store 1 + 2 comes back up
// they will require a snapshot from Raft.
tc.StopServer(1)
tc.StopServer(2)
h.comment(`
-- Observe the total tracked tokens per-stream on n1. 1MiB is (still) tracked
-- for n1-n5. Typically n2, n3 would release their tokens, but this test is
-- intentionally suppressing that behavior to observe token returns only once
-- issuing a raft snapshot.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
h.comment(`
-- (Issuing another 1MiB of 5x replicated writes while n2 and n3 are down and
-- below-raft admission is paused.)
`)
incArgs = incrementArgs(k, incB)
if _, err := kv.SendWrappedWithAdmission(ctx, tc.Server(0).DB().NonTransactionalSender(), kvpb.Header{}, kvpb.AdmissionHeader{
Priority: int32(admissionpb.HighPri),
Source: kvpb.AdmissionHeader_FROM_SQL,
}, incArgs); err != nil {
t.Fatal(err)
}
h.comment(`
-- Flow token metrics from n1 after issuing 1 regular 1MiB 5x replicated write
-- that's not admitted. We'll have deducted another 5*1MiB=5MiB worth of tokens.
-- Normally we wouldn't deduct tokens for n2 and n3 since they're dead (both
-- according to the per-replica last-updated map, and according broken
-- RaftTransport streams). But this test is intentionally suppressing that
-- behavior to observe token returns when sending raft snapshots.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`
-- Observe the total tracked tokens per-stream on n1. 2MiB is tracked for n1-n5;
-- see last comment for an explanation why we're still deducting for n2, n3.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
tc.WaitForValues(t, k, []int64{incAB, 0 /* stopped */, 0 /* stopped */, incAB, incAB})
index := repl.GetLastIndex()
h.comment(`-- (Truncating raft log.)`)
// Truncate the log at index+1 (log entries < N are removed, so this
// includes the increment).
truncArgs := truncateLogArgs(index+1, repl.GetRangeID())
if _, err := kv.SendWrappedWithAdmission(ctx, tc.Server(0).DB().NonTransactionalSender(), kvpb.Header{}, kvpb.AdmissionHeader{
Priority: int32(admissionpb.HighPri),
Source: kvpb.AdmissionHeader_FROM_SQL,
}, truncArgs); err != nil {
t.Fatal(err)
}
// Allow the flow control integration layer to react to raft progress state.
maintainStreamsForBehindFollowers.Store(false)
h.comment(`-- (Restarting n2 and n3.)`)
require.NoError(t, tc.RestartServer(1))
require.NoError(t, tc.RestartServer(2))
// Go back to the default kvflowcontrol integration behavior.
maintainStreamsForInactiveFollowers.Store(false)
maintainStreamsForBrokenRaftTransport.Store(false)
tc.WaitForValues(t, k, []int64{incAB, incAB, incAB, incAB, incAB})
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 646 adjusted flow tokens (pri=high-pri stream=t1/s2 delta=+1.0 MiB): regular=+16 MiB elastic=+8.0 MiB
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 647 disconnected stream: t1/s2
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 648 tracked disconnected stream: t1/s2 (reason: not actively replicating)
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 705 adjusted flow tokens (pri=high-pri stream=t1/s3 delta=+1.0 MiB): regular=+16 MiB elastic=+8.0 MiB
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 706 disconnected stream: t1/s3
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 707 tracked disconnected stream: t1/s3 (reason: not actively replicating)
h.comment(`
-- Flow token metrics from n1 after restarting n2 and n3. We've returned the
-- 2MiB previously held by those nodes (2MiB each). We're reacting to it's raft
-- progress state, noting that since we've truncated our log, we need to catch
-- it up via snapshot. So we release all held tokens.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`
-- Observe the total tracked tokens per-stream on n1. There's nothing tracked
-- for n2 and n3 anymore.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
WHERE total_tracked_tokens > 0
`, "range_id", "store_id", "total_tracked_tokens")
h.waitForConnectedStreams(ctx, repl.RangeID, 5, 0 /* serverIdx */)
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 651 connected to stream: t1/s2
// [T1,n1,s1,r63/1:/{Table/Max-Max},raft] 710 connected to stream: t1/s3
h.comment(`-- (Allow below-raft admission to proceed.)`)
disableWorkQueueGranting.Store(false)
// Ensure that tokens are returned, the streams stay connected and that the
// tracked tokens goes to 0.
h.waitForConnectedStreams(ctx, repl.RangeID, 5, 0 /* serverIdx */)
h.waitForTotalTrackedTokens(ctx, repl.RangeID, 0 /* 0B */, 0 /* serverIdx */)
h.waitForAllTokensReturned(ctx, 5, 0 /* serverIdx */)
h.comment(`-- Observe flow token dispatch metrics from n4.`)
h.query(n4, `
SELECT name, value
FROM crdb_internal.node_metrics
WHERE name LIKE '%kvadmission.flow_token_dispatch.pending_nodes%'
ORDER BY name ASC;
`)
h.comment(`
-- Flow token metrics from n1 after work gets admitted. We see the remaining
-- 6MiB of {regular,elastic} tokens returned.
`)
h.query(n1, v1FlowTokensQueryStr)
h.comment(`
-- Observe the total tracked tokens per-stream on n1; there should be nothing.
`)
h.query(n1, `
SELECT range_id, store_id, crdb_internal.humanize_bytes(total_tracked_tokens::INT8)
FROM crdb_internal.kv_flow_control_handles
`, "range_id", "store_id", "total_tracked_tokens")
h.comment(`-- Another view of tokens, using /inspectz-backed vtables.`)
h.query(n1, `
SELECT store_id,
crdb_internal.humanize_bytes(available_regular_tokens),
crdb_internal.humanize_bytes(available_elastic_tokens)
FROM crdb_internal.kv_flow_controller
ORDER BY store_id ASC;
`, "store_id", "regular_available", "elastic_available")
}
// TestFlowControlRaftTransportBreak tests flow token behavior when the raft
// transport breaks (due to crashed nodes, in this test).
func TestFlowControlRaftTransportBreak(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()