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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
|
/**
* Copyright (C) 2017 MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/client.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/repl/mock_repl_coord_server_fixture.h"
#include "mongo/db/repl/oplog.h"
#include "mongo/db/repl/oplog_entry.h"
#include "mongo/db/repl/optime.h"
#include "mongo/db/service_context.h"
#include "mongo/db/session_catalog.h"
#include "mongo/db/stats/fill_locker_info.h"
#include "mongo/stdx/future.h"
#include "mongo/stdx/memory.h"
#include "mongo/unittest/death_test.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/net/sock.h"
namespace mongo {
namespace {
const NamespaceString kNss("TestDB", "TestColl");
const OptionalCollectionUUID kUUID;
const bool kKillCursors = true;
/**
* Creates an OplogEntry with given parameters and preset defaults for this test suite.
*/
repl::OplogEntry makeOplogEntry(repl::OpTime opTime,
repl::OpTypeEnum opType,
BSONObj object,
OperationSessionInfo sessionInfo,
boost::optional<Date_t> wallClockTime,
boost::optional<StmtId> stmtId,
boost::optional<repl::OpTime> prevWriteOpTimeInTransaction) {
return repl::OplogEntry(
opTime, // optime
0, // hash
opType, // opType
kNss, // namespace
boost::none, // uuid
boost::none, // fromMigrate
0, // version
object, // o
boost::none, // o2
sessionInfo, // sessionInfo
boost::none, // upsert
wallClockTime, // wall clock time
stmtId, // statement id
prevWriteOpTimeInTransaction, // optime of previous write within same transaction
boost::none, // pre-image optime
boost::none); // post-image optime
}
class SessionTest : public MockReplCoordServerFixture {
protected:
void setUp() final {
MockReplCoordServerFixture::setUp();
auto service = opCtx()->getServiceContext();
SessionCatalog::get(service)->reset_forTest();
SessionCatalog::get(service)->onStepUp(opCtx());
}
SessionCatalog* catalog() {
return SessionCatalog::get(opCtx()->getServiceContext());
}
static repl::OpTime logOp(OperationContext* opCtx,
const NamespaceString& nss,
const LogicalSessionId& lsid,
TxnNumber txnNumber,
StmtId stmtId) {
return logOp(opCtx, nss, lsid, txnNumber, stmtId, {});
}
static repl::OpTime logOp(OperationContext* opCtx,
const NamespaceString& nss,
const LogicalSessionId& lsid,
TxnNumber txnNumber,
StmtId stmtId,
repl::OpTime prevOpTime) {
OperationSessionInfo osi;
osi.setSessionId(lsid);
osi.setTxnNumber(txnNumber);
repl::OplogLink link;
link.prevOpTime = prevOpTime;
return repl::logOp(opCtx,
"n",
nss,
kUUID,
BSON("TestValue" << 0),
nullptr,
false,
Date_t::now(),
osi,
stmtId,
link);
}
void bumpTxnNumberFromDifferentOpCtx(Session* session, TxnNumber newTxnNum) {
// Stash the original client.
auto originalClient = Client::releaseCurrent();
// Create a migration client and opCtx.
auto service = opCtx()->getServiceContext();
auto migrationClientOwned = service->makeClient("migrationClient");
auto migrationClient = migrationClientOwned.get();
Client::setCurrent(std::move(migrationClientOwned));
auto migrationOpCtx = migrationClient->makeOperationContext();
// Check that there is a transaction in progress with a lower txnNumber.
ASSERT(session->inMultiDocumentTransaction());
ASSERT_LT(session->getActiveTxnNumberForTest(), newTxnNum);
// Check that the transaction has some operations, so we can ensure they are cleared.
ASSERT_GT(session->transactionOperationsForTest().size(), 0u);
// Bump the active transaction number on the session. This should clear all state from the
// previous transaction.
session->beginOrContinueTxnOnMigration(migrationOpCtx.get(), newTxnNum);
ASSERT_EQ(session->getActiveTxnNumberForTest(), newTxnNum);
ASSERT_FALSE(session->inMultiDocumentTransaction());
ASSERT_FALSE(session->transactionIsAborted());
ASSERT_EQ(session->transactionOperationsForTest().size(), 0u);
// Restore the original client.
migrationOpCtx.reset();
Client::releaseCurrent();
Client::setCurrent(std::move(originalClient));
}
};
size_t noopKillCursorFunction(OperationContext*, LogicalSessionId, TxnNumber) {
return 0;
};
bool noopCursorExistsFunction(LogicalSessionId, TxnNumber) {
return false;
};
TEST_F(SessionTest, SessionEntryNotWrittenOnBegin) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 20;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
ASSERT_EQ(sessionId, session.getSessionId());
ASSERT(session.getLastWriteOpTime(txnNum).isNull());
DBDirectClient client(opCtx());
auto cursor = client.query(NamespaceString::kSessionTransactionsTableNamespace.ns(),
{BSON("_id" << sessionId.toBSON())});
ASSERT(cursor);
ASSERT(!cursor->more());
}
TEST_F(SessionTest, SessionEntryWrittenAtFirstWrite) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 21;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
const auto opTime = [&] {
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, 0);
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {0}, opTime, Date_t::now());
wuow.commit();
return opTime;
}();
DBDirectClient client(opCtx());
auto cursor = client.query(NamespaceString::kSessionTransactionsTableNamespace.ns(),
{BSON("_id" << sessionId.toBSON())});
ASSERT(cursor);
ASSERT(cursor->more());
auto txnRecord = SessionTxnRecord::parse(
IDLParserErrorContext("SessionEntryWrittenAtFirstWrite"), cursor->next());
ASSERT(!cursor->more());
ASSERT_EQ(sessionId, txnRecord.getSessionId());
ASSERT_EQ(txnNum, txnRecord.getTxnNum());
ASSERT_EQ(opTime, txnRecord.getLastWriteOpTime());
ASSERT_EQ(opTime, session.getLastWriteOpTime(txnNum));
}
TEST_F(SessionTest, StartingNewerTransactionUpdatesThePersistedSession) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const auto writeTxnRecordFn = [&](TxnNumber txnNum, StmtId stmtId, repl::OpTime prevOpTime) {
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, stmtId, prevOpTime);
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {stmtId}, opTime, Date_t::now());
wuow.commit();
return opTime;
};
const auto firstOpTime = writeTxnRecordFn(100, 0, {});
const auto secondOpTime = writeTxnRecordFn(200, 1, firstOpTime);
DBDirectClient client(opCtx());
auto cursor = client.query(NamespaceString::kSessionTransactionsTableNamespace.ns(),
{BSON("_id" << sessionId.toBSON())});
ASSERT(cursor);
ASSERT(cursor->more());
auto txnRecord = SessionTxnRecord::parse(
IDLParserErrorContext("SessionEntryWrittenAtFirstWrite"), cursor->next());
ASSERT(!cursor->more());
ASSERT_EQ(sessionId, txnRecord.getSessionId());
ASSERT_EQ(200, txnRecord.getTxnNum());
ASSERT_EQ(secondOpTime, txnRecord.getLastWriteOpTime());
ASSERT_EQ(secondOpTime, session.getLastWriteOpTime(200));
session.invalidate();
session.refreshFromStorageIfNeeded(opCtx());
ASSERT_EQ(secondOpTime, session.getLastWriteOpTime(200));
}
TEST_F(SessionTest, StartingOldTxnShouldAssert) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 20;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
ASSERT_THROWS_CODE(session.beginOrContinueTxn(opCtx(), txnNum - 1, boost::none, boost::none),
AssertionException,
ErrorCodes::TransactionTooOld);
ASSERT(session.getLastWriteOpTime(txnNum).isNull());
}
TEST_F(SessionTest, SessionTransactionsCollectionNotDefaultCreated) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
// Drop the transactions table
BSONObj dropResult;
DBDirectClient client(opCtx());
const auto& nss = NamespaceString::kSessionTransactionsTableNamespace;
ASSERT(client.runCommand(nss.db().toString(), BSON("drop" << nss.coll()), dropResult));
const TxnNumber txnNum = 21;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, 0);
ASSERT_THROWS(session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {0}, opTime, Date_t::now()),
AssertionException);
}
TEST_F(SessionTest, CheckStatementExecuted) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 100;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
const auto writeTxnRecordFn = [&](StmtId stmtId, repl::OpTime prevOpTime) {
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, stmtId, prevOpTime);
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {stmtId}, opTime, Date_t::now());
wuow.commit();
return opTime;
};
ASSERT(!session.checkStatementExecuted(opCtx(), txnNum, 1000));
ASSERT(!session.checkStatementExecutedNoOplogEntryFetch(txnNum, 1000));
const auto firstOpTime = writeTxnRecordFn(1000, {});
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 1000));
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 1000));
ASSERT(!session.checkStatementExecuted(opCtx(), txnNum, 2000));
ASSERT(!session.checkStatementExecutedNoOplogEntryFetch(txnNum, 2000));
writeTxnRecordFn(2000, firstOpTime);
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 2000));
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 2000));
// Invalidate the session and ensure the statements still check out
session.invalidate();
session.refreshFromStorageIfNeeded(opCtx());
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 1000));
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 2000));
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 1000));
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 2000));
}
TEST_F(SessionTest, CheckStatementExecutedForOldTransactionThrows) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 100;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
ASSERT_THROWS_CODE(session.checkStatementExecuted(opCtx(), txnNum - 1, 0),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, CheckStatementExecutedForInvalidatedTransactionThrows) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.invalidate();
ASSERT_THROWS_CODE(session.checkStatementExecuted(opCtx(), 100, 0),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, WriteOpCompletedOnPrimaryForOldTransactionThrows) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 100;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
{
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, 0);
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {0}, opTime, Date_t::now());
wuow.commit();
}
{
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum - 1, 0);
ASSERT_THROWS_CODE(
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum - 1, {0}, opTime, Date_t::now()),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
}
TEST_F(SessionTest, WriteOpCompletedOnPrimaryForInvalidatedTransactionThrows) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 100;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, 0);
session.invalidate();
ASSERT_THROWS_CODE(
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {0}, opTime, Date_t::now()),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, WriteOpCompletedOnPrimaryCommitIgnoresInvalidation) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 100;
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
{
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto opTime = logOp(opCtx(), kNss, sessionId, txnNum, 0);
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {0}, opTime, Date_t::now());
session.invalidate();
wuow.commit();
}
session.refreshFromStorageIfNeeded(opCtx());
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 0));
}
TEST_F(SessionTest, IncompleteHistoryDueToOpLogTruncation) {
const auto sessionId = makeLogicalSessionIdForTest();
const TxnNumber txnNum = 2;
{
OperationSessionInfo osi;
osi.setSessionId(sessionId);
osi.setTxnNumber(txnNum);
auto entry0 =
makeOplogEntry(repl::OpTime(Timestamp(100, 0), 0), // optime
repl::OpTypeEnum::kInsert, // op type
BSON("x" << 0), // o
osi, // session info
Date_t::now(), // wall clock time
0, // statement id
boost::none); // optime of previous write within same transaction
// Intentionally skip writing the oplog entry for statement 0, so that it appears as if the
// chain of log entries is broken because of oplog truncation
auto entry1 =
makeOplogEntry(repl::OpTime(Timestamp(100, 1), 0), // optime
repl::OpTypeEnum::kInsert, // op type
BSON("x" << 1), // o
osi, // session info
Date_t::now(), // wall clock time
1, // statement id
entry0.getOpTime()); // optime of previous write within same transaction
insertOplogEntry(entry1);
auto entry2 =
makeOplogEntry(repl::OpTime(Timestamp(100, 2), 0), // optime
repl::OpTypeEnum::kInsert, // op type
BSON("x" << 2), // o
osi, // session info
Date_t::now(), // wall clock time
2, // statement id
entry1.getOpTime()); // optime of previous write within same transaction
insertOplogEntry(entry2);
DBDirectClient client(opCtx());
client.insert(NamespaceString::kSessionTransactionsTableNamespace.ns(), [&] {
SessionTxnRecord sessionRecord;
sessionRecord.setSessionId(sessionId);
sessionRecord.setTxnNum(txnNum);
sessionRecord.setLastWriteOpTime(entry2.getOpTime());
sessionRecord.setLastWriteDate(*entry2.getWallClockTime());
return sessionRecord.toBSON();
}());
}
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
ASSERT_THROWS_CODE(session.checkStatementExecuted(opCtx(), txnNum, 0),
AssertionException,
ErrorCodes::IncompleteTransactionHistory);
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 1));
ASSERT(session.checkStatementExecuted(opCtx(), txnNum, 2));
ASSERT_THROWS_CODE(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 0),
AssertionException,
ErrorCodes::IncompleteTransactionHistory);
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 1));
ASSERT(session.checkStatementExecutedNoOplogEntryFetch(txnNum, 2));
}
TEST_F(SessionTest, ErrorOnlyWhenStmtIdBeingCheckedIsNotInCache) {
const auto sessionId = makeLogicalSessionIdForTest();
const TxnNumber txnNum = 2;
OperationSessionInfo osi;
osi.setSessionId(sessionId);
osi.setTxnNumber(txnNum);
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none);
auto firstOpTime = ([&]() {
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto wallClockTime = Date_t::now();
auto opTime = repl::logOp(opCtx(),
"i",
kNss,
kUUID,
BSON("x" << 1),
&Session::kDeadEndSentinel,
false,
wallClockTime,
osi,
1,
{});
session.onWriteOpCompletedOnPrimary(opCtx(), txnNum, {1}, opTime, wallClockTime);
wuow.commit();
return opTime;
})();
{
repl::OplogLink link;
link.prevOpTime = firstOpTime;
AutoGetCollection autoColl(opCtx(), kNss, MODE_IX);
WriteUnitOfWork wuow(opCtx());
const auto wallClockTime = Date_t::now();
auto opTime = repl::logOp(opCtx(),
"n",
kNss,
kUUID,
{},
&Session::kDeadEndSentinel,
false,
wallClockTime,
osi,
kIncompleteHistoryStmtId,
link);
session.onWriteOpCompletedOnPrimary(
opCtx(), txnNum, {kIncompleteHistoryStmtId}, opTime, wallClockTime);
wuow.commit();
}
{
auto oplog = session.checkStatementExecuted(opCtx(), txnNum, 1);
ASSERT_TRUE(oplog);
ASSERT_EQ(firstOpTime, oplog->getOpTime());
}
ASSERT_THROWS(session.checkStatementExecuted(opCtx(), txnNum, 2), AssertionException);
// Should have the same behavior after loading state from storage.
session.invalidate();
session.refreshFromStorageIfNeeded(opCtx());
{
auto oplog = session.checkStatementExecuted(opCtx(), txnNum, 1);
ASSERT_TRUE(oplog);
ASSERT_EQ(firstOpTime, oplog->getOpTime());
}
ASSERT_THROWS(session.checkStatementExecuted(opCtx(), txnNum, 2), AssertionException);
}
DEATH_TEST_F(SessionTest, CommitWithoutCursorKillFunctionInvariants, "_cursorKillFunction") {
Session::registerCursorKillFunction(nullptr);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "find");
session.commitTransaction(opCtx());
}
TEST_F(SessionTest, StashAndUnstashResources) {
const auto sessionId = makeLogicalSessionIdForTest();
const TxnNumber txnNum = 20;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
Locker* originalLocker = opCtx()->lockState();
RecoveryUnit* originalRecoveryUnit = opCtx()->recoveryUnit();
ASSERT(originalLocker);
ASSERT(originalRecoveryUnit);
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
repl::ReadConcernArgs readConcernArgs;
ASSERT_OK(readConcernArgs.initialize(BSON("find"
<< "test"
<< repl::ReadConcernArgs::kReadConcernFieldName
<< BSON(repl::ReadConcernArgs::kLevelFieldName
<< "snapshot"))));
repl::ReadConcernArgs::get(opCtx()) = readConcernArgs;
// Perform initial unstash which sets up a WriteUnitOfWork.
session.unstashTransactionResources(opCtx(), "find");
ASSERT_EQUALS(originalLocker, opCtx()->lockState());
ASSERT_EQUALS(originalRecoveryUnit, opCtx()->recoveryUnit());
ASSERT(opCtx()->getWriteUnitOfWork());
// Take a lock. This is expected in order to stash resources.
Lock::GlobalRead lk(opCtx(), Date_t::now());
ASSERT(lk.isLocked());
// Stash resources. The original Locker and RecoveryUnit now belong to the stash.
session.stashTransactionResources(opCtx());
ASSERT_NOT_EQUALS(originalLocker, opCtx()->lockState());
ASSERT_NOT_EQUALS(originalRecoveryUnit, opCtx()->recoveryUnit());
ASSERT(!opCtx()->getWriteUnitOfWork());
// Unset the read concern on the OperationContext. This is needed to unstash.
repl::ReadConcernArgs::get(opCtx()) = repl::ReadConcernArgs();
// Unstash the stashed resources. This restores the original Locker and RecoveryUnit to the
// OperationContext.
session.unstashTransactionResources(opCtx(), "find");
ASSERT_EQUALS(originalLocker, opCtx()->lockState());
ASSERT_EQUALS(originalRecoveryUnit, opCtx()->recoveryUnit());
ASSERT(opCtx()->getWriteUnitOfWork());
// Commit the transaction. This allows us to release locks.
session.commitTransaction(opCtx());
}
TEST_F(SessionTest, ReportStashedResources) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
const TxnNumber txnNum = 20;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
ASSERT(opCtx()->lockState());
ASSERT(opCtx()->recoveryUnit());
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
repl::ReadConcernArgs readConcernArgs;
ASSERT_OK(readConcernArgs.initialize(BSON("find"
<< "test"
<< repl::ReadConcernArgs::kReadConcernFieldName
<< BSON(repl::ReadConcernArgs::kLevelFieldName
<< "snapshot"))));
repl::ReadConcernArgs::get(opCtx()) = readConcernArgs;
// Perform initial unstash which sets up a WriteUnitOfWork.
session.unstashTransactionResources(opCtx(), "find");
ASSERT(opCtx()->getWriteUnitOfWork());
// Take a lock. This is expected in order to stash resources.
Lock::GlobalRead lk(opCtx(), Date_t::now());
ASSERT(lk.isLocked());
// Build a BSONObj containing the details which we expect to see reported when we call
// Session::reportStashedState.
const auto lockerInfo = opCtx()->lockState()->getLockerInfo();
ASSERT(lockerInfo);
auto reportBuilder =
std::move(BSONObjBuilder() << "host" << getHostNameCachedAndPort() << "desc"
<< "inactive transaction"
<< "lsid"
<< sessionId.toBSON()
<< "txnNumber"
<< txnNum
<< "waitingForLock"
<< false
<< "active"
<< false);
fillLockerInfo(*lockerInfo, reportBuilder);
// Stash resources. The original Locker and RecoveryUnit now belong to the stash.
session.stashTransactionResources(opCtx());
ASSERT(!opCtx()->getWriteUnitOfWork());
// Verify that the Session's report of its own stashed state aligns with our expectations.
ASSERT_BSONOBJ_EQ(session.reportStashedState(), reportBuilder.obj());
// Unset the read concern on the OperationContext. This is needed to unstash.
repl::ReadConcernArgs::get(opCtx()) = repl::ReadConcernArgs();
// Unstash the stashed resources. This restores the original Locker and RecoveryUnit to the
// OperationContext.
session.unstashTransactionResources(opCtx(), "commitTransaction");
ASSERT(opCtx()->getWriteUnitOfWork());
// With the resources unstashed, verify that the Session reports an empty stashed state.
ASSERT(session.reportStashedState().isEmpty());
// Commit the transaction. This allows us to release locks.
session.commitTransaction(opCtx());
}
TEST_F(SessionTest, CannotSpecifyStartTransactionOnInProgressTxn) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
// Autocommit should be true by default
ASSERT(session.getAutocommit());
const TxnNumber txnNum = 100;
// Must specify startTransaction=true and autocommit=false to start a transaction.
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
// Autocommit should be set to false and we should be in a mult-doc transaction.
ASSERT_FALSE(session.getAutocommit());
ASSERT_TRUE(session.inSnapshotReadOrMultiDocumentTransaction());
// Cannot try to start a transaction that already started.
ASSERT_THROWS_CODE(session.beginOrContinueTxn(opCtx(), txnNum, false, true),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, AutocommitRequiredOnEveryTxnOp) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
// Autocommit should be true by default
ASSERT(session.getAutocommit());
const TxnNumber txnNum = 100;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
// We must have stashed transaction resources to do a second operation on the transaction.
session.unstashTransactionResources(opCtx(), "insert");
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now()); }
session.stashTransactionResources(opCtx());
// Autocommit should be set to false
ASSERT_FALSE(session.getAutocommit());
// Omitting 'autocommit' after the first statement of a transaction should throw an error.
ASSERT_THROWS_CODE(session.beginOrContinueTxn(opCtx(), txnNum, boost::none, boost::none),
AssertionException,
ErrorCodes::InvalidOptions);
// Setting 'autocommit=true' should throw an error.
ASSERT_THROWS_CODE(session.beginOrContinueTxn(opCtx(), txnNum, true, boost::none),
AssertionException,
ErrorCodes::InvalidOptions);
// Including autocommit=false should succeed.
session.beginOrContinueTxn(opCtx(), txnNum, false, boost::none);
}
TEST_F(SessionTest, TransactionsOnlyPermitAllowedReadPreferences) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
TxnNumber txnNum = 1;
//
// Multi-statement transaction operations can only be run with 'readPreference=primary'.
//
auto startTxnWithReadPref = [&](ReadPreference readPref,
boost::optional<bool> autocommit,
boost::optional<bool> startTransaction) {
txnNum++;
ReadPreferenceSetting::get(opCtx()) = ReadPreferenceSetting(readPref);
session.beginOrContinueTxn(opCtx(), txnNum, autocommit, startTransaction);
};
// Shouldn't throw.
startTxnWithReadPref(ReadPreference::PrimaryOnly, false, true);
ASSERT_TRUE(session.inSnapshotReadOrMultiDocumentTransaction());
// All unsupported read preferences should throw.
ASSERT_THROWS_CODE(startTxnWithReadPref(ReadPreference::PrimaryPreferred, false, true),
AssertionException,
50789);
ASSERT_THROWS_CODE(startTxnWithReadPref(ReadPreference::SecondaryOnly, false, true),
AssertionException,
50789);
ASSERT_THROWS_CODE(startTxnWithReadPref(ReadPreference::SecondaryPreferred, false, true),
AssertionException,
50789);
ASSERT_THROWS_CODE(
startTxnWithReadPref(ReadPreference::Nearest, false, true), AssertionException, 50789);
//
// Operations that are not on a multi-statement transaction are allowed to specify any
// readPreference.
//
auto activeTxnNum = TxnNumber{-1};
// None of these should throw. Each should start a transaction with a new, higher, transaction
// number.
startTxnWithReadPref(ReadPreference::PrimaryOnly, boost::none, boost::none);
ASSERT_GT(session.getActiveTxnNumberForTest(), activeTxnNum);
activeTxnNum = session.getActiveTxnNumberForTest();
startTxnWithReadPref(ReadPreference::PrimaryPreferred, boost::none, boost::none);
ASSERT_GT(session.getActiveTxnNumberForTest(), activeTxnNum);
activeTxnNum = session.getActiveTxnNumberForTest();
startTxnWithReadPref(ReadPreference::SecondaryOnly, boost::none, boost::none);
ASSERT_GT(session.getActiveTxnNumberForTest(), activeTxnNum);
activeTxnNum = session.getActiveTxnNumberForTest();
startTxnWithReadPref(ReadPreference::SecondaryPreferred, boost::none, boost::none);
ASSERT_GT(session.getActiveTxnNumberForTest(), activeTxnNum);
activeTxnNum = session.getActiveTxnNumberForTest();
startTxnWithReadPref(ReadPreference::Nearest, boost::none, boost::none);
ASSERT_GT(session.getActiveTxnNumberForTest(), activeTxnNum);
}
TEST_F(SessionTest, SameTransactionPreservesStoredStatements) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 22;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
// We must have stashed transaction resources to re-open the transaction.
session.unstashTransactionResources(opCtx(), "insert");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
ASSERT_BSONOBJ_EQ(operation.toBSON(), session.transactionOperationsForTest()[0].toBSON());
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now()); }
session.stashTransactionResources(opCtx());
// Check the transaction operations before re-opening the transaction.
ASSERT_BSONOBJ_EQ(operation.toBSON(), session.transactionOperationsForTest()[0].toBSON());
// Re-opening the same transaction should have no effect.
session.beginOrContinueTxn(opCtx(), txnNum, false, boost::none);
ASSERT_BSONOBJ_EQ(operation.toBSON(), session.transactionOperationsForTest()[0].toBSON());
}
TEST_F(SessionTest, AbortClearsStoredStatements) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 24;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
ASSERT_BSONOBJ_EQ(operation.toBSON(), session.transactionOperationsForTest()[0].toBSON());
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now()); }
session.stashTransactionResources(opCtx());
session.abortArbitraryTransaction(opCtx(), kKillCursors);
ASSERT_TRUE(session.transactionOperationsForTest().empty());
ASSERT_TRUE(session.transactionIsAborted());
}
// This test makes sure the commit machinery works even when no operations are done on the
// transaction.
TEST_F(SessionTest, EmptyTransactionCommit) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 25;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "commitTransaction");
// The transaction machinery cannot store an empty locker.
Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now());
session.commitTransaction(opCtx());
session.stashTransactionResources(opCtx());
ASSERT_TRUE(session.transactionIsCommitted());
}
// This test makes sure the abort machinery works even when no operations are done on the
// transaction.
TEST_F(SessionTest, EmptyTransactionAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "abortTransaction");
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now()); }
session.stashTransactionResources(opCtx());
session.abortArbitraryTransaction(opCtx(), kKillCursors);
ASSERT_TRUE(session.transactionIsAborted());
}
TEST_F(SessionTest, ConcurrencyOfUnstashAndAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
// The transaction may be aborted without checking out the session.
session.abortArbitraryTransaction(opCtx(), kKillCursors);
// An unstash after an abort should uassert.
ASSERT_THROWS_CODE(session.unstashTransactionResources(opCtx(), "find"),
AssertionException,
ErrorCodes::NoSuchTransaction);
}
TEST_F(SessionTest, ConcurrencyOfUnstashAndMigration) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
// The transaction machinery cannot store an empty locker.
{ Lock::GlobalLock lk(opCtx(), MODE_IX, Date_t::now()); }
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
session.stashTransactionResources(opCtx());
// A migration may bump the active transaction number without checking out the session.
const TxnNumber higherTxnNum = 27;
bumpTxnNumberFromDifferentOpCtx(&session, higherTxnNum);
// An unstash after a migration that bumps the active transaction number should uassert.
ASSERT_THROWS_CODE(session.unstashTransactionResources(opCtx(), "insert"),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, ConcurrencyOfStashAndAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "find");
// The transaction may be aborted without checking out the session.
session.abortArbitraryTransaction(opCtx(), kKillCursors);
// A stash after an abort should be a noop.
session.stashTransactionResources(opCtx());
}
TEST_F(SessionTest, ConcurrencyOfStashAndMigration) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
// A migration may bump the active transaction number without checking out the session.
const TxnNumber higherTxnNum = 27;
bumpTxnNumberFromDifferentOpCtx(&session, higherTxnNum);
// A stash after a migration that bumps the active transaction number should uassert.
ASSERT_THROWS_CODE(session.stashTransactionResources(opCtx()),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, ConcurrencyOfAddTransactionOperationAndAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
// The transaction may be aborted without checking out the session.
session.abortArbitraryTransaction(opCtx(), kKillCursors);
// An addTransactionOperation() after an abort should uassert.
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
ASSERT_THROWS_CODE(session.addTransactionOperation(opCtx(), operation),
AssertionException,
ErrorCodes::NoSuchTransaction);
}
TEST_F(SessionTest, ConcurrencyOfAddTransactionOperationAndMigration) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "find");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
// A migration may bump the active transaction number without checking out the session.
const TxnNumber higherTxnNum = 27;
bumpTxnNumberFromDifferentOpCtx(&session, higherTxnNum);
// An addTransactionOperation() after a migration that bumps the active transaction number
// should uassert.
ASSERT_THROWS_CODE(session.addTransactionOperation(opCtx(), operation),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, ConcurrencyOfEndTransactionAndRetrieveOperationsAndAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
// The transaction may be aborted without checking out the session.
session.abortArbitraryTransaction(opCtx(), kKillCursors);
// An endTransactionAndRetrieveOperations() after an abort should uassert.
ASSERT_THROWS_CODE(session.endTransactionAndRetrieveOperations(opCtx()),
AssertionException,
ErrorCodes::NoSuchTransaction);
}
TEST_F(SessionTest, ConcurrencyOfEndTransactionAndRetrieveOperationsAndMigration) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
// A migration may bump the active transaction number without checking out the session.
const TxnNumber higherTxnNum = 27;
bumpTxnNumberFromDifferentOpCtx(&session, higherTxnNum);
// An endTransactionAndRetrieveOperations() after a migration that bumps the active transaction
// number should uassert.
ASSERT_THROWS_CODE(session.endTransactionAndRetrieveOperations(opCtx()),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
TEST_F(SessionTest, ConcurrencyOfCommitTransactionAndAbort) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "commitTransaction");
// The transaction may be aborted without checking out the session.
session.abortArbitraryTransaction(opCtx(), kKillCursors);
// An commitTransaction() after an abort should uassert.
ASSERT_THROWS_CODE(
session.commitTransaction(opCtx()), AssertionException, ErrorCodes::NoSuchTransaction);
}
TEST_F(SessionTest, ConcurrencyOfCommitTransactionAndMigration) {
Session::registerCursorKillFunction(noopKillCursorFunction);
Session::registerCursorExistsFunction(noopCursorExistsFunction);
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 26;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
auto operation = repl::OplogEntry::makeInsertOperation(kNss, kUUID, BSON("TestValue" << 0));
session.addTransactionOperation(opCtx(), operation);
// A migration may bump the active transaction number without checking out the session.
const TxnNumber higherTxnNum = 27;
bumpTxnNumberFromDifferentOpCtx(&session, higherTxnNum);
// An commitTransaction() after a migration that bumps the active transaction number should
// uassert.
ASSERT_THROWS_CODE(session.commitTransaction(opCtx()),
AssertionException,
ErrorCodes::ConflictingOperationInProgress);
}
// Tests that a transaction aborts if it becomes too large before trying to commit it.
TEST_F(SessionTest, TransactionTooLargeWhileBuilding) {
const auto sessionId = makeLogicalSessionIdForTest();
Session session(sessionId);
session.refreshFromStorageIfNeeded(opCtx());
const TxnNumber txnNum = 28;
opCtx()->setLogicalSessionId(sessionId);
opCtx()->setTxnNumber(txnNum);
session.beginOrContinueTxn(opCtx(), txnNum, false, true);
session.unstashTransactionResources(opCtx(), "insert");
// Two 6MB operations should succeed; three 6MB operations should fail.
constexpr size_t kBigDataSize = 6 * 1024 * 1024;
std::unique_ptr<uint8_t[]> bigData(new uint8_t[kBigDataSize]());
auto operation = repl::OplogEntry::makeInsertOperation(
kNss,
kUUID,
BSON("_id" << 0 << "data" << BSONBinData(bigData.get(), kBigDataSize, BinDataGeneral)));
session.addTransactionOperation(opCtx(), operation);
session.addTransactionOperation(opCtx(), operation);
ASSERT_THROWS_CODE(session.addTransactionOperation(opCtx(), operation),
AssertionException,
ErrorCodes::TransactionTooLarge);
}
} // namespace
} // namespace mongo
|