-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
txn_test.go
1141 lines (1025 loc) · 34.4 KB
/
txn_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_test
import (
"bytes"
"context"
"fmt"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/closedts"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/isolation"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/lock"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/tscache"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"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/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
// TestTxnDBBasics verifies that a simple transaction can be run and
// either committed or aborted. On commit, mutations are visible; on
// abort, mutations are never visible. During the txn, verify that
// uncommitted writes cannot be read outside of the txn but can be
// read from inside the txn.
func TestTxnDBBasics(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
value := []byte("value")
for _, commit := range []bool{true, false} {
key := []byte(fmt.Sprintf("key-%t", commit))
err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// Put transactional value.
if err := txn.Put(ctx, key, value); err != nil {
return err
}
// Attempt to read in another txn.
conflictTxn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
conflictTxn.TestingSetPriority(enginepb.MaxTxnPriority)
if gr, err := conflictTxn.Get(ctx, key); err != nil {
return err
} else if gr.Exists() {
return errors.Errorf("expected nil value; got %v", gr.Value)
}
// Read within the transaction.
if gr, err := txn.Get(ctx, key); err != nil {
return err
} else if !gr.Exists() || !bytes.Equal(gr.ValueBytes(), value) {
return errors.Errorf("expected value %q; got %q", value, gr.Value)
}
if !commit {
return errors.Errorf("purposefully failing transaction")
}
return nil
})
if commit != (err == nil) {
t.Errorf("expected success? %t; got %s", commit, err)
} else if !commit && !testutils.IsError(err, "purposefully failing transaction") {
t.Errorf("unexpected failure with !commit: %v", err)
}
// Verify the value is now visible on commit == true, and not visible otherwise.
gr, err := s.DB.Get(context.Background(), key)
if commit {
if err != nil || !gr.Exists() || !bytes.Equal(gr.ValueBytes(), value) {
t.Errorf("expected success reading value: %+v, %s", gr.ValueBytes(), err)
}
} else {
if err != nil || gr.Exists() {
t.Errorf("expected success and nil value: %s, %s", gr, err)
}
}
}
}
// BenchmarkSingleRoundtripWithLatency runs a number of transactions writing
// to the same key back to back in a single round-trip. Latency is simulated
// by pausing before each RPC sent.
func BenchmarkSingleRoundtripWithLatency(b *testing.B) {
defer leaktest.AfterTest(b)()
defer log.Scope(b).Close(b)
for _, latency := range []time.Duration{0, 10 * time.Millisecond} {
b.Run(fmt.Sprintf("latency=%s", latency), func(b *testing.B) {
var s localtestcluster.LocalTestCluster
s.Latency = latency
s.Start(b, testutils.NewNodeTestBaseContext(), kvcoord.InitFactoryForLocalTestCluster)
defer s.Stop()
defer b.StopTimer()
key := roachpb.Key("key")
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
b := txn.NewBatch()
b.Put(key, fmt.Sprintf("value-%d", i))
return txn.CommitInBatch(ctx, b)
}); err != nil {
b.Fatal(err)
}
}
})
}
}
// TestLostIncrement verifies that Increment with any isolation level is not
// susceptible to the lost update anomaly between the value that the increment
// reads and the value that it writes. In other words, the increment is atomic,
// regardless of isolation level.
//
// The transaction history looks as follows:
//
// R1(A) W2(A,+1) W1(A,+1) [write-write restart] R1(A) W1(A,+1) C1
//
// TODO(nvanbenschoten): once we address #100133, update this test to advance
// the read snapshot for ReadCommitted transactions between the read and the
// increment. Demonstrate that doing so allows for increment to applied to a
// newer value than that returned by the get, but that the increment is still
// atomic.
func TestLostIncrement(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
run := func(isoLevel isolation.Level, commitInBatch bool) {
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
key := roachpb.Key("a")
incrementKey := func() {
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
_, err := txn.Inc(ctx, key, 1)
require.NoError(t, err)
return nil
})
require.NoError(t, err)
}
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
epoch := txn.Epoch()
require.LessOrEqual(t, epoch, enginepb.TxnEpoch(1), "should experience just one restart")
require.NoError(t, txn.SetIsoLevel(isoLevel))
// Issue a read to get initial value.
gr, err := txn.Get(ctx, key)
require.NoError(t, err)
// NOTE: expect 0 during first attempt, 1 during second attempt.
require.Equal(t, int64(epoch), gr.ValueInt())
// During the first attempt, perform a conflicting increment in a
// different transaction.
if epoch == 0 {
incrementKey()
}
// Increment the key.
b := txn.NewBatch()
b.Inc(key, 1)
if commitInBatch {
err = txn.CommitInBatch(ctx, b)
} else {
err = txn.Run(ctx, b)
}
ir := b.Results[0].Rows[0]
// During the first attempt, this should encounter a write-write conflict
// and force a transaction retry.
if epoch == 0 {
require.Error(t, err)
require.Regexp(t, "TransactionRetryWithProtoRefreshError: .*WriteTooOldError", err)
return err
}
// During the second attempt, this should succeed.
require.NoError(t, err)
require.Equal(t, int64(2), ir.ValueInt())
return nil
})
require.NoError(t, err)
}
for _, isoLevel := range isolation.Levels() {
t.Run(isoLevel.String(), func(t *testing.T) {
testutils.RunTrueAndFalse(t, "commitInBatch", func(t *testing.T, commitInBatch bool) {
run(isoLevel, commitInBatch)
})
})
}
}
// TestLostUpdate verifies that transactions are not susceptible to the
// lost update anomaly, regardless of isolation level.
//
// The transaction history looks as follows:
//
// R1(A) W2(A,"hi") W1(A,"oops!") C1 [write-write restart] R1(A) W1(A,"correct") C1
//
// TODO(nvanbenschoten): once we address #100133, update this test to advance
// the read snapshot for ReadCommitted transactions between the read and the
// write. Demonstrate that doing so allows for a lost update.
func TestLostUpdate(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
run := func(isoLevel isolation.Level, commitInBatch bool) {
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
key := roachpb.Key("a")
putKey := func() {
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
return txn.Put(ctx, key, "hi")
})
require.NoError(t, err)
}
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
epoch := txn.Epoch()
require.LessOrEqual(t, epoch, enginepb.TxnEpoch(1))
require.NoError(t, txn.SetIsoLevel(isoLevel))
// Issue a read to get initial value.
gr, err := txn.Get(ctx, key)
require.NoError(t, err)
var newVal string
if epoch == 0 {
require.False(t, gr.Exists())
newVal = "oops!"
} else {
require.True(t, gr.Exists())
require.Equal(t, []byte("hi"), gr.ValueBytes())
newVal = "correct"
}
// During the first attempt, perform a conflicting write.
if epoch == 0 {
putKey()
}
// Write to the key.
b := txn.NewBatch()
b.Put(key, newVal)
if commitInBatch {
err = txn.CommitInBatch(ctx, b)
} else {
err = txn.Run(ctx, b)
}
// During the first attempt, this should encounter a write-write conflict
// and force a transaction retry.
if epoch == 0 {
require.Error(t, err)
require.Regexp(t, "TransactionRetryWithProtoRefreshError: .*WriteTooOldError", err)
return err
}
// During the second attempt, this should succeed.
require.NoError(t, err)
return nil
})
require.NoError(t, err)
// Verify final value.
gr, err := s.DB.Get(ctx, key)
require.NoError(t, err)
require.True(t, gr.Exists())
require.Equal(t, []byte("correct"), gr.ValueBytes())
}
for _, isoLevel := range isolation.Levels() {
t.Run(isoLevel.String(), func(t *testing.T) {
testutils.RunTrueAndFalse(t, "commitInBatch", func(t *testing.T, commitInBatch bool) {
run(isoLevel, commitInBatch)
})
})
}
}
// TestPriorityRatchetOnAbortOrPush verifies that the priority of
// a transaction is ratcheted by successive aborts or pushes. In
// particular, we want to ensure ratcheted priorities when the txn
// discovers it's been aborted or pushed through a poisoned sequence
// cache. This happens when a concurrent writer aborts an intent or a
// concurrent reader pushes an intent.
func TestPriorityRatchetOnAbortOrPush(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDBWithKnobs(t, &kvserver.StoreTestingKnobs{
TestingRequestFilter: func(_ context.Context, ba *kvpb.BatchRequest) *kvpb.Error {
// Reject transaction heartbeats, which can make the test flaky when they
// detect an aborted transaction before the Get operation does. See #68584
// for an explanation.
if ba.IsSingleHeartbeatTxnRequest() {
return kvpb.NewErrorf("rejected")
}
return nil
},
})
defer s.Stop()
pushByReading := func(key roachpb.Key) {
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
if err := txn.SetUserPriority(roachpb.MaxUserPriority); err != nil {
t.Fatal(err)
}
_, err := txn.Get(ctx, key)
return err
}); err != nil {
t.Fatal(err)
}
}
abortByWriting := func(key roachpb.Key) {
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
if err := txn.SetUserPriority(roachpb.MaxUserPriority); err != nil {
t.Fatal(err)
}
return txn.Put(ctx, key, "foo")
}); err != nil {
t.Fatal(err)
}
}
// Try both read and write.
for _, read := range []bool{true, false} {
var iteration int
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
defer func() { iteration++ }()
key := roachpb.Key(fmt.Sprintf("read=%t", read))
// Write to lay down an intent (this will send the begin
// transaction which gets the updated priority).
if err := txn.Put(ctx, key, "bar"); err != nil {
return err
}
if iteration == 1 {
// Verify our priority has ratcheted to one less than the pusher's priority
expPri := enginepb.MaxTxnPriority - 1
if pri := txn.TestingCloneTxn().Priority; pri != expPri {
t.Fatalf("%s: expected priority on retry to ratchet to %d; got %d", key, expPri, pri)
}
return nil
}
// Now simulate a concurrent reader or writer. Our txn will
// either be pushed or aborted. Then issue a read and verify
// that if we've been pushed, no error is returned and if we
// have been aborted, we get an aborted error.
var err error
if read {
pushByReading(key)
_, err = txn.Get(ctx, key)
if err != nil {
t.Fatalf("%s: expected no error; got %s", key, err)
}
} else {
abortByWriting(key)
_, err = txn.Get(ctx, key)
assertTransactionAbortedError(t, err)
}
return err
}); err != nil {
t.Fatal(err)
}
}
}
// TestTxnTimestampRegression verifies that if a transaction's timestamp is
// pushed forward by a concurrent read, it may still commit. A bug in the EndTxn
// implementation used to compare the transaction's current timestamp instead of
// original timestamp.
func TestTxnTimestampRegression(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
keyA := "a"
keyB := "b"
err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// Put transactional value.
if err := txn.Put(ctx, keyA, "value1"); err != nil {
return err
}
// Attempt to read in another txn (this will push timestamp of transaction).
conflictTxn := kv.NewTxn(ctx, s.DB, 0 /* gatewayNodeID */)
conflictTxn.TestingSetPriority(enginepb.MaxTxnPriority)
if _, err := conflictTxn.Get(context.Background(), keyA); err != nil {
return err
}
// Now, read again outside of txn to warmup timestamp cache with higher timestamp.
if _, err := s.DB.Get(context.Background(), keyB); err != nil {
return err
}
// Write now to keyB, which will get a higher timestamp than keyB was written at.
return txn.Put(ctx, keyB, "value2")
})
if err != nil {
t.Fatal(err)
}
}
// TestTxnLongDelayBetweenWritesWithConcurrentRead simulates a
// situation where the delay between two writes in a txn is longer
// than 10 seconds.
// See issue #676 for full details about original bug.
func TestTxnLongDelayBetweenWritesWithConcurrentRead(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
keyA := roachpb.Key("a")
keyB := roachpb.Key("b")
ch := make(chan struct{})
errChan := make(chan error)
go func() {
errChan <- s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// Put transactional value.
if err := txn.Put(ctx, keyA, "value1"); err != nil {
return err
}
// Notify txnB do 1st get(b).
ch <- struct{}{}
// Wait for txnB notify us to put(b).
<-ch
// Write now to keyB.
return txn.Put(ctx, keyB, "value2")
})
}()
// Wait till txnA finish put(a).
<-ch
// Delay for longer than the cache window.
s.Manual.Advance(tscache.MinRetentionWindow + time.Second)
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// Attempt to get first keyB.
gr1, err := txn.Get(ctx, keyB)
if err != nil {
return err
}
// Notify txnA put(b).
ch <- struct{}{}
// Wait for txnA finish commit.
if err := <-errChan; err != nil {
t.Fatal(err)
}
// get(b) again.
gr2, err := txn.Get(ctx, keyB)
if err != nil {
return err
}
if gr1.Exists() || gr2.Exists() {
t.Fatalf("Repeat read same key in same txn but get different value gr1: %q, gr2 %q", gr1.Value, gr2.Value)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// TestTxnRepeatGetWithRangeSplit simulates two writes in a single
// transaction, with a range split occurring between. The second write
// is sent to the new range. The test verifies that another transaction
// reading before and after the split will read the same values.
// See issue #676 for full details about original bug.
func TestTxnRepeatGetWithRangeSplit(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()
keyA := roachpb.Key("a")
keyC := roachpb.Key("c")
splitKey := roachpb.Key("b")
ch := make(chan struct{})
errChan := make(chan error)
go func() {
errChan <- s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// Put transactional value.
if err := txn.Put(ctx, keyA, "value1"); err != nil {
return err
}
// Notify txnB do 1st get(c).
ch <- struct{}{}
// Wait for txnB notify us to put(c).
<-ch
// Write now to keyC, which will keep timestamp.
return txn.Put(ctx, keyC, "value2")
})
}()
// Wait till txnA finish put(a).
<-ch
if err := s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
// First get keyC, value will be nil.
gr1, err := txn.Get(ctx, keyC)
if err != nil {
return err
}
s.Manual.Advance(time.Second)
// Split range by keyB.
if err := s.DB.AdminSplit(
context.Background(),
splitKey,
hlc.MaxTimestamp, /* expirationTime */
); err != nil {
t.Fatal(err)
}
// Wait till split complete.
// Check that we split 1 times in allotted time.
testutils.SucceedsSoon(t, func() error {
// Scan the meta records.
rows, serr := s.DB.Scan(context.Background(), keys.Meta2Prefix, keys.MetaMax, 0)
if serr != nil {
t.Fatalf("failed to scan meta2 keys: %s", serr)
}
if len(rows) >= 2 {
return nil
}
return errors.Errorf("failed to split")
})
// Notify txnA put(c).
ch <- struct{}{}
// Wait for txnA finish commit.
if err := <-errChan; err != nil {
t.Fatal(err)
}
// Get(c) again.
gr2, err := txn.Get(ctx, keyC)
if err != nil {
return err
}
if !gr1.Exists() && gr2.Exists() {
t.Fatalf("Repeat read same key in same txn but get different value gr1 nil gr2 %v", gr2.Value)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// TestTxnRestartedSerializableTimestampRegression verifies that there is
// no timestamp regression error in the event that a pushed txn record disagrees
// with the original timestamp of a restarted transaction.
func TestTxnRestartedSerializableTimestampRegression(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
keyA := "a"
keyB := "b"
ch := make(chan struct{})
errChan := make(chan error)
var count int
go func() {
errChan <- s.DB.Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
count++
// Use a low priority for the transaction so that it can be pushed.
if err := txn.SetUserPriority(roachpb.MinUserPriority); err != nil {
t.Fatal(err)
}
// Put transactional value.
if err := txn.Put(ctx, keyA, "value1"); err != nil {
return err
}
if count <= 1 {
// Notify concurrent getter to push txnA on get(a).
ch <- struct{}{}
// Wait for txnB notify us to commit.
<-ch
}
// Do a write to keyB, which will forward txn timestamp.
return txn.Put(ctx, keyB, "value2")
})
}()
// Wait until txnA finishes put(a).
<-ch
// Attempt to get keyA, which will push txnA.
if _, err := s.DB.Get(context.Background(), keyA); err != nil {
t.Fatal(err)
}
// Do a read at keyB to cause txnA to forward timestamp.
if _, err := s.DB.Get(context.Background(), keyB); err != nil {
t.Fatal(err)
}
// Notify txnA to commit.
ch <- struct{}{}
// Wait for txnA to finish.
if err := <-errChan; err != nil {
t.Fatal(err)
}
// We expect no restarts (so a count of one). The transaction continues
// despite the push and timestamp forwarding in order to lay down all
// intents in the first pass. On the first EndTxn, the difference in
// timestamps would cause the serializable transaction to update spans, but
// only writes occurred during the transaction, so the commit succeeds.
const expCount = 1
if count != expCount {
t.Fatalf("expected %d restarts, but got %d", expCount, count)
}
}
// TestTxnResolveIntentsFromMultipleEpochs verifies that that intents
// from earlier epochs are cleaned up on transaction commit.
func TestTxnResolveIntentsFromMultipleEpochs(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := createTestDB(t)
defer s.Stop()
ctx := context.Background()
writeSkewKey := "write-skew"
keys := []string{"a", "b", "c"}
ch := make(chan struct{})
errChan := make(chan error, 1)
// Launch goroutine to write the three keys on three successive epochs.
go func() {
var count int
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
// Read the write skew key, which will be written by another goroutine
// to ensure transaction restarts.
if _, err := txn.Get(ctx, writeSkewKey); err != nil {
return err
}
// Signal that the transaction has (re)started.
ch <- struct{}{}
// Wait for concurrent writer to write key.
<-ch
// Now write our version over the top (will get a pushed timestamp).
if err := txn.Put(ctx, keys[count], "txn"); err != nil {
return err
}
count++
return nil
})
if err != nil {
errChan <- err
} else if count < len(keys) {
errChan <- fmt.Errorf(
"expected to have to retry %d times and only retried %d times", len(keys), count-1)
} else {
errChan <- nil
}
}()
step := func(key string, causeWriteSkew bool) {
// Wait for transaction to start.
<-ch
if causeWriteSkew {
// Write to the write skew key to ensure a restart.
if err := s.DB.Put(ctx, writeSkewKey, "skew-"+key); err != nil {
t.Fatal(err)
}
}
// Read key to push txn's timestamp forward on its write.
if _, err := s.DB.Get(ctx, key); err != nil {
t.Fatal(err)
}
// Signal the transaction to continue.
ch <- struct{}{}
}
// Step 1 causes a restart.
step(keys[0], true)
// Step 2 causes a restart.
step(keys[1], true)
// Step 3 does not result in a restart.
step(keys[2], false)
// Wait for txn to finish.
if err := <-errChan; err != nil {
t.Fatal(err)
}
// Read values for three keys. The first two should be empty, the last should be "txn".
for i, k := range keys {
v, err := s.DB.Get(ctx, k)
if err != nil {
t.Fatal(err)
}
str := string(v.ValueBytes())
if i < len(keys)-1 {
if str != "" {
t.Errorf("key %s expected \"\"; got %s", k, str)
}
} else {
if str != "txn" {
t.Errorf("key %s expected \"txn\"; got %s", k, str)
}
}
}
}
// Test that txn.CommitTimestamp() reflects refreshes.
func TestTxnCommitTimestampAdvancedByRefresh(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// We're going to inject an uncertainty error, expect the refresh to succeed,
// and then check that the txn.CommitTimestamp() value reflects the refresh.
injected := false
var refreshTS hlc.Timestamp
errKey := roachpb.Key("inject_err")
s := createTestDBWithKnobs(t, &kvserver.StoreTestingKnobs{
TestingRequestFilter: func(_ context.Context, ba *kvpb.BatchRequest) *kvpb.Error {
if g, ok := ba.GetArg(kvpb.Get); ok && g.(*kvpb.GetRequest).Key.Equal(errKey) {
if injected {
return nil
}
injected = true
txn := ba.Txn.Clone()
refreshTS = txn.WriteTimestamp.Add(0, 1)
pErr := kvpb.NewReadWithinUncertaintyIntervalError(
txn.ReadTimestamp,
hlc.ClockTimestamp{},
txn,
refreshTS,
hlc.ClockTimestamp{})
return kvpb.NewErrorWithTxn(pErr, txn)
}
return nil
},
})
defer s.Stop()
err := s.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
_, err := txn.Get(ctx, errKey)
if err != nil {
return err
}
if !injected {
return errors.Errorf("didn't inject err")
}
commitTS := txn.CommitTimestamp()
// We expect to have refreshed just after the timestamp injected by the error.
expTS := refreshTS.Add(0, 1)
if !commitTS.Equal(expTS) {
return errors.Errorf("expected refreshTS: %s, got: %s", refreshTS, commitTS)
}
return nil
})
require.NoError(t, err)
}
// Test that in some write too old situations (i.e. when the server returns the
// WriteTooOld flag set and then the client fails to refresh), intents are
// properly left behind.
func TestTxnLeavesIntentBehindAfterWriteTooOldError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()
key := []byte("b")
txn := s.DB.NewTxn(ctx, "test txn")
// Perform a Get so that the transaction can't refresh.
_, err := txn.Get(ctx, key)
require.NoError(t, err)
// Another guy writes at a higher timestamp.
require.NoError(t, s.DB.Put(ctx, key, "newer value"))
// Now we write and expect a WriteTooOld.
intentVal := []byte("test")
err = txn.Put(ctx, key, intentVal)
require.IsType(t, &kvpb.TransactionRetryWithProtoRefreshError{}, err)
require.Regexp(t, "WriteTooOld", err)
// Check that the intent was left behind.
b := kv.Batch{}
b.Header.ReadConsistency = kvpb.READ_UNCOMMITTED
b.Get(key)
require.NoError(t, s.DB.Run(ctx, &b))
getResp := b.RawResponse().Responses[0].GetGet()
require.NotNil(t, getResp)
intent := getResp.IntentValue
require.NotNil(t, intent)
intentBytes, err := intent.GetBytes()
require.NoError(t, err)
require.Equal(t, intentVal, intentBytes)
// Cleanup.
require.NoError(t, txn.Rollback(ctx))
}
// Test that a transaction can be used after a CPut returns a
// ConditionFailedError. This is not generally allowed for other errors, but
// ConditionFailedError is special.
func TestTxnContinueAfterCputError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()
txn := s.DB.NewTxn(ctx, "test txn")
// Note: Since we're expecting the CPut to fail, the massaging done by
// StrToCPutExistingValue() is not actually necessary.
expVal := kvclientutils.StrToCPutExistingValue("dummy")
err := txn.CPut(ctx, "a", "val", expVal)
require.IsType(t, &kvpb.ConditionFailedError{}, err)
require.NoError(t, txn.Put(ctx, "a", "b'"))
require.NoError(t, txn.Commit(ctx))
}
// Test that a transaction can be used after a locking request returns a
// WriteIntentError. This is not generally allowed for other errors, but
// WriteIntentError is special.
func TestTxnContinueAfterWriteIntentError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()
otherTxn := s.DB.NewTxn(ctx, "lock holder txn")
require.NoError(t, otherTxn.Put(ctx, "a", "b"))
txn := s.DB.NewTxn(ctx, "test txn")
b := txn.NewBatch()
b.Header.WaitPolicy = lock.WaitPolicy_Error
b.Put("a", "c")
err := txn.Run(ctx, b)
require.IsType(t, &kvpb.WriteIntentError{}, err)
require.NoError(t, txn.Put(ctx, "a'", "c"))
require.NoError(t, txn.Commit(ctx))
}
func TestTxnWaitPolicies(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()
testutils.RunTrueAndFalse(t, "highPriority", func(t *testing.T, highPriority bool) {
key := []byte("b")
require.NoError(t, s.DB.Put(ctx, key, "old value"))
txn := s.DB.NewTxn(ctx, "test txn")
require.NoError(t, txn.Put(ctx, key, "new value"))
pri := roachpb.NormalUserPriority
if highPriority {
pri = roachpb.MaxUserPriority
}
// Block wait policy.
blockC := make(chan error)
go func() {
var b kv.Batch
b.Header.UserPriority = pri
b.Header.WaitPolicy = lock.WaitPolicy_Block
b.Get(key)
blockC <- s.DB.Run(ctx, &b)
}()
if highPriority {
// Should push txn and not block.
require.NoError(t, <-blockC)
} else {
// Should block.
select {
case err := <-blockC:
t.Fatalf("blocking wait policy unexpected returned with err=%v", err)
case <-time.After(10 * time.Millisecond):
}
}
// Error wait policy.
errorC := make(chan error)
go func() {
var b kv.Batch
b.Header.UserPriority = pri
b.Header.WaitPolicy = lock.WaitPolicy_Error
b.Get(key)
errorC <- s.DB.Run(ctx, &b)
}()
// Should return error immediately, without blocking.
// Priority does not matter.
err := <-errorC
require.NotNil(t, err)
wiErr := new(kvpb.WriteIntentError)
require.True(t, errors.As(err, &wiErr))
require.Equal(t, kvpb.WriteIntentError_REASON_WAIT_POLICY, wiErr.Reason)
// SkipLocked wait policy.
type skipRes struct {
res []kv.Result
err error
}
skipC := make(chan skipRes)
go func() {
var b kv.Batch
b.Header.UserPriority = pri
b.Header.WaitPolicy = lock.WaitPolicy_SkipLocked
b.Get(key)
err := s.DB.Run(ctx, &b)
skipC <- skipRes{res: b.Results, err: err}
}()
// Should return successful but empty result immediately, without blocking.
// Priority does not matter.
res := <-skipC
require.Nil(t, res.err)
require.Len(t, res.res, 1)
getRes := res.res[0]
require.Len(t, getRes.Rows, 1)
require.False(t, getRes.Rows[0].Exists())
// Let blocked requests proceed.
require.NoError(t, txn.Commit(ctx))
if !highPriority {
require.NoError(t, <-blockC)
}
})
}
func TestTxnLockTimeout(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()
key := []byte("b")
txn := s.DB.NewTxn(ctx, "test txn")
require.NoError(t, txn.Put(ctx, key, "new value"))
var b kv.Batch
b.Header.LockTimeout = 25 * time.Millisecond
b.Get(key)
err := s.DB.Run(ctx, &b)
require.NotNil(t, err)
wiErr := new(kvpb.WriteIntentError)
require.True(t, errors.As(err, &wiErr))
require.Equal(t, kvpb.WriteIntentError_REASON_LOCK_TIMEOUT, wiErr.Reason)
}
// TestTxnReturnsWriteTooOldErrorOnConflictingDeleteRange tests that if two
// transactions issue delete range operations over the same keys, the later
// transaction eagerly returns a WriteTooOld error instead of deferring the
// error and temporarily leaking a non-serializable state through its ReturnKeys
// field.
func TestTxnReturnsWriteTooOldErrorOnConflictingDeleteRange(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s := createTestDB(t)
defer s.Stop()