-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathtxn_coord_sender_test.go
2394 lines (2170 loc) · 74.6 KB
/
txn_coord_sender_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kvcoord
import (
"bytes"
"context"
"fmt"
"reflect"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/kvclientutils"
"github.com/cockroachdb/cockroach/pkg/testutils/localtestcluster"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
// createTestDB creates a local test server and starts it. The caller
// is responsible for stopping the test server.
func createTestDB(t testing.TB) *localtestcluster.LocalTestCluster {
return createTestDBWithKnobs(t, nil)
}
func createTestDBWithKnobs(
t testing.TB, knobs *kvserver.StoreTestingKnobs,
) *localtestcluster.LocalTestCluster {
s := &localtestcluster.LocalTestCluster{
StoreTestingKnobs: knobs,
}
s.Start(t, testutils.NewNodeTestBaseContext(), InitFactoryForLocalTestCluster)
return s
}
// makeTS creates a new timestamp.
func makeTS(walltime int64, logical int32) hlc.Timestamp {
return hlc.Timestamp{
WallTime: walltime,
Logical: logical,
}
}
// TestTxnCoordSenderBeginTransaction verifies that a command sent with a
// not-nil Txn with empty ID gets a new transaction initialized.
func TestTxnCoordSenderBeginTransaction(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
// Put request will create a new transaction.
key := roachpb.Key("key")
txn.TestingSetPriority(10)
txn.SetDebugName("test txn")
if err := txn.Put(ctx, key, []byte("value")); err != nil {
t.Fatal(err)
}
proto := txn.TestingCloneTxn()
if proto.Name != "test txn" {
t.Errorf("expected txn name to be %q; got %q", "test txn", proto.Name)
}
if proto.Priority != 10 {
t.Errorf("expected txn priority 10; got %d", proto.Priority)
}
if !bytes.Equal(proto.Key, key) {
t.Errorf("expected txn Key to match %q != %q", key, proto.Key)
}
}
// TestTxnCoordSenderKeyRanges verifies that multiple requests to same or
// overlapping key ranges causes the coordinator to keep track only of
// the minimum number of ranges.
func TestTxnCoordSenderKeyRanges(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
ranges := []struct {
start, end roachpb.Key
}{
{roachpb.Key("a"), roachpb.Key(nil)},
{roachpb.Key("a"), roachpb.Key(nil)},
{roachpb.Key("aa"), roachpb.Key(nil)},
{roachpb.Key("b"), roachpb.Key(nil)},
{roachpb.Key("aa"), roachpb.Key("c")},
{roachpb.Key("b"), roachpb.Key("c")},
}
s := createTestDB(t)
defer s.Stop()
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
// Disable txn pipelining so that all write spans are immediately
// added to the transaction's lock footprint.
if err := txn.DisablePipelining(); err != nil {
t.Fatal(err)
}
tc := txn.Sender().(*TxnCoordSender)
for _, rng := range ranges {
if rng.end != nil {
if err := txn.DelRange(ctx, rng.start, rng.end); err != nil {
t.Fatal(err)
}
} else {
if err := txn.Put(ctx, rng.start, []byte("value")); err != nil {
t.Fatal(err)
}
}
}
// Verify that the transaction coordinator is only tracking two lock
// spans. "a" and range "aa"-"c".
tc.interceptorAlloc.txnPipeliner.lockFootprint.mergeAndSort()
lockSpans := tc.interceptorAlloc.txnPipeliner.lockFootprint.asSlice()
if len(lockSpans) != 2 {
t.Errorf("expected 2 entries in keys range group; got %v", lockSpans)
}
}
// TestTxnCoordSenderCondenseLockSpans verifies that lock spans are condensed
// along range boundaries when they exceed the maximum intent bytes threshold.
func TestTxnCoordSenderCondenseLockSpans(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
a := roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key(nil)}
b := roachpb.Span{Key: roachpb.Key("b"), EndKey: roachpb.Key(nil)}
c := roachpb.Span{Key: roachpb.Key("c"), EndKey: roachpb.Key(nil)}
d := roachpb.Span{Key: roachpb.Key("dddddd"), EndKey: roachpb.Key(nil)}
e := roachpb.Span{Key: roachpb.Key("e"), EndKey: roachpb.Key(nil)}
aToBClosed := roachpb.Span{Key: roachpb.Key("a"), EndKey: roachpb.Key("b").Next()}
cToEClosed := roachpb.Span{Key: roachpb.Key("c"), EndKey: roachpb.Key("e").Next()}
fTof0 := roachpb.Span{Key: roachpb.Key("f"), EndKey: roachpb.Key("f0")}
g := roachpb.Span{Key: roachpb.Key("g"), EndKey: roachpb.Key(nil)}
g0Tog1 := roachpb.Span{Key: roachpb.Key("g0"), EndKey: roachpb.Key("g1")}
fTog1Closed := roachpb.Span{Key: roachpb.Key("f"), EndKey: roachpb.Key("g1")}
testCases := []struct {
span roachpb.Span
expLocks []roachpb.Span
expLocksSize int64
}{
{span: a, expLocks: []roachpb.Span{a}, expLocksSize: 1},
{span: b, expLocks: []roachpb.Span{a, b}, expLocksSize: 2},
{span: c, expLocks: []roachpb.Span{a, b, c}, expLocksSize: 3},
{span: d, expLocks: []roachpb.Span{a, b, c, d}, expLocksSize: 9},
// Note that c-e condenses and then lists first.
{span: e, expLocks: []roachpb.Span{cToEClosed, a, b}, expLocksSize: 5},
{span: fTof0, expLocks: []roachpb.Span{cToEClosed, a, b, fTof0}, expLocksSize: 8},
{span: g, expLocks: []roachpb.Span{cToEClosed, a, b, fTof0, g}, expLocksSize: 9},
{span: g0Tog1, expLocks: []roachpb.Span{fTog1Closed, cToEClosed, aToBClosed}, expLocksSize: 9},
// Add a key in the middle of a span, which will get merged on commit.
{span: c, expLocks: []roachpb.Span{aToBClosed, cToEClosed, fTog1Closed}, expLocksSize: 9},
}
splits := []roachpb.Span{
{Key: roachpb.Key("a"), EndKey: roachpb.Key("c")},
{Key: roachpb.Key("c"), EndKey: roachpb.Key("f")},
{Key: roachpb.Key("f"), EndKey: roachpb.Key("j")},
}
descs := []roachpb.RangeDescriptor{testMetaRangeDescriptor}
for i, s := range splits {
descs = append(descs, roachpb.RangeDescriptor{
RangeID: roachpb.RangeID(2 + i),
StartKey: roachpb.RKey(s.Key),
EndKey: roachpb.RKey(s.EndKey),
InternalReplicas: []roachpb.ReplicaDescriptor{{NodeID: 1, StoreID: 1}},
})
}
descDB := mockRangeDescriptorDBForDescs(descs...)
s := createTestDB(t)
st := s.Store.ClusterSettings()
trackedWritesMaxSize.Override(&st.SV, 10) /* 10 bytes and it will condense */
defer s.Stop()
// Check end transaction locks, which should be condensed and split
// at range boundaries.
expLocks := []roachpb.Span{aToBClosed, cToEClosed, fTog1Closed}
sendFn := func(_ context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, error) {
resp := ba.CreateReply()
resp.Txn = ba.Txn
if req, ok := ba.GetArg(roachpb.EndTxn); ok {
if !req.(*roachpb.EndTxnRequest).Commit {
t.Errorf("expected commit to be true")
}
et := req.(*roachpb.EndTxnRequest)
if a, e := et.LockSpans, expLocks; !reflect.DeepEqual(a, e) {
t.Errorf("expected end transaction to have locks %+v; got %+v", e, a)
}
resp.Txn.Status = roachpb.COMMITTED
}
return resp, nil
}
ambient := log.AmbientContext{Tracer: tracing.NewTracer()}
ds := NewDistSender(DistSenderConfig{
AmbientCtx: ambient,
Clock: s.Clock,
NodeDescs: s.Gossip,
RPCContext: s.Cfg.RPCContext,
TestingKnobs: ClientTestingKnobs{
TransportFactory: adaptSimpleTransport(sendFn),
},
RangeDescriptorDB: descDB,
Settings: cluster.MakeTestingClusterSettings(),
})
tsf := NewTxnCoordSenderFactory(
TxnCoordSenderFactoryConfig{
AmbientCtx: ambient,
Settings: st,
Clock: s.Clock,
Stopper: s.Stopper(),
},
ds,
)
db := kv.NewDB(ambient, tsf, s.Clock, s.Stopper())
ctx := context.Background()
txn := kv.NewTxn(ctx, db, 0 /* gatewayNodeID */)
// Disable txn pipelining so that all write spans are immediately
// added to the transaction's lock footprint.
if err := txn.DisablePipelining(); err != nil {
t.Fatal(err)
}
for i, tc := range testCases {
if tc.span.EndKey != nil {
if err := txn.DelRange(ctx, tc.span.Key, tc.span.EndKey); err != nil {
t.Fatal(err)
}
} else {
if err := txn.Put(ctx, tc.span.Key, []byte("value")); err != nil {
t.Fatal(err)
}
}
tcs := txn.Sender().(*TxnCoordSender)
locks := tcs.interceptorAlloc.txnPipeliner.lockFootprint.asSlice()
if a, e := locks, tc.expLocks; !reflect.DeepEqual(a, e) {
t.Errorf("%d: expected keys %+v; got %+v", i, e, a)
}
locksSize := int64(0)
for _, i := range locks {
locksSize += int64(len(i.Key) + len(i.EndKey))
}
if a, e := locksSize, tc.expLocksSize; a != e {
t.Errorf("%d: keys size expected %d; got %d", i, e, a)
}
}
if err := txn.Commit(ctx); err != nil {
t.Fatal(err)
}
}
// Test that the theartbeat loop detects aborted transactions and stops.
func TestTxnCoordSenderHeartbeat(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDBWithKnobs(t, &kvserver.StoreTestingKnobs{
DisableScanner: true,
DisableSplitQueue: true,
DisableMergeQueue: true,
})
defer s.Stop()
ctx := context.Background()
keyA := roachpb.Key("a")
keyC := roachpb.Key("c")
splitKey := roachpb.Key("b")
if err := s.DB.AdminSplit(ctx, splitKey /* splitKey */, hlc.MaxTimestamp /* expirationTimestamp */); err != nil {
t.Fatal(err)
}
// Make a db with a short heartbeat interval.
ambient := log.AmbientContext{Tracer: tracing.NewTracer()}
tsf := NewTxnCoordSenderFactory(
TxnCoordSenderFactoryConfig{
AmbientCtx: ambient,
// Short heartbeat interval.
HeartbeatInterval: time.Millisecond,
Settings: s.Cfg.Settings,
Clock: s.Clock,
Stopper: s.Stopper(),
},
NewDistSenderForLocalTestCluster(
s.Cfg.Settings, &roachpb.NodeDescriptor{NodeID: 1},
ambient.Tracer, s.Clock, s.Latency, s.Stores, s.Stopper(), s.Gossip,
),
)
quickHeartbeatDB := kv.NewDB(ambient, tsf, s.Clock, s.Stopper())
// We're going to test twice. In both cases the heartbeat is supposed to
// notice that its transaction is aborted, but:
// - once the abort span is populated on the txn's range.
// - once the abort span is not populated.
// The two conditions are created by either clearing an intent from the txn's
// range or not (i.e. clearing an intent from another range).
// The difference is supposed to be immaterial for the heartbeat loop (that's
// what we're testing). As of June 2018, HeartbeatTxnRequests don't check the
// abort span.
for _, pusherKey := range []roachpb.Key{keyA, keyC} {
t.Run(fmt.Sprintf("pusher:%s", pusherKey), func(t *testing.T) {
// Make a db with a short heartbeat interval.
initialTxn := kv.NewTxn(ctx, quickHeartbeatDB, 0 /* gatewayNodeID */)
tc := initialTxn.Sender().(*TxnCoordSender)
if err := initialTxn.Put(ctx, keyA, []byte("value")); err != nil {
t.Fatal(err)
}
if err := initialTxn.Put(ctx, keyC, []byte("value")); err != nil {
t.Fatal(err)
}
// Verify 3 heartbeats.
var heartbeatTS hlc.Timestamp
for i := 0; i < 3; i++ {
testutils.SucceedsSoon(t, func() error {
txn, pErr := getTxn(ctx, initialTxn)
if pErr != nil {
t.Fatal(pErr)
}
// Advance clock by 1ns.
s.Manual.Increment(1)
if lastActive := txn.LastActive(); heartbeatTS.Less(lastActive) {
heartbeatTS = lastActive
return nil
}
return errors.Errorf("expected heartbeat")
})
}
// Push our txn with another high-priority txn.
{
if err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
if err := txn.SetUserPriority(roachpb.MaxUserPriority); err != nil {
return err
}
return txn.Put(ctx, pusherKey, []byte("pusher val"))
}); err != nil {
t.Fatal(err)
}
}
// Verify that the abort is discovered and the heartbeat discontinued.
// This relies on the heartbeat loop stopping once it figures out that the txn
// has been aborted.
testutils.SucceedsSoon(t, func() error {
if tc.IsTracking() {
return fmt.Errorf("transaction is not aborted")
}
return nil
})
// Trying to do something else should give us a TransactionAbortedError.
_, err := initialTxn.Get(ctx, "a")
assertTransactionAbortedError(t, err)
})
}
}
// getTxn fetches the requested key and returns the transaction info.
func getTxn(ctx context.Context, txn *kv.Txn) (*roachpb.Transaction, *roachpb.Error) {
txnMeta := txn.TestingCloneTxn().TxnMeta
qt := &roachpb.QueryTxnRequest{
RequestHeader: roachpb.RequestHeader{
Key: txnMeta.Key,
},
Txn: txnMeta,
}
ba := roachpb.BatchRequest{}
ba.Timestamp = txnMeta.WriteTimestamp
ba.Add(qt)
db := txn.DB()
sender := db.NonTransactionalSender()
br, pErr := sender.Send(ctx, ba)
if pErr != nil {
return nil, pErr
}
return &br.Responses[0].GetInner().(*roachpb.QueryTxnResponse).QueriedTxn, nil
}
func verifyCleanup(key roachpb.Key, eng storage.Engine, t *testing.T, coords ...*TxnCoordSender) {
testutils.SucceedsSoon(t, func() error {
for _, coord := range coords {
if coord.IsTracking() {
return fmt.Errorf("expected no heartbeat")
}
}
meta := &enginepb.MVCCMetadata{}
//lint:ignore SA1019 historical usage of deprecated eng.MVCCGetProto is OK
ok, _, _, err := eng.MVCCGetProto(storage.MakeMVCCMetadataKey(key), meta)
if err != nil {
return fmt.Errorf("error getting MVCC metadata: %s", err)
}
if ok && meta.Txn != nil {
return fmt.Errorf("found unexpected write intent: %s", meta)
}
return nil
})
}
// TestTxnCoordSenderEndTxn verifies that ending a transaction
// sends resolve write intent requests.
func TestTxnCoordSenderEndTxn(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
// 4 cases: no deadline, past deadline, equal deadline, future deadline.
for i := 0; i < 4; i++ {
key := roachpb.Key("key: " + strconv.Itoa(i))
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
// Initialize the transaction.
if pErr := txn.Put(ctx, key, []byte("value")); pErr != nil {
t.Fatal(pErr)
}
// Conflicting transaction that pushes the above transaction.
conflictTxn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
conflictTxn.TestingSetPriority(enginepb.MaxTxnPriority)
if _, pErr := conflictTxn.Get(ctx, key); pErr != nil {
t.Fatal(pErr)
}
// The transaction was pushed at least to conflictTxn's timestamp (but
// it could have been pushed more - the push takes a timestamp off the
// HLC).
pusheeTxn, pErr := getTxn(ctx, txn)
if pErr != nil {
t.Fatal(pErr)
}
pushedTimestamp := pusheeTxn.WriteTimestamp
{
var err error
switch i {
case 0:
// No deadline.
case 1:
// Past deadline.
if !txn.UpdateDeadlineMaybe(ctx, pushedTimestamp.Prev()) {
t.Fatalf("did not update deadline")
}
case 2:
// Equal deadline.
if !txn.UpdateDeadlineMaybe(ctx, pushedTimestamp) {
t.Fatalf("did not update deadline")
}
case 3:
// Future deadline.
if !txn.UpdateDeadlineMaybe(ctx, pushedTimestamp.Next()) {
t.Fatalf("did not update deadline")
}
}
err = txn.CommitOrCleanup(ctx)
switch i {
case 0:
// No deadline.
if err != nil {
t.Fatal(err)
}
case 1:
// Past deadline.
fallthrough
case 2:
// Equal deadline.
assertTransactionRetryError(t, err)
if !testutils.IsError(err, "RETRY_COMMIT_DEADLINE_EXCEEDED") {
t.Fatalf("expected deadline exceeded, got: %s", err)
}
case 3:
// Future deadline.
if err != nil {
t.Fatal(err)
}
}
}
verifyCleanup(key, s.Eng, t, txn.Sender().(*TxnCoordSender))
}
}
// TestTxnCoordSenderAddLockOnError verifies that locks are tracked if the
// transaction is, even on error.
func TestTxnCoordSenderAddLockOnError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
// Create a transaction with intent at "x".
key := roachpb.Key("x")
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
tc := txn.Sender().(*TxnCoordSender)
// Write so that the coordinator begins tracking this txn.
if err := txn.Put(ctx, "x", "y"); err != nil {
t.Fatal(err)
}
{
err := txn.CPut(ctx, key, []byte("x"), kvclientutils.StrToCPutExistingValue("born to fail"))
if !errors.HasType(err, (*roachpb.ConditionFailedError)(nil)) {
t.Fatal(err)
}
}
tc.interceptorAlloc.txnPipeliner.lockFootprint.mergeAndSort()
lockSpans := tc.interceptorAlloc.txnPipeliner.lockFootprint.asSlice()
expSpans := []roachpb.Span{{Key: key, EndKey: []byte("")}}
equal := !reflect.DeepEqual(lockSpans, expSpans)
if err := txn.Rollback(ctx); err != nil {
t.Fatal(err)
}
if !equal {
t.Fatalf("expected stored locks %v, got %v", expSpans, lockSpans)
}
}
func assertTransactionRetryError(t *testing.T, e error) {
t.Helper()
if retErr := (*roachpb.TransactionRetryWithProtoRefreshError)(nil); errors.As(e, &retErr) {
if !testutils.IsError(retErr, "TransactionRetryError") {
t.Fatalf("expected the cause to be TransactionRetryError, but got %s",
retErr)
}
} else {
t.Fatalf("expected a retryable error, but got %s (%T)", e, e)
}
}
func assertTransactionAbortedError(t *testing.T, e error) {
if retErr := (*roachpb.TransactionRetryWithProtoRefreshError)(nil); errors.As(e, &retErr) {
if !testutils.IsError(retErr, "TransactionAbortedError") {
t.Fatalf("expected the cause to be TransactionAbortedError, but got %s",
retErr)
}
} else {
t.Fatalf("expected a retryable error, but got %s (%T)", e, e)
}
}
// TestTxnCoordSenderCleanupOnAborted verifies that if a txn receives a
// TransactionAbortedError, the coordinator cleans up the transaction.
func TestTxnCoordSenderCleanupOnAborted(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
// Create a transaction with intent at "a".
key := roachpb.Key("a")
txn1 := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
if err := txn1.Put(ctx, key, []byte("value")); err != nil {
t.Fatal(err)
}
// Push the transaction (by writing key "a" with higher priority) to abort it.
txn2 := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
if err := txn2.SetUserPriority(roachpb.MaxUserPriority); err != nil {
t.Fatal(err)
}
if err := txn2.Put(ctx, key, []byte("value2")); err != nil {
t.Fatal(err)
}
// Now end the transaction and verify we've cleanup up, even though
// end transaction failed.
err := txn1.CommitOrCleanup(ctx)
assertTransactionAbortedError(t, err)
if err := txn2.CommitOrCleanup(ctx); err != nil {
t.Fatal(err)
}
verifyCleanup(key, s.Eng, t, txn1.Sender().(*TxnCoordSender), txn2.Sender().(*TxnCoordSender))
}
// TestTxnCoordSenderCleanupOnCommitAfterRestart verifies that if a txn restarts
// at a higher epoch and then commits before it has acquired any locks in the new
// epoch, the coordinator still cleans up the transaction. In #40466, we saw that
// this case could be detected as a 1PC transaction and the cleanup during the
// commit could be omitted.
func TestTxnCoordSenderCleanupOnCommitAfterRestart(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
// Create a transaction with intent at "a".
key := roachpb.Key("a")
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
if err := txn.Put(ctx, key, []byte("value")); err != nil {
t.Fatal(err)
}
// Restart the transaction with a new epoch.
txn.ManualRestart(ctx, s.Clock.Now())
// Now immediately commit.
if err := txn.CommitOrCleanup(ctx); err != nil {
t.Fatal(err)
}
verifyCleanup(key, s.Eng, t, txn.Sender().(*TxnCoordSender))
}
// TestTxnCoordSenderGCWithAmbiguousResultErr verifies that the coordinator
// cleans up extant transactions and locks after an ambiguous result error is
// observed, even if the error is on the first request.
func TestTxnCoordSenderGCWithAmbiguousResultErr(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testutils.RunTrueAndFalse(t, "errOnFirst", func(t *testing.T, errOnFirst bool) {
key := roachpb.Key("a")
are := roachpb.NewAmbiguousResultError("very ambiguous")
knobs := &kvserver.StoreTestingKnobs{
TestingResponseFilter: func(ctx context.Context, ba roachpb.BatchRequest, br *roachpb.BatchResponse) *roachpb.Error {
for _, req := range ba.Requests {
if putReq, ok := req.GetInner().(*roachpb.PutRequest); ok && putReq.Key.Equal(key) {
return roachpb.NewError(are)
}
}
return nil
},
}
s := createTestDBWithKnobs(t, knobs)
defer s.Stop()
ctx := context.Background()
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
tc := txn.Sender().(*TxnCoordSender)
if !errOnFirst {
otherKey := roachpb.Key("other")
if err := txn.Put(ctx, otherKey, []byte("value")); err != nil {
t.Fatal(err)
}
}
if err := txn.Put(ctx, key, []byte("value")); !testutils.IsError(err, "result is ambiguous") {
t.Fatalf("expected error %v, found %v", are, err)
}
if err := txn.Rollback(ctx); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
// Locking the TxnCoordSender to prevent a data race.
if tc.IsTracking() {
return errors.Errorf("expected garbage collection")
}
return nil
})
verifyCleanup(key, s.Eng, t, tc)
})
}
// TestTxnCoordSenderTxnUpdatedOnError verifies that errors adjust the
// response transaction's timestamp and priority as appropriate.
func TestTxnCoordSenderTxnUpdatedOnError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
origTS := makeTS(123, 0)
plus10 := origTS.Add(10, 10).SetSynthetic(false)
plus20 := origTS.Add(20, 0).SetSynthetic(false)
testCases := []struct {
// The test's name.
name string
pErrGen func(txn *roachpb.Transaction) *roachpb.Error
expEpoch enginepb.TxnEpoch
expPri enginepb.TxnPriority
expTS, expOrigTS hlc.Timestamp
// Is set, we're expecting that the Transaction proto is re-initialized (as
// opposed to just having the epoch incremented).
expNewTransaction bool
nodeSeen bool
}{
{
// No error, so nothing interesting either.
name: "nil",
pErrGen: func(_ *roachpb.Transaction) *roachpb.Error { return nil },
expEpoch: 0,
expPri: 1,
expTS: origTS,
expOrigTS: origTS,
},
{
// On uncertainty error, new epoch begins and node is seen.
// Timestamp moves ahead of the existing write.
name: "ReadWithinUncertaintyIntervalError",
pErrGen: func(txn *roachpb.Transaction) *roachpb.Error {
const nodeID = 1
txn.UpdateObservedTimestamp(nodeID, plus10.UnsafeToClockTimestamp())
pErr := roachpb.NewErrorWithTxn(
roachpb.NewReadWithinUncertaintyIntervalError(
hlc.Timestamp{}, hlc.Timestamp{}, nil),
txn)
pErr.OriginNode = nodeID
return pErr
},
expEpoch: 1,
expPri: 1,
expTS: plus10,
expOrigTS: plus10,
nodeSeen: true,
},
{
// On abort, nothing changes but we get a new priority to use for
// the next attempt.
name: "TransactionAbortedError",
pErrGen: func(txn *roachpb.Transaction) *roachpb.Error {
txn.WriteTimestamp = plus20
txn.Priority = 10
return roachpb.NewErrorWithTxn(&roachpb.TransactionAbortedError{}, txn)
},
expNewTransaction: true,
expPri: 10,
expTS: plus20,
expOrigTS: plus20,
},
{
// On failed push, new epoch begins just past the pushed timestamp.
// Additionally, priority ratchets up to just below the pusher's.
name: "TransactionPushError",
pErrGen: func(txn *roachpb.Transaction) *roachpb.Error {
return roachpb.NewErrorWithTxn(&roachpb.TransactionPushError{
PusheeTxn: roachpb.Transaction{
TxnMeta: enginepb.TxnMeta{WriteTimestamp: plus10, Priority: 10},
},
}, txn)
},
expEpoch: 1,
expPri: 9,
expTS: plus10,
expOrigTS: plus10,
},
{
// On retry, restart with new epoch, timestamp and priority.
name: "TransactionRetryError",
pErrGen: func(txn *roachpb.Transaction) *roachpb.Error {
txn.WriteTimestamp = plus10
txn.Priority = 10
return roachpb.NewErrorWithTxn(&roachpb.TransactionRetryError{}, txn)
},
expEpoch: 1,
expPri: 10,
expTS: plus10,
expOrigTS: plus10,
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
stopper := stop.NewStopper()
manual := hlc.NewManualClock(origTS.WallTime)
clock := hlc.NewClock(manual.UnixNano, 20*time.Nanosecond)
var senderFn kv.SenderFunc = func(
_ context.Context, ba roachpb.BatchRequest,
) (*roachpb.BatchResponse, *roachpb.Error) {
var reply *roachpb.BatchResponse
pErr := test.pErrGen(ba.Txn)
if pErr == nil {
reply = ba.CreateReply()
reply.Txn = ba.Txn
} else if txn := pErr.GetTxn(); txn != nil {
// Update the manual clock to simulate an
// error updating a local hlc clock.
manual.Set(txn.WriteTimestamp.WallTime)
}
return reply, pErr
}
ambient := log.AmbientContext{Tracer: tracing.NewTracer()}
tsf := NewTxnCoordSenderFactory(
TxnCoordSenderFactoryConfig{
AmbientCtx: ambient,
Clock: clock,
Stopper: stopper,
},
senderFn,
)
db := kv.NewDB(ambient, tsf, clock, stopper)
key := roachpb.Key("test-key")
now := clock.NowAsClockTimestamp()
origTxnProto := roachpb.MakeTransaction(
"test txn",
key,
roachpb.UserPriority(0),
now.ToTimestamp(),
clock.MaxOffset().Nanoseconds(),
)
// TODO(andrei): I've monkeyed with the priorities on this initial
// Transaction to keep the test happy from a previous version in which the
// Transaction was not initialized before use (which became insufficient
// when we started testing that TransactionAbortedError's properly
// re-initializes the proto), but this deserves cleanup. I think this test
// is strict in what updated priorities it expects and also our mechanism
// for assigning exact priorities doesn't work properly when faced with
// updates.
origTxnProto.Priority = 1
txn := kv.NewTxnFromProto(ctx, db, 0 /* gatewayNodeID */, now, kv.RootTxn, &origTxnProto)
txn.TestingSetPriority(1)
err := txn.Put(ctx, key, []byte("value"))
stopper.Stop(ctx)
if test.name != "nil" && err == nil {
t.Fatalf("expected an error")
}
proto := txn.TestingCloneTxn()
txnReset := origTxnProto.ID != proto.ID
if txnReset != test.expNewTransaction {
t.Fatalf("expected txn reset: %t and got: %t", test.expNewTransaction, txnReset)
}
if proto.Epoch != test.expEpoch {
t.Errorf("expected epoch = %d; got %d",
test.expEpoch, proto.Epoch)
}
if proto.Priority != test.expPri {
t.Errorf("expected priority = %d; got %d",
test.expPri, proto.Priority)
}
if proto.WriteTimestamp != test.expTS {
t.Errorf("expected timestamp to be %s; got %s",
test.expTS, proto.WriteTimestamp)
}
if proto.ReadTimestamp != test.expOrigTS {
t.Errorf("expected orig timestamp to be %s; got %s",
test.expOrigTS, proto.ReadTimestamp)
}
if ns := proto.ObservedTimestamps; (len(ns) != 0) != test.nodeSeen {
t.Errorf("expected nodeSeen=%t, but list of hosts is %v",
test.nodeSeen, ns)
}
})
}
}
// TestTxnMultipleCoord checks that multiple txn coordinators can be
// used for reads by a single transaction, and their state can be combined.
func TestTxnMultipleCoord(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
txn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
// Start the transaction.
key := roachpb.Key("a")
if _, err := txn.Get(ctx, key); err != nil {
t.Fatal(err)
}
// New create a second, leaf coordinator.
leafInputState := txn.GetLeafTxnInputState(ctx)
txn2 := kv.NewLeafTxn(ctx, s.DB, 0 /* gatewayNodeID */, &leafInputState)
// Start the second transaction.
key2 := roachpb.Key("b")
if _, err := txn2.Get(ctx, key2); err != nil {
t.Fatal(err)
}
// Augment txn with txn2's meta & commit.
tfs, err := txn2.GetLeafTxnFinalState(ctx)
if err != nil {
t.Fatal(err)
}
if err := txn.UpdateRootWithLeafFinalState(ctx, &tfs); err != nil {
t.Fatal(err)
}
// Verify presence of both locks.
tcs := txn.Sender().(*TxnCoordSender)
refreshSpans := tcs.interceptorAlloc.txnSpanRefresher.refreshFootprint.asSlice()
require.Equal(t, []roachpb.Span{{Key: key}, {Key: key2}}, refreshSpans)
ba := txn.NewBatch()
ba.AddRawRequest(&roachpb.EndTxnRequest{Commit: true})
if err := txn.Run(ctx, ba); err != nil {
t.Fatal(err)
}
}
// TestTxnCoordSenderNoDuplicateLockSpans verifies that TxnCoordSender does not
// generate duplicate lock spans and that it merges lock spans that have
// overlapping ranges.
func TestTxnCoordSenderNoDuplicateLockSpans(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
stopper := stop.NewStopper()
manual := hlc.NewManualClock(123)
clock := hlc.NewClock(manual.UnixNano, time.Nanosecond)
var expectedLockSpans []roachpb.Span
var senderFn kv.SenderFunc = func(_ context.Context, ba roachpb.BatchRequest) (
*roachpb.BatchResponse, *roachpb.Error) {
br := ba.CreateReply()
br.Txn = ba.Txn.Clone()
if rArgs, ok := ba.GetArg(roachpb.EndTxn); ok {
et := rArgs.(*roachpb.EndTxnRequest)
if !reflect.DeepEqual(et.LockSpans, expectedLockSpans) {
t.Errorf("Invalid lock spans: %+v; expected %+v", et.LockSpans, expectedLockSpans)
}
br.Txn.Status = roachpb.COMMITTED
}
return br, nil
}
ambient := log.AmbientContext{Tracer: tracing.NewTracer()}
factory := NewTxnCoordSenderFactory(
TxnCoordSenderFactoryConfig{
AmbientCtx: ambient,
Clock: clock,
Stopper: stopper,
Settings: cluster.MakeTestingClusterSettings(),
},
senderFn,
)
defer stopper.Stop(ctx)
db := kv.NewDB(ambient, factory, clock, stopper)
txn := kv.NewTxn(ctx, db, 0 /* gatewayNodeID */)
// Acquire locks on a-b, c, u-w before the final batch.
_, pErr := txn.ReverseScanForUpdate(ctx, roachpb.Key("a"), roachpb.Key("b"), 0)
if pErr != nil {
t.Fatal(pErr)
}
pErr = txn.Put(ctx, roachpb.Key("c"), []byte("value"))
if pErr != nil {
t.Fatal(pErr)
}
pErr = txn.DelRange(ctx, roachpb.Key("u"), roachpb.Key("w"))
if pErr != nil {
t.Fatal(pErr)
}
// The final batch overwrites key c and overlaps part of the a-b and u-w ranges.
b := txn.NewBatch()
b.Put(roachpb.Key("b"), []byte("value"))
b.Put(roachpb.Key("c"), []byte("value"))
b.Put(roachpb.Key("d"), []byte("value"))
b.ReverseScanForUpdate(roachpb.Key("v"), roachpb.Key("z"))
// The expected locks are a-b, c, and u-z.
expectedLockSpans = []roachpb.Span{
{Key: roachpb.Key("a"), EndKey: roachpb.Key("b").Next()},
{Key: roachpb.Key("c"), EndKey: nil},
{Key: roachpb.Key("d"), EndKey: nil},
{Key: roachpb.Key("u"), EndKey: roachpb.Key("z")},
}
pErr = txn.CommitInBatch(ctx, b)
if pErr != nil {
t.Fatal(pErr)
}
}