summaryrefslogtreecommitdiff
path: root/jstests/core/txns/timestamped_reads_wait_for_prepare_oplog_visibility.js
blob: e26f88b85c355a8b500be1310e2b52c107812e88 (plain)
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
/**
 * Tests that timestamped reads, reads with snapshot and afterClusterTime, wait for the prepare
 * transaction oplog entry to be visible before choosing a read timestamp.
 *
 * @tags: [uses_transactions, uses_prepare_transaction]
 */
(function() {
    'use strict';
    load("jstests/libs/check_log.js");
    load('jstests/core/txns/libs/prepare_helpers.js');
    load('jstests/libs/parallel_shell_helpers.js');

    TestData.dbName = 'test';
    const baseCollName = 'timestamped_reads_wait_for_prepare_oplog_visibility';
    const testDB = db.getSiblingDB(TestData.dbName);
    TestData.failureTimeout = 1 * 1000;       // 1 second.
    TestData.successTimeout = 5 * 60 * 1000;  // 5 minutes.
    TestData.txnDoc = {_id: 1, x: 1};
    TestData.otherDoc = {_id: 2, y: 7};
    TestData.txnDocFilter = {_id: TestData.txnDoc._id};
    TestData.otherDocFilter = {_id: TestData.otherDoc._id};

    /**
     * A function that accepts a 'readFunc' and a collection name. 'readFunc' accepts a collection
     * name and returns an object with an 'oplogVisibility' test field and a 'prepareConflict' test
     * field. This function is run in a separate thread and tests that oplog visibility blocks
     * certain reads and that prepare conflicts block other types of reads.
     */
    const readThreadFunc = function(readFunc, _collName) {
        load("jstests/libs/check_log.js");

        // Do not start reads until we are blocked in 'prepareTransaction'.
        checkLog.contains(db.getMongo(), "hangAfterReservingPrepareTimestamp fail point enabled");

        // Create a 'readFuncObj' from the 'readFunc'.
        const readFuncObj = readFunc(_collName);
        readFuncObj.oplogVisibility();

        // Let the transaction finish preparing and wait for 'prepareTransaction' to complete.
        assert.commandWorked(db.adminCommand(
            {configureFailPoint: 'hangAfterReservingPrepareTimestamp', mode: 'off'}));
        checkLog.contains(db.getMongo(), "command: prepareTransaction");

        readFuncObj.prepareConflict();
    };

    function runTest(prefix, readFunc) {
        // Reset the log history between tests.
        assert.commandWorked(db.adminCommand({clearLog: 'global'}));

        jsTestLog('Testing oplog visibility for ' + prefix);
        const collName = baseCollName + '_' + prefix;
        const testColl = testDB.getCollection(collName);

        testColl.drop({writeConcern: {w: "majority"}});
        assert.commandWorked(testDB.runCommand({create: collName, writeConcern: {w: 'majority'}}));

        assert.commandWorked(testDB.adminCommand(
            {configureFailPoint: 'hangAfterReservingPrepareTimestamp', mode: 'alwaysOn'}));

        // Insert a document for the transaction.
        assert.commandWorked(testColl.insert(TestData.txnDoc));
        // Insert a document untouched by the transaction.
        assert.commandWorked(testColl.insert(TestData.otherDoc, {writeconcern: {w: "majority"}}));

        // Start a transaction with a single update on the 'txnDoc'.
        const session = db.getMongo().startSession({causalConsistency: false});
        const sessionDB = session.getDatabase(TestData.dbName);
        session.startTransaction({readConcern: {level: 'snapshot'}});
        assert.commandWorked(sessionDB[collName].update(TestData.txnDoc, {$inc: {x: 1}}));

        // We set the log level up to know when 'prepareTransaction' completes.
        db.setLogLevel(1);

        // Clear the log history to ensure we only see the most recent 'prepareTransaction'
        // failpoint log message.
        assert.commandWorked(db.adminCommand({clearLog: 'global'}));
        const joinReadThread = startParallelShell(funWithArgs(readThreadFunc, readFunc, collName));

        jsTestLog("Preparing the transaction for " + prefix);
        const prepareTimestamp = PrepareHelpers.prepareTransaction(session);

        db.setLogLevel(0);
        joinReadThread({checkExitSuccess: true});

        PrepareHelpers.commitTransaction(session, prepareTimestamp);
    }

    const snapshotRead = function(_collName) {
        const _db = db.getSiblingDB(TestData.dbName);

        const session = db.getMongo().startSession({causalConsistency: false});
        const sessionDB = session.getDatabase(TestData.dbName);

        const oplogVisibility = function() {
            jsTestLog("Snapshot reads should not block on oplog visibility.");
            session.startTransaction({readConcern: {level: 'snapshot'}});
            let cursor = assert.commandWorked(sessionDB.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.txnDoc], tojson(cursor));
            assert.commandWorked(session.abortTransaction_forTesting());

            session.startTransaction({readConcern: {level: 'snapshot'}});
            cursor = assert.commandWorked(sessionDB.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.otherDoc], tojson(cursor));
            assert.commandWorked(session.abortTransaction_forTesting());
        };

        const prepareConflict = function() {
            jsTestLog("Snapshot reads should block on prepared transactions for " +
                      "conflicting documents.");
            session.startTransaction({readConcern: {level: 'snapshot'}});
            let cursor = assert.commandFailedWithCode(sessionDB.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                maxTimeMS: TestData.failureTimeout
            }),
                                                      ErrorCodes.MaxTimeMSExpired);
            assert.commandFailedWithCode(session.abortTransaction_forTesting(),
                                         ErrorCodes.NoSuchTransaction);

            jsTestLog("Snapshot reads should succeed on non-conflicting documents while a " +
                      "transaction is in prepare.");
            session.startTransaction({readConcern: {level: 'snapshot'}});
            cursor = assert.commandWorked(sessionDB.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.otherDoc], tojson(cursor));
            assert.commandWorked(session.abortTransaction_forTesting());
        };

        return {oplogVisibility: oplogVisibility, prepareConflict: prepareConflict};
    };

    const afterClusterTime = function(_collName) {
        const _db = db.getSiblingDB(TestData.dbName);

        // Advance the cluster time with an arbitrary other insert.
        let res = assert.commandWorked(
            _db.runCommand({insert: _collName, documents: [{advanceClusterTime: 1}]}));
        assert(res.hasOwnProperty("$clusterTime"), tojson(res));
        assert(res.$clusterTime.hasOwnProperty("clusterTime"), tojson(res));
        const clusterTime = res.$clusterTime.clusterTime;
        jsTestLog("Using afterClusterTime: " + clusterTime);

        const oplogVisibility = function() {
            jsTestLog("afterClusterTime reads should block on oplog visibility.");
            assert.commandFailedWithCode(_db.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                readConcern: {afterClusterTime: clusterTime},
                maxTimeMS: TestData.failureTimeout
            }),
                                         ErrorCodes.MaxTimeMSExpired);
            assert.commandFailedWithCode(_db.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                readConcern: {afterClusterTime: clusterTime},
                maxTimeMS: TestData.failureTimeout
            }),
                                         ErrorCodes.MaxTimeMSExpired);
        };

        const prepareConflict = function() {
            jsTestLog("afterClusterTime reads should block on prepared transactions for " +
                      "conflicting documents.");
            assert.commandFailedWithCode(_db.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                readConcern: {afterClusterTime: clusterTime},
                maxTimeMS: TestData.failureTimeout
            }),
                                         ErrorCodes.MaxTimeMSExpired);

            jsTestLog("afterClusterTime reads should succeed on non-conflicting documents " +
                      "while transaction is in prepare.");
            let cursor = assert.commandWorked(_db.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                readConcern: {afterClusterTime: clusterTime},
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.otherDoc], tojson(cursor));
        };

        return {oplogVisibility: oplogVisibility, prepareConflict: prepareConflict};
    };

    const normalRead = function(_collName) {
        const _db = db.getSiblingDB(TestData.dbName);

        const oplogVisibility = function() {
            jsTestLog("Ordinary reads should not block on oplog visibility.");
            let cursor = assert.commandWorked(_db.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.txnDoc], tojson(cursor));
            cursor = assert.commandWorked(_db.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.otherDoc], tojson(cursor));
        };

        const prepareConflict = function() {
            jsTestLog("Ordinary reads should not block on prepared transactions.");
            let cursor = assert.commandWorked(_db.runCommand({
                find: _collName,
                filter: TestData.txnDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.txnDoc], tojson(cursor));
            cursor = assert.commandWorked(_db.runCommand({
                find: _collName,
                filter: TestData.otherDocFilter,
                maxTimeMS: TestData.successTimeout
            }));
            assert.sameMembers(cursor.cursor.firstBatch, [TestData.otherDoc], tojson(cursor));
        };

        return {oplogVisibility: oplogVisibility, prepareConflict: prepareConflict};
    };

    runTest('normal_reads', normalRead);
    runTest('snapshot_reads', snapshotRead);
    runTest('afterClusterTime', afterClusterTime);
})();