-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathprocessor_test.go
1616 lines (1440 loc) · 51.6 KB
/
processor_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 2018 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package rangefeed
import (
"bytes"
"context"
"fmt"
"math"
"runtime"
"sort"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestProcessorBasic(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
p, h, stopper := newTestProcessor(t, withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// Test processor without registrations.
require.Equal(t, 0, p.Len())
require.NotPanics(t, func() { p.ConsumeLogicalOps(ctx) })
require.NotPanics(t, func() { p.ConsumeLogicalOps(ctx, []enginepb.MVCCLogicalOp{}...) })
require.NotPanics(t, func() {
txn1, txn2 := uuid.MakeV4(), uuid.MakeV4()
p.ConsumeLogicalOps(ctx,
writeValueOp(hlc.Timestamp{WallTime: 1}),
writeIntentOp(txn1, hlc.Timestamp{WallTime: 2}),
updateIntentOp(txn1, hlc.Timestamp{WallTime: 3}),
commitIntentOp(txn1, hlc.Timestamp{WallTime: 4}),
writeIntentOp(txn2, hlc.Timestamp{WallTime: 5}),
abortIntentOp(txn2))
h.syncEventC()
require.Equal(t, 0, h.rts.intentQ.Len())
})
require.NotPanics(t, func() { p.ForwardClosedTS(ctx, hlc.Timestamp{}) })
require.NotPanics(t, func() { p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 1}) })
// Add a registration.
r1Stream := newTestStream()
r1OK, r1Filter := p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
require.True(t, r1OK)
h.syncEventAndRegistrations()
require.Equal(t, 1, p.Len())
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 1},
),
},
r1Stream.Events(),
)
// Test the processor's operation filter.
require.True(t, r1Filter.NeedVal(roachpb.Span{Key: roachpb.Key("a")}))
require.True(t, r1Filter.NeedVal(roachpb.Span{Key: roachpb.Key("d"), EndKey: roachpb.Key("r")}))
require.False(t, r1Filter.NeedVal(roachpb.Span{Key: roachpb.Key("z")}))
require.False(t, r1Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("a")}))
require.False(t,
r1Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("d"), EndKey: roachpb.Key("r")}))
require.False(t, r1Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("z")}))
// Test checkpoint with one registration.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 5})
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 5},
),
},
r1Stream.Events(),
)
// Test value with one registration.
p.ConsumeLogicalOps(ctx,
writeValueOpWithKV(roachpb.Key("c"), hlc.Timestamp{WallTime: 6}, []byte("val")))
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("c"),
roachpb.Value{
RawBytes: []byte("val"),
Timestamp: hlc.Timestamp{WallTime: 6},
},
),
},
r1Stream.Events(),
)
// Test value to non-overlapping key with one registration.
p.ConsumeLogicalOps(ctx,
writeValueOpWithKV(roachpb.Key("s"), hlc.Timestamp{WallTime: 6}, []byte("val")))
h.syncEventAndRegistrations()
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r1Stream.Events())
// Test intent that is aborted with one registration.
txn1 := uuid.MakeV4()
// Write intent.
p.ConsumeLogicalOps(ctx, writeIntentOp(txn1, hlc.Timestamp{WallTime: 6}))
h.syncEventAndRegistrations()
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r1Stream.Events())
// Abort.
p.ConsumeLogicalOps(ctx, abortIntentOp(txn1))
h.syncEventC()
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r1Stream.Events())
require.Equal(t, 0, h.rts.intentQ.Len())
// Test intent that is committed with one registration.
txn2 := uuid.MakeV4()
// Write intent.
p.ConsumeLogicalOps(ctx, writeIntentOp(txn2, hlc.Timestamp{WallTime: 10}))
h.syncEventAndRegistrations()
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r1Stream.Events())
// Forward closed timestamp. Should now be stuck on intent.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 15})
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 9},
),
},
r1Stream.Events(),
)
// Update the intent. Should forward resolved timestamp.
p.ConsumeLogicalOps(ctx, updateIntentOp(txn2, hlc.Timestamp{WallTime: 12}))
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 11},
),
},
r1Stream.Events(),
)
// Commit intent. Should forward resolved timestamp to closed timestamp.
p.ConsumeLogicalOps(ctx,
commitIntentOpWithKV(txn2, roachpb.Key("e"), hlc.Timestamp{WallTime: 13},
[]byte("ival"), false /* omitInRangefeeds */, 0 /* originID */))
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("e"),
roachpb.Value{
RawBytes: []byte("ival"),
Timestamp: hlc.Timestamp{WallTime: 13},
},
),
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 15},
),
},
r1Stream.Events(),
)
// Add another registration with withDiff = true and withFiltering = true.
r2Stream := newTestStream()
r2OK, r1And2Filter := p.Register(
r2Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("c"), EndKey: roachpb.RKey("z")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
true, /* withDiff */
true, /* withFiltering */
false, /* withOmitRemote */
r2Stream,
func() {},
)
require.True(t, r2OK)
h.syncEventAndRegistrations()
require.Equal(t, 2, p.Len())
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("c"), EndKey: roachpb.Key("z")},
hlc.Timestamp{WallTime: 15},
),
},
r2Stream.Events(),
)
// Test the processor's new operation filter.
require.True(t, r1And2Filter.NeedVal(roachpb.Span{Key: roachpb.Key("a")}))
require.True(t, r1And2Filter.NeedVal(roachpb.Span{Key: roachpb.Key("y")}))
require.True(t,
r1And2Filter.NeedVal(roachpb.Span{Key: roachpb.Key("y"), EndKey: roachpb.Key("zzz")}))
require.False(t, r1And2Filter.NeedVal(roachpb.Span{Key: roachpb.Key("zzz")}))
require.False(t, r1And2Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("a")}))
require.True(t, r1And2Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("y")}))
require.True(t,
r1And2Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("y"), EndKey: roachpb.Key("zzz")}))
require.False(t, r1And2Filter.NeedPrevVal(roachpb.Span{Key: roachpb.Key("zzz")}))
// Both registrations should see checkpoint.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 20})
h.syncEventAndRegistrations()
chEventAM := []*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 20},
),
}
require.Equal(t, chEventAM, r1Stream.Events())
chEventCZ := []*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("c"), EndKey: roachpb.Key("z")},
hlc.Timestamp{WallTime: 20},
),
}
require.Equal(t, chEventCZ, r2Stream.Events())
// Test value with two registration that overlaps both.
p.ConsumeLogicalOps(ctx,
writeValueOpWithKV(roachpb.Key("k"), hlc.Timestamp{WallTime: 22}, []byte("val2")))
h.syncEventAndRegistrations()
valEvent := []*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("k"),
roachpb.Value{
RawBytes: []byte("val2"),
Timestamp: hlc.Timestamp{WallTime: 22},
},
),
}
require.Equal(t, valEvent, r1Stream.Events())
require.Equal(t, valEvent, r2Stream.Events())
// Test value that only overlaps the second registration.
p.ConsumeLogicalOps(ctx,
writeValueOpWithKV(roachpb.Key("v"), hlc.Timestamp{WallTime: 23}, []byte("val3")))
h.syncEventAndRegistrations()
valEvent2 := []*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("v"),
roachpb.Value{
RawBytes: []byte("val3"),
Timestamp: hlc.Timestamp{WallTime: 23},
},
),
}
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r1Stream.Events())
require.Equal(t, valEvent2, r2Stream.Events())
// Test committing intent with OmitInRangefeeds that overlaps two
// registration (one withFiltering = true and one withFiltering = false).
p.ConsumeLogicalOps(ctx,
commitIntentOpWithKV(txn2, roachpb.Key("k"), hlc.Timestamp{WallTime: 22},
[]byte("val3"), true /* omitInRangefeeds */, 0 /* originID */))
h.syncEventAndRegistrations()
valEvent3 := []*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("k"),
roachpb.Value{
RawBytes: []byte("val3"),
Timestamp: hlc.Timestamp{WallTime: 22},
},
),
}
require.Equal(t, valEvent3, r1Stream.Events())
// r2Stream should not see the event.
// Cancel the first registration.
r1Stream.Cancel()
require.NotNil(t, r1Stream.WaitForError(t))
// Disconnect the registration via Disconnect should work.
r3Stream := newTestStream()
r30K, _ := p.Register(
r3Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("c"), EndKey: roachpb.RKey("z")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r3Stream,
func() {},
)
require.True(t, r30K)
r3Stream.Disconnect(kvpb.NewError(fmt.Errorf("disconnection error")))
require.NotNil(t, r3Stream.WaitForError(t))
// Stop the processor with an error.
pErr := kvpb.NewErrorf("stop err")
p.StopWithErr(pErr)
require.NotNil(t, r2Stream.WaitForError(t))
// Adding another registration should fail.
r4Stream := newTestStream()
r4OK, _ := p.Register(
r3Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("c"), EndKey: roachpb.RKey("z")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r4Stream,
func() {},
)
require.False(t, r4OK)
})
}
func TestProcessorOmitRemote(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
p, h, stopper := newTestProcessor(t, withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
require.NotPanics(t, func() { p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 1}) })
// Add a registration.
r1Stream := newTestStream()
r1OK, _ := p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
require.True(t, r1OK)
h.syncEventAndRegistrations()
require.Equal(t, 1, p.Len())
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 1},
),
},
r1Stream.Events(),
)
// Add another registration with withOmitRemote = true.
r2Stream := newTestStream()
r2OK, _ := p.Register(
r2Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
true, /* withOmitRemote */
r2Stream,
func() {},
)
require.True(t, r2OK)
h.syncEventAndRegistrations()
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 1},
),
},
r2Stream.Events(),
)
txn2 := uuid.MakeV4()
p.ConsumeLogicalOps(ctx,
commitIntentOpWithKV(txn2, roachpb.Key("k"), hlc.Timestamp{WallTime: 22},
[]byte("val3"), false /* omitInRangefeeds */, 1))
h.syncEventAndRegistrations()
valEvent3 := []*kvpb.RangeFeedEvent{
rangeFeedValue(
roachpb.Key("k"),
roachpb.Value{
RawBytes: []byte("val3"),
Timestamp: hlc.Timestamp{WallTime: 22},
},
),
}
require.Equal(t, valEvent3, r1Stream.Events())
require.Equal(t, []*kvpb.RangeFeedEvent(nil), r2Stream.Events())
})
}
func TestProcessorSlowConsumer(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
p, h, stopper := newTestProcessor(t, withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// Add a registration.
r1Stream := newTestStream()
_, _ = p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
r2Stream := newTestStream()
p.Register(
r2Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("z")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r2Stream,
func() {},
)
h.syncEventAndRegistrations()
require.Equal(t, 2, p.Len())
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 0},
),
},
r1Stream.Events(),
)
require.Equal(t,
[]*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("z")},
hlc.Timestamp{WallTime: 0},
),
},
r2Stream.Events(),
)
// Block its Send method and fill up the registration's input channel.
unblock := r1Stream.BlockSend()
defer func() {
if unblock != nil {
unblock()
}
}()
// Need one more message to fill the channel because the first one will be
// sent to the stream and block the registration outputLoop goroutine.
toFill := testProcessorEventCCap + 1
for i := 0; i < toFill; i++ {
ts := hlc.Timestamp{WallTime: int64(i + 2)}
p.ConsumeLogicalOps(ctx, writeValueOpWithKV(roachpb.Key("k"), ts, []byte("val")))
// Wait for just the unblocked registration to catch up. This prevents
// the race condition where this registration overflows anyway due to
// the rapid event consumption and small buffer size.
h.syncEventAndRegistrationsSpan(spXY)
}
// Consume one more event. Should not block, but should cause r1 to overflow
// its registration buffer and drop the event.
p.ConsumeLogicalOps(ctx,
writeValueOpWithKV(roachpb.Key("k"), hlc.Timestamp{WallTime: 18}, []byte("val")))
// Wait for just the unblocked registration to catch up.
h.syncEventAndRegistrationsSpan(spXY)
require.Equal(t, toFill+1, len(r2Stream.Events()))
require.Equal(t, 2, p.Len())
// Unblock the send channel. The events should quickly be consumed.
unblock()
unblock = nil
h.syncEventAndRegistrations()
// At least one event should have been dropped due to overflow. We expect
// exactly one event to be dropped, but it is possible that multiple events
// were dropped due to rapid event consumption before the r1's outputLoop
// began consuming from its event buffer.
require.LessOrEqual(t, len(r1Stream.Events()), toFill)
require.Equal(t, newErrBufferCapacityExceeded().GoError(), r1Stream.WaitForError(t))
testutils.SucceedsSoon(t, func() error {
if act, exp := p.Len(), 1; exp != act {
return fmt.Errorf("processor had %d regs, wanted %d", act, exp)
}
return nil
})
})
}
// TestProcessorMemoryBudgetExceeded tests that memory budget will limit amount
// of data buffered for the feed and result in a registration being removed as a
// result of budget exhaustion.
func TestProcessorMemoryBudgetExceeded(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
fb := newTestBudget(40)
m := NewMetrics()
p, h, stopper := newTestProcessor(t, withBudget(fb), withChanTimeout(time.Millisecond),
withMetrics(m), withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// Add a registration.
r1Stream := newTestStream()
_, _ = p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
h.syncEventAndRegistrations()
// Block it.
unblock := r1Stream.BlockSend()
defer func() {
if unblock != nil {
unblock()
}
}()
// Write entries till budget is exhausted
for i := 0; i < 10; i++ {
if !p.ConsumeLogicalOps(ctx, writeValueOpWithKV(
roachpb.Key("k"),
hlc.Timestamp{WallTime: int64(i + 2)},
[]byte(fmt.Sprintf("this is big value %02d", i)))) {
break
}
}
// Ensure that stop event generated by memory budget error is processed.
h.syncEventC()
// Unblock the 'send' channel. The events should quickly be consumed.
unblock()
unblock = nil
h.syncEventAndRegistrations()
require.Equal(t, newErrBufferCapacityExceeded().GoError(), r1Stream.WaitForError(t))
require.Equal(t, 0, p.Len(), "registration was not removed")
require.Equal(t, int64(1), m.RangeFeedBudgetExhausted.Count())
})
}
// TestProcessorMemoryBudgetReleased that memory budget is correctly released.
func TestProcessorMemoryBudgetReleased(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
fb := newTestBudget(250)
p, h, stopper := newTestProcessor(t, withBudget(fb), withChanTimeout(15*time.Minute),
withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// Add a registration.
r1Stream := newTestStream()
p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
h.syncEventAndRegistrations()
// Write entries and check they are consumed so that we could write more
// data than total budget if inflight messages are within budget.
const eventCount = 10
for i := 0; i < eventCount; i++ {
p.ConsumeLogicalOps(ctx, writeValueOpWithKV(
roachpb.Key("k"),
hlc.Timestamp{WallTime: int64(i + 2)},
[]byte("value")))
}
h.syncEventAndRegistrations()
// Count consumed values
consumedOps := 0
for _, e := range r1Stream.Events() {
if e.Val != nil {
consumedOps++
}
}
require.Equal(t, 1, p.Len(), "registration was removed")
require.Equal(t, 10, consumedOps)
})
}
// TestIntentScannerOnError tests that when a processor is given with an intent
// scanner constructor that fails to create a scanner, the processor will fail
// to start gracefully. Regression for #127204.
func TestIntentScannerOnError(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
cfg := testConfig{
Config: Config{
RangeID: 2,
Stopper: stopper,
Span: roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("z")},
Metrics: NewMetrics(),
Priority: true,
},
}
sch := NewScheduler(SchedulerConfig{
Workers: 1,
PriorityWorkers: 1,
Metrics: NewSchedulerMetrics(time.Second),
})
require.NoError(t, sch.Start(ctx, stopper))
cfg.Scheduler = sch
s := NewProcessor(cfg.Config)
require.ErrorContains(t, s.Start(stopper, func() (IntentScanner, error) {
return nil, errors.New("scanner error")
}), "scanner error")
p := (s).(*ScheduledProcessor)
testutils.SucceedsSoon(t, func() error {
select {
case <-p.stoppedC:
_, ok := sch.shards[shardIndex(p.ID(), len(sch.shards), p.Priority)].procs[p.ID()]
require.False(t, ok)
require.False(t, sch.priorityIDs.Contains(p.ID()))
return nil
default:
return errors.New("processor not stopped")
}
})
}
// TestProcessorInitializeResolvedTimestamp tests that when a Processor is given
// a resolved timestamp iterator, it doesn't initialize its resolved timestamp
// until it has consumed all intents in the iterator.
func TestProcessorInitializeResolvedTimestamp(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
txn1 := makeTxn("txn1", uuid.MakeV4(), isolation.Serializable, hlc.Timestamp{})
txn2 := makeTxn("txn2", uuid.MakeV4(), isolation.Serializable, hlc.Timestamp{})
txnWithTs := func(txn roachpb.Transaction, ts int64) *roachpb.Transaction {
txnTs := hlc.Timestamp{WallTime: ts}
txn.TxnMeta.MinTimestamp = txnTs
txn.TxnMeta.WriteTimestamp = txnTs
txn.ReadTimestamp = txnTs
return &txn
}
data := []storeOp{
{kv: makeKV("a", "val1", 10)},
{kv: makeKV("c", "val4", 9)},
{kv: makeKV("c", "val3", 11)},
{kv: makeProvisionalKV("c", "txnKey1", 15), txn: txnWithTs(txn1, 15)},
{kv: makeKV("d", "val6", 19)},
{kv: makeKV("d", "val5", 20)},
{kv: makeProvisionalKV("d", "txnKey2", 21), txn: txnWithTs(txn2, 21)},
{kv: makeKV("m", "val8", 1)},
{kv: makeProvisionalKV("n", "txnKey1", 12), txn: txnWithTs(txn1, 12)},
{kv: makeKV("r", "val9", 4)},
{kv: makeProvisionalKV("r", "txnKey1", 19), txn: txnWithTs(txn1, 19)},
{kv: makeProvisionalKV("w", "txnKey1", 3), txn: txnWithTs(txn1, 3)},
{kv: makeKV("z", "val11", 4)},
{kv: makeProvisionalKV("z", "txnKey2", 21), txn: txnWithTs(txn2, 21)},
}
scanner, cleanup, err := makeIntentScanner(data, roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("zz")})
require.NoError(t, err, "failed to prepare test data")
defer cleanup()
p, h, stopper := newTestProcessor(t, withRtsScanner(scanner), withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// The resolved timestamp should not be initialized.
require.False(t, h.rts.IsInit())
require.Equal(t, hlc.Timestamp{}, h.rts.Get())
// Add a registration.
r1Stream := newTestStream()
p.Register(
r1Stream.ctx,
roachpb.RSpan{Key: roachpb.RKey("a"), EndKey: roachpb.RKey("m")},
hlc.Timestamp{WallTime: 1},
nil, /* catchUpIter */
false, /* withDiff */
false, /* withFiltering */
false, /* withOmitRemote */
r1Stream,
func() {},
)
h.syncEventAndRegistrations()
require.Equal(t, 1, p.Len())
// The registration should be provided a checkpoint immediately with an
// empty resolved timestamp because it did not perform a catch-up scan.
chEvent := []*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{},
),
}
require.Equal(t, chEvent, r1Stream.Events())
// The resolved timestamp should still not be initialized.
require.False(t, h.rts.IsInit())
require.Equal(t, hlc.Timestamp{}, h.rts.Get())
// Forward the closed timestamp. The resolved timestamp should still
// not be initialized.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 20})
require.False(t, h.rts.IsInit())
require.Equal(t, hlc.Timestamp{}, h.rts.Get())
// Let the scan proceed.
close(scanner.block)
<-scanner.done
// Synchronize the event channel then verify that the resolved timestamp is
// initialized and that it's blocked on the oldest unresolved intent's txn
// timestamp. Txn1 has intents at many times but the unresolvedIntentQueue
// tracks its latest, which is 19, so the resolved timestamp is
// 19.FloorPrev() = 18.
h.syncEventAndRegistrations()
require.True(t, h.rts.IsInit())
require.Equal(t, hlc.Timestamp{WallTime: 18}, h.rts.Get())
// The registration should have been informed of the new resolved timestamp.
chEvent = []*kvpb.RangeFeedEvent{
rangeFeedCheckpoint(
roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("m")},
hlc.Timestamp{WallTime: 18},
),
}
require.Equal(t, chEvent, r1Stream.Events())
})
}
func TestProcessorTxnPushAttempt(t *testing.T) {
defer leaktest.AfterTest(t)()
testutils.RunValues(t, "feed type", testTypes, func(t *testing.T, rt rangefeedTestType) {
ts10 := hlc.Timestamp{WallTime: 10}
ts20 := hlc.Timestamp{WallTime: 20}
ts25 := hlc.Timestamp{WallTime: 25}
ts30 := hlc.Timestamp{WallTime: 30}
ts50 := hlc.Timestamp{WallTime: 50}
ts60 := hlc.Timestamp{WallTime: 60}
ts70 := hlc.Timestamp{WallTime: 70}
ts90 := hlc.Timestamp{WallTime: 90}
// Create a set of transactions.
txn1, txn2, txn3 := uuid.MakeV4(), uuid.MakeV4(), uuid.MakeV4()
txn1Meta := enginepb.TxnMeta{ID: txn1, Key: keyA, IsoLevel: isolation.Serializable, WriteTimestamp: ts10, MinTimestamp: ts10}
txn2Meta := enginepb.TxnMeta{ID: txn2, Key: keyB, IsoLevel: isolation.Snapshot, WriteTimestamp: ts20, MinTimestamp: ts20}
txn3Meta := enginepb.TxnMeta{ID: txn3, Key: keyC, IsoLevel: isolation.ReadCommitted, WriteTimestamp: ts30, MinTimestamp: ts30}
txn1Proto := &roachpb.Transaction{TxnMeta: txn1Meta, Status: roachpb.PENDING}
txn2Proto := &roachpb.Transaction{TxnMeta: txn2Meta, Status: roachpb.PENDING}
txn3Proto := &roachpb.Transaction{TxnMeta: txn3Meta, Status: roachpb.PENDING}
// Modifications for test 2.
txn1MetaT2Pre := enginepb.TxnMeta{ID: txn1, Key: keyA, IsoLevel: isolation.Serializable, WriteTimestamp: ts25, MinTimestamp: ts10}
txn1MetaT2Post := enginepb.TxnMeta{ID: txn1, Key: keyA, IsoLevel: isolation.Serializable, WriteTimestamp: ts50, MinTimestamp: ts10}
txn2MetaT2Post := enginepb.TxnMeta{ID: txn2, Key: keyB, IsoLevel: isolation.Snapshot, WriteTimestamp: ts60, MinTimestamp: ts20}
txn3MetaT2Post := enginepb.TxnMeta{ID: txn3, Key: keyC, IsoLevel: isolation.ReadCommitted, WriteTimestamp: ts70, MinTimestamp: ts30}
txn1ProtoT2 := &roachpb.Transaction{TxnMeta: txn1MetaT2Post, Status: roachpb.COMMITTED}
txn2ProtoT2 := &roachpb.Transaction{TxnMeta: txn2MetaT2Post, Status: roachpb.PENDING}
txn3ProtoT2 := &roachpb.Transaction{TxnMeta: txn3MetaT2Post, Status: roachpb.PENDING}
// Modifications for test 3.
txn2MetaT3Post := enginepb.TxnMeta{ID: txn2, Key: keyB, IsoLevel: isolation.Snapshot, WriteTimestamp: ts60, MinTimestamp: ts20}
txn3MetaT3Post := enginepb.TxnMeta{ID: txn3, Key: keyC, IsoLevel: isolation.ReadCommitted, WriteTimestamp: ts90, MinTimestamp: ts30}
txn2ProtoT3 := &roachpb.Transaction{TxnMeta: txn2MetaT3Post, Status: roachpb.ABORTED}
txn3ProtoT3 := &roachpb.Transaction{TxnMeta: txn3MetaT3Post, Status: roachpb.PENDING}
testNum := 0
pausePushAttemptsC := make(chan struct{})
resumePushAttemptsC := make(chan struct{})
defer close(pausePushAttemptsC)
defer close(resumePushAttemptsC)
// Create a TxnPusher that performs assertions during the first 3 uses.
var tp testTxnPusher
tp.mockPushTxns(func(
ctx context.Context, txns []enginepb.TxnMeta, ts hlc.Timestamp,
) ([]*roachpb.Transaction, bool, error) {
// The txns are not in a sorted order. Enforce one.
sort.Slice(txns, func(i, j int) bool {
return bytes.Compare(txns[i].Key, txns[j].Key) < 0
})
testNum++
switch testNum {
case 1:
assert.Equal(t, 3, len(txns))
assert.Equal(t, txn1Meta, txns[0])
assert.Equal(t, txn2Meta, txns[1])
assert.Equal(t, txn3Meta, txns[2])
if t.Failed() {
return nil, false, errors.New("test failed")
}
// Push does not succeed. Protos not at larger ts.
return []*roachpb.Transaction{txn1Proto, txn2Proto, txn3Proto}, false, nil
case 2:
assert.Equal(t, 3, len(txns))
assert.Equal(t, txn1MetaT2Pre, txns[0])
assert.Equal(t, txn2Meta, txns[1])
assert.Equal(t, txn3Meta, txns[2])
if t.Failed() {
return nil, false, errors.New("test failed")
}
// Push succeeds. Return new protos.
return []*roachpb.Transaction{txn1ProtoT2, txn2ProtoT2, txn3ProtoT2}, false, nil
case 3:
assert.Equal(t, 2, len(txns))
assert.Equal(t, txn2MetaT2Post, txns[0])
assert.Equal(t, txn3MetaT2Post, txns[1])
if t.Failed() {
return nil, false, errors.New("test failed")
}
// Push succeeds. Return new protos.
return []*roachpb.Transaction{txn2ProtoT3, txn3ProtoT3}, false, nil
default:
return nil, false, nil
}
})
tp.mockResolveIntentsFn(func(ctx context.Context, intents []roachpb.LockUpdate) error {
// There's nothing to assert here. We expect the intents to correspond to
// transactions that had their LockSpans populated when we pushed them. This
// test doesn't simulate that.
if testNum > 3 {
return nil
}
pausePushAttemptsC <- struct{}{}
<-resumePushAttemptsC
return nil
})
p, h, stopper := newTestProcessor(t, withPusher(&tp), withRangefeedTestType(rt))
ctx := context.Background()
defer stopper.Stop(ctx)
// Add a few intents and move the closed timestamp forward.
p.ConsumeLogicalOps(ctx,
writeIntentOpFromMeta(txn1Meta),
writeIntentOpFromMeta(txn2Meta),
writeIntentOpFromMeta(txn2Meta),
writeIntentOpFromMeta(txn3Meta),
)
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 40})
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 9}, h.rts.Get())
// Wait for the first txn push attempt to complete.
h.triggerTxnPushUntilPushed(t, pausePushAttemptsC)
// The resolved timestamp hasn't moved.
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 9}, h.rts.Get())
// Write another intent for one of the txns. This moves the resolved
// timestamp forward.
p.ConsumeLogicalOps(ctx, writeIntentOpFromMeta(txn1MetaT2Pre))
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 19}, h.rts.Get())
// Unblock the second txn push attempt and wait for it to complete.
resumePushAttemptsC <- struct{}{}
h.triggerTxnPushUntilPushed(t, pausePushAttemptsC)
// The resolved timestamp should have moved forwards to the closed
// timestamp.
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 40}, h.rts.Get())
// Forward the closed timestamp.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 80})
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 49}, h.rts.Get())
// Txn1's first intent is committed. Resolved timestamp doesn't change.
p.ConsumeLogicalOps(ctx, commitIntentOp(txn1MetaT2Post.ID, txn1MetaT2Post.WriteTimestamp))
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 49}, h.rts.Get())
// Txn1's second intent is committed. Resolved timestamp moves forward.
p.ConsumeLogicalOps(ctx, commitIntentOp(txn1MetaT2Post.ID, txn1MetaT2Post.WriteTimestamp))
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 59}, h.rts.Get())
// Unblock the third txn push attempt and wait for it to complete.
resumePushAttemptsC <- struct{}{}
h.triggerTxnPushUntilPushed(t, pausePushAttemptsC)
// The resolved timestamp should have moved forwards to the closed
// timestamp.
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 80}, h.rts.Get())
// Forward the closed timestamp.
p.ForwardClosedTS(ctx, hlc.Timestamp{WallTime: 100})
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 89}, h.rts.Get())
// Commit txn3's only intent. Resolved timestamp moves forward.
p.ConsumeLogicalOps(ctx, commitIntentOp(txn3MetaT3Post.ID, txn3MetaT3Post.WriteTimestamp))
h.syncEventC()
require.Equal(t, hlc.Timestamp{WallTime: 100}, h.rts.Get())
// Release push attempt to avoid deadlock.
resumePushAttemptsC <- struct{}{}
})
}
// TestProcessorTxnPushDisabled tests that processors don't attempt txn pushes
// when disabled.
func TestProcessorTxnPushDisabled(t *testing.T) {
defer leaktest.AfterTest(t)()
const pushInterval = 10 * time.Millisecond
// Set up a txn to write intents.
ts := hlc.Timestamp{WallTime: 10}
txnID := uuid.MakeV4()
txnMeta := enginepb.TxnMeta{
ID: txnID,
Key: keyA,
IsoLevel: isolation.Serializable,
WriteTimestamp: ts,
MinTimestamp: ts,
}
// Disable txn pushes.
ctx := context.Background()
st := cluster.MakeTestingClusterSettings()
PushTxnsEnabled.Override(ctx, &st.SV, false)
// Set up a txn pusher and processor that errors on any pushes.
//
// TODO(kv): We don't test the scheduled processor here, since the setting
// instead controls the Store.startRangefeedTxnPushNotifier() loop which sits
// outside of the processor and can't be tested with this test harness. Write
// a new test when the legacy processor is removed and the scheduled processor
// is used by default.
var tp testTxnPusher
tp.mockPushTxns(func(ctx context.Context, txns []enginepb.TxnMeta, ts hlc.Timestamp) ([]*roachpb.Transaction, bool, error) {
err := errors.Errorf("unexpected txn push for txns=%v ts=%s", txns, ts)
t.Errorf("%v", err)