-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_replica_test.go
5029 lines (4625 loc) · 177 KB
/
client_replica_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 2015 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 kvserver_test
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"sort"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed/rangefeedcache"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/batcheval"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptutil"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/stateloader"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigptsreader"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/kvclientutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/caller"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"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/randutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft/v3/raftpb"
)
// TestReplicaClockUpdates verifies that the leaseholder updates its clocks
// when executing a command to the command's timestamp, as long as the
// request timestamp is from a clock (i.e. is not synthetic).
func TestReplicaClockUpdates(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
run := func(t *testing.T, write bool, synthetic bool) {
const numNodes = 3
var manuals []*hlc.HybridManualClock
var clocks []*hlc.Clock
for i := 0; i < numNodes; i++ {
manuals = append(manuals, hlc.NewHybridManualClock())
}
serverArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manuals[i],
},
},
}
}
ctx := context.Background()
tc := testcluster.StartTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
for _, s := range tc.Servers {
clocks = append(clocks, s.Clock())
}
store := tc.GetFirstStoreFromServer(t, 0)
reqKey := roachpb.Key("a")
tc.SplitRangeOrFatal(t, reqKey)
tc.AddVotersOrFatal(t, reqKey, tc.Targets(1, 2)...)
// Pause the hybrid clocks, so we can make an exact measurement.
for _, clock := range manuals {
clock.Pause()
}
// Pick a timestamp in the future of all nodes by less than the
// MaxOffset. Set the synthetic flag according to the test case.
reqTS := clocks[0].Now().Add(clocks[0].MaxOffset().Nanoseconds()/2, 0).WithSynthetic(synthetic)
h := roachpb.Header{Timestamp: reqTS}
// Execute the command.
var req roachpb.Request
if write {
req = incrementArgs(reqKey, 5)
} else {
req = getArgs(reqKey)
}
if _, err := kv.SendWrappedWith(ctx, store.TestSender(), h, req); err != nil {
t.Fatal(err)
}
// Verify that clocks were updated as expected. Only the leaseholder should
// have updated its clock for either a read or a write. In theory, we should
// be able to assert that _only_ the leaseholder's clock is updated, but in
// practice an assertion against followers' clocks being updated is very
// difficult to make without being flaky because it's difficult to prevent
// other channels (background work, etc.) from carrying the clock update.
expUpdated := !synthetic
require.Equal(t, expUpdated, reqTS.Less(clocks[0].Now()))
}
testutils.RunTrueAndFalse(t, "write", func(t *testing.T, write bool) {
testutils.RunTrueAndFalse(t, "synthetic", func(t *testing.T, synthetic bool) {
run(t, write, synthetic)
})
})
}
// TestLeaseholdersRejectClockUpdateWithJump verifies that leaseholders reject
// commands that would cause a large time jump.
func TestLeaseholdersRejectClockUpdateWithJump(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
manual := hlc.NewHybridManualClock()
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manual,
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
manual.Pause()
ts1 := s.Clock().Now()
key := roachpb.Key("a")
incArgs := incrementArgs(key, 5)
// Commands with a future timestamp that is within the MaxOffset
// bound will be accepted and will cause the clock to advance.
const numCmds = 3
clockOffset := s.Clock().MaxOffset() / numCmds
for i := int64(1); i <= numCmds; i++ {
ts := ts1.Add(i*clockOffset.Nanoseconds(), 0).WithSynthetic(false)
if _, err := kv.SendWrappedWith(context.Background(), store.TestSender(), roachpb.Header{Timestamp: ts}, incArgs); err != nil {
t.Fatal(err)
}
}
ts2 := s.Clock().Now()
if expAdvance, advance := ts2.GoTime().Sub(ts1.GoTime()), numCmds*clockOffset; advance != expAdvance {
t.Fatalf("expected clock to advance %s; got %s", expAdvance, advance)
}
// Once the accumulated offset reaches MaxOffset, commands will be rejected.
tsFuture := ts1.Add(s.Clock().MaxOffset().Nanoseconds()+1, 0).WithSynthetic(false)
_, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{Timestamp: tsFuture}, incArgs)
if !testutils.IsPError(pErr, "remote wall time is too far ahead") {
t.Fatalf("unexpected error %v", pErr)
}
// The clock did not advance and the final command was not executed.
ts3 := s.Clock().Now()
if advance := ts3.GoTime().Sub(ts2.GoTime()); advance != 0 {
t.Fatalf("expected clock not to advance, but it advanced by %s", advance)
}
val, _, err := storage.MVCCGet(context.Background(), store.Engine(), key, ts3,
storage.MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if a, e := mustGetInt(val), incArgs.Increment*numCmds; a != e {
t.Errorf("expected %d, got %d", e, a)
}
}
// TestTxnPutOutOfOrder tests a case where a put operation of an older
// timestamp comes after a put operation of a newer timestamp in a
// txn. The test ensures such an out-of-order put succeeds and
// overrides an old value. The test uses a "Writer" and a "Reader"
// to reproduce an out-of-order put.
//
// 1) The Writer executes a cput operation and writes a write intent with
// time T in a txn.
// 2) Before the Writer's txn is committed, the Reader sends a high priority
// get operation with time T+100. This pushes the Writer txn timestamp to
// T+100. The Reader also writes to the same key the Writer did a cput to
// in order to trigger the restart of the Writer's txn. The original
// write intent timestamp is also updated to T+100.
// 3) The Writer starts a new epoch of the txn, but before it writes, the
// Reader sends another high priority get operation with time T+200. This
// pushes the Writer txn timestamp to T+200 to trigger a restart of the
// Writer txn. The Writer will not actually restart until it tries to commit
// the current epoch of the transaction. The Reader updates the timestamp of
// the write intent to T+200. The test deliberately fails the Reader get
// operation, and cockroach doesn't update its timestamp cache.
// 4) The Writer executes the put operation again. This put operation comes
// out-of-order since its timestamp is T+100, while the intent timestamp
// updated at Step 3 is T+200.
// 5) The put operation overrides the old value using timestamp T+100.
// 6) When the Writer attempts to commit its txn, the txn will be restarted
// again at a new epoch timestamp T+200, which will finally succeed.
func TestTxnPutOutOfOrder(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// key is selected to fall within the meta range in order for the later
// routing of requests to range 1 to work properly. Removing the routing
// of all requests to range 1 would allow us to make the key more normal.
const (
key = "key"
restartKey = "restart"
)
// Set up a filter to so that the get operation at Step 3 will return an error.
var numGets int32
testingEvalFilter := func(filterArgs kvserverbase.FilterArgs) *roachpb.Error {
if _, ok := filterArgs.Req.(*roachpb.GetRequest); ok &&
filterArgs.Req.Header().Key.Equal(roachpb.Key(key)) &&
filterArgs.Hdr.Txn == nil {
// The Reader executes two get operations, each of which triggers two get requests
// (the first request fails and triggers txn push, and then the second request
// succeeds). Returns an error for the fourth get request to avoid timestamp cache
// update after the third get operation pushes the txn timestamp.
if atomic.AddInt32(&numGets, 1) == 4 {
return roachpb.NewErrorWithTxn(errors.Errorf("Test"), filterArgs.Hdr.Txn)
}
}
return nil
}
manual := hlc.NewHybridManualClock()
ctx := context.Background()
serv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manual,
},
Store: &kvserver.StoreTestingKnobs{
// Splits can cause our chosen key to end up on a range other than range 1,
// and trying to handle that complicates the test without providing any
// added benefit.
DisableSplitQueue: true,
EvalKnobs: kvserverbase.BatchEvalTestingKnobs{
TestingEvalFilter: testingEvalFilter,
},
},
},
})
s := serv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
// Put an initial value.
initVal := []byte("initVal")
err = store.DB().Put(context.Background(), key, initVal)
if err != nil {
t.Fatalf("failed to put: %+v", err)
}
manual.Pause()
waitPut := make(chan struct{})
waitFirstGet := make(chan struct{})
waitTxnRestart := make(chan struct{})
waitSecondGet := make(chan struct{})
errChan := make(chan error)
// Start the Writer.
go func() {
epoch := -1
// Start a txn that does read-after-write.
// The txn will be restarted twice, and the out-of-order put
// will happen in the second epoch.
errChan <- store.DB().Txn(context.Background(), func(ctx context.Context, txn *kv.Txn) error {
epoch++
if epoch == 1 {
// Wait until the second get operation is issued.
close(waitTxnRestart)
<-waitSecondGet
}
// Get a key which we can write to from the Reader in order to force a restart.
if _, err := txn.Get(ctx, restartKey); err != nil {
return err
}
updatedVal := []byte("updatedVal")
if err := txn.CPut(ctx, key, updatedVal, kvclientutils.StrToCPutExistingValue("initVal")); err != nil {
log.Errorf(context.Background(), "failed put value: %+v", err)
return err
}
// Make sure a get will return the value that was just written.
actual, err := txn.Get(ctx, key)
if err != nil {
return err
}
if !bytes.Equal(actual.ValueBytes(), updatedVal) {
return errors.Errorf("unexpected get result: %s", actual)
}
if epoch == 0 {
// Wait until the first get operation will push the txn timestamp.
close(waitPut)
<-waitFirstGet
}
b := txn.NewBatch()
return txn.CommitInBatch(ctx, b)
})
if epoch != 2 {
file, line, _ := caller.Lookup(0)
errChan <- errors.Errorf("%s:%d unexpected number of txn retries. "+
"Expected epoch 2, got: %d.", file, line, epoch)
} else {
errChan <- nil
}
}()
<-waitPut
// Start the Reader.
// Advance the clock and send a get operation with higher
// priority to trigger the txn restart.
manual.Increment(100)
priority := roachpb.UserPriority(-math.MaxInt32)
requestHeader := roachpb.RequestHeader{
Key: roachpb.Key(key),
}
h := roachpb.Header{
Timestamp: s.Clock().Now(),
UserPriority: priority,
}
if _, err := kv.SendWrappedWith(
context.Background(), store.TestSender(), h, &roachpb.GetRequest{RequestHeader: requestHeader},
); err != nil {
t.Fatalf("failed to get: %+v", err)
}
// Write to the restart key so that the Writer's txn must restart.
putReq := &roachpb.PutRequest{
RequestHeader: roachpb.RequestHeader{Key: roachpb.Key(restartKey)},
Value: roachpb.MakeValueFromBytes([]byte("restart-value")),
}
if _, err := kv.SendWrappedWith(context.Background(), store.TestSender(), h, putReq); err != nil {
t.Fatalf("failed to put: %+v", err)
}
// Wait until the writer restarts the txn.
close(waitFirstGet)
<-waitTxnRestart
// Advance the clock and send a get operation again. This time
// we use TestingCommandFilter so that a get operation is not
// processed after the write intent is resolved (to prevent the
// timestamp cache from being updated).
manual.Increment(100)
h.Timestamp = s.Clock().Now()
if _, err := kv.SendWrappedWith(
context.Background(), store.TestSender(), h, &roachpb.GetRequest{RequestHeader: requestHeader},
); err == nil {
t.Fatal("unexpected success of get")
}
if _, err := kv.SendWrappedWith(context.Background(), store.TestSender(), h, putReq); err != nil {
t.Fatalf("failed to put: %+v", err)
}
close(waitSecondGet)
for i := 0; i < 2; i++ {
if err := <-errChan; err != nil {
t.Fatal(err)
}
}
}
// TestTxnReadWithinUncertaintyInterval tests cases where a transaction observes
// a committed value below its global uncertainty limit while performing a read.
//
// In one variant of the test, the transaction does not have an observed
// timestamp from the KV node serving the read, so its uncertainty interval
// during its read extends all the way to its global uncertainty limit. As a
// result, it observes the committed value in its uncertain future and receives
// a ReadWithinUncertaintyIntervalError.
//
// In a second variant of the test, the transaction does have an observed
// timestamp from the KV node serving the read, so its uncertainty interval
// during its read extends only up to this observed timestamp. This observed
// timestamp is below the committed value's timestamp. As a result, the
// transaction observes the committed value in its certain future, allowing it
// to avoid the ReadWithinUncertaintyIntervalError.
func TestTxnReadWithinUncertaintyInterval(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testutils.RunTrueAndFalse(t, "observedTS", func(t *testing.T, observedTS bool) {
ctx := context.Background()
manual := hlc.NewHybridManualClock()
srv, _, _ := serverutils.StartServer(t, base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manual,
},
},
})
s := srv.(*server.TestServer)
defer s.Stopper().Stop(ctx)
store, err := s.Stores().GetStore(s.GetFirstStoreID())
require.NoError(t, err)
// Split off a scratch range.
key, err := s.ScratchRange()
require.NoError(t, err)
// Pause the server's clocks going forward.
manual.Pause()
// Create a new transaction.
now := s.Clock().Now()
maxOffset := s.Clock().MaxOffset().Nanoseconds()
require.NotZero(t, maxOffset)
txn := roachpb.MakeTransaction("test", key, 1, now, maxOffset, int32(s.SQLInstanceID()))
require.True(t, txn.ReadTimestamp.Less(txn.GlobalUncertaintyLimit))
require.Len(t, txn.ObservedTimestamps, 0)
// If the test variant wants an observed timestamp from the server at a
// timestamp below the value, collect one now.
if observedTS {
get := getArgs(key)
resp, pErr := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{Txn: &txn}, get)
require.Nil(t, pErr)
txn.Update(resp.Header().Txn)
require.Len(t, txn.ObservedTimestamps, 1)
}
// Perform a non-txn write. This will grab a timestamp from the clock.
put := putArgs(key, []byte("val"))
_, pErr := kv.SendWrapped(ctx, store.TestSender(), put)
require.Nil(t, pErr)
// Perform another read on the same key. Depending on whether or not the txn
// had collected an observed timestamp, it may or may not observe the value
// in its uncertainty interval and throw an error.
get := getArgs(key)
_, pErr = kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{Txn: &txn}, get)
if observedTS {
require.Nil(t, pErr)
} else {
require.NotNil(t, pErr)
require.IsType(t, &roachpb.ReadWithinUncertaintyIntervalError{}, pErr.GetDetail())
}
})
}
// TestTxnReadWithinUncertaintyIntervalAfterIntentResolution tests cases where a
// reader transaction observes a committed value that was committed before the
// reader began, but that was resolved after the reader began. The test ensures
// that even if the reader has collected an observed timestamp from the node
// that holds the intent, and even if this observed timestamp is less than the
// timestamp that the intent is eventually committed at, the reader still
// considers the value to be in its uncertainty interval. Not doing so could
// allow for stale read, which would be a violation of linearizability.
//
// This is a regression test for #36431. Before this issue was addressed,
// it was possible for the following series of events to lead to a stale
// read:
// - txn W is coordinated by node B. It lays down an intent on node A (key k) at
// ts 95.
// - txn W gets pushed to ts 105 (taken from B's clock). It refreshes
// successfully and commits at 105. Node A's clock is at, say, 100; this is
// within clock offset bounds.
// - after all this, txn R starts on node A. It gets assigned ts 100. The txn
// has no uncertainty for node A.
// - txn W's async intent resolution comes around and resolves the intent on
// node A, moving the value fwd from ts 95 to 105.
// - txn R reads key k and doesn't see anything. There's a value at 105, but the
// txn have no uncertainty due to an observed timestamp. This is a stale read.
//
// The test's rangedResolution parameter dictates whether the intent is
// asynchronously resolved using point or ranged intent resolution.
//
// The test's movedWhilePending parameter dictates whether the intent is moved
// to a higher timestamp first by a PENDING intent resolution and then COMMITTED
// at that same timestamp, or whether it is moved to a higher timestamp at the
// same time as it is COMMITTED.
//
// The test's alreadyResolved parameter dictates whether the intent is
// already resolved by the time the reader observes it, or whether the
// reader must resolve the intent itself.
//
func TestTxnReadWithinUncertaintyIntervalAfterIntentResolution(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testutils.RunTrueAndFalse(t, "rangedResolution", func(t *testing.T, rangedResolution bool) {
testutils.RunTrueAndFalse(t, "movedWhilePending", func(t *testing.T, movedWhilePending bool) {
testutils.RunTrueAndFalse(t, "alreadyResolved", func(t *testing.T, alreadyResolved bool) {
testTxnReadWithinUncertaintyIntervalAfterIntentResolution(
t, rangedResolution, movedWhilePending, alreadyResolved,
)
})
})
})
}
func testTxnReadWithinUncertaintyIntervalAfterIntentResolution(
t *testing.T, rangedResolution, movedWhilePending, alreadyResolved bool,
) {
const numNodes = 2
var manuals []*hlc.HybridManualClock
var clocks []*hlc.Clock
for i := 0; i < numNodes; i++ {
manuals = append(manuals, hlc.NewHybridManualClock())
}
serverArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manuals[i],
},
Store: &kvserver.StoreTestingKnobs{
IntentResolverKnobs: kvserverbase.IntentResolverTestingKnobs{
// Disable async intent resolution, so that the test can carefully
// control when intent resolution occurs.
DisableAsyncIntentResolution: true,
},
},
},
}
}
ctx := context.Background()
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
// Split off two scratch ranges.
keyA, keyB := roachpb.Key("a"), roachpb.Key("b")
tc.SplitRangeOrFatal(t, keyA)
_, keyBDesc := tc.SplitRangeOrFatal(t, keyB)
// Place key A's sole replica on node 1 and key B's sole replica on node 2.
tc.AddVotersOrFatal(t, keyB, tc.Target(1))
tc.TransferRangeLeaseOrFatal(t, keyBDesc, tc.Target(1))
tc.RemoveVotersOrFatal(t, keyB, tc.Target(0))
// Pause the servers' clocks going forward.
var maxNanos int64
for i, m := range manuals {
m.Pause()
if cur := m.UnixNano(); cur > maxNanos {
maxNanos = cur
}
clocks = append(clocks, tc.Servers[i].Clock())
}
// After doing so, perfectly synchronize them.
for _, m := range manuals {
m.Increment(maxNanos - m.UnixNano())
}
// Create a new writer transaction.
maxOffset := clocks[0].MaxOffset().Nanoseconds()
require.NotZero(t, maxOffset)
writerTxn := roachpb.MakeTransaction("test_writer", keyA, 1, clocks[0].Now(), maxOffset, int32(tc.Servers[0].NodeID()))
// Write to key A and key B in the writer transaction.
for _, key := range []roachpb.Key{keyA, keyB} {
put := putArgs(key, []byte("val"))
resp, pErr := kv.SendWrappedWith(ctx, tc.Servers[0].DistSender(), roachpb.Header{Txn: &writerTxn}, put)
require.Nil(t, pErr)
writerTxn.Update(resp.Header().Txn)
}
// Move the clock on just the first server and bump the transaction commit
// timestamp to this value. The clock on the second server will trail behind.
manuals[0].Increment(100)
require.True(t, writerTxn.WriteTimestamp.Forward(clocks[0].Now()))
// Refresh the writer transaction's timestamp.
writerTxn.ReadTimestamp.Forward(writerTxn.WriteTimestamp)
// Commit the writer transaction. Key A will be synchronously resolved because
// it is on the same range as the transaction record. However, key B will be
// handed to the IntentResolver for asynchronous resolution. Because we
// disabled async resolution, it will not be resolved yet.
et, etH := endTxnArgs(&writerTxn, true /* commit */)
et.LockSpans = []roachpb.Span{
{Key: keyA}, {Key: keyB},
}
if rangedResolution {
for i := range et.LockSpans {
et.LockSpans[i].EndKey = et.LockSpans[i].Key.Next()
}
}
etResp, pErr := kv.SendWrappedWith(ctx, tc.Servers[0].DistSender(), etH, et)
require.Nil(t, pErr)
writerTxn.Update(etResp.Header().Txn)
// Create a new reader transaction. The reader uses the second server as a
// gateway, so its initial read timestamp actually trails the commit timestamp
// of the writer transaction due to clock skew between the two servers. This
// is the classic case where the reader's uncertainty interval is needed to
// avoid stale reads. Remember that the reader transaction began after the
// writer transaction committed and received an ack, so it must observe the
// writer's writes if it is to respect real-time ordering.
//
// NB: we use writerTxn.MinTimestamp instead of clocks[1].Now() so that a
// stray clock update doesn't influence the reader's read timestamp.
readerTxn := roachpb.MakeTransaction("test_reader", keyA, 1, writerTxn.MinTimestamp, maxOffset, int32(tc.Servers[1].NodeID()))
require.True(t, readerTxn.ReadTimestamp.Less(writerTxn.WriteTimestamp))
require.False(t, readerTxn.GlobalUncertaintyLimit.Less(writerTxn.WriteTimestamp))
// Collect an observed timestamp from each of the nodes. We read the key
// following (Key.Next) each of the written keys to avoid conflicting with
// read values. We read keyB first to avoid advancing the clock on node 2
// before we collect an observed timestamp from it.
//
// NOTE: this wasn't even a necessary step to hit #36431, because new
// transactions are always an observed timestamp from their own gateway node.
for i, key := range []roachpb.Key{keyB, keyA} {
get := getArgs(key.Next())
resp, pErr := kv.SendWrappedWith(ctx, tc.Servers[1].DistSender(), roachpb.Header{Txn: &readerTxn}, get)
require.Nil(t, pErr)
require.Nil(t, resp.(*roachpb.GetResponse).Value)
readerTxn.Update(resp.Header().Txn)
require.Len(t, readerTxn.ObservedTimestamps, i+1)
}
// Resolve the intent on key B zero, one, or two times.
{
resolveIntentArgs := func(status roachpb.TransactionStatus) roachpb.Request {
if rangedResolution {
return &roachpb.ResolveIntentRangeRequest{
RequestHeader: roachpb.RequestHeader{Key: keyB, EndKey: keyB.Next()},
IntentTxn: writerTxn.TxnMeta,
Status: status,
}
} else {
return &roachpb.ResolveIntentRequest{
RequestHeader: roachpb.RequestHeader{Key: keyB},
IntentTxn: writerTxn.TxnMeta,
Status: status,
}
}
}
if movedWhilePending {
// First change the intent's timestamp without committing it. This
// exercises the case where the intent's timestamp is moved forward by a
// PENDING intent resolution request and kept the same when the intent is
// eventually COMMITTED. This PENDING intent resolution may still be
// evaluated after the transaction commit has been acknowledged in
// real-time, so it still needs to lead to the committed value retaining
// its original local timestamp.
//
// For instance, consider the following timeline:
//
// 1. txn W writes intent on key A @ time 10
// 2. txn W writes intent on key B @ time 10
// 3. high priority reader @ 15 reads key B
// 4. high priority reader pushes txn W to time 15
// 5. txn W commits @ 15 and resolves key A synchronously
// 6. txn R begins and collects observed timestamp from key B's node @
// time 11
// 7. high priority reader moves intent on key B to time 15
// 8. async intent resolution commits intent on key B, still @ time 15
// 9. txn R reads key B with read ts 11, observed ts 11, and uncertainty
// interval [11, 21]. If step 7 updated the intent's local timestamp
// to the current time when changing its version timestamp, txn R
// could use its observed timestamp to avoid an uncertainty error,
// leading to a stale read.
//
resolve := resolveIntentArgs(roachpb.PENDING)
_, pErr = kv.SendWrapped(ctx, tc.Servers[0].DistSender(), resolve)
require.Nil(t, pErr)
}
if alreadyResolved {
// Resolve the committed value on key B to COMMITTED.
resolve := resolveIntentArgs(roachpb.COMMITTED)
_, pErr = kv.SendWrapped(ctx, tc.Servers[0].DistSender(), resolve)
require.Nil(t, pErr)
}
}
// Read key A and B in the reader transaction. Both should produce
// ReadWithinUncertaintyIntervalErrors.
for _, key := range []roachpb.Key{keyA, keyB} {
get := getArgs(key)
_, pErr := kv.SendWrappedWith(ctx, tc.Servers[0].DistSender(), roachpb.Header{Txn: &readerTxn}, get)
require.NotNil(t, pErr)
var rwuiErr *roachpb.ReadWithinUncertaintyIntervalError
require.True(t, errors.As(pErr.GetDetail(), &rwuiErr))
require.Equal(t, readerTxn.ReadTimestamp, rwuiErr.ReadTimestamp)
require.Equal(t, readerTxn.GlobalUncertaintyLimit, rwuiErr.GlobalUncertaintyLimit)
require.Equal(t, readerTxn.ObservedTimestamps, rwuiErr.ObservedTimestamps)
require.Equal(t, writerTxn.WriteTimestamp, rwuiErr.ExistingTimestamp)
}
}
// TestTxnReadWithinUncertaintyIntervalAfterLeaseTransfer tests a case where a
// transaction observes a committed value in its uncertainty interval that was
// written under a previous leaseholder. In the test, the transaction does
// collect an observed timestamp from the KV node that eventually serves the
// read, but this observed timestamp is not allowed to be used to constrain its
// local uncertainty limit below the lease start time and avoid the uncertainty
// error. As a result, it observes the committed value in its uncertain future
// and receives a ReadWithinUncertaintyIntervalError, which avoids a stale read.
//
// See TestRangeLocalUncertaintyLimitAfterNewLease for a similar test.
func TestTxnReadWithinUncertaintyIntervalAfterLeaseTransfer(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numNodes = 2
var manuals []*hlc.HybridManualClock
var clocks []*hlc.Clock
for i := 0; i < numNodes; i++ {
manuals = append(manuals, hlc.NewHybridManualClock())
}
serverArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manuals[i],
},
},
}
}
ctx := context.Background()
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
// Split off two scratch ranges.
keyA, keyB := roachpb.Key("a"), roachpb.Key("b")
tc.SplitRangeOrFatal(t, keyA)
keyADesc, keyBDesc := tc.SplitRangeOrFatal(t, keyB)
// Place key A's sole replica on node 1 and key B's sole replica on node 2.
tc.AddVotersOrFatal(t, keyB, tc.Target(1))
tc.TransferRangeLeaseOrFatal(t, keyBDesc, tc.Target(1))
tc.RemoveVotersOrFatal(t, keyB, tc.Target(0))
// Pause the servers' clocks going forward.
var maxNanos int64
for i, m := range manuals {
m.Pause()
if cur := m.UnixNano(); cur > maxNanos {
maxNanos = cur
}
clocks = append(clocks, tc.Servers[i].Clock())
}
// After doing so, perfectly synchronize them.
for _, m := range manuals {
m.Increment(maxNanos - m.UnixNano())
}
// Create a new transaction using the second node as the gateway.
now := clocks[1].Now()
maxOffset := clocks[1].MaxOffset().Nanoseconds()
require.NotZero(t, maxOffset)
txn := roachpb.MakeTransaction("test", keyB, 1, now, maxOffset, int32(tc.Servers[1].SQLInstanceID()))
require.True(t, txn.ReadTimestamp.Less(txn.GlobalUncertaintyLimit))
require.Len(t, txn.ObservedTimestamps, 0)
// Collect an observed timestamp in that transaction from node 2.
getB := getArgs(keyB)
resp, pErr := kv.SendWrappedWith(ctx, tc.Servers[1].DistSender(), roachpb.Header{Txn: &txn}, getB)
require.Nil(t, pErr)
txn.Update(resp.Header().Txn)
require.Len(t, txn.ObservedTimestamps, 1)
// Advance the clock on the first node.
manuals[0].Increment(100)
// Perform a non-txn write on node 1. This will grab a timestamp from node 1's
// clock, which leads the clock on node 2.
//
// NOTE: we perform the clock increment and write _after_ creating the
// transaction and collecting an observed timestamp. Ideally, we would write
// this test such that we did this before beginning the transaction on node 2,
// so that the absence of an uncertainty error would be a true "stale read".
// However, doing so causes the test to be flaky because background operations
// can leak the clock signal from node 1 to node 2 between the time that we
// write and the time that the transaction begins. If we had a way to disable
// all best-effort HLC clock stabilization channels and only propagate clock
// signals when strictly necessary then it's possible that we could avoid
// flakiness. For now, we just re-order the operations and assert that we
// receive an uncertainty error even though its absence would not be a true
// stale read.
ba := roachpb.BatchRequest{}
ba.Add(putArgs(keyA, []byte("val")))
br, pErr := tc.Servers[0].DistSender().Send(ctx, ba)
require.Nil(t, pErr)
writeTs := br.Timestamp
// The transaction has a read timestamp beneath the write's commit timestamp
// but a global uncertainty limit above the write's commit timestamp. The
// observed timestamp collected is also beneath the write's commit timestamp.
require.True(t, txn.ReadTimestamp.Less(writeTs))
require.True(t, writeTs.Less(txn.GlobalUncertaintyLimit))
require.True(t, txn.ObservedTimestamps[0].Timestamp.ToTimestamp().Less(writeTs))
// Add a replica for key A's range to node 2. Transfer the lease.
tc.AddVotersOrFatal(t, keyA, tc.Target(1))
tc.TransferRangeLeaseOrFatal(t, keyADesc, tc.Target(1))
// Perform another read in the transaction, this time on key A. This will be
// routed to node 2, because it now holds the lease for key A. Even though the
// transaction has collected an observed timestamp from node 2, it cannot use
// it to constrain its local uncertainty limit below the lease start time and
// avoid the uncertainty error. This is a good thing, as doing so would allow
// for a stale read.
getA := getArgs(keyA)
_, pErr = kv.SendWrappedWith(ctx, tc.Servers[1].DistSender(), roachpb.Header{Txn: &txn}, getA)
require.NotNil(t, pErr)
require.IsType(t, &roachpb.ReadWithinUncertaintyIntervalError{}, pErr.GetDetail())
}
// TestNonTxnReadWithinUncertaintyIntervalAfterLeaseTransfer tests a case where
// a non-transactional request defers its timestamp allocation to a replica that
// does not hold the lease at the time of receiving the request, but does by the
// time that the request consults the lease. In the test, a value is written on
// the previous leaseholder at a higher timestamp than that assigned to the non-
// transactional request. After the lease transfer, the non-txn request is
// required by uncertainty.ComputeInterval to forward its local uncertainty
// limit to the new lease start time. This prevents the read from ignoring the
// previous write, which avoids a stale read. Instead, the non-txn read hits an
// uncertainty error, performs a server-side retry, and re-evaluates with a
// timestamp above the write.
//
// This test exercises the hazard described in "reason #1" of uncertainty.D7.
func TestNonTxnReadWithinUncertaintyIntervalAfterLeaseTransfer(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// Inject a request filter, which intercepts the server-assigned timestamp
// of a non-transactional request and then blocks that request until after
// the lease has been transferred to the server.
type nonTxnGetKey struct{}
nonTxnOrigTsC := make(chan hlc.Timestamp, 1)
nonTxnBlockerC := make(chan struct{})
requestFilter := func(ctx context.Context, ba roachpb.BatchRequest) *roachpb.Error {
if ctx.Value(nonTxnGetKey{}) != nil {
// Give the test the server-assigned timestamp.
require.NotNil(t, ba.TimestampFromServerClock)
nonTxnOrigTsC <- ba.Timestamp
// Wait for the test to give the go-ahead.
select {
case <-nonTxnBlockerC:
case <-ctx.Done():
case <-time.After(testutils.DefaultSucceedsSoonDuration):
}
}
return nil
}
var uncertaintyErrs int32
concurrencyRetryFilter := func(ctx context.Context, _ roachpb.BatchRequest, pErr *roachpb.Error) {
if ctx.Value(nonTxnGetKey{}) != nil {
if _, ok := pErr.GetDetail().(*roachpb.ReadWithinUncertaintyIntervalError); ok {
atomic.AddInt32(&uncertaintyErrs, 1)
}
}
}
const numNodes = 2
var manuals []*hlc.HybridManualClock
for i := 0; i < numNodes; i++ {
manuals = append(manuals, hlc.NewHybridManualClock())
}
serverArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manuals[i],
},
Store: &kvserver.StoreTestingKnobs{
TestingRequestFilter: requestFilter,
TestingConcurrencyRetryFilter: concurrencyRetryFilter,
},
},
}
}
tc := testcluster.StartTestCluster(t, numNodes, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
// Split off a scratch range and upreplicate to node 2.
key := tc.ScratchRange(t)
desc := tc.LookupRangeOrFatal(t, key)
tc.AddVotersOrFatal(t, key, tc.Target(1))
// Pause the servers' clocks going forward.
var maxNanos int64
for _, m := range manuals {
m.Pause()
if cur := m.UnixNano(); cur > maxNanos {
maxNanos = cur
}
}
// After doing so, perfectly synchronize them.
for _, m := range manuals {
m.Increment(maxNanos - m.UnixNano())
}
// Initiate a non-txn read on node 2. The request will be intercepted after
// the request has received a server-assigned timestamp, but before it has
// consulted the lease. We'll transfer the lease to node 2 before the request
// checks, so that it ends up evaluating on node 2.
type resp struct {
*roachpb.BatchResponse
*roachpb.Error
}
nonTxnRespC := make(chan resp, 1)
_ = tc.Stopper().RunAsyncTask(ctx, "non-txn get", func(ctx context.Context) {
ctx = context.WithValue(ctx, nonTxnGetKey{}, "foo")
ba := roachpb.BatchRequest{}
ba.RangeID = desc.RangeID
ba.Add(getArgs(key))
br, pErr := tc.GetFirstStoreFromServer(t, 1).Send(ctx, ba)
nonTxnRespC <- resp{br, pErr}
})
// Wait for the non-txn read to get stuck.
var nonTxnOrigTs hlc.Timestamp
select {
case nonTxnOrigTs = <-nonTxnOrigTsC:
case nonTxnResp := <-nonTxnRespC:
t.Fatalf("unexpected response %+v", nonTxnResp)
case <-time.After(testutils.DefaultSucceedsSoonDuration):
t.Fatalf("timeout")
}
// Advance the clock on node 1.
manuals[0].Increment(100)
// Perform a non-txn write on node 1. This will grab a timestamp from node 1's
// clock, which leads the clock on node 2 and the timestamp assigned to the
// non-txn read.
//
// NOTE: we perform the clock increment and write _after_ sending the non-txn
// read. Ideally, we would write this test such that we did this before
// beginning the read on node 2, so that the absence of an uncertainty error
// would be a true "stale read". However, doing so causes the test to be flaky
// because background operations can leak the clock signal from node 1 to node
// 2 between the time that we write and the time that the non-txn read request
// is sent. If we had a way to disable all best-effort HLC clock stabilization
// channels and only propagate clock signals when strictly necessary then it's
// possible that we could avoid flakiness. For now, we just re-order the
// operations and assert that we observe an uncertainty error even though its
// absence would not be a true stale read.
ba := roachpb.BatchRequest{}